@teamclaws/teamclaw 2026.11.5 → 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 (70) hide show
  1. package/README.md +17 -11
  2. package/dist/src/config.js +3 -3
  3. package/dist/src/controller/config-routes.js +7 -3
  4. package/dist/src/controller/controller-service.js +12 -1
  5. package/dist/src/controller/http-server.js +2 -2
  6. package/dist/src/controller/managed-gateway-process.js +17 -1
  7. package/dist/src/controller/provisioning/container-shared.js +6 -1
  8. package/dist/src/controller/provisioning/docker.js +1 -1
  9. package/dist/src/controller/provisioning/kubernetes.js +1 -1
  10. package/dist/src/controller/provisioning/process-supervisor.js +23 -1
  11. package/dist/src/controller/provisioning-config.js +8 -0
  12. package/dist/src/controller/route-table.js +2 -2
  13. package/dist/src/controller/security.js +30 -15
  14. package/dist/src/controller/task-assignment.js +126 -2
  15. package/dist/src/controller/task-results.js +34 -3
  16. package/dist/src/controller/task-routes.js +63 -3
  17. package/dist/src/controller/tunnel-manager.js +11 -0
  18. package/dist/src/controller/tunnel-routes.js +11 -0
  19. package/dist/src/controller/worker-provisioning.js +35 -0
  20. package/dist/src/controller/worker-routes.js +21 -6
  21. package/dist/src/controller/workspace-routes.js +16 -2
  22. package/dist/src/openclaw-workspace.js +39 -20
  23. package/dist/src/task-executor.js +44 -3
  24. package/dist/src/teamauto/github-client.js +107 -5
  25. package/dist/src/teamauto/repo-sync.js +172 -26
  26. package/dist/src/teamauto/scanner.js +22 -1
  27. package/dist/src/teamauto/scheduler.js +988 -190
  28. package/dist/src/teamauto/store.js +171 -3
  29. package/dist/src/teamauto/write-payload-guard.js +209 -0
  30. package/dist/src/types.js +11 -3
  31. package/dist/src/ui/app.js +2 -2
  32. package/dist/src/worker/tools.js +5 -0
  33. package/dist/src/worker/worker-service.js +13 -1
  34. package/dist/src/workspace-browser.js +14 -0
  35. package/openclaw.plugin.json +5 -5
  36. package/package.json +4 -2
  37. package/src/config.ts +3 -3
  38. package/src/controller/config-routes.ts +7 -3
  39. package/src/controller/controller-service.ts +12 -1
  40. package/src/controller/http-server.ts +2 -2
  41. package/src/controller/managed-gateway-process.ts +17 -1
  42. package/src/controller/provisioning/backend-contract.ts +4 -0
  43. package/src/controller/provisioning/container-shared.ts +6 -1
  44. package/src/controller/provisioning/docker.ts +1 -1
  45. package/src/controller/provisioning/kubernetes.ts +1 -1
  46. package/src/controller/provisioning/process-supervisor.ts +23 -1
  47. package/src/controller/provisioning-config.ts +9 -0
  48. package/src/controller/route-table.ts +2 -2
  49. package/src/controller/security.ts +30 -15
  50. package/src/controller/task-assignment.ts +128 -1
  51. package/src/controller/task-results.ts +33 -3
  52. package/src/controller/task-routes.ts +64 -2
  53. package/src/controller/tunnel-manager.ts +12 -1
  54. package/src/controller/tunnel-routes.ts +11 -0
  55. package/src/controller/worker-provisioning.ts +35 -0
  56. package/src/controller/worker-routes.ts +21 -7
  57. package/src/controller/workspace-routes.ts +17 -2
  58. package/src/openclaw-workspace.ts +43 -23
  59. package/src/task-executor.ts +46 -3
  60. package/src/teamauto/github-client.ts +103 -5
  61. package/src/teamauto/repo-sync.ts +158 -23
  62. package/src/teamauto/scanner.ts +23 -2
  63. package/src/teamauto/scheduler.ts +883 -113
  64. package/src/teamauto/store.ts +205 -3
  65. package/src/teamauto/write-payload-guard.ts +222 -0
  66. package/src/types.ts +30 -7
  67. package/src/ui/app.js +2 -2
  68. package/src/worker/tools.ts +5 -0
  69. package/src/worker/worker-service.ts +15 -1
  70. package/src/workspace-browser.ts +15 -0
@@ -18,6 +18,10 @@ export type TeamAutoActionPolicy = {
18
18
  prReview: boolean;
19
19
  createPR: boolean;
20
20
  fullReview: "off" | "weekly" | "daily";
21
+ /** #pr-rework: pick up fresh review activity on OUR delivered PRs and
22
+ * rework them (developer role, write mode). Default true - closing the
23
+ * loop is the expected behavior for every deployment. */
24
+ prRework?: boolean;
21
25
  };
22
26
 
23
27
  export type TeamAutoKeywordFilter = {
@@ -65,6 +69,11 @@ export type TeamAutoRepo = {
65
69
  addedAt: number;
66
70
  lastSweepAt: number;
67
71
  lastSweepSummary: string | null;
72
+ // #5641: task failures surfaced in the next sweep summary. Incremented
73
+ // whenever a write-back is dead-lettered because its task failed without
74
+ // a result; read + reset by the sweep so owners see "failed N" next to
75
+ // "created N/N" instead of a silently dying leg.
76
+ failedTasksSinceLastSweep?: number;
68
77
  pausedReason: string | null;
69
78
  /** Consecutive auto-paused sweep failures; drives retry backoff (0/undefined = healthy). */
70
79
  sweepFailures?: number;
@@ -88,6 +97,9 @@ export type TeamAutoRepo = {
88
97
  export type TeamAutoWriteBack = {
89
98
  taskId: string;
90
99
  action: "issueComment" | "prComment" | "createIssue" | "createPR";
100
+ /** #5815: identical-error-text circuit breaker state. */
101
+ lastErrorText?: string;
102
+ lastErrorStreak?: number;
91
103
  repoId: string;
92
104
  targetId: number | null;
93
105
  doneAt: number | null;
@@ -95,6 +107,8 @@ export type TeamAutoWriteBack = {
95
107
  error: string | null;
96
108
  /** Joint full-review cycle id: same-cycle sections share one umbrella issue. */
97
109
  cycleKey?: string;
110
+ /** #5735: delivery-shape disambiguation for the ok activity line (umbrella-created vs section-appended-to-umbrella). */
111
+ deliveryNote?: string;
98
112
  /**
99
113
  * Issue #24: failed delivery attempts so far. Drives the retry backoff and
100
114
  * the terminal give-up marker instead of a sticky error that nothing ever
@@ -173,6 +187,34 @@ export type TeamAutoStore = {
173
187
  * stamp (and the bot's self-assignment) once per taskId so the next sweep
174
188
  * re-candidates naturally, while the dead-letter caps bound retries. */
175
189
  failedClaimRecovery?: Record<string, number>;
190
+ /** #5725: once-per-task guard for orphan-result alarms (completed with result, no write-back entry, no delivery line). */
191
+ orphanResultAlarms?: Record<string, number>;
192
+ /** #5736: durable delivered-ledger. doneAt write-back entries are pruned
193
+ * every pass and the activity ring is tiny - without this ledger every
194
+ * normally-delivered task re-alarms as an orphan hours later. taskId -> deliveredAt. */
195
+ deliveredResults?: Record<string, number>;
196
+ /** #5738: one-time ledger migration marker (seed from task state, pardoning pre-deploy history once). */
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>;
211
+ /** #5685 (ggcode, 2026-11-16): "repoId|cycleKey" -> umbrella issue number
212
+ * for joint full reviews. Done write-back entries are pruned at end-of-pass,
213
+ * so an in-store peer scan cannot carry the umbrella pointer across passes
214
+ * (or restarts) and same-cycle sections each minted a duplicate umbrella
215
+ * (live: cycle 20772 -> ggcode issues #5686/#5687/#5688, zero section
216
+ * comments). Bounded to the newest 100 cycles. */
217
+ fullReviewUmbrellas?: Record<string, number>;
176
218
  };
177
219
 
178
220
  export function defaultPolicy(): TeamAutoRepoPolicy {
@@ -197,6 +239,11 @@ function emptyStore(): TeamAutoStore {
197
239
  writebacks: [],
198
240
  activity: [],
199
241
  failedClaimRecovery: {},
242
+ orphanResultAlarms: {},
243
+ deliveredResults: {},
244
+ prDeliveries: {},
245
+ undeliveredPrAlarms: {},
246
+ fullReviewUmbrellas: {},
200
247
  budget: {
201
248
  maxTasksPerDay: 150,
202
249
  firstSweepDryRun: true,
@@ -236,8 +283,10 @@ const writeQueue: Promise<void>[] = [];
236
283
 
237
284
  export async function loadTeamAutoStore(): Promise<TeamAutoStore> {
238
285
  const { storeFile } = resolveTeamAutoPaths();
286
+ let baseFingerprint = "";
239
287
  try {
240
288
  const raw = await fs.readFile(storeFile, "utf8");
289
+ baseFingerprint = staleWriteFingerprint(raw);
241
290
  const parsed = JSON.parse(raw) as Partial<TeamAutoStore>;
242
291
  const store = emptyStore();
243
292
  if (Array.isArray(parsed.repos)) {
@@ -258,21 +307,174 @@ export async function loadTeamAutoStore(): Promise<TeamAutoStore> {
258
307
  if (parsed.failedClaimRecovery && typeof parsed.failedClaimRecovery === "object") {
259
308
  store.failedClaimRecovery = parsed.failedClaimRecovery as Record<string, number>;
260
309
  }
310
+ if (parsed.fullReviewUmbrellas && typeof parsed.fullReviewUmbrellas === "object") {
311
+ store.fullReviewUmbrellas = parsed.fullReviewUmbrellas as Record<string, number>;
312
+ }
313
+ // #5736 (ggcode): the orphan-alarm chain (#5725 -> #5736 -> #5738) learned
314
+ // this the hard way three times over - loadTeamAutoStore rebuilds the store
315
+ // field-by-field, so a persistence field missing from this copy list is
316
+ // dropped on EVERY 20s settle reload even though saveTeamAutoStore writes
317
+ // it to disk. With all three alarm fields missing, the alarm silently
318
+ // disarmed: deliveredResultsInit dropped => the one-time migration re-ran
319
+ // each pass and pardoned every completed in-window task (genuine #5725
320
+ // registration loss could never alarm again); deliveredResults dropped =>
321
+ // prune-time delivery records evaporated; orphanResultAlarms dropped =>
322
+ // the once-per-task gate reset (99 alarm lines in 80s live).
323
+ if (parsed.orphanResultAlarms && typeof parsed.orphanResultAlarms === "object") {
324
+ store.orphanResultAlarms = parsed.orphanResultAlarms as Record<string, number>;
325
+ }
326
+ if (parsed.deliveredResults && typeof parsed.deliveredResults === "object") {
327
+ store.deliveredResults = parsed.deliveredResults as Record<string, number>;
328
+ }
329
+ if (typeof parsed.deliveredResultsInit === "boolean") {
330
+ store.deliveredResultsInit = parsed.deliveredResultsInit;
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
+ }
261
343
  store.budget = { ...store.budget, ...(parsed.budget ?? {}) };
344
+ (store as TeamAutoStore & { __baseFp?: string }).__baseFp = baseFingerprint;
262
345
  return store;
263
346
  } catch {
264
347
  return emptyStore();
265
348
  }
266
349
  }
267
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
+
428
+ /** #5677 (ggcode, 2026-11-15): store-level async mutex. The 20s write-back
429
+ * reconcile re-reads the store from disk and saves the whole object; the
430
+ * sweep transaction (registerWriteback + summary) does the same. Without
431
+ * serialization their read-modify-write cycles interleave: reconcile reads
432
+ * BEFORE the sweep's entry save, then its tail-save clobbers the entry the
433
+ * sweep just persisted (live: b3f688c6/#5676 write-back vanished; 3 earlier
434
+ * legs survived by timing luck). Every load→mutate→save section must hold
435
+ * this lock; it is process-local (single controller per state dir). */
436
+ const storeLock: { tail: Promise<void> } = { tail: Promise.resolve() };
437
+ export async function withStoreLock<T>(section: () => Promise<T>): Promise<T> {
438
+ const prev = storeLock.tail;
439
+ let release!: () => void;
440
+ storeLock.tail = new Promise<void>((r) => { release = r; });
441
+ await prev;
442
+ try {
443
+ return await section();
444
+ } finally {
445
+ release();
446
+ }
447
+ }
448
+
268
449
  export async function saveTeamAutoStore(store: TeamAutoStore): Promise<void> {
269
450
  const { storeFile } = resolveTeamAutoPaths();
270
451
  await fs.mkdir(path.dirname(storeFile), { recursive: true });
271
- const tmp = `${storeFile}.tmp-${process.pid}-${Date.now()}`;
272
452
  const next = writeQueue.length ? writeQueue[writeQueue.length - 1].catch(() => {}) : Promise.resolve();
273
453
  const job = next.then(async () => {
274
- await fs.writeFile(tmp, JSON.stringify(store, null, 2) + "\n", { encoding: "utf8", mode: 0o600 });
275
- 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
+ }
276
478
  });
277
479
  writeQueue.push(job);
278
480
  writeQueue.splice(0, Math.max(0, writeQueue.length - 20));
@@ -0,0 +1,222 @@
1
+ /**
2
+ * #5704 (ggcode, 2026-11-16): LLM envelope/frame leakage into GitHub write
3
+ * surfaces. Three documented cases - a raw transport frame posted verbatim as
4
+ * an issue comment (#5699), a write timeout with nothing landed (#5687), and
5
+ * a PR body that was nothing but the frame JSON (#5703, PR<->issue linkage
6
+ * survived only via title). The frame shape:
7
+ *
8
+ * {"role":"assistant","content":[],"api":"openai-completions","provider":"zai",
9
+ * "model":"glm-5.3","usage":{...},"usageReport":{...},"contextUsage":{...}}
10
+ *
11
+ * reached GitHub because the reply-extraction fallback serialized the whole
12
+ * message object as prose (fixed at the extraction site in task-executor.ts),
13
+ * and nothing between task.result and the REST call ever asked "is this
14
+ * intended text?". This module is the write-channel half of the fix: every
15
+ * GitHub write body funnels through sanitizeGithubWriteBody - ordinary text
16
+ * passes through untouched, a frame with recoverable content is repaired to
17
+ * that content, a frame without recoverable content is rejected loudly
18
+ * (EnvelopeLeakError) so the write-back ladder fails terminally instead of
19
+ * retrying deterministic corruption or posting frame JSON.
20
+ */
21
+
22
+ /** Error-message prefix the write-back ladder keys terminal classification on. */
23
+ export const ENVELOPE_LEAK_MARKER = "[envelope-leak]";
24
+
25
+ export class EnvelopeLeakError extends Error {
26
+ constructor(message: string) {
27
+ super(ENVELOPE_LEAK_MARKER + " " + message);
28
+ this.name = "EnvelopeLeakError";
29
+ }
30
+ }
31
+
32
+ /** True when the message starts with a "{" and closes a top-level object. */
33
+ function leadingJsonObject(text: string): Record<string, unknown> | null {
34
+ const trimmed = String(text ?? "").trimStart();
35
+ if (!trimmed.startsWith("{")) {
36
+ return null;
37
+ }
38
+ let depth = 0;
39
+ let inString = false;
40
+ let escaped = false;
41
+ for (let i = 0; i < trimmed.length; i++) {
42
+ const ch = trimmed[i];
43
+ if (inString) {
44
+ if (escaped) {
45
+ escaped = false;
46
+ } else if (ch === "\\") {
47
+ escaped = true;
48
+ } else if (ch === '"') {
49
+ inString = false;
50
+ }
51
+ continue;
52
+ }
53
+ if (ch === '"') {
54
+ inString = true;
55
+ } else if (ch === "{") {
56
+ depth++;
57
+ } else if (ch === "}") {
58
+ depth--;
59
+ if (depth === 0) {
60
+ try {
61
+ const parsed: unknown = JSON.parse(trimmed.slice(0, i + 1));
62
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
63
+ return parsed as Record<string, unknown>;
64
+ }
65
+ return null;
66
+ } catch {
67
+ return null;
68
+ }
69
+ }
70
+ }
71
+ }
72
+ return null;
73
+ }
74
+
75
+ /**
76
+ * Frame signature: transport metadata keys that never appear in intended
77
+ * prose. role==="assistant" plus any one transport key is decisive (chat
78
+ * turns carry none of these); without the assistant role we require at
79
+ * least two transport keys AND a content field, so ordinary JSON bodies
80
+ * (result contracts, settings objects) never trip the guard.
81
+ */
82
+ export function looksLikeLlmEnvelopeFrame(value: Record<string, unknown>): boolean {
83
+ const transportKeys = ["api", "usage", "provider", "usageReport", "contextUsage"].filter(
84
+ (key) => key in value,
85
+ );
86
+ if (value.role === "assistant" && transportKeys.length >= 1) {
87
+ return true;
88
+ }
89
+ return transportKeys.length >= 2 && "content" in value;
90
+ }
91
+
92
+ /** Recover intended text from a frame's content field (string or text blocks). */
93
+ export function envelopeFrameContentText(frame: Record<string, unknown>): string | null {
94
+ const content: unknown = frame.content;
95
+ if (typeof content === "string") {
96
+ return content.trim() ? content : null;
97
+ }
98
+ if (Array.isArray(content)) {
99
+ const text = content
100
+ .filter(
101
+ (block): block is { type?: unknown; text?: unknown } =>
102
+ !!block && typeof block === "object" && (block as { type?: unknown }).type === "text",
103
+ )
104
+ .map((block) => (typeof block.text === "string" ? block.text : ""))
105
+ .filter(Boolean)
106
+ .join("\n")
107
+ .trim();
108
+ return text ? text : null;
109
+ }
110
+ return null;
111
+ }
112
+
113
+ /**
114
+ * Split a write payload into (frame?, recoverable text?).
115
+ * Returns false when the body is not a frame (ordinary text - pass through),
116
+ * null when it is a frame with no recoverable text (reject), and the
117
+ * recovered string when the frame carries content (repair). The scan reads
118
+ * only the LEADING object, so our own marker footer appended after the frame
119
+ * does not defeat detection, and prose that merely MENTIONS frame keys in
120
+ * backticks (audit reports like the #5704 watchdog sweep) passes untouched.
121
+ */
122
+ export function splitLlmEnvelopeFrame(body: string): string | null | false {
123
+ const frame = leadingJsonObject(body);
124
+ if (!frame || !looksLikeLlmEnvelopeFrame(frame)) {
125
+ return false;
126
+ }
127
+ return envelopeFrameContentText(frame);
128
+ }
129
+
130
+ /** A whole body line that is exactly one frame object (umbrella section
131
+ * bodies embed task.result as a block between the section header and the
132
+ * marker footer, so the leading-object scan alone cannot see them). */
133
+ function parseStandaloneFrameLine(line: string): Record<string, unknown> | null {
134
+ const trimmed = line.trim();
135
+ if (!trimmed.startsWith("{") || !trimmed.endsWith("}")) {
136
+ return null;
137
+ }
138
+ try {
139
+ const parsed: unknown = JSON.parse(trimmed);
140
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
141
+ const frame = parsed as Record<string, unknown>;
142
+ return looksLikeLlmEnvelopeFrame(frame) ? frame : null;
143
+ }
144
+ } catch {
145
+ /* not JSON - ordinary prose line */
146
+ }
147
+ return null;
148
+ }
149
+
150
+ /** Structural chrome around a deliverable: section headers, marker footers
151
+ * (the live footer shape is a bare "---" line followed by a
152
+ * "[teamclaw:<role>] autonomous via TeamClaw" line). */
153
+ function isNonSubstantiveLine(line: string): boolean {
154
+ const trimmed = line.trim();
155
+ if (!trimmed) {
156
+ return true;
157
+ }
158
+ if (trimmed.startsWith("#")) {
159
+ return true;
160
+ }
161
+ if (trimmed === "---" || trimmed === "***") {
162
+ return true;
163
+ }
164
+ if (/^\[teamclaw:/.test(trimmed)) {
165
+ return true;
166
+ }
167
+ return false;
168
+ }
169
+
170
+ /**
171
+ * Write-channel validator (#5704). Apply to every body GitHub-bound write
172
+ * sends. Ordinary text (including JSON that is not a transport frame) is
173
+ * returned unchanged; frames are repaired or rejected.
174
+ *
175
+ * Two detection shapes:
176
+ * 1. the payload IS a frame (with our footer possibly appended) - repair to
177
+ * the recovered content text, or reject when none exists;
178
+ * 2. the payload EMBEDS standalone frame lines (umbrella section bodies) -
179
+ * each is replaced by its recovered text (dropped when textless), and the
180
+ * write is rejected when nothing substantive remains besides chrome.
181
+ */
182
+ export function sanitizeGithubWriteBody(body: string, context: string): string {
183
+ const outcome = splitLlmEnvelopeFrame(body);
184
+ if (typeof outcome === "string") {
185
+ return outcome;
186
+ }
187
+ if (outcome === null) {
188
+ throw new EnvelopeLeakError(
189
+ context +
190
+ ": payload is a raw LLM transport envelope frame with no recoverable content text - write rejected (#5704)",
191
+ );
192
+ }
193
+
194
+ const lines = String(body ?? "").split("\n");
195
+ const mapped: string[] = [];
196
+ let touched = false;
197
+ let recoveredAny = false;
198
+ for (const line of lines) {
199
+ const frame = parseStandaloneFrameLine(line);
200
+ if (frame) {
201
+ touched = true;
202
+ const recovered = envelopeFrameContentText(frame);
203
+ if (recovered) {
204
+ recoveredAny = true;
205
+ mapped.push(recovered);
206
+ }
207
+ continue;
208
+ }
209
+ mapped.push(line);
210
+ }
211
+ if (!touched) {
212
+ return body;
213
+ }
214
+ const substantive = mapped.filter((line) => !isNonSubstantiveLine(line));
215
+ if (!recoveredAny && substantive.length === 0) {
216
+ throw new EnvelopeLeakError(
217
+ context +
218
+ ": payload embeds only LLM transport envelope frame lines with no recoverable text - write rejected (#5704)",
219
+ );
220
+ }
221
+ return mapped.join("\n");
222
+ }
package/src/types.ts CHANGED
@@ -158,6 +158,16 @@ export type TaskInfo = {
158
158
  /** Surviving progress snapshot for interrupted executions (resume support). */
159
159
  checkpoint?: TaskCheckpoint;
160
160
  resumeAttempt?: number;
161
+ /**
162
+ * #5740 (ggcode, 2026-11-17): assignment backoff after a claim-at-dequeue
163
+ * ELIGIBILITY-CHECK failure reverted a dispatched assignment. While
164
+ * assignmentHoldUntil is in the future, the auto-assign round skips this
165
+ * pending task; assignmentHoldCount grows the hold exponentially (20s
166
+ * doubling, 160s cap) across consecutive failures and is reset by any
167
+ * conclusive claim outcome.
168
+ */
169
+ assignmentHoldUntil?: number;
170
+ assignmentHoldCount?: number;
161
171
  /**
162
172
  * Design 2.4 workflow-chain membership: set ONLY by the workflow engine
163
173
  * (controller/workflow-routes.ts) when it creates a step task, never by
@@ -598,8 +608,8 @@ export type PluginConfig = {
598
608
  agentIsolationMode: AgentIsolationMode;
599
609
  /**
600
610
  * Issue #23: controller device-pairing security options. Parsed with
601
- * safe defaults (autoPair: true) so hand-built configs without the key
602
- * 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.
603
613
  */
604
614
  security?: SecurityConfig;
605
615
  /**
@@ -614,6 +624,11 @@ export type PluginConfig = {
614
624
  workerProvisioningControllerUrl: string;
615
625
  workerProvisioningRoles: RoleId[];
616
626
  workerProvisioningMinPerRole: number;
627
+ /** #rate-limit-999: provider rate-limit retries for provisioned workers
628
+ * (passed through to every provisioner backend and written into the
629
+ * worker's settings.json). teamclaw workloads are long-running and
630
+ * unattended - the host default of 9 abandons tasks nobody watches. */
631
+ workerRateLimitMaxRetries: number;
617
632
  workerProvisioningMaxPerRole: number;
618
633
  workerProvisioningIdleTtlMs: number;
619
634
  workerProvisioningStartupTimeoutMs: number;
@@ -648,8 +663,8 @@ export type WorkerIdentity = {
648
663
  // L0 local - no devices persisted => no authentication at all (the
649
664
  // historical behavior; a state without `security` is L0)
650
665
  // L1 LAN - LAN peers (loopback / RFC1918 / ULA / link-local) may
651
- // self-pair via POST /api/v1/security/pair-auto while
652
- // 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)
653
668
  // L2 exposed - one-shot 60s pairing codes minted by an authenticated
654
669
  // device or the loopback console
655
670
  // The user never configures a token and the UI never shows a login page.
@@ -920,14 +935,16 @@ export function parsePluginConfig(raw: Record<string, unknown> = {}): PluginConf
920
935
  ? raw.agentIsolationMode
921
936
  : "independent";
922
937
 
923
- // Issue #23: security.autoPair defaults to true (L1 zero-input LAN
924
- // 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.
925
942
  const rawSecurity = raw.security;
926
943
  const rawAutoPair = rawSecurity && typeof rawSecurity === "object" && !Array.isArray(rawSecurity)
927
944
  ? (rawSecurity as { autoPair?: unknown }).autoPair
928
945
  : undefined;
929
946
  const security: SecurityConfig = {
930
- autoPair: typeof rawAutoPair === "boolean" ? rawAutoPair : true,
947
+ autoPair: typeof rawAutoPair === "boolean" ? rawAutoPair : false,
931
948
  };
932
949
 
933
950
  // Issue #23 (client wave): the paired device token, if this instance
@@ -958,6 +975,11 @@ export function parsePluginConfig(raw: Record<string, unknown> = {}): PluginConf
958
975
  ? Math.floor(raw.workerProvisioningMaxPerRole)
959
976
  : 3;
960
977
  const workerProvisioningMaxPerRole = Math.max(rawProvisioningMaxPerRole, workerProvisioningMinPerRole);
978
+ const workerRateLimitMaxRetries = typeof raw.workerRateLimitMaxRetries === "number" && raw.workerRateLimitMaxRetries >= 0
979
+ ? Math.floor(raw.workerRateLimitMaxRetries)
980
+ : 999; // #retry-999: operators WANT persistent retries (999); the host-side
981
+ // hard ceiling that clamped everything to 9 is exempted for explicit
982
+ // budgets (see openclaw failover-retry-controller #retry-999).
961
983
  const workerProvisioningIdleTtlMs = typeof raw.workerProvisioningIdleTtlMs === "number" && raw.workerProvisioningIdleTtlMs >= 1000
962
984
  ? raw.workerProvisioningIdleTtlMs
963
985
  : 120_000;
@@ -1050,6 +1072,7 @@ export function parsePluginConfig(raw: Record<string, unknown> = {}): PluginConf
1050
1072
  workerProvisioningMinPerRole,
1051
1073
  workerProvisioningMaxPerRole,
1052
1074
  workerProvisioningIdleTtlMs,
1075
+ workerRateLimitMaxRetries,
1053
1076
  workerProvisioningStartupTimeoutMs,
1054
1077
  workerProvisioningImage,
1055
1078
  workerProvisioningPassEnv,
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)",
@@ -587,6 +587,11 @@ export function createWorkerTools(deps: WorkerToolsDeps) {
587
587
  if (status) {
588
588
  patch.status = status;
589
589
  }
590
+ // #5740 (ggcode): identify the reporting worker so the controller
591
+ // can apply the same stale-worker guard as the result routes.
592
+ if (typeof identity.workerId === "string" && identity.workerId) {
593
+ patch.workerId = identity.workerId;
594
+ }
590
595
  if (progressContract) {
591
596
  patch.progressContract = progressContract;
592
597
  }
@@ -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}`);