@teamclaws/teamclaw 2026.5.0 → 2026.7.0

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.
@@ -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: {
@@ -1374,6 +1374,54 @@ function buildProvisionedWorkerConfig(
1374
1374
  } else {
1375
1375
  delete agentDefaults.workspace;
1376
1376
  }
1377
+ // The host controller may run a newer openclaw that persists the keyed
1378
+ // agents.entries schema (e.g. agents.entries.teamclaw.model written by the
1379
+ // model-configuration feature). Provisioned workers can run an older
1380
+ // openclaw that rejects unknown agents keys ("Unrecognized key: entries"),
1381
+ // so fold the teamclaw entry's model back into the legacy
1382
+ // agents.defaults.model and drop the entries map. New-schema workers also
1383
+ // accept agents.defaults, keeping the folded config compatible both ways.
1384
+ const agentsRecord = agents as {
1385
+ entries?: Record<string, { model?: string }>;
1386
+ };
1387
+ if (agentsRecord.entries && typeof agentsRecord.entries === "object") {
1388
+ const entryModel = agentsRecord.entries[TEAMCLAW_AGENT_ID]?.model;
1389
+ if (entryModel && !agentDefaults.model) {
1390
+ agentDefaults.model = entryModel;
1391
+ }
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
+ }
1424
+ }
1377
1425
  agents.defaults = agentDefaults;
1378
1426
  config.agents = agents;
1379
1427
 
@@ -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,
@@ -14,6 +15,7 @@ import {
14
15
  loadTeamAutoStore,
15
16
  pushTeamAutoActivity,
16
17
  saveTeamAutoStore,
18
+ type TeamAutoActivityEntry,
17
19
  type TeamAutoRepo,
18
20
  type TeamAutoRepoNorms,
19
21
  type TeamAutoRepoProvision,
@@ -33,32 +35,24 @@ function newId(prefix: string): string {
33
35
  return `${prefix}-${Date.now().toString(36)}-${randomBytes(4).toString("hex")}`;
34
36
  }
35
37
 
36
- /** Minimal cron: supports minute-step schedules like "star-slash-n" (every n minutes), "@hourly", "@daily", plain-number fallback to minutes. */
37
- export function nextFireMs(schedule: string): number {
38
- const trimmed = schedule.trim();
39
- if (trimmed === "@hourly") {
40
- return 3600_000;
41
- }
42
- if (trimmed === "@daily") {
43
- return 24 * 3600_000;
44
- }
45
- const match = trimmed.match(/^\*\/(\d+)\s+\*\s+\*\s+\*\s+\*$/);
46
- if (match) {
47
- return Math.max(1, Number(match[1])) * 60_000;
48
- }
49
- const digits = trimmed.match(/\d+/);
50
- return digits ? Math.max(1, Number(digits[0])) * 60_000 : 30 * 60_000;
51
- }
38
+ export { nextFireMs, ScheduleParseError } from "./schedule.js";
52
39
  export type TeamAutoSchedulerDeps = {
53
40
  logger: PluginLogger;
54
41
  auth: GithubAuthManager;
55
42
  getTeamState: () => TeamState | null;
56
43
  updateTeamState: (updater: (state: TeamState) => void) => TeamState;
57
44
  onTasksCreated: () => Promise<void>;
45
+ /** Optional hook fired for every recorded activity entry (WS broadcast). */
46
+ onActivity?: (entry: TeamAutoActivityEntry) => void;
58
47
  };
59
48
 
60
49
  export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
61
50
  const { logger, auth } = deps;
51
+
52
+ function recordActivity(store: TeamAutoStore, entry: TeamAutoActivityEntry): void {
53
+ pushTeamAutoActivity(store, entry);
54
+ deps.onActivity?.(entry);
55
+ }
62
56
  const client = createGithubClient(auth);
63
57
  const sync = createRepoSync(auth, logger);
64
58
  const timers = new Map<string, NodeJS.Timeout>();
@@ -90,10 +84,12 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
90
84
  if (!info.permissions.pull) {
91
85
  throw new Error(`no read access to ${normalized}`);
92
86
  }
87
+ const schedule = options.schedule?.trim() || "*/30 * * * *";
88
+ nextFireMs(schedule); // validates: throws ScheduleParseError for unsupported expressions
93
89
  const repo: TeamAutoRepo = {
94
90
  id: normalized,
95
91
  enabled: true,
96
- schedule: options.schedule?.trim() || "*/30 * * * *",
92
+ schedule,
97
93
  addedAt: Date.now(),
98
94
  lastSweepAt: 0,
99
95
  lastSweepSummary: null,
@@ -113,7 +109,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
113
109
  // returns immediately; sweeps stay gated until provision completes.
114
110
  repo.provision = { status: "provisioning", message: "cloning repo", startedAt: Date.now(), updatedAt: Date.now() };
115
111
  s.repos.push(repo);
116
- pushTeamAutoActivity(s, { at: Date.now(), repoId: normalized, kind: "bind", text: `bound (schedule ${repo.schedule})` });
112
+ recordActivity(s, { at: Date.now(), repoId: normalized, kind: "bind", text: `bound (schedule ${repo.schedule})` });
117
113
  await saveTeamAutoStore(s);
118
114
  scheduleRepo(repo);
119
115
  void provisionRepoInBackground(normalized, info.cloneUrl, info.defaultBranch);
@@ -130,12 +126,14 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
130
126
  const norms = await learnNorms(repoRef, client, sync, cloneUrl, defaultBranch);
131
127
  await updateRepoProvision(repoId, { status: "ready", message: "ready", norms });
132
128
  const sReady = await ensureStore();
133
- pushTeamAutoActivity(sReady, { at: Date.now(), repoId, kind: "provision", text: "ready (clone + norms done)" });
129
+ recordActivity(sReady, { at: Date.now(), repoId, kind: "provision", text: "ready (clone + norms done)" });
134
130
  logger.info(`TeamAuto: provisioned ${repoId} (clone + norms done)`);
135
131
  } catch (err) {
136
132
  const message = err instanceof Error ? err.message : String(err);
137
133
  logger.warn(`TeamAuto: provisioning failed for ${repoId}: ${message}`);
138
134
  await updateRepoProvision(repoId, { status: "failed", message });
135
+ const sFailed = await ensureStore();
136
+ recordActivity(sFailed, { at: Date.now(), repoId, kind: "provision", text: `failed: ${message}` });
139
137
  }
140
138
  }
141
139
 
@@ -180,7 +178,9 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
180
178
  throw new Error(`${repoId} not bound`);
181
179
  }
182
180
  if (patch.schedule?.trim()) {
183
- repo.schedule = patch.schedule.trim();
181
+ const schedule = patch.schedule.trim();
182
+ nextFireMs(schedule); // validates before persisting
183
+ repo.schedule = schedule;
184
184
  }
185
185
  if (typeof patch.maxTasksPerSweep === "number" && patch.maxTasksPerSweep > 0) {
186
186
  repo.policy.maxTasksPerSweep = Math.min(20, Math.floor(patch.maxTasksPerSweep));
@@ -260,7 +260,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
260
260
  for (const candidate of capped) {
261
261
  const taskId = enqueueCandidate(repo, candidate);
262
262
  if (taskId) {
263
- pushTeamAutoActivity(s, { at: Date.now(), repoId: repo.id, kind: "task", text: `${candidate.kind}: ${candidate.title}` });
263
+ recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "task", text: `${candidate.kind}: ${candidate.title}` });
264
264
  const action = candidate.kind === "prReview"
265
265
  ? ("prComment" as const)
266
266
  : candidate.kind === "fullReview"
@@ -279,7 +279,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
279
279
  repo.lastSweepSummary = "no new work";
280
280
  }
281
281
  repo.lastSweepAt = Date.now();
282
- pushTeamAutoActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: repo.lastSweepSummary ?? "sweep complete" });
282
+ recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: repo.lastSweepSummary ?? "sweep complete" });
283
283
  await saveTeamAutoStore(s);
284
284
  if (created > 0) {
285
285
  await deps.onTasksCreated().catch((err) => {
@@ -424,7 +424,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
424
424
  const pr = await client.createPullRequest(repoId.split("/")[0]!, repoId.split("/")[1]!, branch, info.defaultBranch, `[teamclaw:${role}] ${task.title.replace(/^\[[^\]]+\]\s*/, "")}`.slice(0, 120), `${task.result.trim()}\n${MARKER_FOOTER(role)}`);
425
425
  entry.prUrl = pr.url;
426
426
  body = `${body}\n\nDelivered as PR: ${pr.url}`;
427
- pushTeamAutoActivity(s, { at: Date.now(), repoId, kind: "writeback", text: `PR opened: ${pr.url}` });
427
+ recordActivity(s, { at: Date.now(), repoId, kind: "writeback", text: `PR opened: ${pr.url}` });
428
428
  }
429
429
  await sync.removeTaskWorktree(repoId, task.id);
430
430
  } catch (prErr) {
@@ -474,7 +474,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
474
474
  entry.error = `unsupported action ${entry.action}`;
475
475
  }
476
476
  if (writebackDone) {
477
- pushTeamAutoActivity(s, { at: Date.now(), repoId: entry.repoId, kind: "writeback", text: `${entry.action} #${entry.targetId ?? "-"} ok (${task.id})` });
477
+ recordActivity(s, { at: Date.now(), repoId: entry.repoId, kind: "writeback", text: `${entry.action} #${entry.targetId ?? "-"} ok (${task.id})` });
478
478
  }
479
479
  }
480
480
  } catch (err) {
@@ -509,7 +509,13 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
509
509
  if (!repo.enabled) {
510
510
  return;
511
511
  }
512
- const delay = nextFireMs(repo.schedule);
512
+ let delay: number;
513
+ try {
514
+ delay = nextFireMs(repo.schedule);
515
+ } catch (err) {
516
+ logger.error(`TeamAuto: ${repo.id} has an unsupported schedule "${repo.schedule}" and will not be scheduled: ${err instanceof Error ? err.message : String(err)}`);
517
+ return;
518
+ }
513
519
  const timer = setTimeout(() => {
514
520
  void (async () => {
515
521
  const s = await ensureStore();