@teamclaws/teamclaw 2026.6.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 +5 -0
- package/openclaw.plugin.json +6 -3
- package/package.json +1 -1
- package/src/controller/controller-service.ts +17 -1
- package/src/controller/controller-tools.ts +72 -0
- package/src/controller/tunnel-manager.ts +76 -16
- package/src/controller/worker-provisioning.ts +77 -4
- package/src/prompt-policy.ts +3 -0
- package/src/teamauto/schedule.ts +136 -0
- package/src/teamauto/scheduler.ts +185 -31
- package/src/teamauto/store.ts +5 -1
- package/src/ui/app.js +2 -0
- package/src/ui/index.html +1 -0
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
|
}
|
package/openclaw.plugin.json
CHANGED
|
@@ -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.
|
|
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
|
|
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
|
@@ -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")
|
|
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
|
-
|
|
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
|
|
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
|
|
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
|
|
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
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
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
|
})();
|
|
@@ -1353,7 +1353,7 @@ function createProvisionerBackend(
|
|
|
1353
1353
|
}
|
|
1354
1354
|
}
|
|
1355
1355
|
|
|
1356
|
-
function buildProvisionedWorkerConfig(
|
|
1356
|
+
export function buildProvisionedWorkerConfig(
|
|
1357
1357
|
baseConfig: Record<string, unknown>,
|
|
1358
1358
|
controllerConfig: PluginConfig,
|
|
1359
1359
|
spec: {
|
|
@@ -1381,13 +1381,46 @@ function buildProvisionedWorkerConfig(
|
|
|
1381
1381
|
// so fold the teamclaw entry's model back into the legacy
|
|
1382
1382
|
// agents.defaults.model and drop the entries map. New-schema workers also
|
|
1383
1383
|
// accept agents.defaults, keeping the folded config compatible both ways.
|
|
1384
|
-
const agentsRecord = agents as {
|
|
1384
|
+
const agentsRecord = agents as {
|
|
1385
|
+
entries?: Record<string, { model?: string }>;
|
|
1386
|
+
};
|
|
1385
1387
|
if (agentsRecord.entries && typeof agentsRecord.entries === "object") {
|
|
1386
1388
|
const entryModel = agentsRecord.entries[TEAMCLAW_AGENT_ID]?.model;
|
|
1387
1389
|
if (entryModel && !agentDefaults.model) {
|
|
1388
1390
|
agentDefaults.model = entryModel;
|
|
1389
1391
|
}
|
|
1390
|
-
|
|
1392
|
+
// Container backends may run older openclaw runtimes that reject the
|
|
1393
|
+
// keyed agents schema ("Unrecognized key: entries") - fold down to
|
|
1394
|
+
// legacy defaults there. Process workers share the controller's own
|
|
1395
|
+
// runtime, which REQUIRES at least one entry ("agents.entries must
|
|
1396
|
+
// contain at least one configured agent" crash-loop, exit 78, observed
|
|
1397
|
+
// 2026-11-03 when entries was deleted unconditionally) - keep only the
|
|
1398
|
+
// teamclaw worker entry for them.
|
|
1399
|
+
const containerized =
|
|
1400
|
+
controllerConfig.workerProvisioningType === "docker" ||
|
|
1401
|
+
controllerConfig.workerProvisioningType === "kubernetes";
|
|
1402
|
+
if (containerized) {
|
|
1403
|
+
delete agentsRecord.entries;
|
|
1404
|
+
} else {
|
|
1405
|
+
agentsRecord.entries = {
|
|
1406
|
+
[TEAMCLAW_AGENT_ID]: agentsRecord.entries[TEAMCLAW_AGENT_ID] ?? {},
|
|
1407
|
+
};
|
|
1408
|
+
// Pruning entries can dangle defaults.heartbeat.agentId /
|
|
1409
|
+
// defaults.systemAgent.agentId ("main" no longer exists in the worker
|
|
1410
|
+
// config) - remap any dangling agentId reference to the surviving
|
|
1411
|
+
// teamclaw entry.
|
|
1412
|
+
for (const sectionKey of Object.keys(agentDefaults)) {
|
|
1413
|
+
const section = (agentDefaults as Record<string, unknown>)[sectionKey];
|
|
1414
|
+
if (
|
|
1415
|
+
section &&
|
|
1416
|
+
typeof section === "object" &&
|
|
1417
|
+
typeof (section as { agentId?: unknown }).agentId === "string" &&
|
|
1418
|
+
!agentsRecord.entries[(section as { agentId: string }).agentId]
|
|
1419
|
+
) {
|
|
1420
|
+
(section as { agentId: string }).agentId = TEAMCLAW_AGENT_ID;
|
|
1421
|
+
}
|
|
1422
|
+
}
|
|
1423
|
+
}
|
|
1391
1424
|
}
|
|
1392
1425
|
agents.defaults = agentDefaults;
|
|
1393
1426
|
config.agents = agents;
|
|
@@ -1489,7 +1522,20 @@ async function prepareProcessRuntimeExtensions(stateDir: string): Promise<void>
|
|
|
1489
1522
|
await fs.symlink(controllerExtensionsDir, runtimeExtensionsDir, "dir");
|
|
1490
1523
|
} else {
|
|
1491
1524
|
await fs.mkdir(runtimeExtensionsDir, { recursive: true });
|
|
1492
|
-
|
|
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
|
+
}
|
|
1493
1539
|
}
|
|
1494
1540
|
|
|
1495
1541
|
await copyControllerAuthProfiles(stateDir);
|
|
@@ -1664,6 +1710,33 @@ function resolveCurrentTeamClawPluginRootDir(): string {
|
|
|
1664
1710
|
return process.env.TEAMCLAW_BAKED_IN === "true" ? "" : path.resolve(fileURLToPath(new URL("../../", import.meta.url)));
|
|
1665
1711
|
}
|
|
1666
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
|
+
|
|
1667
1740
|
function attachChildLogs(child: ChildProcess, logger: PluginLogger, prefix: string): void {
|
|
1668
1741
|
if (child.stdout) {
|
|
1669
1742
|
const stdoutReader = readline.createInterface({ input: child.stdout });
|
package/src/prompt-policy.ts
CHANGED
|
@@ -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
|
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// Wall-clock aligned schedule resolution for TeamAuto sweeps.
|
|
2
|
+
//
|
|
3
|
+
// The previous implementation translated an expression into a plain
|
|
4
|
+
// interval and chained setTimeout()s from "now". Two problems:
|
|
5
|
+
//
|
|
6
|
+
// 1. Every gateway restart reset the countdown: with restarts less than
|
|
7
|
+
// one period apart, star-slash-30 never fired at all (observed
|
|
8
|
+
// 2026-11-02: three restarts within 30 minutes froze both repos).
|
|
9
|
+
// 2. Unrecognised expressions silently fell back to "first number of
|
|
10
|
+
// digits x 1 minute" - "0 9 * * *" (daily at nine) became a sweep
|
|
11
|
+
// every single minute.
|
|
12
|
+
//
|
|
13
|
+
// This module resolves schedules to the NEXT WALL-CLOCK boundary
|
|
14
|
+
// (local time, matching cron semantics) so a restart costs at most one
|
|
15
|
+
// partial period, and unsupported expressions throw ScheduleParseError
|
|
16
|
+
// instead of guessing a cadence.
|
|
17
|
+
//
|
|
18
|
+
// Supported expressions (5-field cron, local time):
|
|
19
|
+
// every N minutes: star-slash-N in the minute field
|
|
20
|
+
// hourly at minute M: "M * * * *"
|
|
21
|
+
// every N hours on :00: "0 star-slash-N * * *"
|
|
22
|
+
// daily at H:M: "M H * * *"
|
|
23
|
+
// @hourly @daily @weekly (Monday 00:00) @monthly (1st 00:00)
|
|
24
|
+
|
|
25
|
+
export class ScheduleParseError extends Error {
|
|
26
|
+
constructor(schedule: string) {
|
|
27
|
+
super(
|
|
28
|
+
`unsupported schedule "${schedule}": use */N * * * *, M * * * *, 0 */N * * *, M H * * *, @hourly, @daily, @weekly or @monthly`,
|
|
29
|
+
);
|
|
30
|
+
this.name = "ScheduleParseError";
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function nextFireMs(schedule: string, now: number = Date.now()): number {
|
|
35
|
+
const s = schedule.trim();
|
|
36
|
+
const next = new Date(now);
|
|
37
|
+
next.setSeconds(0, 0);
|
|
38
|
+
|
|
39
|
+
if (s === "@hourly") {
|
|
40
|
+
next.setMinutes(0);
|
|
41
|
+
if (next.getTime() <= now) {
|
|
42
|
+
next.setHours(next.getHours() + 1);
|
|
43
|
+
}
|
|
44
|
+
return next.getTime() - now;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
if (s === "@daily") {
|
|
48
|
+
next.setHours(0, 0, 0, 0);
|
|
49
|
+
if (next.getTime() <= now) {
|
|
50
|
+
next.setDate(next.getDate() + 1);
|
|
51
|
+
}
|
|
52
|
+
return next.getTime() - now;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (s === "@weekly") {
|
|
56
|
+
next.setHours(0, 0, 0, 0);
|
|
57
|
+
if (next.getTime() <= now) {
|
|
58
|
+
next.setDate(next.getDate() + 1);
|
|
59
|
+
}
|
|
60
|
+
// Monday = day 1. Day-0 first guarantees strictly-future even on Mondays.
|
|
61
|
+
while (next.getDay() !== 1) {
|
|
62
|
+
next.setDate(next.getDate() + 1);
|
|
63
|
+
}
|
|
64
|
+
return next.getTime() - now;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
if (s === "@monthly") {
|
|
68
|
+
next.setDate(1);
|
|
69
|
+
next.setHours(0, 0, 0, 0);
|
|
70
|
+
if (next.getTime() <= now) {
|
|
71
|
+
next.setMonth(next.getMonth() + 1);
|
|
72
|
+
}
|
|
73
|
+
return next.getTime() - now;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const stepMin = s.match(/^\*\/(\d{1,2})\s+\*\s+\*\s+\*\s+\*$/);
|
|
77
|
+
if (stepMin) {
|
|
78
|
+
const n = Number(stepMin[1]);
|
|
79
|
+
if (n < 1 || n > 59) {
|
|
80
|
+
throw new ScheduleParseError(s);
|
|
81
|
+
}
|
|
82
|
+
if (next.getTime() <= now) {
|
|
83
|
+
next.setMinutes(next.getMinutes() + 1);
|
|
84
|
+
}
|
|
85
|
+
while (next.getMinutes() % n !== 0) {
|
|
86
|
+
next.setMinutes(next.getMinutes() + 1);
|
|
87
|
+
}
|
|
88
|
+
return next.getTime() - now;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const hourlyAt = s.match(/^(\d{1,2})\s+\*\s+\*\s+\*\s+\*$/);
|
|
92
|
+
if (hourlyAt) {
|
|
93
|
+
const m = Number(hourlyAt[1]);
|
|
94
|
+
if (m > 59) {
|
|
95
|
+
throw new ScheduleParseError(s);
|
|
96
|
+
}
|
|
97
|
+
next.setMinutes(m);
|
|
98
|
+
if (next.getTime() <= now) {
|
|
99
|
+
next.setHours(next.getHours() + 1);
|
|
100
|
+
}
|
|
101
|
+
return next.getTime() - now;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const hourStep = s.match(/^0\s+\*\/(\d{1,2})\s+\*\s+\*\s+\*$/);
|
|
105
|
+
if (hourStep) {
|
|
106
|
+
const n = Number(hourStep[1]);
|
|
107
|
+
if (n < 1 || n > 23) {
|
|
108
|
+
throw new ScheduleParseError(s);
|
|
109
|
+
}
|
|
110
|
+
next.setMinutes(0);
|
|
111
|
+
if (next.getTime() <= now) {
|
|
112
|
+
next.setHours(next.getHours() + 1);
|
|
113
|
+
}
|
|
114
|
+
while (next.getHours() % n !== 0) {
|
|
115
|
+
next.setHours(next.getHours() + 1);
|
|
116
|
+
}
|
|
117
|
+
return next.getTime() - now;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const daily = s.match(/^(\d{1,2})\s+(\d{1,2})\s+\*\s+\*\s+\*$/);
|
|
121
|
+
if (daily) {
|
|
122
|
+
const m = Number(daily[1]);
|
|
123
|
+
const h = Number(daily[2]);
|
|
124
|
+
if (m > 59 || h > 23) {
|
|
125
|
+
throw new ScheduleParseError(s);
|
|
126
|
+
}
|
|
127
|
+
next.setMinutes(m);
|
|
128
|
+
next.setHours(h);
|
|
129
|
+
if (next.getTime() <= now) {
|
|
130
|
+
next.setDate(next.getDate() + 1);
|
|
131
|
+
}
|
|
132
|
+
return next.getTime() - now;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
throw new ScheduleParseError(s);
|
|
136
|
+
}
|
|
@@ -6,6 +6,7 @@ import type { RoleId, TaskInfo, TeamState } from "../types.js";
|
|
|
6
6
|
import { createGithubClient } from "./github-client.js";
|
|
7
7
|
import { learnNorms, renderNormsBlock } from "./norms.js";
|
|
8
8
|
import { createRepoSync, teamAutoProjectDir } from "./repo-sync.js";
|
|
9
|
+
import { nextFireMs } from "./schedule.js";
|
|
9
10
|
import { advanceCursors, sweepRepo, type Candidate } from "./scanner.js";
|
|
10
11
|
import {
|
|
11
12
|
consumeDailyBudget,
|
|
@@ -34,22 +35,7 @@ function newId(prefix: string): string {
|
|
|
34
35
|
return `${prefix}-${Date.now().toString(36)}-${randomBytes(4).toString("hex")}`;
|
|
35
36
|
}
|
|
36
37
|
|
|
37
|
-
|
|
38
|
-
export function nextFireMs(schedule: string): number {
|
|
39
|
-
const trimmed = schedule.trim();
|
|
40
|
-
if (trimmed === "@hourly") {
|
|
41
|
-
return 3600_000;
|
|
42
|
-
}
|
|
43
|
-
if (trimmed === "@daily") {
|
|
44
|
-
return 24 * 3600_000;
|
|
45
|
-
}
|
|
46
|
-
const match = trimmed.match(/^\*\/(\d+)\s+\*\s+\*\s+\*\s+\*$/);
|
|
47
|
-
if (match) {
|
|
48
|
-
return Math.max(1, Number(match[1])) * 60_000;
|
|
49
|
-
}
|
|
50
|
-
const digits = trimmed.match(/\d+/);
|
|
51
|
-
return digits ? Math.max(1, Number(digits[0])) * 60_000 : 30 * 60_000;
|
|
52
|
-
}
|
|
38
|
+
export { nextFireMs, ScheduleParseError } from "./schedule.js";
|
|
53
39
|
export type TeamAutoSchedulerDeps = {
|
|
54
40
|
logger: PluginLogger;
|
|
55
41
|
auth: GithubAuthManager;
|
|
@@ -60,6 +46,64 @@ export type TeamAutoSchedulerDeps = {
|
|
|
60
46
|
onActivity?: (entry: TeamAutoActivityEntry) => void;
|
|
61
47
|
};
|
|
62
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
|
+
|
|
63
107
|
export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
|
|
64
108
|
const { logger, auth } = deps;
|
|
65
109
|
|
|
@@ -98,10 +142,12 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
|
|
|
98
142
|
if (!info.permissions.pull) {
|
|
99
143
|
throw new Error(`no read access to ${normalized}`);
|
|
100
144
|
}
|
|
145
|
+
const schedule = options.schedule?.trim() || "*/30 * * * *";
|
|
146
|
+
nextFireMs(schedule); // validates: throws ScheduleParseError for unsupported expressions
|
|
101
147
|
const repo: TeamAutoRepo = {
|
|
102
148
|
id: normalized,
|
|
103
149
|
enabled: true,
|
|
104
|
-
schedule
|
|
150
|
+
schedule,
|
|
105
151
|
addedAt: Date.now(),
|
|
106
152
|
lastSweepAt: 0,
|
|
107
153
|
lastSweepSummary: null,
|
|
@@ -190,7 +236,9 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
|
|
|
190
236
|
throw new Error(`${repoId} not bound`);
|
|
191
237
|
}
|
|
192
238
|
if (patch.schedule?.trim()) {
|
|
193
|
-
|
|
239
|
+
const schedule = patch.schedule.trim();
|
|
240
|
+
nextFireMs(schedule); // validates before persisting
|
|
241
|
+
repo.schedule = schedule;
|
|
194
242
|
}
|
|
195
243
|
if (typeof patch.maxTasksPerSweep === "number" && patch.maxTasksPerSweep > 0) {
|
|
196
244
|
repo.policy.maxTasksPerSweep = Math.min(20, Math.floor(patch.maxTasksPerSweep));
|
|
@@ -269,7 +317,9 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
|
|
|
269
317
|
} else {
|
|
270
318
|
for (const candidate of capped) {
|
|
271
319
|
const taskId = enqueueCandidate(repo, candidate);
|
|
272
|
-
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) {
|
|
273
323
|
recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "task", text: `${candidate.kind}: ${candidate.title}` });
|
|
274
324
|
const action = candidate.kind === "prReview"
|
|
275
325
|
? ("prComment" as const)
|
|
@@ -289,6 +339,11 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
|
|
|
289
339
|
repo.lastSweepSummary = "no new work";
|
|
290
340
|
}
|
|
291
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;
|
|
292
347
|
recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: repo.lastSweepSummary ?? "sweep complete" });
|
|
293
348
|
await saveTeamAutoStore(s);
|
|
294
349
|
if (created > 0) {
|
|
@@ -300,7 +355,14 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
|
|
|
300
355
|
return repo.lastSweepSummary ?? "sweep complete";
|
|
301
356
|
} catch (err) {
|
|
302
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();
|
|
303
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}` });
|
|
304
366
|
await saveTeamAutoStore(s).catch(() => {});
|
|
305
367
|
logger.warn(`TeamAuto: sweep failed for ${repo.id}: ${message}`);
|
|
306
368
|
return `error: ${message}`;
|
|
@@ -309,21 +371,36 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
|
|
|
309
371
|
}
|
|
310
372
|
}
|
|
311
373
|
|
|
312
|
-
function enqueueCandidate(repo: TeamAutoRepo, candidate: Candidate): string | undefined {
|
|
374
|
+
function enqueueCandidate(repo: TeamAutoRepo, candidate: Candidate): string | "dead-lettered" | undefined {
|
|
313
375
|
let createdId: string | undefined;
|
|
376
|
+
let deadLettered = false;
|
|
314
377
|
deps.updateTeamState((state) => {
|
|
315
378
|
// Idempotency: an active task for the same object AND kind wins. The
|
|
316
379
|
// key rides in the description (TaskInfo has no dedicated field) and
|
|
317
380
|
// must be a distinct marked line - titles contain human text that never
|
|
318
381
|
// matches the raw key (that was the pre-fix bug). Kind-scoping matters:
|
|
319
382
|
// object-level keys starved takeOwnership (review always enqueued first).
|
|
320
|
-
const dedupMarker =
|
|
383
|
+
const dedupMarker = idempotencyMarker(candidate);
|
|
321
384
|
const duplicate = Object.values(state.tasks).find(
|
|
322
385
|
(t) => t.description.includes(dedupMarker) && t.status !== "completed" && t.status !== "failed",
|
|
323
386
|
);
|
|
324
387
|
if (duplicate) {
|
|
325
388
|
return;
|
|
326
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
|
+
}
|
|
327
404
|
const task: TaskInfo = {
|
|
328
405
|
id: newId("teamauto"),
|
|
329
406
|
title: `[${candidate.kind}] ${candidate.title}`,
|
|
@@ -359,7 +436,47 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
|
|
|
359
436
|
state.tasks[task.id] = task;
|
|
360
437
|
createdId = task.id;
|
|
361
438
|
});
|
|
362
|
-
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";
|
|
363
480
|
}
|
|
364
481
|
|
|
365
482
|
// ---------- write-back reconciler ----------
|
|
@@ -446,10 +563,22 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
|
|
|
446
563
|
await client.postIssueComment(owner, name, entry.targetId, body);
|
|
447
564
|
entry.doneAt = Date.now();
|
|
448
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
|
+
}
|
|
449
574
|
} else if (entry.action === "prComment" && entry.targetId) {
|
|
450
575
|
await client.postPullReviewComment(owner, name, entry.targetId, body);
|
|
451
576
|
entry.doneAt = Date.now();
|
|
452
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
|
+
}
|
|
453
582
|
} else if (entry.action === "createIssue") {
|
|
454
583
|
// Joint full review: same-cycle sections land in ONE umbrella issue
|
|
455
584
|
// (first completed section creates it, the rest post as comments).
|
|
@@ -519,16 +648,41 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
|
|
|
519
648
|
if (!repo.enabled) {
|
|
520
649
|
return;
|
|
521
650
|
}
|
|
522
|
-
|
|
651
|
+
let delay: number;
|
|
652
|
+
try {
|
|
653
|
+
delay = nextFireMs(repo.schedule);
|
|
654
|
+
} catch (err) {
|
|
655
|
+
logger.error(`TeamAuto: ${repo.id} has an unsupported schedule "${repo.schedule}" and will not be scheduled: ${err instanceof Error ? err.message : String(err)}`);
|
|
656
|
+
return;
|
|
657
|
+
}
|
|
523
658
|
const timer = setTimeout(() => {
|
|
524
659
|
void (async () => {
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
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
|
+
}
|
|
532
686
|
}
|
|
533
687
|
})();
|
|
534
688
|
}, delay);
|
|
@@ -576,7 +730,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
|
|
|
576
730
|
return (s.activity ?? []).slice().reverse();
|
|
577
731
|
}
|
|
578
732
|
|
|
579
|
-
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 };
|
|
580
734
|
|
|
581
735
|
/** Collaboration contract: dispatch asks for a task-scoped worktree dir (rel to projects root). */
|
|
582
736
|
async function ensureWriteWorktree(repoId: string, taskId: string): Promise<string> {
|
package/src/teamauto/store.ts
CHANGED
|
@@ -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:
|
|
148
|
+
maxTasksPerDay: 150,
|
|
145
149
|
firstSweepDryRun: true,
|
|
146
150
|
tasksToday: 0,
|
|
147
151
|
dayStamp: now.toISOString().slice(0, 10),
|
package/src/ui/app.js
CHANGED
|
@@ -144,6 +144,7 @@
|
|
|
144
144
|
"teamauto.provisioning": "preparing",
|
|
145
145
|
"teamauto.provisionFailed": "setup failed",
|
|
146
146
|
"teamauto.hint": "Pick one of your GitHub repositories. TeamClaw sweeps it on its own schedule, reviews issues/PRs, takes ownership of unassigned issues, and posts results with teamclaw markers.",
|
|
147
|
+
"teamauto.scheduleHint": "Schedules: */N * * * * (every N min), M * * * * (hourly at :M), 0 */N * * * (every N h), M H * * * (daily at H:M), @hourly, @daily, @weekly, @monthly. Sweeps align to the clock and survive restarts.",
|
|
147
148
|
"teamauto.loginFirst": "Sign in to GitHub first (top-right Login).",
|
|
148
149
|
"teamauto.loadingRepos": "Loading your repos...",
|
|
149
150
|
"teamauto.noCandidates": "No selectable repos (check GitHub login). You can type owner/repo manually:",
|
|
@@ -302,6 +303,7 @@
|
|
|
302
303
|
"teamauto.provisioning": "准备中",
|
|
303
304
|
"teamauto.provisionFailed": "准备失败",
|
|
304
305
|
"teamauto.hint": "选择你的 GitHub 仓库。TeamClaw 按各自节奏定时扫描,自主 review issue/PR、认领未分配 issue,并以 teamclaw 标识写回结果。",
|
|
306
|
+
"teamauto.scheduleHint": "支持的表达式:*/N * * * *(每 N 分钟)、M * * * *(每小时第 M 分)、0 */N * * *(每 N 小时)、M H * * *(每天 H:M)、@hourly、@daily、@weekly、@monthly。扫描按墙钟对齐,重启后自动恢复。",
|
|
305
307
|
"teamauto.loginFirst": "请先登录 GitHub(右上角 Login)。",
|
|
306
308
|
"teamauto.loadingRepos": "正在加载你的仓库...",
|
|
307
309
|
"teamauto.noCandidates": "无可选仓库(请检查 GitHub 登录),可手动输入 owner/repo:",
|
package/src/ui/index.html
CHANGED
|
@@ -210,6 +210,7 @@
|
|
|
210
210
|
<button id="teamauto-bind" class="btn btn-primary btn-small" type="button" data-i18n="teamauto.bind">Bind</button>
|
|
211
211
|
</div>
|
|
212
212
|
<div id="teamauto-bind-msg" class="teamauto-msg"></div>
|
|
213
|
+
<p class="teamauto-hint" data-i18n="teamauto.scheduleHint">Schedules: */N * * * * (every N min), M * * * * (hourly at :M), 0 */N * * * (every N h), M H * * * (daily at H:M), @hourly, @daily, @weekly, @monthly. Sweeps align to the clock and survive restarts.</p>
|
|
213
214
|
<div id="teamauto-bind-overlay" class="ta-bind-overlay is-hidden" role="dialog" aria-modal="true">
|
|
214
215
|
<div class="ta-bind-dialog">
|
|
215
216
|
<div class="ta-bind-title" id="teamauto-bind-title">Binding...</div>
|