@teamclaws/teamclaw 2026.11.3 → 2026.11.5

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.
@@ -177,6 +177,12 @@ export function createGithubClient(auth) {
177
177
  async assignIssue(owner, repo, issueNumber, assignee) {
178
178
  await request("POST", `/repos/${owner}/${repo}/issues/${issueNumber}/assignees`, { body: { assignees: [assignee] } });
179
179
  },
180
+ /** #claim-recovery: remove the bot's own assignment from an issue whose
181
+ * ownership task failed, so skipAssignedToHumans does not block the
182
+ * re-candidate (other human assignees are untouched). */
183
+ async removeIssueAssignees(owner, repo, issueNumber, assignees) {
184
+ await request("DELETE", `/repos/${owner}/${repo}/issues/${issueNumber}/assignees`, { body: { assignees } });
185
+ },
180
186
  /** Fresh issue state for claim-time re-checks (#268): the scan-time
181
187
  * assignee snapshot is seconds stale by enqueue time - a human may have
182
188
  * self-assigned in between, and claiming over a human is worse than not
@@ -245,7 +245,7 @@ export function createRepoSync(auth, logger) {
245
245
  * matches) or nonexistent (no commits of its own). Undelivered local work
246
246
  * is retained and reported - never silently destroyed.
247
247
  */
248
- async function safeRemoveTaskWorktree(repoId, taskId, deliveryOracle) {
248
+ async function safeRemoveTaskWorktree(repoId, taskId, deliveryOracle, targetClosedOracle) {
249
249
  const base = await repoDir(repoId);
250
250
  const wtName = taskWorktreeDirName(repoId, taskId);
251
251
  const wtPath = path.join(path.dirname(base), path.basename(wtName));
@@ -273,6 +273,19 @@ export function createRepoSync(auth, logger) {
273
273
  if (inUsePid !== null) {
274
274
  return { removed: false, reason: `retained: in use by live process (pid ${inUsePid})` };
275
275
  }
276
+ // #orphan-gc: the target issue/PR is CLOSED - no delivery this worktree
277
+ // could ever produce would be wanted (the issue was fixed/rejected
278
+ // elsewhere, the PR superseded). This is the authoritative orphan
279
+ // signal: it overrides the dirty guard, because "uncommitted work"
280
+ // toward a closed target has no future. Placed AFTER the in-use check -
281
+ // a live foreign controller may still be finishing a delivery race.
282
+ if (targetClosedOracle) {
283
+ const closed = await targetClosedOracle(repoId, taskId).catch(() => null);
284
+ if (closed === true) {
285
+ await removeTaskWorktree(repoId, taskId);
286
+ return { removed: true, reason: "orphaned: target issue/PR closed (dirty tree dropped - no possible delivery)" };
287
+ }
288
+ }
276
289
  // #173 follow-up 1: the dirty guard must cover BOTH removal paths. The
277
290
  // tip-match branch used to remove without any dirty check, silently
278
291
  // destroying post-delivery worker edits (small window, but real).
@@ -327,7 +340,7 @@ export function createRepoSync(auth, logger) {
327
340
  * sibling whose task is terminal (or unknown), apply the delivery-safety
328
341
  * removal. Heals the historical backlog that pre-dates terminal cleanup.
329
342
  */
330
- async function gcTaskWorktrees(repoId, isTerminal, deliveryOracle) {
343
+ async function gcTaskWorktrees(repoId, isTerminal, deliveryOracle, targetClosedOracle) {
331
344
  const base = await repoDir(repoId);
332
345
  const siblings = path.dirname(base);
333
346
  // taskWorktreeDirName(repoId, "x") = "teamauto/<slug>__task-x"; the
@@ -338,7 +351,7 @@ export function createRepoSync(auth, logger) {
338
351
  const retained = [];
339
352
  let stale = 0;
340
353
  const apply = async (taskId) => {
341
- const r = await safeRemoveTaskWorktree(repoId, taskId, deliveryOracle);
354
+ const r = await safeRemoveTaskWorktree(repoId, taskId, deliveryOracle, targetClosedOracle);
342
355
  if (r.removed) {
343
356
  removed.push(taskId);
344
357
  logger.warn(`TeamAuto: worktree GC removed ${taskId} (${r.reason})`);
@@ -39,6 +39,20 @@ export const TRANSIENT_FAILURE_RE = /workspace filesystem changed|ai service nee
39
39
  export function idempotencyMarker(candidate) {
40
40
  return `Idempotency-Key: ${candidate.key}:${candidate.kind}`;
41
41
  }
42
+ /** #claim-recovery: parse the marker back out of a (failed) task's
43
+ * description - `{ repoId, number, kind, key }` or null. Issue candidates
44
+ * only (PR keys `#pr-` are not claim-bearing). */
45
+ export function parseClaimMarker(description) {
46
+ const m = /Idempotency-Key: ([^:\s]+)#issue-(\d+):(\w+)/.exec(description);
47
+ if (!m) {
48
+ return null;
49
+ }
50
+ const number = Number(m[2]);
51
+ if (!m[1] || !Number.isFinite(number)) {
52
+ return null;
53
+ }
54
+ return { repoId: m[1], number, kind: m[3], key: `${m[1]}#issue-${number}` };
55
+ }
42
56
  /** Failed task attempts for a candidate (task history is the attempt log). */
43
57
  export function failedAttemptCount(state, candidate) {
44
58
  const marker = idempotencyMarker(candidate);
@@ -232,11 +246,41 @@ export function createTeamAutoScheduler(deps) {
232
246
  return false;
233
247
  }
234
248
  };
249
+ // #orphan-gc: is the worktree's TARGET (issue/PR) closed? An issue closed
250
+ // without our delivery (fixed elsewhere / rejected / the PR superseded)
251
+ // makes the worktree an orphan no matter how dirty it is - the pre-fix GC
252
+ // retained such trees forever ("retained: dirty worktree", 42 and
253
+ // climbing on the live instance). Resolves true only on a POSITIVE closed
254
+ // state; unknown task / unparsable marker / API failure all resolve null
255
+ // (fail toward keep).
256
+ const targetClosedOracle = async (repoId, taskId) => {
257
+ const teamState = deps.getTeamState();
258
+ const task = teamState?.tasks?.[taskId];
259
+ if (!task || typeof task.description !== "string") {
260
+ return null;
261
+ }
262
+ const parsed = parseClaimMarker(task.description);
263
+ if (!parsed) {
264
+ return null;
265
+ }
266
+ try {
267
+ const [owner, name] = parsed.repoId.split("/");
268
+ if (!owner || !name) {
269
+ return null;
270
+ }
271
+ const fresh = await client.getIssue(owner, name, parsed.number);
272
+ return fresh.state === "closed";
273
+ }
274
+ catch {
275
+ return null;
276
+ }
277
+ };
235
278
  const timers = new Map();
236
279
  const sweeping = new Set();
237
280
  let running = false;
238
281
  let store = null;
239
282
  let writebackTimer = null;
283
+ let claimRecoveryTimer = null;
240
284
  async function ensureStore() {
241
285
  if (!store) {
242
286
  store = await loadTeamAutoStore();
@@ -728,7 +772,7 @@ export function createTeamAutoScheduler(deps) {
728
772
  for (const w of deadOnes) {
729
773
  const t = state0.tasks[w.taskId];
730
774
  if (t && t.writeMode === "write" && t.projectDir?.includes("__task-")) {
731
- const r = await sync.safeRemoveTaskWorktree(w.repoId, w.taskId, squashDeliveryOracle);
775
+ const r = await sync.safeRemoveTaskWorktree(w.repoId, w.taskId, squashDeliveryOracle, targetClosedOracle);
732
776
  if (r.removed) {
733
777
  // #173 follow-up 4: positive removal line - without it a successful
734
778
  // terminal cleanup is invisible in logs (only kept/failed logged).
@@ -812,7 +856,7 @@ export function createTeamAutoScheduler(deps) {
812
856
  // path left - remove it when the worker never produced deliverable
813
857
  // commits (safety-checked, undelivered work is retained + logged).
814
858
  if (task.writeMode === "write" && task.projectDir?.includes("__task-")) {
815
- const r = await sync.safeRemoveTaskWorktree(entry.repoId, task.id, squashDeliveryOracle);
859
+ const r = await sync.safeRemoveTaskWorktree(entry.repoId, task.id, squashDeliveryOracle, targetClosedOracle);
816
860
  if (r.removed) {
817
861
  // #173 follow-up 4: positive removal line - symmetric with the
818
862
  // boot-GC path which logs both directions.
@@ -1017,6 +1061,60 @@ export function createTeamAutoScheduler(deps) {
1017
1061
  }
1018
1062
  })();
1019
1063
  }
1064
+ /** #claim-recovery: a task that CLAIMED an issue (takeOwnership stamps the
1065
+ * seen cursor AND self-assigns the bot at enqueue time; issueReview stamps
1066
+ * the cursor) locks the issue twice against re-candidacy. When the task
1067
+ * fails, the issue must not be orphaned - nobody (human or bot) would ever
1068
+ * pick it up again. Once per failed taskId: clear the seen stamp so the
1069
+ * next sweep re-candidates naturally, and for takeOwnership remove the
1070
+ * bot's own assignment (human assignees untouched). The existing
1071
+ * dead-letter caps (3 hard / 6 transient) bound how often this can loop. */
1072
+ async function recoverFailedClaims() {
1073
+ const teamState = deps.getTeamState();
1074
+ if (!teamState) {
1075
+ return;
1076
+ }
1077
+ const s = await ensureStore();
1078
+ s.failedClaimRecovery ??= {};
1079
+ let changed = false;
1080
+ for (const [taskId, task] of Object.entries(teamState.tasks ?? {})) {
1081
+ if (task?.status !== "failed" || typeof task.description !== "string" || !task.description.includes("Idempotency-Key:")) {
1082
+ continue;
1083
+ }
1084
+ if (s.failedClaimRecovery[taskId]) {
1085
+ continue;
1086
+ }
1087
+ const parsed = parseClaimMarker(task.description);
1088
+ const repo = parsed ? s.repos.find((r) => r.id === parsed.repoId) : undefined;
1089
+ if (!parsed || !repo) {
1090
+ continue;
1091
+ }
1092
+ delete repo.cursors.seen[parsed.key];
1093
+ s.failedClaimRecovery[taskId] = Date.now();
1094
+ changed = true;
1095
+ recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `recovered failed task ${taskId}: issue #${parsed.number} re-opened for the next sweep` });
1096
+ if (parsed.kind === "takeOwnership") {
1097
+ void (async () => {
1098
+ try {
1099
+ const client = createGithubClient(auth);
1100
+ const { login } = await client.getAuthenticatedUser();
1101
+ const [owner, name] = repo.id.split("/");
1102
+ await client.removeIssueAssignees(owner, name, parsed.number, [login]);
1103
+ }
1104
+ catch (err) {
1105
+ logger.warn(`TeamAuto: unassign for failed claim ${repo.id}#${parsed.number} failed (scanner may skip it until a human clears the assignee): ${err instanceof Error ? err.message : String(err)}`);
1106
+ }
1107
+ })();
1108
+ }
1109
+ }
1110
+ if (changed) {
1111
+ const entries = Object.entries(s.failedClaimRecovery).sort((a, b) => a[1] - b[1]);
1112
+ if (entries.length > 200) {
1113
+ s.failedClaimRecovery = Object.fromEntries(entries.slice(entries.length - 200));
1114
+ }
1115
+ await saveTeamAutoStore(s);
1116
+ }
1117
+ }
1020
1118
  // ---------- scheduling loop ----------
1021
1119
  function scheduleRepo(repo) {
1022
1120
  const previous = timers.get(repo.id);
@@ -1097,6 +1195,10 @@ export function createTeamAutoScheduler(deps) {
1097
1195
  void reconcileWritebacks();
1098
1196
  }, 20_000);
1099
1197
  writebackTimer.unref?.();
1198
+ claimRecoveryTimer = setInterval(() => {
1199
+ void recoverFailedClaims();
1200
+ }, 60_000);
1201
+ claimRecoveryTimer.unref?.();
1100
1202
  // Boot reconciliation: heal leftover task worktrees whose task is
1101
1203
  // terminal (or gone entirely) - the pre-cleanup backlog never shrinks
1102
1204
  // on its own. Safety-checked: undelivered work is kept and logged.
@@ -1128,7 +1230,7 @@ export function createTeamAutoScheduler(deps) {
1128
1230
  // too - safeRemoveTaskWorktree still retains unpushed work.
1129
1231
  return !s.writebacks.some((w) => w.taskId === taskId && !w.doneAt && !w.failedAt);
1130
1232
  };
1131
- const r = await sync.gcTaskWorktrees(repo.id, isTerminal, squashDeliveryOracle);
1233
+ const r = await sync.gcTaskWorktrees(repo.id, isTerminal, squashDeliveryOracle, targetClosedOracle);
1132
1234
  removed += r.removed.length;
1133
1235
  retained += r.retained.length;
1134
1236
  stale += r.stale;
@@ -1160,6 +1262,9 @@ export function createTeamAutoScheduler(deps) {
1160
1262
  timers.clear();
1161
1263
  if (writebackTimer) {
1162
1264
  clearInterval(writebackTimer);
1265
+ if (claimRecoveryTimer) {
1266
+ clearInterval(claimRecoveryTimer);
1267
+ }
1163
1268
  writebackTimer = null;
1164
1269
  }
1165
1270
  }
@@ -44,6 +44,7 @@ function emptyStore() {
44
44
  repos: [],
45
45
  writebacks: [],
46
46
  activity: [],
47
+ failedClaimRecovery: {},
47
48
  budget: {
48
49
  maxTasksPerDay: 150,
49
50
  firstSweepDryRun: true,
@@ -101,6 +102,9 @@ export async function loadTeamAutoStore() {
101
102
  if (Array.isArray(parsed.activity)) {
102
103
  store.activity = parsed.activity.slice(-TEAMAUTO_ACTIVITY_LIMIT);
103
104
  }
105
+ if (parsed.failedClaimRecovery && typeof parsed.failedClaimRecovery === "object") {
106
+ store.failedClaimRecovery = parsed.failedClaimRecovery;
107
+ }
104
108
  store.budget = { ...store.budget, ...(parsed.budget ?? {}) };
105
109
  return store;
106
110
  }
@@ -2,7 +2,7 @@
2
2
  "id": "teamclaw",
3
3
  "name": "TeamClaw",
4
4
  "description": "Virtual team collaboration - multiple OpenClaw instances form a virtual software company with role-based task routing.",
5
- "version": "2026.11.3",
5
+ "version": "2026.11.5",
6
6
  "activation": {
7
7
  "onStartup": true
8
8
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teamclaws/teamclaw",
3
- "version": "2026.11.3",
3
+ "version": "2026.11.5",
4
4
  "description": "OpenClaw virtual software team orchestration plugin - controller, role-based workers, Web UI with internet tunnel sharing",
5
5
  "private": false,
6
6
  "keywords": [
@@ -238,6 +238,13 @@ export function createGithubClient(auth: GithubAuthManager) {
238
238
  await request("POST", `/repos/${owner}/${repo}/issues/${issueNumber}/assignees`, { body: { assignees: [assignee] } });
239
239
  },
240
240
 
241
+ /** #claim-recovery: remove the bot's own assignment from an issue whose
242
+ * ownership task failed, so skipAssignedToHumans does not block the
243
+ * re-candidate (other human assignees are untouched). */
244
+ async removeIssueAssignees(owner: string, repo: string, issueNumber: number, assignees: string[]): Promise<void> {
245
+ await request("DELETE", `/repos/${owner}/${repo}/issues/${issueNumber}/assignees`, { body: { assignees } });
246
+ },
247
+
241
248
  /** Fresh issue state for claim-time re-checks (#268): the scan-time
242
249
  * assignee snapshot is seconds stale by enqueue time - a human may have
243
250
  * self-assigned in between, and claiming over a human is worse than not
@@ -26,6 +26,16 @@ export type TaskDeliveryOracle = (
26
26
  headTip: string,
27
27
  ) => Promise<boolean>;
28
28
 
29
+ /**
30
+ * #orphan-gc oracle: is the worktree's TARGET (issue/PR) closed? true =
31
+ * positively closed (the worktree is an orphan - even a dirty tree has no
32
+ * possible delivery), null/false = unknown or still open (fail toward keep).
33
+ */
34
+ export type TaskTargetClosedOracle = (
35
+ repoId: string,
36
+ taskId: string,
37
+ ) => Promise<boolean | null>;
38
+
29
39
  /** TaskInfo.projectDir slug for a bound repo (relative to the projects dir). */
30
40
  export function teamAutoProjectDir(repoId: string): string {
31
41
  return `teamauto/${repoSlugToDirName(repoId)}`;
@@ -283,6 +293,7 @@ export function createRepoSync(auth: GithubAuthManager, logger: { warn: (m: stri
283
293
  repoId: string,
284
294
  taskId: string,
285
295
  deliveryOracle?: TaskDeliveryOracle,
296
+ targetClosedOracle?: TaskTargetClosedOracle,
286
297
  ): Promise<{ removed: boolean; reason: string }> {
287
298
  const base = await repoDir(repoId);
288
299
  const wtName = taskWorktreeDirName(repoId, taskId);
@@ -310,6 +321,19 @@ export function createRepoSync(auth: GithubAuthManager, logger: { warn: (m: stri
310
321
  if (inUsePid !== null) {
311
322
  return { removed: false, reason: `retained: in use by live process (pid ${inUsePid})` };
312
323
  }
324
+ // #orphan-gc: the target issue/PR is CLOSED - no delivery this worktree
325
+ // could ever produce would be wanted (the issue was fixed/rejected
326
+ // elsewhere, the PR superseded). This is the authoritative orphan
327
+ // signal: it overrides the dirty guard, because "uncommitted work"
328
+ // toward a closed target has no future. Placed AFTER the in-use check -
329
+ // a live foreign controller may still be finishing a delivery race.
330
+ if (targetClosedOracle) {
331
+ const closed = await targetClosedOracle(repoId, taskId).catch(() => null);
332
+ if (closed === true) {
333
+ await removeTaskWorktree(repoId, taskId);
334
+ return { removed: true, reason: "orphaned: target issue/PR closed (dirty tree dropped - no possible delivery)" };
335
+ }
336
+ }
313
337
  // #173 follow-up 1: the dirty guard must cover BOTH removal paths. The
314
338
  // tip-match branch used to remove without any dirty check, silently
315
339
  // destroying post-delivery worker edits (small window, but real).
@@ -368,6 +392,7 @@ export function createRepoSync(auth: GithubAuthManager, logger: { warn: (m: stri
368
392
  repoId: string,
369
393
  isTerminal: (taskId: string) => boolean,
370
394
  deliveryOracle?: TaskDeliveryOracle,
395
+ targetClosedOracle?: TaskTargetClosedOracle,
371
396
  ): Promise<{ removed: string[]; retained: { taskId: string; reason: string }[]; stale: number }> {
372
397
  const base = await repoDir(repoId);
373
398
  const siblings = path.dirname(base);
@@ -379,7 +404,7 @@ export function createRepoSync(auth: GithubAuthManager, logger: { warn: (m: stri
379
404
  const retained: { taskId: string; reason: string }[] = [];
380
405
  let stale = 0;
381
406
  const apply = async (taskId: string): Promise<void> => {
382
- const r = await safeRemoveTaskWorktree(repoId, taskId, deliveryOracle);
407
+ const r = await safeRemoveTaskWorktree(repoId, taskId, deliveryOracle, targetClosedOracle);
383
408
  if (r.removed) {
384
409
  removed.push(taskId);
385
410
  logger.warn(`TeamAuto: worktree GC removed ${taskId} (${r.reason})`);
@@ -11,7 +11,7 @@ import { getActiveDefaultRole, validateActiveRoleId } from "../profile-loader.js
11
11
  import type { TaskInfo, TeamState } from "../types.js";
12
12
  import { createGithubClient } from "./github-client.js";
13
13
  import { learnNorms, renderNormsBlock } from "./norms.js";
14
- import { createRepoSync, teamAutoProjectDir, type TaskDeliveryOracle } from "./repo-sync.js";
14
+ import { createRepoSync, teamAutoProjectDir, type TaskDeliveryOracle, type TaskTargetClosedOracle } from "./repo-sync.js";
15
15
  import { nextFireMs } from "./schedule.js";
16
16
  import { resolveTeamAutoPaths } from "./store.js";
17
17
  import { advanceCursors, sweepRepo, type Candidate } from "./scanner.js";
@@ -76,6 +76,21 @@ export function idempotencyMarker(candidate: { key: string; kind: string }): str
76
76
  return `Idempotency-Key: ${candidate.key}:${candidate.kind}`;
77
77
  }
78
78
 
79
+ /** #claim-recovery: parse the marker back out of a (failed) task's
80
+ * description - `{ repoId, number, kind, key }` or null. Issue candidates
81
+ * only (PR keys `#pr-` are not claim-bearing). */
82
+ export function parseClaimMarker(description: string): { repoId: string; number: number; kind: string; key: string } | null {
83
+ const m = /Idempotency-Key: ([^:\s]+)#issue-(\d+):(\w+)/.exec(description);
84
+ if (!m) {
85
+ return null;
86
+ }
87
+ const number = Number(m[2]);
88
+ if (!m[1] || !Number.isFinite(number)) {
89
+ return null;
90
+ }
91
+ return { repoId: m[1], number, kind: m[3], key: `${m[1]}#issue-${number}` };
92
+ }
93
+
79
94
  /** Failed task attempts for a candidate (task history is the attempt log). */
80
95
  export function failedAttemptCount(
81
96
  state: { tasks: Record<string, { description: string; status: string; error?: string }> },
@@ -310,11 +325,40 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
310
325
  return false;
311
326
  }
312
327
  };
328
+ // #orphan-gc: is the worktree's TARGET (issue/PR) closed? An issue closed
329
+ // without our delivery (fixed elsewhere / rejected / the PR superseded)
330
+ // makes the worktree an orphan no matter how dirty it is - the pre-fix GC
331
+ // retained such trees forever ("retained: dirty worktree", 42 and
332
+ // climbing on the live instance). Resolves true only on a POSITIVE closed
333
+ // state; unknown task / unparsable marker / API failure all resolve null
334
+ // (fail toward keep).
335
+ const targetClosedOracle: TaskTargetClosedOracle = async (repoId, taskId) => {
336
+ const teamState = deps.getTeamState();
337
+ const task = teamState?.tasks?.[taskId];
338
+ if (!task || typeof task.description !== "string") {
339
+ return null;
340
+ }
341
+ const parsed = parseClaimMarker(task.description);
342
+ if (!parsed) {
343
+ return null;
344
+ }
345
+ try {
346
+ const [owner, name] = parsed.repoId.split("/");
347
+ if (!owner || !name) {
348
+ return null;
349
+ }
350
+ const fresh = await client.getIssue(owner, name, parsed.number);
351
+ return fresh.state === "closed";
352
+ } catch {
353
+ return null;
354
+ }
355
+ };
313
356
  const timers = new Map<string, NodeJS.Timeout>();
314
357
  const sweeping = new Set<string>();
315
358
  let running = false;
316
359
  let store: TeamAutoStore | null = null;
317
360
  let writebackTimer: NodeJS.Timeout | null = null;
361
+ let claimRecoveryTimer: NodeJS.Timeout | null = null;
318
362
 
319
363
  async function ensureStore(): Promise<TeamAutoStore> {
320
364
  if (!store) {
@@ -807,7 +851,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
807
851
  for (const w of deadOnes) {
808
852
  const t = state0.tasks[w.taskId];
809
853
  if (t && t.writeMode === "write" && t.projectDir?.includes("__task-")) {
810
- const r = await sync.safeRemoveTaskWorktree(w.repoId, w.taskId, squashDeliveryOracle);
854
+ const r = await sync.safeRemoveTaskWorktree(w.repoId, w.taskId, squashDeliveryOracle, targetClosedOracle);
811
855
  if (r.removed) {
812
856
  // #173 follow-up 4: positive removal line - without it a successful
813
857
  // terminal cleanup is invisible in logs (only kept/failed logged).
@@ -895,7 +939,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
895
939
  // path left - remove it when the worker never produced deliverable
896
940
  // commits (safety-checked, undelivered work is retained + logged).
897
941
  if (task.writeMode === "write" && task.projectDir?.includes("__task-")) {
898
- const r = await sync.safeRemoveTaskWorktree(entry.repoId, task.id, squashDeliveryOracle);
942
+ const r = await sync.safeRemoveTaskWorktree(entry.repoId, task.id, squashDeliveryOracle, targetClosedOracle);
899
943
  if (r.removed) {
900
944
  // #173 follow-up 4: positive removal line - symmetric with the
901
945
  // boot-GC path which logs both directions.
@@ -1098,6 +1142,60 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1098
1142
  })();
1099
1143
  }
1100
1144
 
1145
+ /** #claim-recovery: a task that CLAIMED an issue (takeOwnership stamps the
1146
+ * seen cursor AND self-assigns the bot at enqueue time; issueReview stamps
1147
+ * the cursor) locks the issue twice against re-candidacy. When the task
1148
+ * fails, the issue must not be orphaned - nobody (human or bot) would ever
1149
+ * pick it up again. Once per failed taskId: clear the seen stamp so the
1150
+ * next sweep re-candidates naturally, and for takeOwnership remove the
1151
+ * bot's own assignment (human assignees untouched). The existing
1152
+ * dead-letter caps (3 hard / 6 transient) bound how often this can loop. */
1153
+ async function recoverFailedClaims(): Promise<void> {
1154
+ const teamState = deps.getTeamState();
1155
+ if (!teamState) {
1156
+ return;
1157
+ }
1158
+ const s = await ensureStore();
1159
+ s.failedClaimRecovery ??= {};
1160
+ let changed = false;
1161
+ for (const [taskId, task] of Object.entries(teamState.tasks ?? {})) {
1162
+ if (task?.status !== "failed" || typeof task.description !== "string" || !task.description.includes("Idempotency-Key:")) {
1163
+ continue;
1164
+ }
1165
+ if (s.failedClaimRecovery[taskId]) {
1166
+ continue;
1167
+ }
1168
+ const parsed = parseClaimMarker(task.description);
1169
+ const repo = parsed ? s.repos.find((r) => r.id === parsed.repoId) : undefined;
1170
+ if (!parsed || !repo) {
1171
+ continue;
1172
+ }
1173
+ delete repo.cursors.seen[parsed.key];
1174
+ s.failedClaimRecovery[taskId] = Date.now();
1175
+ changed = true;
1176
+ recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `recovered failed task ${taskId}: issue #${parsed.number} re-opened for the next sweep` });
1177
+ if (parsed.kind === "takeOwnership") {
1178
+ void (async () => {
1179
+ try {
1180
+ const client = createGithubClient(auth);
1181
+ const { login } = await client.getAuthenticatedUser();
1182
+ const [owner, name] = repo.id.split("/");
1183
+ await client.removeIssueAssignees(owner, name, parsed.number, [login]);
1184
+ } catch (err) {
1185
+ logger.warn(`TeamAuto: unassign for failed claim ${repo.id}#${parsed.number} failed (scanner may skip it until a human clears the assignee): ${err instanceof Error ? err.message : String(err)}`);
1186
+ }
1187
+ })();
1188
+ }
1189
+ }
1190
+ if (changed) {
1191
+ const entries = Object.entries(s.failedClaimRecovery).sort((a, b) => a[1] - b[1]);
1192
+ if (entries.length > 200) {
1193
+ s.failedClaimRecovery = Object.fromEntries(entries.slice(entries.length - 200));
1194
+ }
1195
+ await saveTeamAutoStore(s);
1196
+ }
1197
+ }
1198
+
1101
1199
  // ---------- scheduling loop ----------
1102
1200
 
1103
1201
  function scheduleRepo(repo: TeamAutoRepo): void {
@@ -1176,6 +1274,10 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1176
1274
  void reconcileWritebacks();
1177
1275
  }, 20_000);
1178
1276
  writebackTimer.unref?.();
1277
+ claimRecoveryTimer = setInterval(() => {
1278
+ void recoverFailedClaims();
1279
+ }, 60_000);
1280
+ claimRecoveryTimer.unref?.();
1179
1281
  // Boot reconciliation: heal leftover task worktrees whose task is
1180
1282
  // terminal (or gone entirely) - the pre-cleanup backlog never shrinks
1181
1283
  // on its own. Safety-checked: undelivered work is kept and logged.
@@ -1205,7 +1307,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1205
1307
  // too - safeRemoveTaskWorktree still retains unpushed work.
1206
1308
  return !s.writebacks.some((w) => w.taskId === taskId && !w.doneAt && !w.failedAt);
1207
1309
  };
1208
- const r = await sync.gcTaskWorktrees(repo.id, isTerminal, squashDeliveryOracle);
1310
+ const r = await sync.gcTaskWorktrees(repo.id, isTerminal, squashDeliveryOracle, targetClosedOracle);
1209
1311
  removed += r.removed.length;
1210
1312
  retained += r.retained.length;
1211
1313
  stale += r.stale;
@@ -1237,6 +1339,9 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1237
1339
  timers.clear();
1238
1340
  if (writebackTimer) {
1239
1341
  clearInterval(writebackTimer);
1342
+ if (claimRecoveryTimer) {
1343
+ clearInterval(claimRecoveryTimer);
1344
+ }
1240
1345
  writebackTimer = null;
1241
1346
  }
1242
1347
  }
@@ -168,6 +168,11 @@ export type TeamAutoStore = {
168
168
  tasksToday: number;
169
169
  dayStamp: string;
170
170
  };
171
+ /** #claim-recovery: taskId -> recoveredAt. A failed task whose candidate
172
+ * claimed an issue must not orphan it - the recovery pass clears the seen
173
+ * stamp (and the bot's self-assignment) once per taskId so the next sweep
174
+ * re-candidates naturally, while the dead-letter caps bound retries. */
175
+ failedClaimRecovery?: Record<string, number>;
171
176
  };
172
177
 
173
178
  export function defaultPolicy(): TeamAutoRepoPolicy {
@@ -191,6 +196,7 @@ function emptyStore(): TeamAutoStore {
191
196
  repos: [],
192
197
  writebacks: [],
193
198
  activity: [],
199
+ failedClaimRecovery: {},
194
200
  budget: {
195
201
  maxTasksPerDay: 150,
196
202
  firstSweepDryRun: true,
@@ -249,6 +255,9 @@ export async function loadTeamAutoStore(): Promise<TeamAutoStore> {
249
255
  if (Array.isArray(parsed.activity)) {
250
256
  store.activity = parsed.activity.slice(-TEAMAUTO_ACTIVITY_LIMIT);
251
257
  }
258
+ if (parsed.failedClaimRecovery && typeof parsed.failedClaimRecovery === "object") {
259
+ store.failedClaimRecovery = parsed.failedClaimRecovery as Record<string, number>;
260
+ }
252
261
  store.budget = { ...store.budget, ...(parsed.budget ?? {}) };
253
262
  return store;
254
263
  } catch {