@teamclaws/teamclaw 2026.11.4 → 2026.11.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/controller/config-routes.js +7 -3
- package/dist/src/controller/controller-service.js +12 -1
- package/dist/src/controller/provisioning/container-shared.js +6 -1
- package/dist/src/controller/provisioning/docker.js +1 -1
- package/dist/src/controller/provisioning/kubernetes.js +1 -1
- package/dist/src/controller/provisioning/process-supervisor.js +12 -1
- package/dist/src/controller/provisioning-config.js +8 -0
- package/dist/src/controller/task-assignment.js +65 -2
- package/dist/src/controller/task-results.js +34 -3
- package/dist/src/controller/task-routes.js +24 -1
- package/dist/src/controller/worker-provisioning.js +35 -0
- package/dist/src/controller/worker-routes.js +21 -6
- package/dist/src/openclaw-workspace.js +39 -20
- package/dist/src/task-executor.js +44 -3
- package/dist/src/teamauto/github-client.js +88 -5
- package/dist/src/teamauto/repo-sync.js +90 -5
- package/dist/src/teamauto/scanner.js +22 -1
- package/dist/src/teamauto/scheduler.js +587 -182
- package/dist/src/teamauto/store.js +46 -0
- package/dist/src/teamauto/write-payload-guard.js +209 -0
- package/dist/src/types.js +6 -0
- package/dist/src/worker/tools.js +5 -0
- package/openclaw.plugin.json +1 -1
- package/package.json +1 -1
- package/src/controller/config-routes.ts +7 -3
- package/src/controller/controller-service.ts +12 -1
- package/src/controller/provisioning/backend-contract.ts +4 -0
- package/src/controller/provisioning/container-shared.ts +6 -1
- package/src/controller/provisioning/docker.ts +1 -1
- package/src/controller/provisioning/kubernetes.ts +1 -1
- package/src/controller/provisioning/process-supervisor.ts +12 -1
- package/src/controller/provisioning-config.ts +9 -0
- package/src/controller/task-assignment.ts +71 -1
- package/src/controller/task-results.ts +33 -3
- package/src/controller/task-routes.ts +25 -1
- package/src/controller/worker-provisioning.ts +35 -0
- package/src/controller/worker-routes.ts +21 -7
- package/src/openclaw-workspace.ts +43 -23
- package/src/task-executor.ts +46 -3
- package/src/teamauto/github-client.ts +83 -5
- package/src/teamauto/repo-sync.ts +100 -4
- package/src/teamauto/scanner.ts +23 -2
- package/src/teamauto/scheduler.ts +503 -106
- package/src/teamauto/store.ts +72 -0
- package/src/teamauto/write-payload-guard.ts +222 -0
- package/src/types.ts +21 -0
- package/src/worker/tools.ts +5 -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
|
|
@@ -177,7 +179,10 @@ export function createTeamAutoScheduler(deps) {
|
|
|
177
179
|
entry.attempts = (entry.attempts ?? 0) + 1;
|
|
178
180
|
entry.lastErrorAt = Date.now();
|
|
179
181
|
entry.nextAttemptAt = writebackRetryDueAt(entry.attempts, entry.lastErrorAt);
|
|
180
|
-
|
|
182
|
+
// #5651: a non-fast-forward push whose rebase self-heal also failed is
|
|
183
|
+
// deterministic - retrying the same push 6 more times just burns ~25min.
|
|
184
|
+
// 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);
|
|
181
186
|
if (gaveUp && !entry.doneAt) {
|
|
182
187
|
entry.failedAt = Date.now();
|
|
183
188
|
recordActivity(store, {
|
|
@@ -246,12 +251,42 @@ export function createTeamAutoScheduler(deps) {
|
|
|
246
251
|
return false;
|
|
247
252
|
}
|
|
248
253
|
};
|
|
254
|
+
// #orphan-gc: is the worktree's TARGET (issue/PR) closed? An issue closed
|
|
255
|
+
// without our delivery (fixed elsewhere / rejected / the PR superseded)
|
|
256
|
+
// makes the worktree an orphan no matter how dirty it is - the pre-fix GC
|
|
257
|
+
// retained such trees forever ("retained: dirty worktree", 42 and
|
|
258
|
+
// climbing on the live instance). Resolves true only on a POSITIVE closed
|
|
259
|
+
// state; unknown task / unparsable marker / API failure all resolve null
|
|
260
|
+
// (fail toward keep).
|
|
261
|
+
const targetClosedOracle = async (repoId, taskId) => {
|
|
262
|
+
const teamState = deps.getTeamState();
|
|
263
|
+
const task = teamState?.tasks?.[taskId];
|
|
264
|
+
if (!task || typeof task.description !== "string") {
|
|
265
|
+
return null;
|
|
266
|
+
}
|
|
267
|
+
const parsed = parseClaimMarker(task.description);
|
|
268
|
+
if (!parsed) {
|
|
269
|
+
return null;
|
|
270
|
+
}
|
|
271
|
+
try {
|
|
272
|
+
const [owner, name] = parsed.repoId.split("/");
|
|
273
|
+
if (!owner || !name) {
|
|
274
|
+
return null;
|
|
275
|
+
}
|
|
276
|
+
const fresh = await client.getIssue(owner, name, parsed.number);
|
|
277
|
+
return fresh.state === "closed";
|
|
278
|
+
}
|
|
279
|
+
catch {
|
|
280
|
+
return null;
|
|
281
|
+
}
|
|
282
|
+
};
|
|
249
283
|
const timers = new Map();
|
|
250
284
|
const sweeping = new Set();
|
|
251
285
|
let running = false;
|
|
252
286
|
let store = null;
|
|
253
287
|
let writebackTimer = null;
|
|
254
288
|
let claimRecoveryTimer = null;
|
|
289
|
+
let gcTimer = null;
|
|
255
290
|
async function ensureStore() {
|
|
256
291
|
if (!store) {
|
|
257
292
|
store = await loadTeamAutoStore();
|
|
@@ -423,6 +458,10 @@ export function createTeamAutoScheduler(deps) {
|
|
|
423
458
|
for (let attempt = 1; attempt <= SWEEP_INPLACE_RETRIES; attempt++) {
|
|
424
459
|
try {
|
|
425
460
|
swept = await sweepRepo(repo, client);
|
|
461
|
+
// #5706 (ggcode): sweep observability - "no new work" is ambiguous
|
|
462
|
+
// between an empty fetch (etag 304 / API silence) and full filter
|
|
463
|
+
// rejection. Log the funnel so starvation diagnoses itself.
|
|
464
|
+
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"})`);
|
|
426
465
|
break;
|
|
427
466
|
}
|
|
428
467
|
catch (err) {
|
|
@@ -449,72 +488,94 @@ export function createTeamAutoScheduler(deps) {
|
|
|
449
488
|
// -> still zero candidates -> dryRunDone never set).
|
|
450
489
|
repo.dryRunDone = true;
|
|
451
490
|
}
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
//
|
|
459
|
-
//
|
|
460
|
-
//
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
// observable in sweep summaries (was silently dead before).
|
|
469
|
-
if (newCommits.length > 0) {
|
|
470
|
-
summary.push(`${newCommits.length} new commit(s) (HEAD ${newCommits[0].sha.slice(0, 7)})`);
|
|
471
|
-
}
|
|
472
|
-
if (capped.length && dryRun) {
|
|
473
|
-
summary.push(...capped.map((c) => `DRY-RUN would ${c.kind}: ${c.title}`));
|
|
474
|
-
repo.lastSweepSummary = `dry-run: ${summary.join("; ")}`;
|
|
475
|
-
}
|
|
476
|
-
else if (capped.length) {
|
|
477
|
-
if (!consumeDailyBudget(s, capped.length)) {
|
|
478
|
-
summary.push("skipped: daily task budget exhausted");
|
|
491
|
+
// #5712 (ggcode) / teamclaw#274: the ENTIRE sweep store transaction -
|
|
492
|
+
// cursor/seen advance, budget consume, task activity, write-back
|
|
493
|
+
// registrations, summary, sweep record, and the commit save - is one
|
|
494
|
+
// read-modify-write section. It previously raced the (locked) 20s
|
|
495
|
+
// write-back reconcile: reconcile's disk reload + tail save clobbered
|
|
496
|
+
// the sweep's writes (live: 20:30 batch lost summary/budget/activity
|
|
497
|
+
// while later claim/write-back saves survived). registerWriteback
|
|
498
|
+
// inside uses the *Unlocked core - the promise-chain mutex is NOT
|
|
499
|
+
// re-entrant.
|
|
500
|
+
let created = 0; // #5712: outside the lock scope - read after commit
|
|
501
|
+
await withStoreLock(async () => {
|
|
502
|
+
if (!dryRun) {
|
|
503
|
+
// Advance only for acting sweeps: a dry-run must leave the cursors
|
|
504
|
+
// untouched so the reported actions are actually performed next time
|
|
505
|
+
// instead of being marked as already-seen.
|
|
506
|
+
advanceCursors(repo, issues, pulls, Date.now(), commits);
|
|
479
507
|
}
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
508
|
+
// Joint full reviews bypass the per-sweep cap: they append AFTER issue/
|
|
509
|
+
// pull candidates, so a busy repo would otherwise starve them forever
|
|
510
|
+
// (cap filled every sweep, lastFullReviewAt never advancing). They are
|
|
511
|
+
// at most one cycle (3 sections) per interval, so this stays bounded.
|
|
512
|
+
const fullReviews = candidates.filter((c) => c.kind === "fullReview");
|
|
513
|
+
const regular = candidates.filter((c) => c.kind !== "fullReview").slice(0, Math.max(0, repo.policy.maxTasksPerSweep - fullReviews.length));
|
|
514
|
+
const capped = [...fullReviews, ...regular];
|
|
515
|
+
const summary = [`found ${candidates.length} candidate(s)`];
|
|
516
|
+
// #265: surface the commits delta so the third signal source is
|
|
517
|
+
// observable in sweep summaries (was silently dead before).
|
|
518
|
+
if (newCommits.length > 0) {
|
|
519
|
+
summary.push(`${newCommits.length} new commit(s) (HEAD ${newCommits[0].sha.slice(0, 7)})`);
|
|
520
|
+
}
|
|
521
|
+
if (capped.length && dryRun) {
|
|
522
|
+
summary.push(...capped.map((c) => `DRY-RUN would ${c.kind}: ${c.title}`));
|
|
523
|
+
repo.lastSweepSummary = `dry-run: ${summary.join("; ")}`;
|
|
524
|
+
}
|
|
525
|
+
else if (capped.length) {
|
|
526
|
+
if (!consumeDailyBudget(s, capped.length)) {
|
|
527
|
+
summary.push("skipped: daily task budget exhausted");
|
|
528
|
+
}
|
|
529
|
+
else {
|
|
530
|
+
for (const candidate of capped) {
|
|
531
|
+
const taskId = enqueueCandidate(repo, candidate);
|
|
532
|
+
if (taskId === "dead-lettered") {
|
|
533
|
+
recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `dead-lettered after ${TEAMAUTO_DEAD_LETTER_ATTEMPTS} failed attempts: ${candidate.kind}: ${candidate.title}` });
|
|
534
|
+
}
|
|
535
|
+
else if (taskId) {
|
|
536
|
+
recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "task", text: `${candidate.kind}: ${candidate.title}` });
|
|
537
|
+
// #claim-dequeue (user 2026-11-15): claiming at ENQUEUE locked a
|
|
538
|
+
// string of issues behind the one-writer-per-repo queue while
|
|
539
|
+
// they waited - and blindly claimed issues where external
|
|
540
|
+
// collaborators had started working in the scan-to-claim gap.
|
|
541
|
+
// Claiming now happens at DEQUEUE (claimTaskAtDequeue, called
|
|
542
|
+
// from the task assignment path) after a fresh conflict check.
|
|
543
|
+
const action = candidate.kind === "prReview"
|
|
544
|
+
? "prComment"
|
|
545
|
+
: candidate.kind === "fullReview"
|
|
546
|
+
? "createIssue"
|
|
547
|
+
: candidate.kind === "prRework"
|
|
548
|
+
? "prComment"
|
|
549
|
+
: "issueComment";
|
|
550
|
+
await registerWritebackUnlocked(taskId, action, repo.id, candidate.number || null, candidate.cycle !== undefined ? String(candidate.cycle) : undefined);
|
|
551
|
+
created++;
|
|
552
|
+
}
|
|
485
553
|
}
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
: candidate.kind === "fullReview"
|
|
492
|
-
? "createIssue"
|
|
493
|
-
: "issueComment";
|
|
494
|
-
registerWriteback(taskId, action, repo.id, candidate.number || null, candidate.cycle !== undefined ? String(candidate.cycle) : undefined);
|
|
495
|
-
created++;
|
|
554
|
+
const failedSince = repo.failedTasksSinceLastSweep ?? 0;
|
|
555
|
+
repo.failedTasksSinceLastSweep = 0;
|
|
556
|
+
repo.lastSweepSummary = `created ${created}/${capped.length} task(s)${failedSince > 0 ? `; FAILED ${failedSince} since last sweep` : ""}`;
|
|
557
|
+
if (capped.some((c) => c.kind === "fullReview")) {
|
|
558
|
+
repo.cursors.lastFullReviewAt = Date.now();
|
|
496
559
|
}
|
|
497
560
|
}
|
|
498
|
-
repo.lastSweepSummary = `created ${created}/${capped.length} task(s)`;
|
|
499
|
-
if (capped.some((c) => c.kind === "fullReview")) {
|
|
500
|
-
repo.cursors.lastFullReviewAt = Date.now();
|
|
501
|
-
}
|
|
502
561
|
}
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
repo.pausedReason
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
562
|
+
else {
|
|
563
|
+
const failedSince0 = repo.failedTasksSinceLastSweep ?? 0;
|
|
564
|
+
repo.failedTasksSinceLastSweep = 0;
|
|
565
|
+
repo.lastSweepSummary = failedSince0 > 0 ? `no new work; FAILED ${failedSince0} since last sweep` : "no new work";
|
|
566
|
+
}
|
|
567
|
+
repo.lastSweepAt = Date.now();
|
|
568
|
+
if (isAutoPause(repo.pausedReason)) {
|
|
569
|
+
repo.pausedReason = null;
|
|
570
|
+
recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: "sweep recovered, auto-pause cleared" });
|
|
571
|
+
}
|
|
572
|
+
repo.sweepFailures = 0;
|
|
573
|
+
repo.lastAttemptAt = Date.now(); // #266: success is also an attempt
|
|
574
|
+
const etagAfter = client.etagStats();
|
|
575
|
+
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
|
+
recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: repo.lastSweepSummary ?? "sweep complete" });
|
|
577
|
+
await saveTeamAutoStore(s);
|
|
578
|
+
}); // withStoreLock: sweep transaction
|
|
518
579
|
if (created > 0) {
|
|
519
580
|
await deps.onTasksCreated().catch((err) => {
|
|
520
581
|
logger.warn(`TeamAuto: auto-assign trigger failed: ${String(err)}`);
|
|
@@ -529,15 +590,18 @@ export function createTeamAutoScheduler(deps) {
|
|
|
529
590
|
// pause a repo FOREVER - teamclaw sat auto-paused 15h on one "fetch
|
|
530
591
|
// failed". Auto-pauses are cooldowns now: the timer retries after the
|
|
531
592
|
// backoff below, and a success clears the state in the block above.
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
593
|
+
// #5712: failure bookkeeping is a store RMW too - same lock.
|
|
594
|
+
await withStoreLock(async () => {
|
|
595
|
+
repo.sweepFailures = (repo.sweepFailures ?? 0) + 1;
|
|
596
|
+
repo.lastSweepErrorAt = Date.now();
|
|
597
|
+
repo.lastAttemptAt = repo.lastSweepErrorAt; // #266: failures must be visible without inferring from lastSweepErrorAt
|
|
598
|
+
const failClass = classifySweepError(err);
|
|
599
|
+
repo.pausedReason = `sweep failed[${failClass}]: ${message}`;
|
|
600
|
+
const etagAfter = client.etagStats();
|
|
601
|
+
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) });
|
|
602
|
+
recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `sweep failed[${failClass}] (auto-retry in ~${sweepBackoffMinutesFor(failClass, repo.sweepFailures)}min): ${message}` });
|
|
603
|
+
await saveTeamAutoStore(s).catch(() => { });
|
|
604
|
+
}); // withStoreLock: failure bookkeeping
|
|
541
605
|
logger.warn(`TeamAuto: sweep failed for ${repo.id}: ${message}`);
|
|
542
606
|
return `error: ${message}`;
|
|
543
607
|
}
|
|
@@ -708,6 +772,24 @@ export function createTeamAutoScheduler(deps) {
|
|
|
708
772
|
}
|
|
709
773
|
}
|
|
710
774
|
async function doReconcileWritebacks() {
|
|
775
|
+
// #2677: the WHOLE read-modify-write section holds the store lock -
|
|
776
|
+
// an unlocked reload+save here clobbered a concurrently-registered
|
|
777
|
+
// write-back entry (see store.ts withStoreLock).
|
|
778
|
+
await withStoreLock(async () => {
|
|
779
|
+
await doReconcileWritebacksLocked();
|
|
780
|
+
}).catch((err) => {
|
|
781
|
+
// #5677 ask: never swallow a delivery-pass crash silently - a lost
|
|
782
|
+
// entry with zero trace is invisible; surface it in the log AND the
|
|
783
|
+
// activity feed so the failure class is diagnosable.
|
|
784
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
785
|
+
logger.warn(`TeamAuto: write-back pass CRASHED (entries may retry next tick): ${msg}`);
|
|
786
|
+
void ensureStore().then((s) => {
|
|
787
|
+
recordActivity(s, { at: Date.now(), repoId: "*", kind: "writeback", text: `delivery pass crashed: ${msg.slice(0, 140)}` });
|
|
788
|
+
return saveTeamAutoStore(s);
|
|
789
|
+
}).catch(() => { });
|
|
790
|
+
});
|
|
791
|
+
}
|
|
792
|
+
async function doReconcileWritebacksLocked() {
|
|
711
793
|
// #269 recurrence: re-read the store from disk EVERY pass - the
|
|
712
794
|
// closure cache is a startup snapshot that never sees another
|
|
713
795
|
// process's persisted inFlightAt/doneAt, which is exactly how the
|
|
@@ -729,12 +811,81 @@ export function createTeamAutoScheduler(deps) {
|
|
|
729
811
|
if (dead) {
|
|
730
812
|
logger.warn(`TeamAuto: dropping dead write-back ${w.taskId} (${t ? "task failed without result" : "task missing"})`);
|
|
731
813
|
deadOnes.push(w);
|
|
814
|
+
// #5641: the 3-day architect-leg outage was invisible because a
|
|
815
|
+
// failed-without-result task produced NO activity line and the next
|
|
816
|
+
// sweep summary still said "created 3/3". Record both surfaces.
|
|
817
|
+
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)})` : ""}` });
|
|
818
|
+
const failedRepo = s.repos.find((r) => r.id === w.repoId);
|
|
819
|
+
if (failedRepo) {
|
|
820
|
+
failedRepo.failedTasksSinceLastSweep = (failedRepo.failedTasksSinceLastSweep ?? 0) + 1;
|
|
821
|
+
}
|
|
732
822
|
}
|
|
733
823
|
return !dead;
|
|
734
824
|
});
|
|
735
825
|
if (s.writebacks.length !== before) {
|
|
736
826
|
await saveTeamAutoStore(s);
|
|
737
827
|
}
|
|
828
|
+
// #5725 (ggcode): settle self-audit. A COMPLETED teamauto task with a
|
|
829
|
+
// textual result whose write-back entry is absent AND whose ok line is
|
|
830
|
+
// missing from the activity feed means the registration (or the whole
|
|
831
|
+
// entry) was lost - the ladder redundancy channel silently failed.
|
|
832
|
+
// Alarm once per task so the observability contract survives entry loss.
|
|
833
|
+
let auditDirty = false;
|
|
834
|
+
if (state0) {
|
|
835
|
+
s.orphanResultAlarms ??= {};
|
|
836
|
+
s.deliveredResults ??= {};
|
|
837
|
+
// #5738 (ggcode, 2026-11-17): ONE-TIME migration. The #5736 backfill
|
|
838
|
+
// only stamped entries still present in the write-back array at
|
|
839
|
+
// deploy time - historically delivered legs were already pruned, so
|
|
840
|
+
// they all re-entered the alarm domain on the first settled pass
|
|
841
|
+
// (23 tasks, 99 lines in 80s). Seed the ledger once from the task
|
|
842
|
+
// state itself: everything completed with a result inside the audit
|
|
843
|
+
// window at init time is treated as delivered (the sentinel verified
|
|
844
|
+
// those 23 were all normally delivered). Accepted trade-off: any
|
|
845
|
+
// genuine pre-deploy orphan is pardoned once - signal > archaeology.
|
|
846
|
+
if (!s.deliveredResultsInit) {
|
|
847
|
+
s.deliveredResultsInit = true;
|
|
848
|
+
for (const task of Object.values(state0.tasks ?? {})) {
|
|
849
|
+
if (task?.id && task.status === "completed" && task.result && task.id.startsWith("teamauto-") && task.completedAt && Date.now() - task.completedAt <= 24 * 3600_000) {
|
|
850
|
+
s.deliveredResults[task.id] = task.completedAt;
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
auditDirty = true;
|
|
854
|
+
}
|
|
855
|
+
for (const task of Object.values(state0.tasks ?? {})) {
|
|
856
|
+
if (!task?.id || task.status !== "completed" || !task.result || !task.id.startsWith("teamauto-"))
|
|
857
|
+
continue;
|
|
858
|
+
if (task.completedAt && Date.now() - task.completedAt > 24 * 3600_000)
|
|
859
|
+
continue;
|
|
860
|
+
// #5738: once-per-task gate; the audit now persists its own
|
|
861
|
+
// mutations in the same pass (auditDirty save below), so the gate
|
|
862
|
+
// survives the next 20s disk reload instead of re-alarming.
|
|
863
|
+
const lastAlarmAt = s.orphanResultAlarms[task.id];
|
|
864
|
+
if (lastAlarmAt)
|
|
865
|
+
continue;
|
|
866
|
+
// #5736: delivered-source is the DURABLE ledger (entry present OR
|
|
867
|
+
// recorded at prune time) - never the activity ring, which rolls in
|
|
868
|
+
// 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]);
|
|
870
|
+
if (!hasEntry) {
|
|
871
|
+
s.orphanResultAlarms[task.id] = Date.now();
|
|
872
|
+
auditDirty = true;
|
|
873
|
+
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
|
+
logger.warn(`TeamAuto: orphan completed task ${task.id} without write-back entry`);
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
if (Object.keys(s.orphanResultAlarms).length > 200) {
|
|
878
|
+
const entries = Object.entries(s.orphanResultAlarms).sort((a, b) => a[1] - b[1]);
|
|
879
|
+
for (const [k] of entries.slice(0, entries.length - 100))
|
|
880
|
+
delete s.orphanResultAlarms[k];
|
|
881
|
+
}
|
|
882
|
+
// #5738: the gate lives on disk - persist audit mutations in the SAME
|
|
883
|
+
// pass that makes them, or the next 20s reload resets the gate and
|
|
884
|
+
// re-alarms everything (99 lines / 23 tasks live).
|
|
885
|
+
if (auditDirty) {
|
|
886
|
+
await saveTeamAutoStore(s);
|
|
887
|
+
}
|
|
888
|
+
}
|
|
738
889
|
// Live-verified gap (mw5aun1l, 2026-11-07): this drop path fires for
|
|
739
890
|
// failed-without-result tasks BEFORE the pending loop below, so the
|
|
740
891
|
// terminal worktree cleanup there never ran for them - the single
|
|
@@ -743,7 +894,7 @@ export function createTeamAutoScheduler(deps) {
|
|
|
743
894
|
for (const w of deadOnes) {
|
|
744
895
|
const t = state0.tasks[w.taskId];
|
|
745
896
|
if (t && t.writeMode === "write" && t.projectDir?.includes("__task-")) {
|
|
746
|
-
const r = await sync.safeRemoveTaskWorktree(w.repoId, w.taskId, squashDeliveryOracle);
|
|
897
|
+
const r = await sync.safeRemoveTaskWorktree(w.repoId, w.taskId, squashDeliveryOracle, targetClosedOracle);
|
|
747
898
|
if (r.removed) {
|
|
748
899
|
// #173 follow-up 4: positive removal line - without it a successful
|
|
749
900
|
// terminal cleanup is invisible in logs (only kept/failed logged).
|
|
@@ -766,7 +917,9 @@ export function createTeamAutoScheduler(deps) {
|
|
|
766
917
|
for (const w of s.writebacks) {
|
|
767
918
|
if (w.error && !w.doneAt && !w.failedAt && state0) {
|
|
768
919
|
const t = state0.tasks[w.taskId];
|
|
769
|
-
|
|
920
|
+
// #5719: a FAILED task WITH a result is deliverable too (the result is
|
|
921
|
+
// the work product - analysis/diagnostic legs). Same backoff reset.
|
|
922
|
+
if (t && t.result && (t.status === "completed" || t.status === "failed") && (w.nextAttemptAt ?? 0) <= Date.now()) {
|
|
770
923
|
w.error = null;
|
|
771
924
|
}
|
|
772
925
|
}
|
|
@@ -803,31 +956,41 @@ export function createTeamAutoScheduler(deps) {
|
|
|
803
956
|
return;
|
|
804
957
|
}
|
|
805
958
|
for (const entry of pending) {
|
|
959
|
+
// #5685 (ggcode, 2026-11-16): gate on a TERMINAL task BEFORE touching
|
|
960
|
+
// the entry. The old order stamped inFlightAt first and `continue`d
|
|
961
|
+
// for still-running tasks, leaving the sticky intent to wedge the
|
|
962
|
+
// entry out of pendingAll until the 600s stale reset - a completed
|
|
963
|
+
// task's write-back was deliverable in exactly one 20s window every
|
|
964
|
+
// ~10 minutes (live: the 02:30 fullReview legs delivered 8m42s-9m51s
|
|
965
|
+
// after completion, long misread as deliberate "slow release"). The
|
|
966
|
+
// intent stamp now happens only when the pass is about to dispatch.
|
|
967
|
+
const task = state.tasks[entry.taskId];
|
|
968
|
+
if (!task || (task.status !== "completed" && task.status !== "failed")) {
|
|
969
|
+
continue;
|
|
970
|
+
}
|
|
806
971
|
// #269 intent-first: persist the dispatch intent BEFORE any await so
|
|
807
972
|
// an overlapping pass (or a future guard-less caller) filters this
|
|
808
973
|
// entry out instead of re-delivering it.
|
|
809
974
|
entry.inFlightAt = Date.now();
|
|
810
975
|
await saveTeamAutoStore(s);
|
|
811
|
-
const task = state.tasks[entry.taskId];
|
|
812
|
-
if (!task || (task.status !== "completed" && task.status !== "failed")) {
|
|
813
|
-
continue;
|
|
814
|
-
}
|
|
815
976
|
const repo = s.repos.find((r) => r.id === entry.repoId);
|
|
816
977
|
const [owner, name] = entry.repoId.split("/");
|
|
817
978
|
try {
|
|
818
|
-
if (
|
|
819
|
-
// Undeliverable in every future pass:
|
|
820
|
-
//
|
|
821
|
-
//
|
|
822
|
-
//
|
|
823
|
-
//
|
|
824
|
-
//
|
|
979
|
+
if (!task.result) {
|
|
980
|
+
// Undeliverable in every future pass: "completed without result"
|
|
981
|
+
// cannot recover. #5719 (ggcode, 2026-11-16): a FAILED task WITH a
|
|
982
|
+
// textual result is NOT in this class - the result is the
|
|
983
|
+
// deliverable (analysis/diagnostic work products). It now falls
|
|
984
|
+
// through to normal delivery with an error footer; only
|
|
985
|
+
// result-less entries (failed or completed) stay terminal.
|
|
986
|
+
// Failed-without-result entries are additionally dropped by the
|
|
987
|
+
// dead-letter pass on the next reconcile.
|
|
825
988
|
markWritebackFailure(s, entry, task.status === "failed" ? (task.error ?? "task failed") : "task completed without a textual result", { terminal: true });
|
|
826
989
|
// Terminal write task: its dispatch-time worktree has no delivery
|
|
827
990
|
// path left - remove it when the worker never produced deliverable
|
|
828
991
|
// commits (safety-checked, undelivered work is retained + logged).
|
|
829
992
|
if (task.writeMode === "write" && task.projectDir?.includes("__task-")) {
|
|
830
|
-
const r = await sync.safeRemoveTaskWorktree(entry.repoId, task.id, squashDeliveryOracle);
|
|
993
|
+
const r = await sync.safeRemoveTaskWorktree(entry.repoId, task.id, squashDeliveryOracle, targetClosedOracle);
|
|
831
994
|
if (r.removed) {
|
|
832
995
|
// #173 follow-up 4: positive removal line - symmetric with the
|
|
833
996
|
// boot-GC path which logs both directions.
|
|
@@ -841,16 +1004,26 @@ export function createTeamAutoScheduler(deps) {
|
|
|
841
1004
|
else {
|
|
842
1005
|
const role = (task.assignedRole ?? "qa");
|
|
843
1006
|
let body = `${task.result.trim()}\n${MARKER_FOOTER(role)}`;
|
|
1007
|
+
// #5719: a failed-with-result task delivers its result (the work
|
|
1008
|
+
// product) with the failure context appended - never silently
|
|
1009
|
+
// dropped as before.
|
|
1010
|
+
if (task.status === "failed" && task.error) {
|
|
1011
|
+
body = `${body}\n\n---\n[task reported failed: ${task.error.slice(0, 300)}]`;
|
|
1012
|
+
}
|
|
844
1013
|
let writebackDone = false;
|
|
845
1014
|
// WRITE TASKS (collaboration contract): commit the task worktree,
|
|
846
1015
|
// push its branch, open a PR, and attach the link to the reply.
|
|
847
1016
|
const repoId = entry.repoId;
|
|
848
1017
|
const isTeamAutoWrite = task.writeMode === "write" && task.projectDir?.includes("__task-");
|
|
849
1018
|
let prDeliveryFailed = false;
|
|
850
|
-
if (isTeamAutoWrite) {
|
|
1019
|
+
if (isTeamAutoWrite && task.status !== "failed") {
|
|
1020
|
+
// #5719: a FAILED write task's worktree carries no deliverable by
|
|
1021
|
+
// construction (that is usually WHY it failed) - the PR step just
|
|
1022
|
+
// burns retries against an empty worktree. Deliver the result
|
|
1023
|
+
// comment directly; the worktree is cleaned by the terminal pass.
|
|
851
1024
|
try {
|
|
852
1025
|
const info = await client.getRepoInfo(repoId.split("/")[0], repoId.split("/")[1]);
|
|
853
|
-
const wtDir = await sync.ensureTaskWorktree(repoId, task.id);
|
|
1026
|
+
const wtDir = await sync.ensureTaskWorktree(repoId, task.id, info.defaultBranch, info.cloneUrl);
|
|
854
1027
|
const committed = await sync.commitAll(wtDir, `[teamclaw:${role}] ${task.title.replace(/^\[[^\]]+\]\s*/, "")}`.slice(0, 200), `teamclaw-${role}`, `teamclaw-${role}@users.noreply.github.com`);
|
|
855
1028
|
const branch = `teamclaw/task-${task.id.replace(/[^\w-]/g, "")}`;
|
|
856
1029
|
// Workers often commit themselves inside the worktree - deliver
|
|
@@ -858,11 +1031,20 @@ export function createTeamAutoScheduler(deps) {
|
|
|
858
1031
|
// commitAll just added new ones.
|
|
859
1032
|
const deliverable = committed || (await sync.branchHasCommits(wtDir, info.defaultBranch));
|
|
860
1033
|
if (deliverable) {
|
|
861
|
-
await sync.pushBranch(repoId, wtDir, info.cloneUrl, branch);
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
1034
|
+
const push = await sync.pushBranch(repoId, wtDir, info.cloneUrl, branch);
|
|
1035
|
+
if (push.alreadyDelivered) {
|
|
1036
|
+
// #stale-base follow-up: a previous incarnation already
|
|
1037
|
+
// delivered this branch (PR merged). Skip PR creation and
|
|
1038
|
+
// the retry ladder - the task's work is on the remote.
|
|
1039
|
+
body = `${body}\n\nWork for this task was already delivered on branch \`${branch}\` (previous delivery).`;
|
|
1040
|
+
recordActivity(s, { at: Date.now(), repoId, kind: "writeback", text: `already delivered on ${branch} - skipped duplicate push/PR` });
|
|
1041
|
+
}
|
|
1042
|
+
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}` });
|
|
1047
|
+
}
|
|
866
1048
|
}
|
|
867
1049
|
await sync.removeTaskWorktree(repoId, task.id);
|
|
868
1050
|
}
|
|
@@ -883,10 +1065,26 @@ export function createTeamAutoScheduler(deps) {
|
|
|
883
1065
|
continue;
|
|
884
1066
|
}
|
|
885
1067
|
if (entry.action === "issueComment" && entry.targetId) {
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
1068
|
+
// #5725 / #5660 parity: the worker may have posted the same body
|
|
1069
|
+
// directly during its execution window (takeOwnership legs deliver
|
|
1070
|
+
// an ownership-wrap comment themselves). Posting again duplicates;
|
|
1071
|
+
// skipping silently breaks the observability contract. Exact
|
|
1072
|
+
// whitespace-normalized match -> mark done + record the skip.
|
|
1073
|
+
const normalizedBody = body.replace(/\s+/g, " ").trim();
|
|
1074
|
+
const existingBodies = await client.getIssueCommentBodies(owner, name, entry.targetId);
|
|
1075
|
+
if (existingBodies.some((b) => b.replace(/\s+/g, " ").trim() === normalizedBody)) {
|
|
1076
|
+
entry.doneAt = Date.now();
|
|
1077
|
+
entry.inFlightAt = undefined;
|
|
1078
|
+
writebackDone = true;
|
|
1079
|
+
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` });
|
|
1080
|
+
logger.info(`TeamAuto: write-back ${entry.taskId} issueComment deduped - identical body already on issue #${entry.targetId}`);
|
|
1081
|
+
}
|
|
1082
|
+
else {
|
|
1083
|
+
await client.postIssueComment(owner, name, entry.targetId, body);
|
|
1084
|
+
entry.doneAt = Date.now();
|
|
1085
|
+
entry.inFlightAt = undefined;
|
|
1086
|
+
writebackDone = true;
|
|
1087
|
+
}
|
|
890
1088
|
// Our own comment bumps the issue's updatedAt, which the scanner
|
|
891
1089
|
// treats as new activity - advance the seen cursor so we do not
|
|
892
1090
|
// re-trigger a review of an object we just replied to. External
|
|
@@ -897,10 +1095,28 @@ export function createTeamAutoScheduler(deps) {
|
|
|
897
1095
|
}
|
|
898
1096
|
}
|
|
899
1097
|
else if (entry.action === "prComment" && entry.targetId) {
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
1098
|
+
// #5660 (ggcode, 2026-11-15): the worker already posted the same
|
|
1099
|
+
// review body directly during its execution window; the ladder
|
|
1100
|
+
// then delivered the IDENTICAL text 20s later - readers got the
|
|
1101
|
+
// review twice. Before posting, check the target's existing
|
|
1102
|
+
// feedback (reviews + comments, whitespace-normalized): an exact
|
|
1103
|
+
// match means delivery already happened through the other
|
|
1104
|
+
// channel - mark done and record the skip.
|
|
1105
|
+
const normalized = body.replace(/\s+/g, " ").trim();
|
|
1106
|
+
const existing = await client.getPullFeedbackBodies(owner, name, entry.targetId).catch(() => []);
|
|
1107
|
+
if (existing.includes(normalized)) {
|
|
1108
|
+
entry.doneAt = Date.now();
|
|
1109
|
+
entry.inFlightAt = undefined;
|
|
1110
|
+
writebackDone = true;
|
|
1111
|
+
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` });
|
|
1112
|
+
logger.info(`TeamAuto: write-back ${entry.taskId} prComment deduped - identical body already on PR #${entry.targetId}`);
|
|
1113
|
+
}
|
|
1114
|
+
else {
|
|
1115
|
+
await client.postPullReviewComment(owner, name, entry.targetId, body);
|
|
1116
|
+
entry.doneAt = Date.now();
|
|
1117
|
+
entry.inFlightAt = undefined;
|
|
1118
|
+
writebackDone = true;
|
|
1119
|
+
}
|
|
904
1120
|
const prRepo = s.repos.find((r) => r.id === entry.repoId);
|
|
905
1121
|
if (prRepo) {
|
|
906
1122
|
prRepo.cursors.seen[`${entry.repoId}#pr-${entry.targetId}`] = Date.now();
|
|
@@ -911,18 +1127,49 @@ export function createTeamAutoScheduler(deps) {
|
|
|
911
1127
|
// (first completed section creates it, the rest post as comments).
|
|
912
1128
|
const sectionBody = `### ${role} section\n\n${task.result.trim()}\n${MARKER_FOOTER(role)}`;
|
|
913
1129
|
if (entry.cycleKey) {
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
1130
|
+
// #5685 (ggcode, 2026-11-16): the umbrella pointer must survive
|
|
1131
|
+
// the end-of-pass pruning of done write-back entries (and
|
|
1132
|
+
// process restarts). The old lookup only saw peers delivered
|
|
1133
|
+
// in the SAME pass, so every cross-pass section minted its own
|
|
1134
|
+
// duplicate umbrella - live: cycle 20772 produced issues
|
|
1135
|
+
// #5686/#5687/#5688 (three "Joint full review" umbrellas,
|
|
1136
|
+
// zero section comments). The store map is the durable
|
|
1137
|
+
// pointer; an in-pass done peer remains as a fallback for
|
|
1138
|
+
// stores written before this fix.
|
|
1139
|
+
const cycleKey = `${entry.repoId}|${entry.cycleKey}`;
|
|
1140
|
+
s.fullReviewUmbrellas = s.fullReviewUmbrellas ?? {};
|
|
1141
|
+
const peerEntry = s.writebacks.find((w) => w.repoId === entry.repoId && w.cycleKey === entry.cycleKey && w.taskId !== entry.taskId && w.targetId != null && w.doneAt);
|
|
1142
|
+
const umbrellaNumber = s.fullReviewUmbrellas[cycleKey] ?? peerEntry?.targetId ?? null;
|
|
1143
|
+
if (umbrellaNumber != null) {
|
|
1144
|
+
// Crash-retry guard: this entry may BE the creator whose
|
|
1145
|
+
// createIssue + umbrella-map write persisted but whose doneAt
|
|
1146
|
+
// did not. The umbrella body already carries its section, so
|
|
1147
|
+
// a creator retry completes silently instead of re-posting.
|
|
1148
|
+
if (entry.targetId !== umbrellaNumber) {
|
|
1149
|
+
await client.postIssueComment(owner, name, umbrellaNumber, sectionBody);
|
|
1150
|
+
}
|
|
1151
|
+
entry.targetId = umbrellaNumber;
|
|
1152
|
+
s.fullReviewUmbrellas[cycleKey] = umbrellaNumber;
|
|
919
1153
|
entry.doneAt = Date.now();
|
|
920
1154
|
entry.inFlightAt = undefined;
|
|
921
1155
|
writebackDone = true;
|
|
1156
|
+
entry.deliveryNote = "section-appended-to-umbrella";
|
|
922
1157
|
}
|
|
923
1158
|
else if (entry.targetId == null) {
|
|
924
1159
|
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"]);
|
|
925
1160
|
entry.targetId = number;
|
|
1161
|
+
s.fullReviewUmbrellas[cycleKey] = number;
|
|
1162
|
+
entry.deliveryNote = "umbrella-created";
|
|
1163
|
+
// Persist the umbrella pointer immediately: done entries are
|
|
1164
|
+
// pruned at end-of-pass, and a crash between create and the
|
|
1165
|
+
// tail save must not lose the only record of the umbrella.
|
|
1166
|
+
const umbrellaKeys = Object.keys(s.fullReviewUmbrellas);
|
|
1167
|
+
if (umbrellaKeys.length > 100) {
|
|
1168
|
+
for (const staleKey of umbrellaKeys.slice(0, umbrellaKeys.length - 100)) {
|
|
1169
|
+
delete s.fullReviewUmbrellas[staleKey];
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
await saveTeamAutoStore(s);
|
|
926
1173
|
entry.doneAt = Date.now();
|
|
927
1174
|
entry.inFlightAt = undefined;
|
|
928
1175
|
writebackDone = true;
|
|
@@ -945,36 +1192,170 @@ export function createTeamAutoScheduler(deps) {
|
|
|
945
1192
|
// does not linger in the errored/failed stats (issue #24).
|
|
946
1193
|
entry.error = null;
|
|
947
1194
|
entry.failedAt = null;
|
|
948
|
-
|
|
1195
|
+
// #5735: distinguish created-vs-appended so umbrella cycles stop
|
|
1196
|
+
// reading as double-creates (two "createIssue #N ok" lines for
|
|
1197
|
+
// one issue is by design: first creates, peers append sections).
|
|
1198
|
+
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)` : ""})` });
|
|
949
1199
|
}
|
|
950
1200
|
}
|
|
951
1201
|
}
|
|
952
1202
|
catch (err) {
|
|
953
|
-
|
|
1203
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1204
|
+
markWritebackFailure(s, entry, message, {
|
|
1205
|
+
// #5704: an envelope-frame rejection is deterministic corruption -
|
|
1206
|
+
// the payload cannot change between attempts. Fail terminally
|
|
1207
|
+
// instead of burning the retry ladder re-posting the same frame.
|
|
1208
|
+
terminal: message.includes(ENVELOPE_LEAK_MARKER),
|
|
1209
|
+
});
|
|
954
1210
|
}
|
|
955
1211
|
void repo;
|
|
956
1212
|
}
|
|
1213
|
+
// #5736 (ggcode): record deliveries into the durable ledger BEFORE the
|
|
1214
|
+
// done-entry prune - the write-back array and the tiny activity ring are
|
|
1215
|
+
// both short-lived, but the orphan audit runs for 24h after completion.
|
|
1216
|
+
// Without this, every normally-delivered task alarms as an orphan once
|
|
1217
|
+
// its entry is pruned and its ok line rolls off the ring.
|
|
1218
|
+
s.deliveredResults ??= {};
|
|
1219
|
+
for (const w of s.writebacks) {
|
|
1220
|
+
if (w.doneAt) {
|
|
1221
|
+
s.deliveredResults[w.taskId] = w.doneAt;
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
const deliveredEntries = Object.entries(s.deliveredResults);
|
|
1225
|
+
if (deliveredEntries.length > 2000) {
|
|
1226
|
+
deliveredEntries.sort((a, b) => a[1] - b[1]);
|
|
1227
|
+
for (const [k] of deliveredEntries.slice(0, deliveredEntries.length - 1500))
|
|
1228
|
+
delete s.deliveredResults[k];
|
|
1229
|
+
}
|
|
957
1230
|
s.writebacks = s.writebacks.filter((w) => !w.doneAt).slice(-500);
|
|
958
1231
|
await saveTeamAutoStore(s);
|
|
959
1232
|
}
|
|
960
1233
|
// Register the write-back intent when a task lands in the task store.
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
1234
|
+
// #5643 (user report 2026-11-15): this used to be fire-and-forget
|
|
1235
|
+
// (void ensureStore().then(...).catch(() => {})) - the push+save raced the
|
|
1236
|
+
// sweep's own awaited store save AND swallowed its own errors. The 11-15
|
|
1237
|
+
// 02:00 batch lost ALL THREE fullReview write-back entries that way
|
|
1238
|
+
// (tasks + activity + "created 3/3" persisted; the entries did not), so
|
|
1239
|
+
// completed reviews delivered nothing, silently. Registration is now part
|
|
1240
|
+
// of the sweep transaction: the caller awaits it before the sweep's own
|
|
1241
|
+
// save, and failures propagate instead of vanishing.
|
|
1242
|
+
async function registerWriteback(taskId, action, repoId, targetId, cycleKey) {
|
|
1243
|
+
// #5712 (ggcode) / teamclaw#274: every store read-modify-write must hold
|
|
1244
|
+
// withStoreLock. Public entry takes the lock; the sweep transaction calls
|
|
1245
|
+
// the *Unlocked core directly because IT already holds the lock (the
|
|
1246
|
+
// promise-chain mutex is NOT re-entrant - nesting would deadlock).
|
|
1247
|
+
await withStoreLock(() => registerWritebackUnlocked(taskId, action, repoId, targetId, cycleKey));
|
|
1248
|
+
}
|
|
1249
|
+
async function registerWritebackUnlocked(taskId, action, repoId, targetId, cycleKey) {
|
|
1250
|
+
const s = await ensureStore();
|
|
1251
|
+
if (s.writebacks.some((w) => w.taskId === taskId)) {
|
|
1252
|
+
return;
|
|
1253
|
+
}
|
|
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.
|
|
1260
|
+
if (targetId != null && s.writebacks.some((w) => w.targetId === targetId && w.repoId === repoId && w.action === action && !w.doneAt)) {
|
|
1261
|
+
return;
|
|
1262
|
+
}
|
|
1263
|
+
s.writebacks.push({ taskId, action, repoId, targetId, doneAt: null, prUrl: null, error: null, cycleKey });
|
|
1264
|
+
await saveTeamAutoStore(s);
|
|
1265
|
+
}
|
|
1266
|
+
// #claim-dequeue (user report 2026-11-15): claim at DEQUEUE time, not
|
|
1267
|
+
// enqueue. Enqueue-time claims locked a whole queue of issues behind the
|
|
1268
|
+
// one-writer-per-repo serialization while they waited; and a blind claim
|
|
1269
|
+
// over issues where external collaborators had begun working (comments,
|
|
1270
|
+
// assignees) only produced conflicts. At dequeue we re-check FRESH state:
|
|
1271
|
+
// - any assignee -> stand down (a human or another bot owns it)
|
|
1272
|
+
// - any external comment posted after the task was enqueued -> stand
|
|
1273
|
+
// down (someone is actively working; our own bot's comments excluded)
|
|
1274
|
+
// Only a quiet, unowned issue gets claimed (assign, comment fallback),
|
|
1275
|
+
// with the existing seen+60s self-bump guard.
|
|
1276
|
+
async function claimTaskAtDequeue(task) {
|
|
1277
|
+
const kindMatch = /^\[([^\]]+)\]/.exec(task.title);
|
|
1278
|
+
if (!kindMatch || kindMatch[1] !== "takeOwnership")
|
|
1279
|
+
return { claimed: false, reason: "not a takeOwnership task" };
|
|
1280
|
+
const numMatch = /issue #(\d+)/.exec(task.title);
|
|
1281
|
+
if (!numMatch)
|
|
1282
|
+
return { claimed: false, reason: "no issue number" };
|
|
1283
|
+
const issueNumber = Number(numMatch[1]);
|
|
1284
|
+
const repoMatch = /TeamAuto autonomous work for ([\w./-]+)\./.exec(task.description);
|
|
1285
|
+
if (!repoMatch)
|
|
1286
|
+
return { claimed: false, reason: "no repo in description" };
|
|
1287
|
+
const repoId = repoMatch[1];
|
|
1288
|
+
const [owner, name] = repoId.split("/");
|
|
1289
|
+
if (!owner || !name)
|
|
1290
|
+
return { claimed: false, reason: "bad repo id" };
|
|
1291
|
+
const client = createGithubClient(auth);
|
|
1292
|
+
// #5740 (ggcode, 2026-11-17): eligibility CHECK failures (fetch failed on
|
|
1293
|
+
// getIssue/getAuthenticatedUser/getIssueCommentsSince) must NOT let the
|
|
1294
|
+
// task run unclaimed - the conflict check is the core #claim-dequeue
|
|
1295
|
+
// contract. Only the WRITE phase (assign/comment) may continue
|
|
1296
|
+
// unclaimed on failure (original 2026-11-15 semantics). The caller
|
|
1297
|
+
// reverts the assignment on retryEligibility so the next auto-assign
|
|
1298
|
+
// pass re-checks; a network blip delays execution by ~20s, an outage
|
|
1299
|
+
// loops at assignment cadence instead of silently bypassing the gate.
|
|
1300
|
+
let login;
|
|
1301
|
+
try {
|
|
1302
|
+
const fresh = await client.getIssue(owner, name, issueNumber);
|
|
1303
|
+
if (fresh.state !== "open") {
|
|
1304
|
+
return { claimed: false, reason: "issue closed" };
|
|
965
1305
|
}
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
1306
|
+
const s0 = await ensureStore();
|
|
1307
|
+
const repo0 = s0.repos.find((r) => r.id === repoId);
|
|
1308
|
+
if ((repo0?.policy.skipAssignedToHumans ?? true) && fresh.assignees.length > 0) {
|
|
1309
|
+
recordActivity(await ensureStore(), { at: Date.now(), repoId, kind: "claim", text: `deferred claim: issue #${issueNumber} has assignee(s) ${fresh.assignees.join(",")} at dequeue - standing down` });
|
|
1310
|
+
return { claimed: false, reason: "assignees present" };
|
|
1311
|
+
}
|
|
1312
|
+
// External-work check: comments posted after the task was ENQUEUED.
|
|
1313
|
+
const sinceIso = new Date(task.createdAt ?? Date.now()).toISOString();
|
|
1314
|
+
login = (await client.getAuthenticatedUser()).login;
|
|
1315
|
+
const comments = await client.getIssueCommentsSince(owner, name, issueNumber, sinceIso);
|
|
1316
|
+
const external = comments.filter((c) => c.user !== login);
|
|
1317
|
+
if (external.length > 0) {
|
|
1318
|
+
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
|
+
return { claimed: false, reason: "external activity" };
|
|
1320
|
+
}
|
|
1321
|
+
}
|
|
1322
|
+
catch (err) {
|
|
1323
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
1324
|
+
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` });
|
|
1325
|
+
return { claimed: false, reason: "eligibility-check-failed", retryEligibility: true };
|
|
1326
|
+
}
|
|
1327
|
+
// #5740 (ggcode, 2026-11-17): the WRITE phase keeps the original
|
|
1328
|
+
// 2026-11-15 "continue unclaimed" semantics when it fails (the
|
|
1329
|
+
// eligibility checks DID pass), but it must not vanish silently - the
|
|
1330
|
+
// caller swallows rejections - so record the audit line here and return
|
|
1331
|
+
// a non-retrying result.
|
|
1332
|
+
try {
|
|
1333
|
+
try {
|
|
1334
|
+
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)` });
|
|
1336
|
+
}
|
|
1337
|
+
catch {
|
|
1338
|
+
// Fallback: a visible claim comment carries the same placeholder
|
|
1339
|
+
// semantics when the App lacks the assignees write surface.
|
|
1340
|
+
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)` });
|
|
974
1342
|
}
|
|
975
|
-
s
|
|
976
|
-
|
|
977
|
-
|
|
1343
|
+
const s = await ensureStore();
|
|
1344
|
+
await withStoreLock(async () => {
|
|
1345
|
+
const freshRepo = s.repos.find((r) => r.id === repoId);
|
|
1346
|
+
if (freshRepo) {
|
|
1347
|
+
// +60s guard: our own write (assign or comment) bumps updated_at.
|
|
1348
|
+
freshRepo.cursors.seen[`${repoId}#issue-${issueNumber}`] = Date.now() + 60_000;
|
|
1349
|
+
await saveTeamAutoStore(s);
|
|
1350
|
+
}
|
|
1351
|
+
});
|
|
1352
|
+
return { claimed: true };
|
|
1353
|
+
}
|
|
1354
|
+
catch (err) {
|
|
1355
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
1356
|
+
recordActivity(await ensureStore(), { at: Date.now(), repoId, kind: "claim", text: `claim-at-dequeue WRITE failed for issue #${issueNumber}: ${msg.slice(0, 120)} - continuing unclaimed` });
|
|
1357
|
+
return { claimed: false, reason: "claim write failed" };
|
|
1358
|
+
}
|
|
978
1359
|
}
|
|
979
1360
|
/** #268: make a takeOwnership claim VISIBLE on the issue itself. Until now
|
|
980
1361
|
* assignIssue was dead code and registerWriteback had no assign action, so
|
|
@@ -1019,13 +1400,15 @@ export function createTeamAutoScheduler(deps) {
|
|
|
1019
1400
|
recordActivity(await ensureStore(), { at: Date.now(), repoId: repo.id, kind: "claim", text: `claimed issue #${candidate.number} via comment (assign unavailable)` });
|
|
1020
1401
|
}
|
|
1021
1402
|
const s = await ensureStore();
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1403
|
+
await withStoreLock(async () => {
|
|
1404
|
+
const freshRepo = s.repos.find((r) => r.id === repo.id);
|
|
1405
|
+
if (freshRepo) {
|
|
1406
|
+
// +60s guard: our own write (assign or comment) bumps updated_at;
|
|
1407
|
+
// see helper doc.
|
|
1408
|
+
freshRepo.cursors.seen[candidate.key] = Date.now() + 60_000;
|
|
1409
|
+
await saveTeamAutoStore(s);
|
|
1410
|
+
}
|
|
1411
|
+
});
|
|
1029
1412
|
}
|
|
1030
1413
|
catch (err) {
|
|
1031
1414
|
logger.warn(`TeamAuto: claim for ${repo.id}#${candidate.number} failed (task continues unclaimed): ${err instanceof Error ? err.message : String(err)}`);
|
|
@@ -1170,60 +1553,79 @@ export function createTeamAutoScheduler(deps) {
|
|
|
1170
1553
|
void recoverFailedClaims();
|
|
1171
1554
|
}, 60_000);
|
|
1172
1555
|
claimRecoveryTimer.unref?.();
|
|
1173
|
-
//
|
|
1174
|
-
//
|
|
1175
|
-
//
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
// too - safeRemoveTaskWorktree still retains unpushed work.
|
|
1202
|
-
return !s.writebacks.some((w) => w.taskId === taskId && !w.doneAt && !w.failedAt);
|
|
1203
|
-
};
|
|
1204
|
-
const r = await sync.gcTaskWorktrees(repo.id, isTerminal, squashDeliveryOracle);
|
|
1205
|
-
removed += r.removed.length;
|
|
1206
|
-
retained += r.retained.length;
|
|
1207
|
-
stale += r.stale;
|
|
1208
|
-
retainedDetails.push(...r.retained.map((x) => `${x.taskId}: ${x.reason}`));
|
|
1209
|
-
}
|
|
1210
|
-
if (removed || retained || stale) {
|
|
1211
|
-
// #173 follow-up 4: per-task retain reasons recorded as activity
|
|
1212
|
-
// (PR #167 promised "outcome logged + recorded as activity"); the
|
|
1213
|
-
// stale count surfaces dir-gone-but-branch-kept leaks too.
|
|
1214
|
-
const detail = retainedDetails.length
|
|
1215
|
-
? `; ${retainedDetails.slice(0, 10).join("; ")}${retainedDetails.length > 10 ? `; +${retainedDetails.length - 10} more` : ""}`
|
|
1216
|
-
: "";
|
|
1217
|
-
const stalePart = stale ? `, stale ${stale}` : "";
|
|
1218
|
-
recordActivity(s, { at: Date.now(), repoId: "*", kind: "task", text: `worktree GC: removed ${removed}, retained ${retained} (undelivered${detail})${stalePart}` });
|
|
1219
|
-
await saveTeamAutoStore(s);
|
|
1220
|
-
logger.warn(`TeamAuto: worktree GC removed ${removed}, retained ${retained}${stalePart}`);
|
|
1221
|
-
}
|
|
1556
|
+
// #gc-periodic: worktree GC used to be boot-only with an enabled-repo
|
|
1557
|
+
// filter - two defects (live-instance audit 2026-11-14): (a) a disabled
|
|
1558
|
+
// repo ("do no NEW work") never got cleaned at all; (b) the single boot
|
|
1559
|
+
// pass ran before the device-flow auth warmed up, so every targetClosed
|
|
1560
|
+
// oracle call failed toward keep and closed-target orphans stayed (4
|
|
1561
|
+
// confirmed misretains). Now a recurring pass: first run delayed 60s
|
|
1562
|
+
// (auth warm), then every 6h - transient oracle failures self-heal on
|
|
1563
|
+
// the next pass.
|
|
1564
|
+
const gcDelay = setTimeout(() => {
|
|
1565
|
+
void runGcPass();
|
|
1566
|
+
gcTimer = setInterval(() => {
|
|
1567
|
+
void runGcPass();
|
|
1568
|
+
}, 6 * 60 * 60_000);
|
|
1569
|
+
gcTimer.unref?.();
|
|
1570
|
+
}, 60_000);
|
|
1571
|
+
gcDelay.unref?.();
|
|
1572
|
+
}
|
|
1573
|
+
/** #gc-periodic: one full worktree GC pass over ALL bound repos (enabled
|
|
1574
|
+
* or not - GC is hygiene, not new work). Shared by the boot-delayed first
|
|
1575
|
+
* run and the 6h recurrence. */
|
|
1576
|
+
async function runGcPass() {
|
|
1577
|
+
try {
|
|
1578
|
+
// #173 follow-up 3: with getTeamState() === null the isTerminal
|
|
1579
|
+
// predicate below classifies EVERY task as terminal - GC must not run
|
|
1580
|
+
// blind over an unloaded team state (fails toward skip).
|
|
1581
|
+
if (!deps.getTeamState()) {
|
|
1582
|
+
logger.warn("TeamAuto: worktree GC skipped (team state unavailable)");
|
|
1583
|
+
return;
|
|
1222
1584
|
}
|
|
1223
|
-
|
|
1224
|
-
|
|
1585
|
+
const s = await ensureStore();
|
|
1586
|
+
let removed = 0;
|
|
1587
|
+
let retained = 0;
|
|
1588
|
+
let stale = 0;
|
|
1589
|
+
const retainedDetails = [];
|
|
1590
|
+
for (const repo of s.repos) {
|
|
1591
|
+
const isTerminal = (taskId) => {
|
|
1592
|
+
const t = deps.getTeamState()?.tasks[taskId];
|
|
1593
|
+
if (t && t.status !== "completed" && t.status !== "failed")
|
|
1594
|
+
return false;
|
|
1595
|
+
// Review F1: a terminal task with a pending write-back (push
|
|
1596
|
+
// ok / PR failed, 20s-retry window) still needs its worktree -
|
|
1597
|
+
// the retry delivers the PR from the surviving branch. Do not
|
|
1598
|
+
// GC until the write-back settles (doneAt or dropped). Issue
|
|
1599
|
+
// #24: terminally failed write-backs (failedAt) count as settled
|
|
1600
|
+
// too - safeRemoveTaskWorktree still retains unpushed work.
|
|
1601
|
+
return !s.writebacks.some((w) => w.taskId === taskId && !w.doneAt && !w.failedAt);
|
|
1602
|
+
};
|
|
1603
|
+
// #gc3: no task record anywhere in team-state -> the owner ruled
|
|
1604
|
+
// outright deletion (2026-11-14, "全删") - such worktrees can never
|
|
1605
|
+
// be judged by any oracle and were retained forever.
|
|
1606
|
+
const isUnknownTask = (taskId) => !deps.getTeamState()?.tasks?.[taskId];
|
|
1607
|
+
const r = await sync.gcTaskWorktrees(repo.id, isTerminal, squashDeliveryOracle, targetClosedOracle, isUnknownTask);
|
|
1608
|
+
removed += r.removed.length;
|
|
1609
|
+
retained += r.retained.length;
|
|
1610
|
+
stale += r.stale;
|
|
1611
|
+
retainedDetails.push(...r.retained.map((x) => `${x.taskId}: ${x.reason}`));
|
|
1225
1612
|
}
|
|
1226
|
-
|
|
1613
|
+
if (removed || retained || stale) {
|
|
1614
|
+
// #173 follow-up 4: per-task retain reasons recorded as activity
|
|
1615
|
+
// (PR #167 promised "outcome logged + recorded as activity"); the
|
|
1616
|
+
// stale count surfaces dir-gone-but-branch-kept leaks too.
|
|
1617
|
+
const detail = retainedDetails.length
|
|
1618
|
+
? `; ${retainedDetails.slice(0, 10).join("; ")}${retainedDetails.length > 10 ? `; +${retainedDetails.length - 10} more` : ""}`
|
|
1619
|
+
: "";
|
|
1620
|
+
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);
|
|
1623
|
+
logger.warn(`TeamAuto: worktree GC removed ${removed}, retained ${retained}${stalePart}`);
|
|
1624
|
+
}
|
|
1625
|
+
}
|
|
1626
|
+
catch (err) {
|
|
1627
|
+
logger.warn(`TeamAuto: worktree GC failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1628
|
+
}
|
|
1227
1629
|
}
|
|
1228
1630
|
async function stop() {
|
|
1229
1631
|
running = false;
|
|
@@ -1236,6 +1638,9 @@ export function createTeamAutoScheduler(deps) {
|
|
|
1236
1638
|
if (claimRecoveryTimer) {
|
|
1237
1639
|
clearInterval(claimRecoveryTimer);
|
|
1238
1640
|
}
|
|
1641
|
+
if (gcTimer) {
|
|
1642
|
+
clearInterval(gcTimer);
|
|
1643
|
+
}
|
|
1239
1644
|
writebackTimer = null;
|
|
1240
1645
|
}
|
|
1241
1646
|
}
|
|
@@ -1250,7 +1655,7 @@ export function createTeamAutoScheduler(deps) {
|
|
|
1250
1655
|
const s = await ensureStore();
|
|
1251
1656
|
return (s.activity ?? []).slice().reverse();
|
|
1252
1657
|
}
|
|
1253
|
-
return { addRepo, removeRepo, setRepoEnabled, updateRepo, runSweepNow, registerWriteback, reconcileWritebacks, start, stop, getStatus, getActivity, ensureWriteWorktree, removeWriteWorktree, proposeManual };
|
|
1658
|
+
return { addRepo, removeRepo, setRepoEnabled, updateRepo, runSweepNow, registerWriteback, reconcileWritebacks, claimTaskAtDequeue, start, stop, getStatus, getActivity, ensureWriteWorktree, removeWriteWorktree, proposeManual };
|
|
1254
1659
|
/** Collaboration contract: dispatch asks for a task-scoped worktree dir (rel to projects root). */
|
|
1255
1660
|
async function ensureWriteWorktree(repoId, taskId) {
|
|
1256
1661
|
const wtAbs = await sync.ensureTaskWorktree(repoId, taskId);
|