@teamclaws/teamclaw 2026.7.0 → 2026.7.1

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/index.ts CHANGED
@@ -39,6 +39,7 @@ function registerController(api: OpenClawPluginApi, config: ReturnType<typeof pa
39
39
  let getControllerTeamState = (): TeamState | null => null;
40
40
  let controllerUrl = `http://127.0.0.1:${config.port}`;
41
41
  let kickoffHandler: ((candidateRoles: import("./src/types.js").RoleId[], complexity: "simple" | "medium" | "complex", requirement: string) => Promise<{ assessments: import("./src/types.js").KickoffAssessment[]; summary: string }>) | undefined;
42
+ let getTeamAutoScheduler: () => import("./src/teamauto/scheduler.js").TeamAutoScheduler | null = () => null;
42
43
 
43
44
  // Service (starts HTTP server + mDNS + WebSocket)
44
45
  api.registerService(createControllerService({
@@ -55,6 +56,9 @@ function registerController(api: OpenClawPluginApi, config: ReturnType<typeof pa
55
56
  kickoffHandler = handler;
56
57
  logger.info("TeamClaw: kickoff handler registered successfully");
57
58
  },
59
+ onTeamAutoSchedulerAvailable: (getter) => {
60
+ getTeamAutoScheduler = getter;
61
+ },
58
62
  }));
59
63
 
60
64
  // Prompt injection
@@ -75,6 +79,7 @@ function registerController(api: OpenClawPluginApi, config: ReturnType<typeof pa
75
79
  getTeamState: getControllerTeamState,
76
80
  sessionKey: ctx.sessionKey ?? null,
77
81
  getKickoffHandler: () => kickoffHandler,
82
+ getTeamAutoScheduler: () => getTeamAutoScheduler(),
78
83
  });
79
84
  });
80
85
  }
@@ -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.7.0",
5
+ "version": "2026.7.1",
6
6
  "activation": {
7
7
  "onStartup": true
8
8
  },
@@ -22,7 +22,10 @@
22
22
  "teamclaw_send_message",
23
23
  "teamclaw_submit_manifest",
24
24
  "teamclaw_submit_result_contract",
25
- "teamclaw_suggest_handoff"
25
+ "teamclaw_suggest_handoff",
26
+ "teamclaw_teamauto_propose",
27
+ "teamclaw_teamauto_status",
28
+ "teamclaw_teamauto_sweep"
26
29
  ]
27
30
  },
28
31
  "skills": [
@@ -60,7 +63,7 @@
60
63
  "maxConcurrentTasks": {
61
64
  "label": "Max Concurrent Tasks",
62
65
  "hint": "number",
63
- "help": "Maximum number of tasks that can be in 'in_progress' status at the same time (1–50)"
66
+ "help": "Maximum number of tasks that can be in 'in_progress' status at the same time (1\u201350)"
64
67
  },
65
68
  "gitEnabled": {
66
69
  "label": "Git Collaboration",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teamclaws/teamclaw",
3
- "version": "2026.7.0",
3
+ "version": "2026.7.1",
4
4
  "description": "OpenClaw virtual software team orchestration plugin",
5
5
  "private": false,
6
6
  "keywords": [
@@ -33,6 +33,8 @@ export type ControllerServiceDeps = {
33
33
  onActualPort?: (port: number) => void;
34
34
  /** Called once the kickoff handler is ready. */
35
35
  onKickoffHandlerAvailable?: (handler: KickoffHandler) => void;
36
+ /** Late-binding getter for the TeamAuto scheduler (created during service start). */
37
+ onTeamAutoSchedulerAvailable?: (getter: () => import("../teamauto/scheduler.js").TeamAutoScheduler | null) => void;
36
38
  };
37
39
 
38
40
  function getPreferredLanUiUrl(port: number): string | null {
@@ -274,6 +276,7 @@ export function createControllerService(deps: ControllerServiceDeps): OpenClawPl
274
276
  },
275
277
  });
276
278
  await teamAutoSchedulerRef.start();
279
+ deps.onTeamAutoSchedulerAvailable?.(() => teamAutoSchedulerRef);
277
280
  } catch (err) {
278
281
  logger.warn(`Controller: TeamAuto scheduler failed to start: ${err instanceof Error ? err.message : String(err)}`);
279
282
  }
@@ -322,7 +325,20 @@ export function createControllerService(deps: ControllerServiceDeps): OpenClawPl
322
325
  const now = Date.now();
323
326
 
324
327
  for (const [workerId, worker] of Object.entries(teamState.workers)) {
325
- if (worker.status === "offline") continue;
328
+ if (worker.status === "offline") {
329
+ // Stale offline entries are dead session workers (provisioned
330
+ // per-task workers exit when their task ends; their registry
331
+ // entries used to linger forever and pile up - observed live:
332
+ // the intake agent read a wall of offline developers and
333
+ // misreported the repos they had served as "repo offline").
334
+ // Same reap semantics as the startup sweep, applied at runtime.
335
+ if (now - worker.lastHeartbeat > WORKER_TIMEOUT_MS) {
336
+ delete teamState.workers[workerId];
337
+ changed = true;
338
+ logger.info(`Controller: reaped stale offline worker ${workerId}`);
339
+ }
340
+ continue;
341
+ }
326
342
  if (now - worker.lastHeartbeat > WORKER_TIMEOUT_MS) {
327
343
  logger.info(`Controller: worker ${workerId} timed out`);
328
344
  const activeTaskId = worker.currentTaskId;
@@ -30,6 +30,8 @@ export type ControllerToolsDeps = {
30
30
  sessionKey?: string | null;
31
31
  /** Handler for kickoff meeting requests. Use a getter for late-binding (service may start after tool registration). */
32
32
  getKickoffHandler?: () => ((candidateRoles: RoleId[], complexity: "simple" | "medium" | "complex", requirement: string) => Promise<{ assessments: KickoffAssessment[]; summary: string }>) | undefined;
33
+ /** Late-binding TeamAuto scheduler getter (scheduler starts with the controller service). */
34
+ getTeamAutoScheduler?: () => import("../teamauto/scheduler.js").TeamAutoScheduler | null;
33
35
  };
34
36
 
35
37
  const EXECUTION_READY_BLOCKERS: Array<{ pattern: RegExp; reason: string }> = [
@@ -501,6 +503,76 @@ export function createControllerTools(deps: ControllerToolsDeps) {
501
503
  }
502
504
  },
503
505
  },
506
+ {
507
+ name: "teamclaw_teamauto_status",
508
+ label: "TeamAuto Status",
509
+ description: "List TeamAuto-managed repositories with their schedule, full-review cadence, pause state, and recent activity. Use this to discover which repos this controller autonomously maintains before proposing improvements to them.",
510
+ parameters: Type.Object({}),
511
+ async execute(_id: string, _params: Record<string, unknown>) {
512
+ const scheduler = deps.getTeamAutoScheduler?.();
513
+ if (!scheduler) {
514
+ return { details: {}, content: [{ type: "text" as const, text: "TeamAuto is not active on this controller." }] };
515
+ }
516
+ const status = await scheduler.getStatus();
517
+ const activity = (await scheduler.getActivity()).slice(-10).map((e: { at: number; repoId?: string; kind: string; text: string }) => `${new Date(e.at).toISOString().slice(11, 19)} ${e.repoId ?? ""} ${e.text}`);
518
+ return { details: {}, content: [{ type: "text" as const, text: `TeamAuto repos:\n${JSON.stringify(status, null, 2)}\nRecent activity:\n${activity.join("\n") || "(none)"}` }] };
519
+ },
520
+ },
521
+ {
522
+ name: "teamclaw_teamauto_sweep",
523
+ label: "TeamAuto Sweep Now",
524
+ description: "Trigger an immediate TeamAuto sweep of a bound repository (scans GitHub issues/PRs and creates review/ownership tasks) instead of waiting for the next cron tick.",
525
+ parameters: Type.Object({
526
+ repoId: Type.String({ description: "Bound repository id in owner/name form, e.g. topcheer/teamclaw" }),
527
+ }),
528
+ async execute(_id: string, params: Record<string, unknown>) {
529
+ const scheduler = deps.getTeamAutoScheduler?.();
530
+ if (!scheduler) {
531
+ return { details: {}, content: [{ type: "text" as const, text: "TeamAuto is not active on this controller." }] };
532
+ }
533
+ try {
534
+ const summary = await scheduler.runSweepNow(String(params.repoId ?? ""), true);
535
+ return { details: {}, content: [{ type: "text" as const, text: `Sweep done: ${summary}` }] };
536
+ } catch (err) {
537
+ return { details: {}, content: [{ type: "text" as const, text: `Sweep failed: ${err instanceof Error ? err.message : String(err)}` }] };
538
+ }
539
+ },
540
+ },
541
+ {
542
+ name: "teamclaw_teamauto_propose",
543
+ label: "TeamAuto Propose",
544
+ description: "Inject a manual work proposal into a TeamAuto-managed repository. The proposal flows through the normal TeamAuto task pipeline (dedup, failure caps, norms, worktree checkout, worker assignment) - no GitHub object is required. Prefer this over teamclaw_create_task when the target repo is TeamAuto-managed so the work inherits its governance.",
545
+ parameters: Type.Object({
546
+ repoId: Type.String({ description: "Bound repository id in owner/name form" }),
547
+ kind: Type.String({ description: "Candidate kind: issueReview, prReview, takeOwnership (write path), or fullReview" }),
548
+ title: Type.String({ description: "Short task title" }),
549
+ context: Type.String({ description: "Full task instructions: goal, scope, constraints, expected deliverable" }),
550
+ role: Type.Optional(Type.String({ description: "Target role id; defaults to developer for takeOwnership, architect otherwise" })),
551
+ writeMode: Type.Optional(Type.String({ description: "read-only (default) or write; takeOwnership defaults to write" })),
552
+ }),
553
+ async execute(_id: string, params: Record<string, unknown>) {
554
+ const scheduler = deps.getTeamAutoScheduler?.();
555
+ if (!scheduler) {
556
+ return { details: {}, content: [{ type: "text" as const, text: "TeamAuto is not active on this controller." }] };
557
+ }
558
+ const writeMode = params.writeMode === "write" ? "write" : params.writeMode === "read-only" ? "read-only" : undefined;
559
+ try {
560
+ const result = await scheduler.proposeManual(String(params.repoId ?? ""), {
561
+ kind: String(params.kind ?? "issueReview") as "issueReview" | "prReview" | "takeOwnership" | "fullReview",
562
+ title: String(params.title ?? ""),
563
+ context: String(params.context ?? ""),
564
+ role: params.role ? String(params.role) : undefined,
565
+ writeMode,
566
+ });
567
+ if (result === "duplicate-active-skipped") {
568
+ return { details: {}, content: [{ type: "text" as const, text: "Skipped: an active task for this proposal key already exists." }] };
569
+ }
570
+ return { details: {}, content: [{ type: "text" as const, text: `TeamAuto task created: ${result}` }] };
571
+ } catch (err) {
572
+ return { details: {}, content: [{ type: "text" as const, text: `Proposal failed: ${err instanceof Error ? err.message : String(err)}` }] };
573
+ }
574
+ },
575
+ },
504
576
  ];
505
577
  }
506
578
 
@@ -65,11 +65,41 @@ export type TunnelHandle = {
65
65
  };
66
66
 
67
67
  const CLOUDFLARED_CANDIDATES = [
68
- "cloudflared",
69
68
  "/opt/homebrew/bin/cloudflared",
70
69
  "/usr/local/bin/cloudflared",
71
70
  "/usr/bin/cloudflared",
72
71
  ];
72
+ function cloudflaredInstallTarget(): string {
73
+ // Keep in sync with installCloudflared(): the one-click install drops the
74
+ // binary at $HOME/.local/bin/cloudflared (no sudo needed, non-root friendly
75
+ // in containers where HOME is writable but /usr/local/bin is not).
76
+ const home = process.env.HOME ?? "/tmp";
77
+ return path.join(home, ".local", "bin", "cloudflared");
78
+ }
79
+ // curl-less download fallback (distroless images): plain https.get with
80
+ // redirect following. GitHub release URLs 302 to objects.githubusercontent.com.
81
+ function nativeDownload(url: string, dest: string, redirects = 0): Promise<void> {
82
+ return new Promise((resolve, reject) => {
83
+ if (redirects > 5) return reject(new Error("too many redirects"));
84
+ const req = https.get(url, (res: import("node:http").IncomingMessage) => {
85
+ if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
86
+ res.resume();
87
+ nativeDownload(res.headers.location, dest, redirects + 1).then(resolve, reject);
88
+ return;
89
+ }
90
+ if (res.statusCode !== 200) {
91
+ res.resume();
92
+ reject(new Error("HTTP " + res.statusCode));
93
+ return;
94
+ }
95
+ const file = fs.createWriteStream(dest);
96
+ res.pipe(file);
97
+ file.on("finish", () => file.close((err?: NodeJS.ErrnoException | null) => (err ? reject(err) : resolve())));
98
+ file.on("error", reject);
99
+ });
100
+ req.on("error", reject);
101
+ });
102
+ }
73
103
  function tunnelRuntimeHome(): string {
74
104
  try {
75
105
  const dir = path.join(os.tmpdir(), "teamclaw-cloudflared-home");
@@ -125,7 +155,15 @@ function connectorPidIsCloudflared(pid: number): boolean {
125
155
  }
126
156
 
127
157
  function findCloudflared(): string | null {
128
- for (const bin of CLOUDFLARED_CANDIDATES) {
158
+ // The install target first: installCloudflared() puts the binary in
159
+ // $HOME/.local/bin, which is on PATH in stock images (Debian node images
160
+ // prepend it) but must be found even when PATH is minimal (K8s pods).
161
+ const candidates = [cloudflaredInstallTarget(), ...CLOUDFLARED_CANDIDATES];
162
+ // Real PATH scan. (fs.existsSync("cloudflared") checks CWD, not PATH -
163
+ // the old behavior missed every PATH-resolvable install.)
164
+ const pathDirs = (process.env.PATH ?? "").split(path.delimiter).filter(Boolean);
165
+ for (const dir of pathDirs) candidates.push(path.join(dir, "cloudflared"));
166
+ for (const bin of candidates) {
129
167
  try {
130
168
  if (fs.existsSync(bin) && fs.accessSync(bin, fs.constants.X_OK) === undefined) {
131
169
  return bin;
@@ -283,7 +321,10 @@ export function createTunnelManager(deps: { logger: PluginLogger; localPort: num
283
321
  /**
284
322
  * One-click cloudflared install across platforms:
285
323
  * darwin -> brew install cloudflared (Homebrew), tarball fallback
286
- * linux -> official tarball into ~/.local/bin (no sudo needed)
324
+ * linux -> official RAW binary into ~/.local/bin (no sudo needed;
325
+ * cloudflared ships NO .tgz asset for linux - only darwin
326
+ * has tgz packages, and the binary is statically linked so
327
+ * it runs on any distro without glibc concerns)
287
328
  * win32 -> winget install Cloudflare.cloudflared
288
329
  */
289
330
 
@@ -325,7 +366,10 @@ export function createTunnelManager(deps: { logger: PluginLogger; localPort: num
325
366
  if (brew.code === 0) return { ok: true, detail: "installed via Homebrew" };
326
367
  }
327
368
  const arch = process.arch === "arm64" ? "arm64" : process.arch === "ia32" ? "386" : "amd64";
328
- const name = process.platform === "darwin" ? "cloudflared-darwin-" + arch + ".tgz" : "cloudflared-linux-" + arch + ".tgz";
369
+ const isDarwin = process.platform === "darwin";
370
+ // Linux assets are RAW binaries (no .tgz exists for linux - verified
371
+ // against the official release page; the old .tgz URL 404s there).
372
+ const name = isDarwin ? "cloudflared-darwin-" + arch + ".tgz" : "cloudflared-linux-" + arch;
329
373
  fs.mkdirSync(userBin, { recursive: true });
330
374
  const tgz = path.join(userBin, name);
331
375
  const url = "https://github.com/cloudflare/cloudflared/releases/latest/download/" + name;
@@ -338,19 +382,35 @@ export function createTunnelManager(deps: { logger: PluginLogger; localPort: num
338
382
  total = Number(head.headers["content-length"] ?? 0);
339
383
  } catch { total = 0; }
340
384
  setPhase("downloading", 0, url);
341
- const timer = setInterval(() => {
385
+ const watch = (file: string) => {
386
+ const timer = setInterval(() => {
387
+ try {
388
+ const size = fs.statSync(file).size;
389
+ if (total > 0) setPhase("downloading", Math.min(99, Math.floor((size / total) * 100)), null);
390
+ } catch { /* file not created yet */ }
391
+ }, 500);
392
+ return () => clearInterval(timer);
393
+ };
394
+ // curl first (resume/retry flags), native https fallback for images
395
+ // without curl (distroless etc.). GitHub releases redirect - follow them.
396
+ const dlPath = isDarwin ? tgz : target;
397
+ const stopWatch = watch(dlPath);
398
+ const dl = await run("curl", ["-fsSL", "--retry", "3", "-o", dlPath, url]);
399
+ stopWatch();
400
+ if (dl.code !== 0) {
401
+ setPhase("downloading", null, "native https fallback");
342
402
  try {
343
- const size = fs.statSync(tgz).size;
344
- if (total > 0) setPhase("downloading", Math.min(99, Math.floor((size / total) * 100)), null);
345
- } catch { /* file not created yet */ }
346
- }, 500);
347
- const dl = await run("curl", ["-fsSL", "--retry", "3", "-o", tgz, url]);
348
- clearInterval(timer);
349
- if (dl.code !== 0) return { ok: false, detail: "download: " + tail(dl.out) };
350
- setPhase("extracting", 99, null);
351
- const ex = await run("tar", ["xzf", tgz, "-C", userBin]);
352
- fs.rmSync(tgz, { force: true });
353
- if (ex.code !== 0) return { ok: false, detail: "extract: " + tail(ex.out) };
403
+ await nativeDownload(url, dlPath);
404
+ } catch (e) {
405
+ return { ok: false, detail: "download: " + (e instanceof Error ? e.message : String(e)) };
406
+ }
407
+ }
408
+ if (isDarwin) {
409
+ setPhase("extracting", 99, null);
410
+ const ex = await run("tar", ["xzf", tgz, "-C", userBin]);
411
+ fs.rmSync(tgz, { force: true });
412
+ if (ex.code !== 0) return { ok: false, detail: "extract: " + tail(ex.out) };
413
+ }
354
414
  fs.chmodSync(target, 0o755);
355
415
  return { ok: true, detail: "installed to " + target };
356
416
  })();
@@ -1522,7 +1522,20 @@ async function prepareProcessRuntimeExtensions(stateDir: string): Promise<void>
1522
1522
  await fs.symlink(controllerExtensionsDir, runtimeExtensionsDir, "dir");
1523
1523
  } else {
1524
1524
  await fs.mkdir(runtimeExtensionsDir, { recursive: true });
1525
- await fs.symlink(resolveCurrentTeamClawPluginRootDir(), path.join(runtimeExtensionsDir, "teamclaw"), "dir");
1525
+ // Baked-in images set TEAMCLAW_BAKED_IN=true and the legacy helper
1526
+ // returned "" for that case, so the symlink target was empty and
1527
+ // process workers fell back to resolving the plugin from their cwd
1528
+ // ("/app/dist/openclaw.plugin.json" not found → exit loop, k3s e2e
1529
+ // 2026-11-03). Probe the baked image layout instead: the controller
1530
+ // entrypoint (process.argv[1], e.g. /app/dist/index.js) sits below
1531
+ // the app root, where the runtime image ships
1532
+ // /app/extensions/teamclaw with its openclaw.plugin.json.
1533
+ const pluginRootDir = process.env.TEAMCLAW_BAKED_IN === "true"
1534
+ ? await resolveBakedTeamClawPluginRootDir()
1535
+ : resolveCurrentTeamClawPluginRootDir();
1536
+ if (pluginRootDir) {
1537
+ await fs.symlink(pluginRootDir, path.join(runtimeExtensionsDir, "teamclaw"), "dir");
1538
+ }
1526
1539
  }
1527
1540
 
1528
1541
  await copyControllerAuthProfiles(stateDir);
@@ -1697,6 +1710,33 @@ function resolveCurrentTeamClawPluginRootDir(): string {
1697
1710
  return process.env.TEAMCLAW_BAKED_IN === "true" ? "" : path.resolve(fileURLToPath(new URL("../../", import.meta.url)));
1698
1711
  }
1699
1712
 
1713
+ /**
1714
+ * Locate the teamclaw plugin root inside a baked runtime image. The image
1715
+ * ships the plugin at <app-root>/extensions/teamclaw; the controller
1716
+ * entrypoint (process.argv[1]) lives under <app-root>, so walk up from it.
1717
+ * Returns "" when no candidate carries an openclaw.plugin.json (the
1718
+ * caller then skips the symlink instead of creating a dangling one).
1719
+ */
1720
+ async function resolveBakedTeamClawPluginRootDir(): Promise<string> {
1721
+ const entrypoint = process.argv[1] ? path.resolve(process.argv[1]) : "";
1722
+ const candidates = entrypoint
1723
+ ? [
1724
+ path.resolve(entrypoint, "../../extensions/teamclaw"),
1725
+ path.resolve(entrypoint, "../extensions/teamclaw"),
1726
+ ]
1727
+ : [];
1728
+ candidates.push("/app/extensions/teamclaw");
1729
+ for (const candidate of candidates) {
1730
+ try {
1731
+ await fs.access(path.join(candidate, "openclaw.plugin.json"));
1732
+ return candidate;
1733
+ } catch {
1734
+ // try the next candidate layout
1735
+ }
1736
+ }
1737
+ return "";
1738
+ }
1739
+
1700
1740
  function attachChildLogs(child: ChildProcess, logger: PluginLogger, prefix: string): void {
1701
1741
  if (child.stdout) {
1702
1742
  const stdoutReader = readline.createInterface({ input: child.stdout });
@@ -285,6 +285,9 @@ export function buildControllerToolRules(): string[] {
285
285
  "- teamclaw_list_tasks: List all tasks with status filtering",
286
286
  "- teamclaw_assign_task: Assign a task to a specific worker",
287
287
  "- teamclaw_send_message: Send messages between team members",
288
+ "- teamclaw_teamauto_status: List TeamAuto-managed repos (schedule, cadence, pause state, recent activity) - call this first when a request mentions improving one of the bound repositories",
289
+ "- teamclaw_teamauto_sweep: Trigger an immediate TeamAuto sweep of a bound repo",
290
+ "- teamclaw_teamauto_propose: Inject a proposal into a TeamAuto-managed repo through its governed pipeline (dedup, failure caps, norms, worktree) - prefer over teamclaw_create_task for repos listed by teamclaw_teamauto_status",
288
291
  ];
289
292
  }
290
293
 
@@ -46,6 +46,64 @@ export type TeamAutoSchedulerDeps = {
46
46
  onActivity?: (entry: TeamAutoActivityEntry) => void;
47
47
  };
48
48
 
49
+ /** Max HARD (non-transient) failures before a candidate is dead-lettered. */
50
+ export const TEAMAUTO_DEAD_LETTER_ATTEMPTS = 3;
51
+
52
+ /** Max TOTAL failures (transient included) before a candidate is dead-lettered. */
53
+ export const TEAMAUTO_DEAD_LETTER_TRANSIENT_ATTEMPTS = 6;
54
+
55
+ /**
56
+ * Failure signatures that are environmental, not the task's fault - the same
57
+ * candidate is likely to succeed on a later sweep. Observed live (92-task
58
+ * dump): upstream rate limiting ("AI service needs a short break"), shared
59
+ * workspace snapshot races ("Workspace filesystem changed"), worker gateway
60
+ * lifecycle races ("Gateway request entry is closed"). These get a wider
61
+ * retry allowance than hard failures so they do not dead-letter good work.
62
+ */
63
+ export const TRANSIENT_FAILURE_RE = /workspace filesystem changed|ai service needs a short break|gateway request entry is closed|rate.?limit|timed? ?out|econnreset|socket hang up|bad gateway|service unavailable/i;
64
+
65
+ /** The dedup marker for a candidate as embedded in task descriptions. */
66
+ export function idempotencyMarker(candidate: { key: string; kind: string }): string {
67
+ return `Idempotency-Key: ${candidate.key}:${candidate.kind}`;
68
+ }
69
+
70
+ /** Failed task attempts for a candidate (task history is the attempt log). */
71
+ export function failedAttemptCount(
72
+ state: { tasks: Record<string, { description: string; status: string; error?: string }> },
73
+ candidate: { key: string; kind: string },
74
+ ): number {
75
+ const marker = idempotencyMarker(candidate);
76
+ return Object.values(state.tasks).filter((t) => t.description.includes(marker) && t.status === "failed").length;
77
+ }
78
+
79
+ /** Failed attempts whose error is NOT a known transient signature. */
80
+ export function hardAttemptCount(
81
+ state: Parameters<typeof failedAttemptCount>[0],
82
+ candidate: { key: string; kind: string },
83
+ ): number {
84
+ const marker = idempotencyMarker(candidate);
85
+ return Object.values(state.tasks).filter(
86
+ (t) => t.description.includes(marker) && t.status === "failed" && !(t.error && TRANSIENT_FAILURE_RE.test(t.error)),
87
+ ).length;
88
+ }
89
+
90
+ /** Auto-pause retry backoff: 30m after the 1st failure, doubling, capped at 4h. */
91
+ export const SWEEP_RETRY_BASE_MINUTES = 30;
92
+ export const SWEEP_RETRY_MAX_MINUTES = 240;
93
+ export function sweepBackoffMinutes(failures: number): number {
94
+ return Math.min(SWEEP_RETRY_BASE_MINUTES * 2 ** Math.max(0, failures - 1), SWEEP_RETRY_MAX_MINUTES);
95
+ }
96
+
97
+ /** Epoch ms when an auto-paused repo becomes due for its next retry attempt. */
98
+ export function sweepRetryDueAt(failures: number, lastErrorAt: number): number {
99
+ return lastErrorAt + sweepBackoffMinutes(failures) * 60_000;
100
+ }
101
+
102
+ /** Auto-pauses (set by the sweep catch block) are cooldowns; user pauses are not. */
103
+ export function isAutoPause(reason: string | null | undefined): boolean {
104
+ return !!reason && reason.startsWith("sweep failed:");
105
+ }
106
+
49
107
  export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
50
108
  const { logger, auth } = deps;
51
109
 
@@ -259,7 +317,9 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
259
317
  } else {
260
318
  for (const candidate of capped) {
261
319
  const taskId = enqueueCandidate(repo, candidate);
262
- if (taskId) {
320
+ if (taskId === "dead-lettered") {
321
+ recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `dead-lettered after ${TEAMAUTO_DEAD_LETTER_ATTEMPTS} failed attempts: ${candidate.kind}: ${candidate.title}` });
322
+ } else if (taskId) {
263
323
  recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "task", text: `${candidate.kind}: ${candidate.title}` });
264
324
  const action = candidate.kind === "prReview"
265
325
  ? ("prComment" as const)
@@ -279,6 +339,11 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
279
339
  repo.lastSweepSummary = "no new work";
280
340
  }
281
341
  repo.lastSweepAt = Date.now();
342
+ if (isAutoPause(repo.pausedReason)) {
343
+ repo.pausedReason = null;
344
+ recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: "sweep recovered, auto-pause cleared" });
345
+ }
346
+ repo.sweepFailures = 0;
282
347
  recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: repo.lastSweepSummary ?? "sweep complete" });
283
348
  await saveTeamAutoStore(s);
284
349
  if (created > 0) {
@@ -290,7 +355,14 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
290
355
  return repo.lastSweepSummary ?? "sweep complete";
291
356
  } catch (err) {
292
357
  const message = err instanceof Error ? err.message : String(err);
358
+ // Transient failures (network blips, restart-interrupted sweeps) used to
359
+ // pause a repo FOREVER - teamclaw sat auto-paused 15h on one "fetch
360
+ // failed". Auto-pauses are cooldowns now: the timer retries after the
361
+ // backoff below, and a success clears the state in the block above.
362
+ repo.sweepFailures = (repo.sweepFailures ?? 0) + 1;
363
+ repo.lastSweepErrorAt = Date.now();
293
364
  repo.pausedReason = `sweep failed: ${message}`;
365
+ recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `sweep failed (auto-retry in ~${sweepBackoffMinutes(repo.sweepFailures)}min): ${message}` });
294
366
  await saveTeamAutoStore(s).catch(() => {});
295
367
  logger.warn(`TeamAuto: sweep failed for ${repo.id}: ${message}`);
296
368
  return `error: ${message}`;
@@ -299,21 +371,36 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
299
371
  }
300
372
  }
301
373
 
302
- function enqueueCandidate(repo: TeamAutoRepo, candidate: Candidate): string | undefined {
374
+ function enqueueCandidate(repo: TeamAutoRepo, candidate: Candidate): string | "dead-lettered" | undefined {
303
375
  let createdId: string | undefined;
376
+ let deadLettered = false;
304
377
  deps.updateTeamState((state) => {
305
378
  // Idempotency: an active task for the same object AND kind wins. The
306
379
  // key rides in the description (TaskInfo has no dedicated field) and
307
380
  // must be a distinct marked line - titles contain human text that never
308
381
  // matches the raw key (that was the pre-fix bug). Kind-scoping matters:
309
382
  // object-level keys starved takeOwnership (review always enqueued first).
310
- const dedupMarker = `Idempotency-Key: ${candidate.key}:${candidate.kind}`;
383
+ const dedupMarker = idempotencyMarker(candidate);
311
384
  const duplicate = Object.values(state.tasks).find(
312
385
  (t) => t.description.includes(dedupMarker) && t.status !== "completed" && t.status !== "failed",
313
386
  );
314
387
  if (duplicate) {
315
388
  return;
316
389
  }
390
+ // Dead-letter: task history doubles as the attempt log. The dedup above
391
+ // only blocks ACTIVE tasks, so a failed candidate would be re-enqueued
392
+ // every sweep forever (observed: issue #12 re-candidated 4 sweeps in a
393
+ // row, burning daily budget on churn). Cap the retries instead - hard
394
+ // failures fast (3), environmental/transient failures get a wider
395
+ // allowance (6 total) so rate limits or workspace races do not kill
396
+ // work that would succeed on a quieter sweep.
397
+ if (
398
+ hardAttemptCount(state, candidate) >= TEAMAUTO_DEAD_LETTER_ATTEMPTS
399
+ || failedAttemptCount(state, candidate) >= TEAMAUTO_DEAD_LETTER_TRANSIENT_ATTEMPTS
400
+ ) {
401
+ deadLettered = true;
402
+ return;
403
+ }
317
404
  const task: TaskInfo = {
318
405
  id: newId("teamauto"),
319
406
  title: `[${candidate.kind}] ${candidate.title}`,
@@ -349,7 +436,47 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
349
436
  state.tasks[task.id] = task;
350
437
  createdId = task.id;
351
438
  });
352
- return createdId;
439
+ return deadLettered ? "dead-lettered" : createdId;
440
+ }
441
+
442
+ /**
443
+ * Agent-facing manual proposal: inject a candidate directly (bypassing the
444
+ * GitHub-object sweep) while reusing the full pipeline - idempotency dedup,
445
+ * dead-letter caps, budget accounting, norms blocks, worktree checkout.
446
+ * No writeback is registered (there is no GitHub object to write back to);
447
+ * the result stays in the task system, visible via teamclaw_list_tasks.
448
+ */
449
+ async function proposeManual(
450
+ repoId: string,
451
+ input: { kind: Candidate["kind"]; title: string; context: string; role?: string; writeMode?: "read-only" | "write" },
452
+ ): Promise<string> {
453
+ const s = await ensureStore();
454
+ const repo = s.repos.find((r) => r.id === repoId);
455
+ if (!repo) {
456
+ throw new Error(`${repoId} not bound`);
457
+ }
458
+ const kind: Candidate["kind"] = input.kind === "takeOwnership" || input.kind === "issueReview" || input.kind === "prReview" || input.kind === "fullReview" ? input.kind : "issueReview";
459
+ const candidate: Candidate = {
460
+ repoId,
461
+ key: `${repoId}#manual-${Date.now()}`,
462
+ kind,
463
+ number: 0,
464
+ role: (input.role || (kind === "takeOwnership" ? "developer" : "architect")) as Candidate["role"],
465
+ writeMode: input.writeMode ?? (kind === "takeOwnership" ? "write" : "read-only"),
466
+ title: input.title.slice(0, 120),
467
+ reason: "manual proposal from agent tool",
468
+ context: input.context,
469
+ };
470
+ const taskId = enqueueCandidate(repo, candidate);
471
+ if (taskId === "dead-lettered") {
472
+ throw new Error(`proposal dead-lettered (${kind} exceeded failure caps for this repo)`);
473
+ }
474
+ if (taskId) {
475
+ recordActivity(s, { at: Date.now(), repoId, kind: "task", text: `manual ${kind}: ${candidate.title}` });
476
+ await saveTeamAutoStore(s);
477
+ return taskId;
478
+ }
479
+ return "duplicate-active-skipped";
353
480
  }
354
481
 
355
482
  // ---------- write-back reconciler ----------
@@ -436,10 +563,22 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
436
563
  await client.postIssueComment(owner, name, entry.targetId, body);
437
564
  entry.doneAt = Date.now();
438
565
  writebackDone = true;
566
+ // Our own comment bumps the issue's updatedAt, which the scanner
567
+ // treats as new activity - advance the seen cursor so we do not
568
+ // re-trigger a review of an object we just replied to. External
569
+ // edits (updatedAt > now) still re-arm the candidate.
570
+ const issueRepo = s.repos.find((r) => r.id === entry.repoId);
571
+ if (issueRepo) {
572
+ issueRepo.cursors.seen[`${entry.repoId}#issue-${entry.targetId}`] = Date.now();
573
+ }
439
574
  } else if (entry.action === "prComment" && entry.targetId) {
440
575
  await client.postPullReviewComment(owner, name, entry.targetId, body);
441
576
  entry.doneAt = Date.now();
442
577
  writebackDone = true;
578
+ const prRepo = s.repos.find((r) => r.id === entry.repoId);
579
+ if (prRepo) {
580
+ prRepo.cursors.seen[`${entry.repoId}#pr-${entry.targetId}`] = Date.now();
581
+ }
443
582
  } else if (entry.action === "createIssue") {
444
583
  // Joint full review: same-cycle sections land in ONE umbrella issue
445
584
  // (first completed section creates it, the rest post as comments).
@@ -518,13 +657,32 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
518
657
  }
519
658
  const timer = setTimeout(() => {
520
659
  void (async () => {
521
- const s = await ensureStore();
522
- const fresh = s.repos.find((r) => r.id === repo.id);
523
- if (fresh?.enabled && fresh.pausedReason === null) {
524
- await runSweep(fresh, false);
525
- }
526
- if (fresh?.enabled) {
527
- scheduleRepo(fresh);
660
+ try {
661
+ const s = await ensureStore();
662
+ const fresh = s.repos.find((r) => r.id === repo.id);
663
+ const retryDue = fresh
664
+ ? isAutoPause(fresh.pausedReason) && Date.now() >= sweepRetryDueAt(fresh.sweepFailures ?? 1, fresh.lastSweepErrorAt ?? 0)
665
+ : false;
666
+ if (fresh?.enabled && (fresh.pausedReason === null || retryDue)) {
667
+ await runSweep(fresh, false);
668
+ }
669
+ if (fresh?.enabled) {
670
+ scheduleRepo(fresh);
671
+ }
672
+ } catch (err) {
673
+ // The timer chain must survive any single tick failure. Before this
674
+ // guard, a rejected ensureStore() (corrupt store file, IO error)
675
+ // unhandled-rejected through `void`, scheduleRepo(fresh) never ran,
676
+ // and the repo's scheduling chain died silently until a gateway
677
+ // restart. Re-arm from the last known config; updateRepo re-arms on
678
+ // config change anyway, so a stale schedule here is bounded.
679
+ logger.warn(`TeamAuto: sweep tick failed for ${repo.id}, re-arming timer: ${err instanceof Error ? err.message : String(err)}`);
680
+ try {
681
+ scheduleRepo(repo);
682
+ } catch {
683
+ // scheduleRepo only throws on programmer error; a dead chain here
684
+ // is still recoverable by restart (start() rebuilds all timers).
685
+ }
528
686
  }
529
687
  })();
530
688
  }, delay);
@@ -572,7 +730,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
572
730
  return (s.activity ?? []).slice().reverse();
573
731
  }
574
732
 
575
- return { addRepo, removeRepo, setRepoEnabled, updateRepo, runSweepNow, registerWriteback, reconcileWritebacks, start, stop, getStatus, getActivity, ensureWriteWorktree, removeWriteWorktree };
733
+ return { addRepo, removeRepo, setRepoEnabled, updateRepo, runSweepNow, registerWriteback, reconcileWritebacks, start, stop, getStatus, getActivity, ensureWriteWorktree, removeWriteWorktree, proposeManual };
576
734
 
577
735
  /** Collaboration contract: dispatch asks for a task-scoped worktree dir (rel to projects root). */
578
736
  async function ensureWriteWorktree(repoId: string, taskId: string): Promise<string> {
@@ -66,6 +66,10 @@ export type TeamAutoRepo = {
66
66
  lastSweepAt: number;
67
67
  lastSweepSummary: string | null;
68
68
  pausedReason: string | null;
69
+ /** Consecutive auto-paused sweep failures; drives retry backoff (0/undefined = healthy). */
70
+ sweepFailures?: number;
71
+ /** Epoch ms of the last auto-pausing sweep failure. */
72
+ lastSweepErrorAt?: number;
69
73
  dryRunDone: boolean;
70
74
  /** Bind-time provisioning state; ready/undefined means sweepable. */
71
75
  provision?: TeamAutoRepoProvision;
@@ -141,7 +145,7 @@ function emptyStore(): TeamAutoStore {
141
145
  writebacks: [],
142
146
  activity: [],
143
147
  budget: {
144
- maxTasksPerDay: 50,
148
+ maxTasksPerDay: 150,
145
149
  firstSweepDryRun: true,
146
150
  tasksToday: 0,
147
151
  dayStamp: now.toISOString().slice(0, 10),