@teamclaws/teamclaw 2026.11.4 → 2026.11.6

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 (47) hide show
  1. package/dist/src/controller/config-routes.js +7 -3
  2. package/dist/src/controller/controller-service.js +12 -1
  3. package/dist/src/controller/provisioning/container-shared.js +6 -1
  4. package/dist/src/controller/provisioning/docker.js +1 -1
  5. package/dist/src/controller/provisioning/kubernetes.js +1 -1
  6. package/dist/src/controller/provisioning/process-supervisor.js +12 -1
  7. package/dist/src/controller/provisioning-config.js +8 -0
  8. package/dist/src/controller/task-assignment.js +65 -2
  9. package/dist/src/controller/task-results.js +34 -3
  10. package/dist/src/controller/task-routes.js +24 -1
  11. package/dist/src/controller/worker-provisioning.js +35 -0
  12. package/dist/src/controller/worker-routes.js +21 -6
  13. package/dist/src/openclaw-workspace.js +39 -20
  14. package/dist/src/task-executor.js +44 -3
  15. package/dist/src/teamauto/github-client.js +88 -5
  16. package/dist/src/teamauto/repo-sync.js +90 -5
  17. package/dist/src/teamauto/scanner.js +22 -1
  18. package/dist/src/teamauto/scheduler.js +587 -182
  19. package/dist/src/teamauto/store.js +46 -0
  20. package/dist/src/teamauto/write-payload-guard.js +209 -0
  21. package/dist/src/types.js +6 -0
  22. package/dist/src/worker/tools.js +5 -0
  23. package/openclaw.plugin.json +1 -1
  24. package/package.json +1 -1
  25. package/src/controller/config-routes.ts +7 -3
  26. package/src/controller/controller-service.ts +12 -1
  27. package/src/controller/provisioning/backend-contract.ts +4 -0
  28. package/src/controller/provisioning/container-shared.ts +6 -1
  29. package/src/controller/provisioning/docker.ts +1 -1
  30. package/src/controller/provisioning/kubernetes.ts +1 -1
  31. package/src/controller/provisioning/process-supervisor.ts +12 -1
  32. package/src/controller/provisioning-config.ts +9 -0
  33. package/src/controller/task-assignment.ts +71 -1
  34. package/src/controller/task-results.ts +33 -3
  35. package/src/controller/task-routes.ts +25 -1
  36. package/src/controller/worker-provisioning.ts +35 -0
  37. package/src/controller/worker-routes.ts +21 -7
  38. package/src/openclaw-workspace.ts +43 -23
  39. package/src/task-executor.ts +46 -3
  40. package/src/teamauto/github-client.ts +83 -5
  41. package/src/teamauto/repo-sync.ts +100 -4
  42. package/src/teamauto/scanner.ts +23 -2
  43. package/src/teamauto/scheduler.ts +503 -106
  44. package/src/teamauto/store.ts +72 -0
  45. package/src/teamauto/write-payload-guard.ts +222 -0
  46. package/src/types.ts +21 -0
  47. package/src/worker/tools.ts +5 -0
@@ -45,6 +45,9 @@ function emptyStore() {
45
45
  writebacks: [],
46
46
  activity: [],
47
47
  failedClaimRecovery: {},
48
+ orphanResultAlarms: {},
49
+ deliveredResults: {},
50
+ fullReviewUmbrellas: {},
48
51
  budget: {
49
52
  maxTasksPerDay: 150,
50
53
  firstSweepDryRun: true,
@@ -105,6 +108,28 @@ export async function loadTeamAutoStore() {
105
108
  if (parsed.failedClaimRecovery && typeof parsed.failedClaimRecovery === "object") {
106
109
  store.failedClaimRecovery = parsed.failedClaimRecovery;
107
110
  }
111
+ if (parsed.fullReviewUmbrellas && typeof parsed.fullReviewUmbrellas === "object") {
112
+ store.fullReviewUmbrellas = parsed.fullReviewUmbrellas;
113
+ }
114
+ // #5736 (ggcode): the orphan-alarm chain (#5725 -> #5736 -> #5738) learned
115
+ // this the hard way three times over - loadTeamAutoStore rebuilds the store
116
+ // field-by-field, so a persistence field missing from this copy list is
117
+ // dropped on EVERY 20s settle reload even though saveTeamAutoStore writes
118
+ // it to disk. With all three alarm fields missing, the alarm silently
119
+ // disarmed: deliveredResultsInit dropped => the one-time migration re-ran
120
+ // each pass and pardoned every completed in-window task (genuine #5725
121
+ // registration loss could never alarm again); deliveredResults dropped =>
122
+ // prune-time delivery records evaporated; orphanResultAlarms dropped =>
123
+ // the once-per-task gate reset (99 alarm lines in 80s live).
124
+ if (parsed.orphanResultAlarms && typeof parsed.orphanResultAlarms === "object") {
125
+ store.orphanResultAlarms = parsed.orphanResultAlarms;
126
+ }
127
+ if (parsed.deliveredResults && typeof parsed.deliveredResults === "object") {
128
+ store.deliveredResults = parsed.deliveredResults;
129
+ }
130
+ if (typeof parsed.deliveredResultsInit === "boolean") {
131
+ store.deliveredResultsInit = parsed.deliveredResultsInit;
132
+ }
108
133
  store.budget = { ...store.budget, ...(parsed.budget ?? {}) };
109
134
  return store;
110
135
  }
@@ -112,6 +137,27 @@ export async function loadTeamAutoStore() {
112
137
  return emptyStore();
113
138
  }
114
139
  }
140
+ /** #5677 (ggcode, 2026-11-15): store-level async mutex. The 20s write-back
141
+ * reconcile re-reads the store from disk and saves the whole object; the
142
+ * sweep transaction (registerWriteback + summary) does the same. Without
143
+ * serialization their read-modify-write cycles interleave: reconcile reads
144
+ * BEFORE the sweep's entry save, then its tail-save clobbers the entry the
145
+ * sweep just persisted (live: b3f688c6/#5676 write-back vanished; 3 earlier
146
+ * legs survived by timing luck). Every load→mutate→save section must hold
147
+ * this lock; it is process-local (single controller per state dir). */
148
+ const storeLock = { tail: Promise.resolve() };
149
+ export async function withStoreLock(section) {
150
+ const prev = storeLock.tail;
151
+ let release;
152
+ storeLock.tail = new Promise((r) => { release = r; });
153
+ await prev;
154
+ try {
155
+ return await section();
156
+ }
157
+ finally {
158
+ release();
159
+ }
160
+ }
115
161
  export async function saveTeamAutoStore(store) {
116
162
  const { storeFile } = resolveTeamAutoPaths();
117
163
  await fs.mkdir(path.dirname(storeFile), { recursive: true });
@@ -0,0 +1,209 @@
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
+ /** Error-message prefix the write-back ladder keys terminal classification on. */
22
+ export const ENVELOPE_LEAK_MARKER = "[envelope-leak]";
23
+ export class EnvelopeLeakError extends Error {
24
+ constructor(message) {
25
+ super(ENVELOPE_LEAK_MARKER + " " + message);
26
+ this.name = "EnvelopeLeakError";
27
+ }
28
+ }
29
+ /** True when the message starts with a "{" and closes a top-level object. */
30
+ function leadingJsonObject(text) {
31
+ const trimmed = String(text ?? "").trimStart();
32
+ if (!trimmed.startsWith("{")) {
33
+ return null;
34
+ }
35
+ let depth = 0;
36
+ let inString = false;
37
+ let escaped = false;
38
+ for (let i = 0; i < trimmed.length; i++) {
39
+ const ch = trimmed[i];
40
+ if (inString) {
41
+ if (escaped) {
42
+ escaped = false;
43
+ }
44
+ else if (ch === "\\") {
45
+ escaped = true;
46
+ }
47
+ else if (ch === '"') {
48
+ inString = false;
49
+ }
50
+ continue;
51
+ }
52
+ if (ch === '"') {
53
+ inString = true;
54
+ }
55
+ else if (ch === "{") {
56
+ depth++;
57
+ }
58
+ else if (ch === "}") {
59
+ depth--;
60
+ if (depth === 0) {
61
+ try {
62
+ const parsed = JSON.parse(trimmed.slice(0, i + 1));
63
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
64
+ return parsed;
65
+ }
66
+ return null;
67
+ }
68
+ catch {
69
+ return null;
70
+ }
71
+ }
72
+ }
73
+ }
74
+ return null;
75
+ }
76
+ /**
77
+ * Frame signature: transport metadata keys that never appear in intended
78
+ * prose. role==="assistant" plus any one transport key is decisive (chat
79
+ * turns carry none of these); without the assistant role we require at
80
+ * least two transport keys AND a content field, so ordinary JSON bodies
81
+ * (result contracts, settings objects) never trip the guard.
82
+ */
83
+ export function looksLikeLlmEnvelopeFrame(value) {
84
+ const transportKeys = ["api", "usage", "provider", "usageReport", "contextUsage"].filter((key) => key in value);
85
+ if (value.role === "assistant" && transportKeys.length >= 1) {
86
+ return true;
87
+ }
88
+ return transportKeys.length >= 2 && "content" in value;
89
+ }
90
+ /** Recover intended text from a frame's content field (string or text blocks). */
91
+ export function envelopeFrameContentText(frame) {
92
+ const content = frame.content;
93
+ if (typeof content === "string") {
94
+ return content.trim() ? content : null;
95
+ }
96
+ if (Array.isArray(content)) {
97
+ const text = content
98
+ .filter((block) => !!block && typeof block === "object" && block.type === "text")
99
+ .map((block) => (typeof block.text === "string" ? block.text : ""))
100
+ .filter(Boolean)
101
+ .join("\n")
102
+ .trim();
103
+ return text ? text : null;
104
+ }
105
+ return null;
106
+ }
107
+ /**
108
+ * Split a write payload into (frame?, recoverable text?).
109
+ * Returns false when the body is not a frame (ordinary text - pass through),
110
+ * null when it is a frame with no recoverable text (reject), and the
111
+ * recovered string when the frame carries content (repair). The scan reads
112
+ * only the LEADING object, so our own marker footer appended after the frame
113
+ * does not defeat detection, and prose that merely MENTIONS frame keys in
114
+ * backticks (audit reports like the #5704 watchdog sweep) passes untouched.
115
+ */
116
+ export function splitLlmEnvelopeFrame(body) {
117
+ const frame = leadingJsonObject(body);
118
+ if (!frame || !looksLikeLlmEnvelopeFrame(frame)) {
119
+ return false;
120
+ }
121
+ return envelopeFrameContentText(frame);
122
+ }
123
+ /** A whole body line that is exactly one frame object (umbrella section
124
+ * bodies embed task.result as a block between the section header and the
125
+ * marker footer, so the leading-object scan alone cannot see them). */
126
+ function parseStandaloneFrameLine(line) {
127
+ const trimmed = line.trim();
128
+ if (!trimmed.startsWith("{") || !trimmed.endsWith("}")) {
129
+ return null;
130
+ }
131
+ try {
132
+ const parsed = JSON.parse(trimmed);
133
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
134
+ const frame = parsed;
135
+ return looksLikeLlmEnvelopeFrame(frame) ? frame : null;
136
+ }
137
+ }
138
+ catch {
139
+ /* not JSON - ordinary prose line */
140
+ }
141
+ return null;
142
+ }
143
+ /** Structural chrome around a deliverable: section headers, marker footers
144
+ * (the live footer shape is a bare "---" line followed by a
145
+ * "[teamclaw:<role>] autonomous via TeamClaw" line). */
146
+ function isNonSubstantiveLine(line) {
147
+ const trimmed = line.trim();
148
+ if (!trimmed) {
149
+ return true;
150
+ }
151
+ if (trimmed.startsWith("#")) {
152
+ return true;
153
+ }
154
+ if (trimmed === "---" || trimmed === "***") {
155
+ return true;
156
+ }
157
+ if (/^\[teamclaw:/.test(trimmed)) {
158
+ return true;
159
+ }
160
+ return false;
161
+ }
162
+ /**
163
+ * Write-channel validator (#5704). Apply to every body GitHub-bound write
164
+ * sends. Ordinary text (including JSON that is not a transport frame) is
165
+ * returned unchanged; frames are repaired or rejected.
166
+ *
167
+ * Two detection shapes:
168
+ * 1. the payload IS a frame (with our footer possibly appended) - repair to
169
+ * the recovered content text, or reject when none exists;
170
+ * 2. the payload EMBEDS standalone frame lines (umbrella section bodies) -
171
+ * each is replaced by its recovered text (dropped when textless), and the
172
+ * write is rejected when nothing substantive remains besides chrome.
173
+ */
174
+ export function sanitizeGithubWriteBody(body, context) {
175
+ const outcome = splitLlmEnvelopeFrame(body);
176
+ if (typeof outcome === "string") {
177
+ return outcome;
178
+ }
179
+ if (outcome === null) {
180
+ throw new EnvelopeLeakError(context +
181
+ ": payload is a raw LLM transport envelope frame with no recoverable content text - write rejected (#5704)");
182
+ }
183
+ const lines = String(body ?? "").split("\n");
184
+ const mapped = [];
185
+ let touched = false;
186
+ let recoveredAny = false;
187
+ for (const line of lines) {
188
+ const frame = parseStandaloneFrameLine(line);
189
+ if (frame) {
190
+ touched = true;
191
+ const recovered = envelopeFrameContentText(frame);
192
+ if (recovered) {
193
+ recoveredAny = true;
194
+ mapped.push(recovered);
195
+ }
196
+ continue;
197
+ }
198
+ mapped.push(line);
199
+ }
200
+ if (!touched) {
201
+ return body;
202
+ }
203
+ const substantive = mapped.filter((line) => !isNonSubstantiveLine(line));
204
+ if (!recoveredAny && substantive.length === 0) {
205
+ throw new EnvelopeLeakError(context +
206
+ ": payload embeds only LLM transport envelope frame lines with no recoverable text - write rejected (#5704)");
207
+ }
208
+ return mapped.join("\n");
209
+ }
package/dist/src/types.js CHANGED
@@ -140,6 +140,11 @@ export function parsePluginConfig(raw = {}) {
140
140
  ? Math.floor(raw.workerProvisioningMaxPerRole)
141
141
  : 3;
142
142
  const workerProvisioningMaxPerRole = Math.max(rawProvisioningMaxPerRole, workerProvisioningMinPerRole);
143
+ const workerRateLimitMaxRetries = typeof raw.workerRateLimitMaxRetries === "number" && raw.workerRateLimitMaxRetries >= 0
144
+ ? Math.floor(raw.workerRateLimitMaxRetries)
145
+ : 999; // #retry-999: operators WANT persistent retries (999); the host-side
146
+ // hard ceiling that clamped everything to 9 is exempted for explicit
147
+ // budgets (see openclaw failover-retry-controller #retry-999).
143
148
  const workerProvisioningIdleTtlMs = typeof raw.workerProvisioningIdleTtlMs === "number" && raw.workerProvisioningIdleTtlMs >= 1000
144
149
  ? raw.workerProvisioningIdleTtlMs
145
150
  : 120_000;
@@ -232,6 +237,7 @@ export function parsePluginConfig(raw = {}) {
232
237
  workerProvisioningMinPerRole,
233
238
  workerProvisioningMaxPerRole,
234
239
  workerProvisioningIdleTtlMs,
240
+ workerRateLimitMaxRetries,
235
241
  workerProvisioningStartupTimeoutMs,
236
242
  workerProvisioningImage,
237
243
  workerProvisioningPassEnv,
@@ -529,6 +529,11 @@ export function createWorkerTools(deps) {
529
529
  if (status) {
530
530
  patch.status = status;
531
531
  }
532
+ // #5740 (ggcode): identify the reporting worker so the controller
533
+ // can apply the same stale-worker guard as the result routes.
534
+ if (typeof identity.workerId === "string" && identity.workerId) {
535
+ patch.workerId = identity.workerId;
536
+ }
532
537
  if (progressContract) {
533
538
  patch.progressContract = progressContract;
534
539
  }
@@ -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.11.4",
5
+ "version": "2026.11.6",
6
6
  "activation": {
7
7
  "onStartup": true
8
8
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teamclaws/teamclaw",
3
- "version": "2026.11.4",
3
+ "version": "2026.11.6",
4
4
  "description": "OpenClaw virtual software team orchestration plugin - controller, role-based workers, Web UI with internet tunnel sharing",
5
5
  "private": false,
6
6
  "keywords": [
@@ -51,7 +51,10 @@ function teamConfigGetRoute(ctx: RouteContext): void {
51
51
  workerProvisioningMaxPerRole: c.workerProvisioningMaxPerRole,
52
52
  workerProvisioningIdleTtlMs: c.workerProvisioningIdleTtlMs,
53
53
  // k8s controllers run on ephemeral container FS: declare it up front.
54
- persistenceMode: c.workerProvisioningType === "kubernetes" ? "memory-only" : "host-config",
54
+ // #hot-reload: persistence is PLUGIN-STATE (beside team-state.json), not
55
+ // host config - a host-config write made the host reload the whole
56
+ // plugin on every PATCH (see openclaw-workspace.ts #hot-reload note).
57
+ persistenceMode: "plugin-state",
55
58
  });
56
59
  }
57
60
 
@@ -105,8 +108,9 @@ async function teamConfigPatchRoute(ctx: RouteContext): Promise<void> {
105
108
  applied.workerProvisioningMaxPerRole = minR;
106
109
  }
107
110
 
108
- // 2) Persist (host config) unless the controller itself runs on an
109
- // ephemeral container FS.
111
+ // 2) Persist to PLUGIN STATE (never the host config - see
112
+ // openclaw-workspace.ts #hot-reload: host writes triggered full plugin
113
+ // reloads that killed in-flight work and usually failed to apply).
110
114
  const memoryOnly = deps.config.workerProvisioningType === "kubernetes";
111
115
  let persisted = false;
112
116
  if (!memoryOnly) {
@@ -17,7 +17,7 @@ import { resumeTeamProfileSwitch } from "./profile-switch.js";
17
17
  import { TaskRouter } from "./task-router.js";
18
18
  import { MessageRouter } from "./message-router.js";
19
19
  import { TeamWebSocketServer, type WsEvent } from "./websocket.js";
20
- import { ensureOpenClawWorkspaceMemoryDir, buildTeamClawAgentSessionKey } from "../openclaw-workspace.js";
20
+ import { ensureOpenClawWorkspaceMemoryDir, buildTeamClawAgentSessionKey, loadProvisioningHotConfig } from "../openclaw-workspace.js";
21
21
  import { ensureControllerGitRepo } from "../git-collaboration.js";
22
22
  import { WorkerProvisioningManager } from "./worker-provisioning.js";
23
23
  import { PreviewManager } from "./preview-manager.js";
@@ -135,6 +135,17 @@ export function createControllerService(deps: ControllerServiceDeps): OpenClawPl
135
135
  async start(_ctx: OpenClawPluginServiceContext) {
136
136
  const serviceStartedAt = Date.now();
137
137
  await ensureOpenClawWorkspaceMemoryDir(logger);
138
+ // #hot-reload: re-apply the persisted hot-config overrides (provisioning
139
+ // caps) from PLUGIN STATE - they intentionally live outside the host
140
+ // config so a PATCH never triggers a plugin reload (see
141
+ // openclaw-workspace.ts #hot-reload for the failure mode this replaces).
142
+ const hotOverrides = await loadProvisioningHotConfig();
143
+ if (hotOverrides) {
144
+ for (const [key, value] of Object.entries(hotOverrides)) {
145
+ (config as unknown as Record<string, number>)[key] = value;
146
+ }
147
+ logger.info(`Controller: provisioning hot-config re-applied from plugin state: ${JSON.stringify(hotOverrides)}`);
148
+ }
138
149
 
139
150
  // Load or create team state. The active profile is resolved FIRST (from
140
151
  // the restored TeamState.profileId, or the config bootstrap value on
@@ -21,6 +21,10 @@ export type LaunchSpec = {
21
21
  workspaceDir?: string;
22
22
  env: Record<string, string>;
23
23
  configJson: string;
24
+ /** #rate-limit-999: provider rate-limit retry budget written into the
25
+ * worker's settings.json by every backend (process writes the file; docker/
26
+ * kubernetes embed it in the bootstrap script). */
27
+ rateLimitMaxRetries: number;
24
28
  };
25
29
 
26
30
  export type LaunchResult = {
@@ -60,7 +60,7 @@ function sanitizeTrailingSegment(value: string, maxLength: number, fallback: str
60
60
  return normalized || fallback;
61
61
  }
62
62
 
63
- export function buildContainerBootstrapScript(): string {
63
+ export function buildContainerBootstrapScript(rateLimitMaxRetries: number): string {
64
64
  return [
65
65
  "set -eu",
66
66
  "mkdir -p \"$OPENCLAW_STATE_DIR\"",
@@ -79,6 +79,11 @@ export function buildContainerBootstrapScript(): string {
79
79
  // creates it owner-only). Chosen over unlink-then-write to avoid the
80
80
  // no-config window mid-rewrite.
81
81
  "node -e 'const fs=require(\"fs\"); const configPath=process.env.OPENCLAW_CONFIG_PATH; const raw=Buffer.from(process.env.TEAMCLAW_BOOTSTRAP_CONFIG_B64||\"\", \"base64\").toString(\"utf8\"); fs.mkdirSync(require(\"path\").dirname(configPath), { recursive: true }); try { fs.chmodSync(configPath, 0o600); } catch (err) { if (err.code !== \"ENOENT\") throw err; } fs.writeFileSync(configPath, raw, { mode: 0o600 });'",
82
+ // #rate-limit-999 (v2): openclaw reads retry settings from its AGENT scope
83
+ // <stateDir>/agents/teamclaw/agent/settings.json (settings-manager:
84
+ // join(agentDir, "settings.json")), NOT from the state dir root. Write the
85
+ // real layer first, plus the legacy root copy for other layouts.
86
+ `node -e 'const fs=require("fs"); const p=require("path"); const sd=p.dirname(process.env.OPENCLAW_CONFIG_PATH); const ad=p.join(sd, "agents", "teamclaw", "agent"); fs.mkdirSync(ad, { recursive: true }); fs.writeFileSync(p.join(ad, "settings.json"), JSON.stringify({retry:{enabled:true,provider:{maxRetries:${rateLimitMaxRetries}}}}, null, 2)+"\\n", { mode: 0o600 }); fs.writeFileSync(p.join(sd, "settings.json"), JSON.stringify({retry:{enabled:true,provider:{maxRetries:${rateLimitMaxRetries}}}}, null, 2)+"\\n", { mode: 0o600 });'`,
82
87
  "exec node dist/index.js gateway --allow-unconfigured",
83
88
  ].join("\n");
84
89
  }
@@ -71,7 +71,7 @@ export class DockerProvisioner implements WorkerProvisionerBackend {
71
71
 
72
72
  const containerConfig: Record<string, unknown> = {
73
73
  Image: this.config.workerProvisioningImage,
74
- Cmd: ["sh", "-lc", buildContainerBootstrapScript()],
74
+ Cmd: ["sh", "-lc", buildContainerBootstrapScript(spec.rateLimitMaxRetries)],
75
75
  Env: Object.entries(env).map(([key, value]) => `${key}=${value}`),
76
76
  User: "root",
77
77
  Labels: {
@@ -192,7 +192,7 @@ export class KubernetesProvisioner implements WorkerProvisionerBackend {
192
192
  name: "worker",
193
193
  image: this.config.workerProvisioningImage,
194
194
  command: ["sh", "-lc"],
195
- args: [buildContainerBootstrapScript()],
195
+ args: [buildContainerBootstrapScript(spec.rateLimitMaxRetries)],
196
196
  env: Object.entries(env).map(([name, value]) => ({ name, value })),
197
197
  volumeMounts: hasPersistentWorkspace
198
198
  ? [
@@ -9,7 +9,7 @@ import path from "node:path";
9
9
  import readline from "node:readline";
10
10
  import { spawn, type ChildProcess } from "node:child_process";
11
11
  import type { PluginLogger } from "../../../api.js";
12
- import { resolveControllerTeamclawEntryPath } from "../provisioning-config.js";
12
+ import { resolveControllerTeamclawEntryPath, workerRetrySettingsJson } from "../provisioning-config.js";
13
13
  import {
14
14
  resolveDefaultOpenClawConfigPath,
15
15
  resolveDefaultTeamClawRuntimeRootDir,
@@ -85,6 +85,17 @@ export class ProcessProvisioner implements WorkerProvisionerBackend {
85
85
  if (err.code !== "ENOENT") throw err;
86
86
  });
87
87
  await fs.writeFile(configPath, spec.configJson, { encoding: "utf8", mode: 0o600 });
88
+ // #rate-limit-999 (v2, user report 2026-11-14 night: retries STILL stopped
89
+ // at 9): openclaw does NOT read stateDir/settings.json - its global scope
90
+ // is <stateDir>/agents/<agentId>/agent/settings.json (verified live:
91
+ // agents/teamclaw/agent/ exists in every provisioned worker; settings-
92
+ // manager reads join(agentDir, "settings.json")). The agent id for our
93
+ // workers is deterministic ("teamclaw"). Write BOTH layers: the real one
94
+ // plus the legacy stateDir copy (harmless; future-proofs other layouts).
95
+ const workerAgentSettingsDir = path.join(stateDir, "agents", "teamclaw", "agent");
96
+ await fs.mkdir(workerAgentSettingsDir, { recursive: true }).catch(() => { /* exists */ });
97
+ await fs.writeFile(path.join(workerAgentSettingsDir, "settings.json"), workerRetrySettingsJson(spec.rateLimitMaxRetries), { encoding: "utf8", mode: 0o600 }).catch(() => { /* best effort */ });
98
+ await fs.writeFile(path.join(stateDir, "settings.json"), workerRetrySettingsJson(spec.rateLimitMaxRetries), { encoding: "utf8", mode: 0o600 }).catch(() => { /* legacy layer */ });
88
99
 
89
100
  // #task-stuck (13th layer, physical half): the worker sandbox has no
90
101
  // teamclaw installation of its own, and entries.enabled does not resolve
@@ -208,6 +208,15 @@ export function buildProvisionedWorkerConfig(
208
208
  return config;
209
209
  }
210
210
 
211
+ /** #rate-limit-999: settings.json content (global settings scope for a
212
+ * worker instance home) raising provider rate-limit retries. Shared by the
213
+ * process backend's file write; docker/kubernetes mirror it in the bootstrap
214
+ * script with the same value baked in from the plugin config. */
215
+ export const TEAMCLAW_RATE_LIMIT_MAX_RETRIES_DEFAULT = 999;
216
+ export function workerRetrySettingsJson(maxRetries: number): string {
217
+ return JSON.stringify({ retry: { enabled: true, provider: { maxRetries } } }, null, 2) + "\n";
218
+ }
219
+
211
220
  export async function loadOpenClawConfig(configPath: string): Promise<Record<string, unknown>> {
212
221
  const raw = await fs.readFile(configPath, "utf8");
213
222
  return parseLooseJsonObject(raw, configPath);
@@ -31,6 +31,7 @@ import {
31
31
  appendTaskExecutionEvent,
32
32
  broadcastTaskExecutionEvent,
33
33
  buildTaskExecutionIdentity,
34
+ cancelTaskExecution,
34
35
  normalizeControllerIntakeSessionKey,
35
36
  recordTaskExecutionEvent,
36
37
  resetTaskForFreshAttempt,
@@ -268,7 +269,12 @@ export function buildConsolidatedPatternsContext(): string {
268
269
  }
269
270
  }
270
271
 
271
- export function revertTaskAssignment(taskId: string, workerId: string, deps: ControllerTaskDomainDeps): TaskInfo | undefined {
272
+ export function revertTaskAssignment(
273
+ taskId: string,
274
+ workerId: string,
275
+ deps: ControllerTaskDomainDeps,
276
+ options?: { holdMs?: number },
277
+ ): TaskInfo | undefined {
272
278
  const { updateTeamState, wsServer } = deps;
273
279
  let revertEvent: TaskExecutionEvent | undefined;
274
280
 
@@ -281,6 +287,13 @@ export function revertTaskAssignment(taskId: string, workerId: string, deps: Con
281
287
  if (task.assignedWorkerId === workerId) {
282
288
  task.status = "pending";
283
289
  task.assignedWorkerId = undefined;
290
+ // #5740 (ggcode, 2026-11-17): optional assignment hold so a reverted
291
+ // claim-eligibility retry does not immediately re-dispatch (outage
292
+ // churn); the heartbeat-driven auto-assign passes retry after expiry.
293
+ if (options?.holdMs && options.holdMs > 0) {
294
+ task.assignmentHoldCount = (task.assignmentHoldCount ?? 0) + 1;
295
+ task.assignmentHoldUntil = Date.now() + options.holdMs;
296
+ }
284
297
  task.updatedAt = Date.now();
285
298
  revertEvent = appendTaskExecutionEvent(task, {
286
299
  type: "error",
@@ -314,6 +327,29 @@ export function revertTaskAssignment(taskId: string, workerId: string, deps: Con
314
327
  return updatedTask;
315
328
  }
316
329
 
330
+ /** #5740 (ggcode): assignment hold after a reverted claim-eligibility check -
331
+ * 20s doubling per consecutive failure, capped at 160s, so a network blip
332
+ * costs one ~20s wait while a sustained outage retries at a bounded cadence
333
+ * instead of assign/cancel churn (and never bypasses the conflict gate). */
334
+ export function claimEligibilityHoldMs(consecutiveFailures: number): number {
335
+ const capped = Math.min(Math.max(consecutiveFailures, 1), 4);
336
+ return Math.min(20_000 * 2 ** (capped - 1), 160_000);
337
+ }
338
+
339
+ /** #5740 (ggcode): any conclusive claim outcome (claimed, stood down, or a
340
+ * WRITE failure that legitimately continues unclaimed) ends the retry cycle -
341
+ * reset the backoff so a future blip starts at the base hold again. */
342
+ export function clearAssignmentHold(taskId: string, deps: ControllerTaskDomainDeps): void {
343
+ deps.updateTeamState((s) => {
344
+ const task = s.tasks[taskId];
345
+ if (task && (task.assignmentHoldUntil !== undefined || task.assignmentHoldCount !== undefined)) {
346
+ delete task.assignmentHoldUntil;
347
+ delete task.assignmentHoldCount;
348
+ task.updatedAt = Date.now();
349
+ }
350
+ });
351
+ }
352
+
317
353
  export async function dispatchTaskToWorker(
318
354
  taskId: string,
319
355
  worker: WorkerInfo,
@@ -579,6 +615,9 @@ export async function runAutoAssignRound(
579
615
  const candidateAssignments = (await taskRouter
580
616
  .autoAssignPendingTasks(state.tasks, state.workers))
581
617
  .filter(({ task, worker }) => !attemptedPairs.has(`${task.id}:${worker.id}`))
618
+ // #5740 (ggcode): a task reverted by a failed claim-eligibility check
619
+ // sits out its exponential assignment hold before re-entering candidacy.
620
+ .filter(({ task }) => !(typeof task.assignmentHoldUntil === "number" && task.assignmentHoldUntil > Date.now()))
582
621
  .filter(({ task }) => {
583
622
  const root = taskWriteRoot(task);
584
623
  return !(root && busyWriteRoots.has(root));
@@ -606,6 +645,37 @@ export async function runAutoAssignRound(
606
645
  });
607
646
 
608
647
  if (updatedTask?.status === "assigned" && updatedTask.assignedWorkerId === nextAssignment.worker.id) {
648
+ // #claim-dequeue (2026-11-15): the GitHub claim happens HERE, at
649
+ // dequeue - after the fresh conflict check (assignees / external
650
+ // comments since enqueue) inside claimTaskAtDequeue. Non-takeOwnership
651
+ // tasks are a no-op there.
652
+ // #5740 (ggcode, 2026-11-17): an ELIGIBILITY-CHECK failure (network)
653
+ // must revert the assignment - the conflict gate never ran, so the
654
+ // task may not proceed. Back to pending; the next auto-assign pass
655
+ // re-checks (a blip costs ~20s, an outage loops at cadence instead of
656
+ // bypassing the gate). Write-phase claim failures still continue
657
+ // unclaimed per the original 2026-11-15 semantics.
658
+ deps.getTeamAutoScheduler?.()?.claimTaskAtDequeue(updatedTask).then((claim) => {
659
+ if (claim?.retryEligibility) {
660
+ logger.warn(`Controller: claim eligibility check failed for ${updatedTask.id} - reverting assignment to retry`);
661
+ // Unlike the #191 dispatch-failure path, the dispatch SUCCEEDED
662
+ // here: cancel the already-dispatched execution before reverting
663
+ // so the orphaned run cannot keep executing (and PATCH the task
664
+ // back to in_progress) while the controller re-queues it. The
665
+ // exponential assignment hold bounds the outage retry cadence.
666
+ void (async () => {
667
+ await cancelTaskExecution(updatedTask.id, nextAssignment.worker.id, "claim eligibility retry (#5740)", deps);
668
+ const failures = (deps.getTeamState()?.tasks[updatedTask.id]?.assignmentHoldCount ?? 0) + 1;
669
+ revertTaskAssignment(updatedTask.id, nextAssignment.worker.id, deps, {
670
+ holdMs: claimEligibilityHoldMs(failures),
671
+ });
672
+ })().catch(() => {});
673
+ } else {
674
+ // Claim attempt concluded definitively (claimed / stood down /
675
+ // WRITE failure continuing unclaimed): end the retry cycle.
676
+ clearAssignmentHold(updatedTask.id, deps);
677
+ }
678
+ }).catch(() => {});
609
679
  wsServer.broadcastUpdate({ type: "task:updated", data: serializeTask(updatedTask) });
610
680
  logger.info(
611
681
  `Controller: auto-assigned pending task ${updatedTask.id} to ${nextAssignment.worker.id}`,
@@ -199,6 +199,19 @@ export function taskRequiresMeaningfulProjectChangeGate(task: TaskInfo): boolean
199
199
  if (/(审计|审核|验证|复检|复查|确认|测试|检查)/u.test(text)) {
200
200
  return false;
201
201
  }
202
+ // #5719 (ggcode, 2026-11-16): analysis-family tasks deliver their product
203
+ // in the result/comment, not in files - perf forensics, research,
204
+ // diagnostics, triage. The write-verb regex below matches their issue
205
+ // CONTEXT ("fix the growth", "add instrumentation") even though the task
206
+ // itself only investigates; a file-change gate on them is a 100% false
207
+ // no-op (live: takeOwnership #5701 completed with jsonl evidence in the
208
+ // claim comment, gate failed it, write-back went terminal, requeue loop).
209
+ if (/\b(perf|profile|investigat|diagnos|research|analy[sz]|evidence|forensic|triage|observ)\b/u.test(text)) {
210
+ return false;
211
+ }
212
+ if (/(性能|取证|调研|分析|诊断|排查|观察)/u.test(text)) {
213
+ return false;
214
+ }
202
215
  return /\b(implement|build|fix|rework|update|add|enhanc|deliver|write|create)\b/u.test(text);
203
216
  }
204
217
 
@@ -263,10 +276,21 @@ export function projectHasMeaningfulFileChanges(
263
276
  // Collaboration contract: write tasks deliver in a dedicated worktree.
264
277
  // An mtime scan is the wrong test there (committed files keep old mtimes
265
278
  // and the gate may run before the flush) - ask git instead: does HEAD carry
266
- // commits beyond the remote refs?
279
+ // commits beyond the task's BASE branch?
267
280
  if (task.projectDir.includes("__task-")) {
281
+ // #5654 (ggcode, 2026-11-15): the old probe counted UNPUSHED commits
282
+ // (`HEAD --not --remotes`). A worker that pushes its branch BEFORE
283
+ // submitting - the encouraged flow since the #5651 rebase-delivery path -
284
+ // always drained to 0 and got rejected as a no-op (live d4ddd1bd:
285
+ // delivered + pushed a3638d1da, gate said 0, task failed + issue
286
+ // reopened). Substantive means HEAD carries commits beyond the BASE
287
+ // branch (origin/<default>), whether or not they were already pushed.
288
+ let base = "origin/main";
289
+ try {
290
+ base = execFileSync("git", ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], { cwd: projectRoot }).toString().trim() || base;
291
+ } catch { /* no origin/HEAD - conventional fallback above */ }
268
292
  try {
269
- const out = execFileSync("git", ["rev-list", "--count", "HEAD", "--not", "--remotes"], { cwd: projectRoot }).toString();
293
+ const out = execFileSync("git", ["rev-list", "--count", "HEAD", "--not", base], { cwd: projectRoot }).toString();
270
294
  return Number(out.trim()) > 0;
271
295
  } catch {
272
296
  return false;
@@ -331,9 +355,15 @@ export function allowsNoChangeCompletion(
331
355
  const noChangeIsExpected =
332
356
  /\b(qa|audit|review|verify|verification|validate|test|retest|confirm|check)\b/u.test(taskText)
333
357
  || /(审计|审核|验证|复检|复查|确认|测试|检查)/u.test(taskText)
358
+ // #5719: analysis-family work products live in the result itself.
359
+ || /\b(perf|profile|investigat|diagnos|research|analy[sz]|evidence|forensic|triage|observ)\b/u.test(taskText)
360
+ || /(性能|取证|调研|分析|诊断|排查|观察)/u.test(taskText)
334
361
  || /\b(already fixed|already resolved|no further changes|no code changes|no file changes|no additional changes|verified existing fix)\b/u.test(evidenceText)
335
362
  || /(已修复|已解决|无需改动|无需修改|没有额外修改|无需额外变更|只需验证)/u.test(evidenceText);
336
- return hasVerificationEvidence && noChangeIsExpected;
363
+ // #5719: for analysis-family tasks the substantive result text IS the
364
+ // verification evidence (metrics, traces, conclusions).
365
+ const analysisFamily = /\b(perf|profile|investigat|diagnos|research|analy[sz]|evidence|forensic|triage|observ)\b/u.test(taskText) || /(性能|取证|调研|分析|诊断|排查|观察)/u.test(taskText);
366
+ return (hasVerificationEvidence || (analysisFamily && resultText.trim().length > 200)) && noChangeIsExpected;
337
367
  }
338
368
 
339
369
  export function applyTaskResult(