@teamclaws/teamclaw 2026.11.6 → 2026.11.7

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.
Files changed (41) hide show
  1. package/README.md +17 -11
  2. package/dist/src/config.js +3 -3
  3. package/dist/src/controller/http-server.js +2 -2
  4. package/dist/src/controller/managed-gateway-process.js +17 -1
  5. package/dist/src/controller/provisioning/process-supervisor.js +11 -0
  6. package/dist/src/controller/route-table.js +2 -2
  7. package/dist/src/controller/security.js +30 -15
  8. package/dist/src/controller/task-assignment.js +62 -1
  9. package/dist/src/controller/task-routes.js +39 -2
  10. package/dist/src/controller/tunnel-manager.js +11 -0
  11. package/dist/src/controller/tunnel-routes.js +11 -0
  12. package/dist/src/controller/workspace-routes.js +16 -2
  13. package/dist/src/teamauto/github-client.js +19 -0
  14. package/dist/src/teamauto/repo-sync.js +96 -22
  15. package/dist/src/teamauto/scheduler.js +458 -36
  16. package/dist/src/teamauto/store.js +125 -3
  17. package/dist/src/types.js +5 -3
  18. package/dist/src/ui/app.js +2 -2
  19. package/dist/src/worker/worker-service.js +13 -1
  20. package/dist/src/workspace-browser.js +14 -0
  21. package/openclaw.plugin.json +5 -5
  22. package/package.json +4 -2
  23. package/src/config.ts +3 -3
  24. package/src/controller/http-server.ts +2 -2
  25. package/src/controller/managed-gateway-process.ts +17 -1
  26. package/src/controller/provisioning/process-supervisor.ts +11 -0
  27. package/src/controller/route-table.ts +2 -2
  28. package/src/controller/security.ts +30 -15
  29. package/src/controller/task-assignment.ts +58 -1
  30. package/src/controller/task-routes.ts +39 -1
  31. package/src/controller/tunnel-manager.ts +12 -1
  32. package/src/controller/tunnel-routes.ts +11 -0
  33. package/src/controller/workspace-routes.ts +17 -2
  34. package/src/teamauto/github-client.ts +21 -1
  35. package/src/teamauto/repo-sync.ts +85 -21
  36. package/src/teamauto/scheduler.ts +434 -33
  37. package/src/teamauto/store.ts +133 -3
  38. package/src/types.ts +9 -7
  39. package/src/ui/app.js +2 -2
  40. package/src/worker/worker-service.ts +15 -1
  41. package/src/workspace-browser.ts +15 -0
@@ -97,6 +97,9 @@ export type TeamAutoRepo = {
97
97
  export type TeamAutoWriteBack = {
98
98
  taskId: string;
99
99
  action: "issueComment" | "prComment" | "createIssue" | "createPR";
100
+ /** #5815: identical-error-text circuit breaker state. */
101
+ lastErrorText?: string;
102
+ lastErrorStreak?: number;
100
103
  repoId: string;
101
104
  targetId: number | null;
102
105
  doneAt: number | null;
@@ -192,6 +195,19 @@ export type TeamAutoStore = {
192
195
  deliveredResults?: Record<string, number>;
193
196
  /** #5738: one-time ledger migration marker (seed from task state, pardoning pre-deploy history once). */
194
197
  deliveredResultsInit?: boolean;
198
+ /** #5785: durable PR-face ledger. taskId -> PR url (or delivery marker).
199
+ * deliveredResults is comment-shaped: a worker direct-post on the issue
200
+ * face stamps it while the WRITE task's PR face (push + createPR, driven
201
+ * only by the write-back ladder) may never have come into existence.
202
+ * This table records PR-face delivery durably (prune-time stamp from
203
+ * entry.prUrl) so the undelivered-PR audit can tell "PR opened, entry
204
+ * pruned" apart from "registration never happened". */
205
+ prDeliveries?: Record<string, string>;
206
+ /** #5785: once-per-task gate for undelivered-PR alarms (completed WRITE
207
+ * task, no write-back entry, no PR-face record, no PR on its task branch).
208
+ * Also stamped when the branch's PR surface verifies the face through
209
+ * another path, so the surface check runs at most once per task. */
210
+ undeliveredPrAlarms?: Record<string, number>;
195
211
  /** #5685 (ggcode, 2026-11-16): "repoId|cycleKey" -> umbrella issue number
196
212
  * for joint full reviews. Done write-back entries are pruned at end-of-pass,
197
213
  * so an in-store peer scan cannot carry the umbrella pointer across passes
@@ -225,6 +241,8 @@ function emptyStore(): TeamAutoStore {
225
241
  failedClaimRecovery: {},
226
242
  orphanResultAlarms: {},
227
243
  deliveredResults: {},
244
+ prDeliveries: {},
245
+ undeliveredPrAlarms: {},
228
246
  fullReviewUmbrellas: {},
229
247
  budget: {
230
248
  maxTasksPerDay: 150,
@@ -265,8 +283,10 @@ const writeQueue: Promise<void>[] = [];
265
283
 
266
284
  export async function loadTeamAutoStore(): Promise<TeamAutoStore> {
267
285
  const { storeFile } = resolveTeamAutoPaths();
286
+ let baseFingerprint = "";
268
287
  try {
269
288
  const raw = await fs.readFile(storeFile, "utf8");
289
+ baseFingerprint = staleWriteFingerprint(raw);
270
290
  const parsed = JSON.parse(raw) as Partial<TeamAutoStore>;
271
291
  const store = emptyStore();
272
292
  if (Array.isArray(parsed.repos)) {
@@ -309,13 +329,102 @@ export async function loadTeamAutoStore(): Promise<TeamAutoStore> {
309
329
  if (typeof parsed.deliveredResultsInit === "boolean") {
310
330
  store.deliveredResultsInit = parsed.deliveredResultsInit;
311
331
  }
332
+ // #5785: same loader-copy discipline as the #5736 chain above - a field
333
+ // missing from this list is dropped on EVERY 20s settle reload even
334
+ // though saveTeamAutoStore writes it to disk (dropped prDeliveries =>
335
+ // healthy pruned tasks re-probe GitHub; dropped undeliveredPrAlarms =>
336
+ // the once-per-task gate resets and one incident re-alarms every pass).
337
+ if (parsed.prDeliveries && typeof parsed.prDeliveries === "object") {
338
+ store.prDeliveries = parsed.prDeliveries as Record<string, string>;
339
+ }
340
+ if (parsed.undeliveredPrAlarms && typeof parsed.undeliveredPrAlarms === "object") {
341
+ store.undeliveredPrAlarms = parsed.undeliveredPrAlarms as Record<string, number>;
342
+ }
312
343
  store.budget = { ...store.budget, ...(parsed.budget ?? {}) };
344
+ (store as TeamAutoStore & { __baseFp?: string }).__baseFp = baseFingerprint;
313
345
  return store;
314
346
  } catch {
315
347
  return emptyStore();
316
348
  }
317
349
  }
318
350
 
351
+ /** #5810/#5730 short-path guard helpers (cross-process stale-write protection). */
352
+ function staleWriteFingerprint(raw: string): string {
353
+ let h = 5381;
354
+ for (let i = 0; i < raw.length; i++) h = ((h * 33) ^ raw.charCodeAt(i)) >>> 0;
355
+ return `${raw.length}:${h.toString(36)}`;
356
+ }
357
+
358
+ function mergeStoresOnConflict(disk: TeamAutoStore, saver: TeamAutoStore): TeamAutoStore {
359
+ const maxKey = <T extends Record<string, number>>(a: T | undefined, b: T | undefined): T => {
360
+ const out: Record<string, number> = { ...(a ?? {}) };
361
+ for (const [k, v] of Object.entries(b ?? {})) out[k] = Math.max(out[k] ?? 0, v);
362
+ return out as T;
363
+ };
364
+ const unionBy = <T>(a: T[] | undefined, b: T[] | undefined, key: (x: T) => string, cap = 600): T[] => {
365
+ const seen = new Set<string>();
366
+ const out: T[] = [];
367
+ for (const x of [...(a ?? []), ...(b ?? [])]) {
368
+ const k = key(x);
369
+ if (seen.has(k)) continue;
370
+ seen.add(k);
371
+ out.push(x);
372
+ }
373
+ return out.slice(-cap);
374
+ };
375
+ const merged: TeamAutoStore = { ...saver };
376
+ const dayOf = (s: TeamAutoStore["budget"] | undefined) => s?.dayStamp ?? "";
377
+ const diskToday = disk.budget?.tasksToday ?? 0;
378
+ const saverToday = saver.budget?.tasksToday ?? 0;
379
+ merged.budget = {
380
+ ...(disk.budget ?? saver.budget),
381
+ dayStamp: dayOf(disk.budget) !== dayOf(saver.budget) && diskToday > saverToday ? dayOf(disk.budget) : (dayOf(saver.budget) || dayOf(disk.budget)),
382
+ tasksToday: dayOf(disk.budget) === dayOf(saver.budget) ? Math.max(diskToday, saverToday) : saverToday,
383
+ maxTasksPerDay: disk.budget?.maxTasksPerDay ?? saver.budget?.maxTasksPerDay ?? 150,
384
+ } as TeamAutoStore["budget"];
385
+ merged.deliveredResults = maxKey(disk.deliveredResults, saver.deliveredResults);
386
+ merged.orphanResultAlarms = maxKey(disk.orphanResultAlarms, saver.orphanResultAlarms);
387
+ merged.undeliveredPrAlarms = maxKey(disk.undeliveredPrAlarms, saver.undeliveredPrAlarms);
388
+ // #5785: PR-face records are durable facts - either side's stamp is
389
+ // evidence of delivery, so union with disk winning key collisions.
390
+ merged.prDeliveries = { ...(saver.prDeliveries ?? {}), ...(disk.prDeliveries ?? {}) };
391
+ merged.failedClaimRecovery = maxKey(disk.failedClaimRecovery, saver.failedClaimRecovery);
392
+ merged.fullReviewUmbrellas = maxKey(disk.fullReviewUmbrellas, saver.fullReviewUmbrellas);
393
+ merged.activity = unionBy(disk.activity, saver.activity, (x) => `${x.at}:${String(x.text).slice(0, 60)}`);
394
+ merged.writebacks = unionBy(disk.writebacks, saver.writebacks, (w) => w.taskId, 600).map((w) => {
395
+ const d = (disk.writebacks ?? []).find((x) => x.taskId === w.taskId);
396
+ if (!d) return w;
397
+ return { ...w, doneAt: w.doneAt ?? d.doneAt, failedAt: w.failedAt ?? d.failedAt, attempts: Math.max(w.attempts ?? 0, d.attempts ?? 0), targetId: w.targetId ?? d.targetId };
398
+ });
399
+ const repoMap = new Map<string, TeamAutoRepo>();
400
+ for (const r of [...(disk.repos ?? []), ...(saver.repos ?? [])]) {
401
+ const prev = repoMap.get(r.id);
402
+ if (!prev) { repoMap.set(r.id, r); continue; }
403
+ const diskSide = disk.repos?.includes(prev) ? prev : r;
404
+ const otherSide = diskSide === prev ? r : prev;
405
+ repoMap.set(r.id, {
406
+ ...diskSide,
407
+ lastSweepAt: Math.max(prev.lastSweepAt ?? 0, r.lastSweepAt ?? 0),
408
+ lastAttemptAt: Math.max(prev.lastAttemptAt ?? 0, r.lastAttemptAt ?? 0),
409
+ lastSweepErrorAt: Math.max(prev.lastSweepErrorAt ?? 0, r.lastSweepErrorAt ?? 0),
410
+ sweepFailures: Math.max(prev.sweepFailures ?? 0, r.sweepFailures ?? 0),
411
+ failedTasksSinceLastSweep: Math.max(prev.failedTasksSinceLastSweep ?? 0, r.failedTasksSinceLastSweep ?? 0),
412
+ lastSweepSummary: (prev.lastSweepAt ?? 0) >= (r.lastSweepAt ?? 0) ? prev.lastSweepSummary : r.lastSweepSummary,
413
+ sweeps: unionBy<TeamAutoSweepRecord>(prev.sweeps, r.sweeps, (x) => `${x.at}:${String(x.summary).slice(0, 40)}`, 40),
414
+ cursors: {
415
+ ...diskSide.cursors,
416
+ seen: maxKey(prev.cursors?.seen, otherSide.cursors?.seen) as TeamAutoRepo["cursors"]["seen"],
417
+ etags: { ...(otherSide.cursors?.etags ?? {}), ...(diskSide.cursors?.etags ?? {}) },
418
+ lastIssueSince: Math.max(prev.cursors?.lastIssueSince ?? 0, r.cursors?.lastIssueSince ?? 0),
419
+ lastPrSince: Math.max(prev.cursors?.lastPrSince ?? 0, r.cursors?.lastPrSince ?? 0),
420
+ lastCommitSha: prev.cursors?.lastCommitSha ?? r.cursors?.lastCommitSha,
421
+ } as TeamAutoRepo["cursors"],
422
+ });
423
+ }
424
+ merged.repos = [...repoMap.values()];
425
+ return merged;
426
+ }
427
+
319
428
  /** #5677 (ggcode, 2026-11-15): store-level async mutex. The 20s write-back
320
429
  * reconcile re-reads the store from disk and saves the whole object; the
321
430
  * sweep transaction (registerWriteback + summary) does the same. Without
@@ -340,11 +449,32 @@ export async function withStoreLock<T>(section: () => Promise<T>): Promise<T> {
340
449
  export async function saveTeamAutoStore(store: TeamAutoStore): Promise<void> {
341
450
  const { storeFile } = resolveTeamAutoPaths();
342
451
  await fs.mkdir(path.dirname(storeFile), { recursive: true });
343
- const tmp = `${storeFile}.tmp-${process.pid}-${Date.now()}`;
344
452
  const next = writeQueue.length ? writeQueue[writeQueue.length - 1].catch(() => {}) : Promise.resolve();
345
453
  const job = next.then(async () => {
346
- await fs.writeFile(tmp, JSON.stringify(store, null, 2) + "\n", { encoding: "utf8", mode: 0o600 });
347
- await fs.rename(tmp, storeFile);
454
+ let toWrite: TeamAutoStore = store;
455
+ const guardDir = `${storeFile}.guard-lock`;
456
+ let tookLock = false;
457
+ try {
458
+ await fs.mkdir(guardDir, { recursive: true }).then(() => { tookLock = true; }, () => {});
459
+ if (tookLock) {
460
+ const diskRaw = await fs.readFile(storeFile, "utf8").catch(() => null);
461
+ const baseFp = (store as TeamAutoStore & { __baseFp?: string }).__baseFp;
462
+ if (diskRaw !== null && baseFp && staleWriteFingerprint(diskRaw) !== baseFp) {
463
+ const diskParsed = JSON.parse(diskRaw) as Partial<TeamAutoStore>;
464
+ const diskStore = { ...emptyStore(), ...diskParsed } as TeamAutoStore;
465
+ toWrite = mergeStoresOnConflict(diskStore, store);
466
+ }
467
+ }
468
+ } catch { /* guard degraded - plain write */ }
469
+ try {
470
+ const tmp = `${storeFile}.tmp-${process.pid}-${Date.now()}`;
471
+ const raw = JSON.stringify(toWrite, (k, v) => (k === "__baseFp" ? undefined : v), 2) + "\n";
472
+ await fs.writeFile(tmp, raw, { encoding: "utf8", mode: 0o600 });
473
+ await fs.rename(tmp, storeFile);
474
+ (store as TeamAutoStore & { __baseFp?: string }).__baseFp = staleWriteFingerprint(raw);
475
+ } finally {
476
+ if (tookLock) await fs.rm(guardDir, { recursive: true, force: true }).catch(() => {});
477
+ }
348
478
  });
349
479
  writeQueue.push(job);
350
480
  writeQueue.splice(0, Math.max(0, writeQueue.length - 20));
package/src/types.ts CHANGED
@@ -608,8 +608,8 @@ export type PluginConfig = {
608
608
  agentIsolationMode: AgentIsolationMode;
609
609
  /**
610
610
  * Issue #23: controller device-pairing security options. Parsed with
611
- * safe defaults (autoPair: true) so hand-built configs without the key
612
- * keep the L1 zero-input LAN pairing behavior.
611
+ * safe defaults (autoPair: false since the ClawHub security review) so
612
+ * hand-built configs without the key require a pairing code per device.
613
613
  */
614
614
  security?: SecurityConfig;
615
615
  /**
@@ -663,8 +663,8 @@ export type WorkerIdentity = {
663
663
  // L0 local - no devices persisted => no authentication at all (the
664
664
  // historical behavior; a state without `security` is L0)
665
665
  // L1 LAN - LAN peers (loopback / RFC1918 / ULA / link-local) may
666
- // self-pair via POST /api/v1/security/pair-auto while
667
- // config.security.autoPair is true (default)
666
+ // self-pair via POST /api/v1/security/pair-auto only while
667
+ // config.security.autoPair is true (opt-in; default false)
668
668
  // L2 exposed - one-shot 60s pairing codes minted by an authenticated
669
669
  // device or the loopback console
670
670
  // The user never configures a token and the UI never shows a login page.
@@ -935,14 +935,16 @@ export function parsePluginConfig(raw: Record<string, unknown> = {}): PluginConf
935
935
  ? raw.agentIsolationMode
936
936
  : "independent";
937
937
 
938
- // Issue #23: security.autoPair defaults to true (L1 zero-input LAN
939
- // pairing); only an explicit boolean false disables pair-auto.
938
+ // Issue #23: security.autoPair defaulted to true (L1 zero-input LAN
939
+ // pairing). ClawHub security review 2026.11.6 (finding 2) flipped the
940
+ // default to false: a LAN peer must now present a pairing code unless
941
+ // the owner opts into zero-input pairing explicitly.
940
942
  const rawSecurity = raw.security;
941
943
  const rawAutoPair = rawSecurity && typeof rawSecurity === "object" && !Array.isArray(rawSecurity)
942
944
  ? (rawSecurity as { autoPair?: unknown }).autoPair
943
945
  : undefined;
944
946
  const security: SecurityConfig = {
945
- autoPair: typeof rawAutoPair === "boolean" ? rawAutoPair : true,
947
+ autoPair: typeof rawAutoPair === "boolean" ? rawAutoPair : false,
946
948
  };
947
949
 
948
950
  // Issue #23 (client wave): the paired device token, if this instance
package/src/ui/app.js CHANGED
@@ -329,7 +329,7 @@
329
329
  "tunnel.selfHostedLabel": "Self-hosted tunnel (your own Cloudflare account/domain):",
330
330
  "tunnel.tokenPlaceholder": "Cloudflare connector token",
331
331
  "tunnel.setupHelp": "How to get a token & set up the tunnel",
332
- "tunnel.setupHelpBody": "Cloudflare Zero Trust → Networks → Tunnels → your tunnel → copy token. Point its public hostname at this machine’s URL (Service: HTTP + the controller port shown in the docs). Protect it with Cloudflare Access — self-hosted domains skip the TeamClaw gate.",
332
+ "tunnel.setupHelpBody": "Cloudflare Zero Trust → Networks → Tunnels → your tunnel → copy token. Point its public hostname at this machine’s URL (Service: HTTP + the controller port shown in the docs). Self-hosted domains skip the TeamClaw gate, so device pairing must be enabled before the tunnel can start, and Cloudflare Access is still recommended.",
333
333
  "tunnel.or": "— or —",
334
334
  "tunnel.requiresGithub": "requires GitHub login",
335
335
  "tunnel.startQuick": "Anonymous one-off tunnel (trycloudflare.com)",
@@ -627,7 +627,7 @@
627
627
  "tunnel.selfHostedLabel": "自托管隧道(你自己的 Cloudflare 账号/域名):",
628
628
  "tunnel.tokenPlaceholder": "Cloudflare 连接器令牌",
629
629
  "tunnel.setupHelp": "如何获取令牌并配置隧道",
630
- "tunnel.setupHelpBody": "Cloudflare Zero Trust → 网络(Networks)→ Tunnels → 你的隧道 → 复制令牌。将其公共域名指向本机 URL(Service:HTTP + 文档中所示的控制器端口)。建议用 Cloudflare Access 保护——自托管域名不走 TeamClaw 门禁。",
630
+ "tunnel.setupHelpBody": "Cloudflare Zero Trust → 网络(Networks)→ Tunnels → 你的隧道 → 复制令牌。将其公共域名指向本机 URL(Service:HTTP + 文档中所示的控制器端口)。自托管域名不走 TeamClaw 门禁,因此必须先启用设备配对才能启动隧道;仍建议用 Cloudflare Access 保护。",
631
631
  "tunnel.or": "— 或 —",
632
632
  "tunnel.requiresGithub": "需要 GitHub 登录",
633
633
  "tunnel.startQuick": "匿名一次性隧道(trycloudflare.com)",
@@ -5,7 +5,7 @@ import type { PluginConfig, TaskAssignmentPayload, WorkerIdentity } from "../typ
5
5
  import { createHeartbeatPayload } from "../protocol.js";
6
6
  import { IdentityManager } from "../identity.js";
7
7
  import { MessageQueue } from "./message-queue.js";
8
- import { createWorkerHttpHandler } from "./http-handler.js";
8
+ import { createWorkerHttpHandler, resolveWorkerInboundTokens } from "./http-handler.js";
9
9
  import { buildTeamClawAgentSessionKey, ensureOpenClawWorkspaceMemoryDir } from "../openclaw-workspace.js";
10
10
 
11
11
  export type TaskExecutorResultLike = string | { text: string; contract?: Record<string, unknown> };
@@ -241,6 +241,20 @@ export function createWorkerService(deps: WorkerServiceDeps): OpenClawPluginServ
241
241
 
242
242
  server = http.createServer(handler);
243
243
  const listenHost = resolveWorkerListenHost(config);
244
+ // ClawHub security review 2026.11.6 (finding 1): the HTTP handler's auth
245
+ // gate is conditional ("while this worker holds an expected token"), so a
246
+ // worker bound to a non-loopback address with NO token would expose task
247
+ // assignment / cancel / install to everyone who can reach the port. Fail
248
+ // closed: refuse to listen unless loopback OR a token is present. Loopback
249
+ // stays the zero-config L0 path (provisioned workers always carry
250
+ // TEAMCLAW_LAUNCH_TOKEN, so containers on 0.0.0.0 are unaffected).
251
+ if (!isLoopbackHost(listenHost) && resolveWorkerInboundTokens(config).length === 0) {
252
+ server = null;
253
+ throw new Error(
254
+ `Worker: refusing to listen on ${listenHost}:${config.port} without an inbound token - the task/message/install API would be unauthenticated on the network. ` +
255
+ `Keep the loopback default, or set the securityToken plugin config (or launch via the controller, which injects TEAMCLAW_LAUNCH_TOKEN).`,
256
+ );
257
+ }
244
258
  await new Promise<void>((resolve, reject) => {
245
259
  server!.listen(config.port, listenHost, () => {
246
260
  logger.info(`Worker: HTTP server listening on ${listenHost}:${config.port}`);
@@ -179,6 +179,21 @@ async function resolveWorkspacePath(relativePath: string): Promise<{
179
179
  throw new Error("workspace path must stay inside the workspace");
180
180
  }
181
181
 
182
+ // ClawHub security review 2026.11.6 (finding 5): the lexical check above
183
+ // does not follow symlinks, but every fs.* call below does - a link
184
+ // inside the workspace pointing at ~/.ssh would pass containment and be
185
+ // read straight through /api/v1/workspace/raw/. Resolve BOTH sides for
186
+ // real and re-check containment on the resolved paths. A dangling link
187
+ // surfaces ENOENT here (mapped to 404 by the routes, same as before).
188
+ // Residual: the realpath->open window is a check-to-use race; the
189
+ // controller trusts its own workspace tree against concurrent local
190
+ // tampering (an attacker who can plant links there already has the host).
191
+ const [realWorkspaceDir, realTarget] = await Promise.all([fs.realpath(workspaceDir), fs.realpath(absolutePath)]);
192
+ const relativeReal = path.relative(realWorkspaceDir, realTarget).replace(/\\/g, "/");
193
+ if (!relativeReal || relativeReal.startsWith("..") || path.isAbsolute(relativeReal)) {
194
+ throw new Error("workspace path must stay inside the workspace");
195
+ }
196
+
182
197
  return {
183
198
  workspaceDir,
184
199
  normalizedPath: relativeFromWorkspace,