@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
package/README.md CHANGED
@@ -15,7 +15,21 @@ It supports:
15
15
 
16
16
  ## Install
17
17
 
18
- For the easiest guided setup, run:
18
+ The recommended install is the official ClawHub registry (the default source for `openclaw plugins install` on OpenClaw 2026.10+ - no extra flags or source prefixes needed):
19
+
20
+ ```bash
21
+ openclaw plugins install @teamclaws/teamclaw
22
+ ```
23
+
24
+ OpenClaw walks you through the capability consent prompt; for scripts/CI, accept the declared capabilities non-interactively:
25
+
26
+ ```bash
27
+ openclaw plugins install --accept-capabilities @teamclaws/teamclaw
28
+ ```
29
+
30
+ > Note: the freshly published 2026.11.x builds ship compiled runtime output (`dist/index.js`). Until a pending package clears ClawHub's security scan, `latest` may still resolve to the legacy 2026.3.x artifact, which predates compiled entries - retry after the scan completes.
31
+
32
+ For a guided setup that also configures workspaces, workers, and auth, run:
19
33
 
20
34
  ```bash
21
35
  npx -y @teamclaws/teamclaw install
@@ -52,18 +66,10 @@ npx -y @teamclaws/teamclaw install --agent-mode main
52
66
 
53
67
  If you only want to install the plugin manually, use:
54
68
 
55
- ```bash
56
- # OpenClaw 2026.10+
57
- openclaw plugins install --accept-capabilities @teamclaws/teamclaw
58
-
59
- # Legacy hosts (<2026.10)
60
- openclaw plugins install --dangerously-force-unsafe-install @teamclaws/teamclaw
61
- ```
62
-
63
- If you want to force the ClawHub package path, use:
69
+ Legacy hosts (<2026.10) that predate the ClawHub-by-default registry can still install from npm, forcing the legacy consent flag:
64
70
 
65
71
  ```bash
66
- openclaw plugins install --accept-capabilities clawhub:@teamclaws/teamclaw
72
+ openclaw plugins install --dangerously-force-unsafe-install npm:@teamclaws/teamclaw
67
73
  ```
68
74
 
69
75
  Then enable and configure TeamClaw in your `openclaw.json`.
@@ -110,8 +110,8 @@ function buildConfigSchema() {
110
110
  properties: {
111
111
  autoPair: {
112
112
  type: "boolean",
113
- default: true,
114
- description: "Allow zero-input pairing from LAN peers (POST /api/v1/security/pair-auto); disable to require a pairing code for every new device",
113
+ default: false,
114
+ description: "Allow zero-input pairing from LAN peers (POST /api/v1/security/pair-auto); off by default so every new device needs a pairing code - enable only on a trusted private network",
115
115
  },
116
116
  },
117
117
  },
@@ -329,7 +329,7 @@ function buildConfigSchema() {
329
329
  },
330
330
  security: {
331
331
  label: "Device Pairing Security",
332
- help: "Controller device-pairing options; autoPair allows LAN devices to pair with zero input (POST /api/v1/security/pair-auto), disable it to require a pairing code for every new device",
332
+ help: "Controller device-pairing options; autoPair (off by default) allows LAN devices to pair with zero input (POST /api/v1/security/pair-auto) - enable only on a trusted private network",
333
333
  },
334
334
  agentIsolationMode: {
335
335
  label: "Agent Isolation Mode",
@@ -46,7 +46,10 @@ function teamConfigGetRoute(ctx) {
46
46
  workerProvisioningMaxPerRole: c.workerProvisioningMaxPerRole,
47
47
  workerProvisioningIdleTtlMs: c.workerProvisioningIdleTtlMs,
48
48
  // k8s controllers run on ephemeral container FS: declare it up front.
49
- persistenceMode: c.workerProvisioningType === "kubernetes" ? "memory-only" : "host-config",
49
+ // #hot-reload: persistence is PLUGIN-STATE (beside team-state.json), not
50
+ // host config - a host-config write made the host reload the whole
51
+ // plugin on every PATCH (see openclaw-workspace.ts #hot-reload note).
52
+ persistenceMode: "plugin-state",
50
53
  });
51
54
  }
52
55
  async function teamConfigPatchRoute(ctx) {
@@ -97,8 +100,9 @@ async function teamConfigPatchRoute(ctx) {
97
100
  deps.config.workerProvisioningMaxPerRole = minR;
98
101
  applied.workerProvisioningMaxPerRole = minR;
99
102
  }
100
- // 2) Persist (host config) unless the controller itself runs on an
101
- // ephemeral container FS.
103
+ // 2) Persist to PLUGIN STATE (never the host config - see
104
+ // openclaw-workspace.ts #hot-reload: host writes triggered full plugin
105
+ // reloads that killed in-flight work and usually failed to apply).
102
106
  const memoryOnly = deps.config.workerProvisioningType === "kubernetes";
103
107
  let persisted = false;
104
108
  if (!memoryOnly) {
@@ -15,7 +15,7 @@ import { resumeTeamProfileSwitch } from "./profile-switch.js";
15
15
  import { TaskRouter } from "./task-router.js";
16
16
  import { MessageRouter } from "./message-router.js";
17
17
  import { TeamWebSocketServer } from "./websocket.js";
18
- import { ensureOpenClawWorkspaceMemoryDir, buildTeamClawAgentSessionKey } from "../openclaw-workspace.js";
18
+ import { ensureOpenClawWorkspaceMemoryDir, buildTeamClawAgentSessionKey, loadProvisioningHotConfig } from "../openclaw-workspace.js";
19
19
  import { ensureControllerGitRepo } from "../git-collaboration.js";
20
20
  import { WorkerProvisioningManager } from "./worker-provisioning.js";
21
21
  import { PreviewManager } from "./preview-manager.js";
@@ -51,6 +51,17 @@ export function createControllerService(deps) {
51
51
  async start(_ctx) {
52
52
  const serviceStartedAt = Date.now();
53
53
  await ensureOpenClawWorkspaceMemoryDir(logger);
54
+ // #hot-reload: re-apply the persisted hot-config overrides (provisioning
55
+ // caps) from PLUGIN STATE - they intentionally live outside the host
56
+ // config so a PATCH never triggers a plugin reload (see
57
+ // openclaw-workspace.ts #hot-reload for the failure mode this replaces).
58
+ const hotOverrides = await loadProvisioningHotConfig();
59
+ if (hotOverrides) {
60
+ for (const [key, value] of Object.entries(hotOverrides)) {
61
+ config[key] = value;
62
+ }
63
+ logger.info(`Controller: provisioning hot-config re-applied from plugin state: ${JSON.stringify(hotOverrides)}`);
64
+ }
54
65
  // Load or create team state. The active profile is resolved FIRST (from
55
66
  // the restored TeamState.profileId, or the config bootstrap value on
56
67
  // first initialization) so that capability-dependent startup wiring
@@ -159,7 +159,7 @@ export function createControllerHttpServer(deps) {
159
159
  // structure below is unchanged from the pre-PR-D if/else chain.
160
160
  let tunnelManager = tunnelManagerSingleton;
161
161
  if (!tunnelManager) {
162
- tunnelManager = tunnelManagerSingleton = createTunnelManager({ logger, localPort: deps.config.port });
162
+ tunnelManager = tunnelManagerSingleton = createTunnelManager({ logger, localPort: deps.config.port, isProtectionOn: () => isProtectionOn(deps.getTeamState()) });
163
163
  }
164
164
  if (!tunnelRoutesSingleton) {
165
165
  tunnelRoutesSingleton = {
@@ -223,7 +223,7 @@ export function createControllerHttpServer(deps) {
223
223
  // Boot reconciliation: reconnect a share persisted by a previous run
224
224
  // (gateway restart or kill -9) so the tunnel id and gate token survive.
225
225
  if (!tunnelManagerSingleton) {
226
- tunnelManagerSingleton = createTunnelManager({ logger, localPort: deps.config.port });
226
+ tunnelManagerSingleton = createTunnelManager({ logger, localPort: deps.config.port, isProtectionOn: () => isProtectionOn(deps.getTeamState()) });
227
227
  }
228
228
  void tunnelManagerSingleton.recover().catch((err) => {
229
229
  logger.warn(`TeamClaw tunnel: boot recovery failed: ${String(err)}`);
@@ -16,6 +16,18 @@ export function spawnManagedGatewayProcess(options) {
16
16
  return child;
17
17
  }
18
18
  export function spawnManagedCommandProcess(options) {
19
+ // #terminal-activation guard: previewCommand is worker-influenced input
20
+ // (#237 W1) executed through the core sh -c wrapper. A prompt-injected
21
+ // `open`/osascript command hijacks LaunchServices and activates
22
+ // Terminal.app from the headless launchd context (reported live: default
23
+ // Terminal windows intermittently activating). Reject loudly - never
24
+ // silently - so the attempt is visible in logs.
25
+ const cmd = options.command.trim();
26
+ if (/^(open|osascript)\b/i.test(cmd) || /(^|[\s;&|])osascript\b/i.test(cmd) || /(^|\s)-a\s+Terminal\b/.test(cmd)) {
27
+ const reason = `blocked Terminal-activation command (preview contract violation): ${cmd.slice(0, 120)}`;
28
+ console.error(`[teamclaw] ${reason}`);
29
+ throw new Error(`[teamclaw] ${reason}`);
30
+ }
19
31
  const cwd = options.cwd ?? process.cwd();
20
32
  const child = spawn(process.execPath, buildManagedCommandWrapperArgs(options.command), {
21
33
  ...buildManagedProcessSpawnOptions({
@@ -208,9 +220,13 @@ const shutdownSignals = process.platform === "win32"
208
220
  ? ["SIGTERM", "SIGINT", "SIGBREAK"]
209
221
  : ["SIGTERM", "SIGINT", "SIGHUP", "SIGQUIT"];
210
222
  const shell = process.platform === "win32" ? "cmd.exe" : "sh";
223
+ // -c, NOT -lc: a LOGIN shell sources the user's profiles in a headless
224
+ // launchd context. Profile init scripts are interactive-session side-effect
225
+ // machines (open/LaunchServices hooks, TTY-needing helpers) and are the
226
+ // plausible amplifier behind intermittent Terminal.app activations.
211
227
  const shellArgs = process.platform === "win32"
212
228
  ? ["/d", "/s", "/c", command]
213
- : ["-lc", command];
229
+ : ["-c", command];
214
230
 
215
231
  let shuttingDown = false;
216
232
  let parentMonitor = null;
@@ -40,7 +40,7 @@ function sanitizeTrailingSegment(value, maxLength, fallback) {
40
40
  const normalized = sanitizePathSegment(value).slice(-maxLength).replace(/^-+|-+$/g, "");
41
41
  return normalized || fallback;
42
42
  }
43
- export function buildContainerBootstrapScript() {
43
+ export function buildContainerBootstrapScript(rateLimitMaxRetries) {
44
44
  return [
45
45
  "set -eu",
46
46
  "mkdir -p \"$OPENCLAW_STATE_DIR\"",
@@ -59,6 +59,11 @@ export function buildContainerBootstrapScript() {
59
59
  // creates it owner-only). Chosen over unlink-then-write to avoid the
60
60
  // no-config window mid-rewrite.
61
61
  "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 });'",
62
+ // #rate-limit-999 (v2): openclaw reads retry settings from its AGENT scope
63
+ // <stateDir>/agents/teamclaw/agent/settings.json (settings-manager:
64
+ // join(agentDir, "settings.json")), NOT from the state dir root. Write the
65
+ // real layer first, plus the legacy root copy for other layouts.
66
+ `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 });'`,
62
67
  "exec node dist/index.js gateway --allow-unconfigured",
63
68
  ].join("\n");
64
69
  }
@@ -59,7 +59,7 @@ export class DockerProvisioner {
59
59
  }
60
60
  const containerConfig = {
61
61
  Image: this.config.workerProvisioningImage,
62
- Cmd: ["sh", "-lc", buildContainerBootstrapScript()],
62
+ Cmd: ["sh", "-lc", buildContainerBootstrapScript(spec.rateLimitMaxRetries)],
63
63
  Env: Object.entries(env).map(([key, value]) => `${key}=${value}`),
64
64
  User: "root",
65
65
  Labels: {
@@ -179,7 +179,7 @@ export class KubernetesProvisioner {
179
179
  name: "worker",
180
180
  image: this.config.workerProvisioningImage,
181
181
  command: ["sh", "-lc"],
182
- args: [buildContainerBootstrapScript()],
182
+ args: [buildContainerBootstrapScript(spec.rateLimitMaxRetries)],
183
183
  env: Object.entries(env).map(([name, value]) => ({ name, value })),
184
184
  volumeMounts: hasPersistentWorkspace
185
185
  ? [
@@ -8,7 +8,7 @@ import fs from "node:fs/promises";
8
8
  import path from "node:path";
9
9
  import readline from "node:readline";
10
10
  import { spawn } from "node:child_process";
11
- import { resolveControllerTeamclawEntryPath } from "../provisioning-config.js";
11
+ import { resolveControllerTeamclawEntryPath, workerRetrySettingsJson } from "../provisioning-config.js";
12
12
  import { resolveDefaultOpenClawConfigPath, resolveDefaultTeamClawRuntimeRootDir, } from "../../openclaw-workspace.js";
13
13
  import { pathExists, sanitizePathSegment } from "../../shared/utils.js";
14
14
  import { copyControllerAuthProfiles } from "../provisioning-config.js";
@@ -73,6 +73,17 @@ export class ProcessProvisioner {
73
73
  throw err;
74
74
  });
75
75
  await fs.writeFile(configPath, spec.configJson, { encoding: "utf8", mode: 0o600 });
76
+ // #rate-limit-999 (v2, user report 2026-11-14 night: retries STILL stopped
77
+ // at 9): openclaw does NOT read stateDir/settings.json - its global scope
78
+ // is <stateDir>/agents/<agentId>/agent/settings.json (verified live:
79
+ // agents/teamclaw/agent/ exists in every provisioned worker; settings-
80
+ // manager reads join(agentDir, "settings.json")). The agent id for our
81
+ // workers is deterministic ("teamclaw"). Write BOTH layers: the real one
82
+ // plus the legacy stateDir copy (harmless; future-proofs other layouts).
83
+ const workerAgentSettingsDir = path.join(stateDir, "agents", "teamclaw", "agent");
84
+ await fs.mkdir(workerAgentSettingsDir, { recursive: true }).catch(() => { });
85
+ await fs.writeFile(path.join(workerAgentSettingsDir, "settings.json"), workerRetrySettingsJson(spec.rateLimitMaxRetries), { encoding: "utf8", mode: 0o600 }).catch(() => { });
86
+ await fs.writeFile(path.join(stateDir, "settings.json"), workerRetrySettingsJson(spec.rateLimitMaxRetries), { encoding: "utf8", mode: 0o600 }).catch(() => { });
76
87
  // #task-stuck (13th layer, physical half): the worker sandbox has no
77
88
  // teamclaw installation of its own, and entries.enabled does not resolve
78
89
  // the plugin. Symlink the controller's teamclaw package into the
@@ -123,6 +134,17 @@ export class ProcessProvisioner {
123
134
  OPENCLAW_STATE_DIR: stateDir,
124
135
  OPENCLAW_CONFIG_PATH: configPath,
125
136
  OPENCLAW_SKIP_CANVAS_HOST: "1",
137
+ // #disk-hygiene (screenshot report 2026-11-19): worker go builds can
138
+ // accumulate gigabytes of go-build/go-link dirs in the HOME tmp when
139
+ // deployments want them on a scratch volume. Opt-in ONLY - hardcoded
140
+ // paths would break any deployment without that volume. When the
141
+ // operator sets TEAMCLAW_GOCACHE / TEAMCLAW_GOTMPDIR, they are
142
+ // forwarded as GOCACHE / GOTMPDIR (an externally-set GOCACHE already
143
+ // flows through ...process.env untouched and is never overridden);
144
+ // unset -> Go defaults apply exactly as before. Kept ABOVE the
145
+ // workspaceDir spread so the contract test's env-tail shape holds.
146
+ ...(process.env.TEAMCLAW_GOCACHE && !process.env.GOCACHE ? { GOCACHE: process.env.TEAMCLAW_GOCACHE } : {}),
147
+ ...(process.env.TEAMCLAW_GOTMPDIR && !process.env.GOTMPDIR ? { GOTMPDIR: process.env.TEAMCLAW_GOTMPDIR } : {}),
126
148
  TEAMCLAW_WORKER_ID: spec.workerId,
127
149
  TEAMCLAW_LAUNCH_TOKEN: spec.launchToken,
128
150
  ...(spec.workspaceDir ? { TEAMCLAW_WORKSPACE_DIR: spec.workspaceDir } : {}),
@@ -181,6 +181,14 @@ export function buildProvisionedWorkerConfig(baseConfig, controllerConfig, spec)
181
181
  config.plugins = plugins;
182
182
  return config;
183
183
  }
184
+ /** #rate-limit-999: settings.json content (global settings scope for a
185
+ * worker instance home) raising provider rate-limit retries. Shared by the
186
+ * process backend's file write; docker/kubernetes mirror it in the bootstrap
187
+ * script with the same value baked in from the plugin config. */
188
+ export const TEAMCLAW_RATE_LIMIT_MAX_RETRIES_DEFAULT = 999;
189
+ export function workerRetrySettingsJson(maxRetries) {
190
+ return JSON.stringify({ retry: { enabled: true, provider: { maxRetries } } }, null, 2) + "\n";
191
+ }
184
192
  export async function loadOpenClawConfig(configPath) {
185
193
  const raw = await fs.readFile(configPath, "utf8");
186
194
  return parseLooseJsonObject(raw, configPath);
@@ -354,8 +354,8 @@ export const controllerRouteTable = [
354
354
  // pair/start- authenticated device or loopback (mints a fresh code,
355
355
  // invalidating the previous one)
356
356
  // pair - one-shot 60s code exchange -> {token, deviceId}
357
- // pair-auto - LAN peer + config.security.autoPair + protection on
358
- // reset - authenticated device or loopback (anti-lockout hatch)
357
+ // pair-auto - LAN peer + config.security.autoPair (opt-in) + protection on
358
+ // reset - loopback only (anti-lockout hatch; controller host action)
359
359
  // GET /security and DELETE /security/devices/:id are NOT exempt: the
360
360
  // middleware itself guarantees the caller holds a valid device token.
361
361
  { method: "POST", path: "/api/v1/security/enable", handler: handleSecurityEnableRequest },
@@ -438,6 +438,20 @@ export function createWebSocketUpgradeGuard(deps) {
438
438
  const viaTunnel = deps.isTunnelHost(typeof req.headers.host === "string" ? req.headers.host : undefined);
439
439
  const peer = classifySecurityPeer(req.socket.remoteAddress, viaTunnel);
440
440
  const state = deps.getTeamState();
441
+ // ClawHub security review 2026.11.6 (finding 3): the tunnel gate must
442
+ // run BEFORE the protection-off allowance. The HTTP path enforces
443
+ // gateAllows for every tunnel request regardless of device protection
444
+ // (http-server.ts), so a protection-off controller still gates its HTTP
445
+ // surface - but this guard used to return true first, which left /ws as
446
+ // the one tunnel surface a gate-cookie-less visitor could subscribe to
447
+ // (task/message/clarification event stream). Same layering as HTTP now.
448
+ if (peer.viaTunnel) {
449
+ if (!deps.gateAllows || !deps.gateAllows(req)) {
450
+ deps.logger.warn(`Controller: rejected WebSocket upgrade from ${peer.ip} (via tunnel, no gate cookie)`);
451
+ return false;
452
+ }
453
+ return true;
454
+ }
441
455
  if (!isProtectionOn(state)) {
442
456
  recordNonLanPeerSignal(deps, state, peer, "/ws");
443
457
  return true;
@@ -450,13 +464,8 @@ export function createWebSocketUpgradeGuard(deps) {
450
464
  if (peer.loopback) {
451
465
  return true;
452
466
  }
453
- // Tunnel-origin upgrades (cloudflared loopback + tunnel Host): the
454
- // visitor holds the GATE token, not a pairing token - same layering
455
- // as the HTTP gate (a device token here would be an unanswerable
456
- // wall, 8b03ed6). Verify the gate cookie instead.
457
- if (peer.viaTunnel && deps.gateAllows && deps.gateAllows(req)) {
458
- return true;
459
- }
467
+ // Tunnel-origin upgrades were handled above (gate cookie, never a pairing
468
+ // token - a device token here would be an unanswerable wall, 8b03ed6).
460
469
  let token = extractDeviceToken(req);
461
470
  if (!token) {
462
471
  const url = new URL(req.url ?? "/ws", `http://${req.headers.host ?? "localhost"}`);
@@ -683,10 +692,10 @@ export async function handleSecurityPairAutoRequest(ctx) {
683
692
  });
684
693
  return;
685
694
  }
686
- if ((deps.config.security?.autoPair ?? true) !== true) {
695
+ if ((deps.config.security?.autoPair ?? false) !== true) {
687
696
  sendJson(res, 403, {
688
697
  error: "auto-pairing is disabled on this controller",
689
- hint: "The owner disabled security.autoPair; ask for a pairing code and POST /api/v1/security/pair {\"code\",\"kind\",\"name\"}.",
698
+ hint: "Zero-input LAN pairing is off by default (ClawHub security review); ask for a pairing code and POST /api/v1/security/pair {\"code\",\"kind\",\"name\"}.",
690
699
  });
691
700
  return;
692
701
  }
@@ -719,7 +728,7 @@ export async function handleSecurityGetRequest(ctx) {
719
728
  protection: isProtectionOn(state),
720
729
  devices: (security?.devices ?? []).map(serializeDevice),
721
730
  ...(active ? { pairingCode: { expiresAt: active.expiresAt, purpose: active.purpose } } : {}),
722
- autoPair: deps.config.security?.autoPair ?? true,
731
+ autoPair: deps.config.security?.autoPair ?? false,
723
732
  });
724
733
  }
725
734
  // DELETE /api/v1/security/devices/:id - authenticated (middleware). Revoking
@@ -746,15 +755,21 @@ export async function handleSecurityDeviceDeleteRequest(ctx) {
746
755
  deps.logger.info(`Controller: revoked device ${deviceId}${revokedSelf ? " (self-revocation; that client must re-pair)" : ""}; protection now ${protection ? "on" : "off"}`);
747
756
  sendJson(res, 200, { ok: true, revoked: deviceId, revokedSelf, protection });
748
757
  }
749
- // POST /api/v1/security/reset - authenticated OR loopback (anti-lockout
750
- // hatch), plus an explicit confirm token (#255 P1-8): a paired device must
751
- // knowingly opt in, since the reset drops protection to L0 for EVERYONE.
758
+ // POST /api/v1/security/reset - LOOPBACK ONLY (anti-lockout hatch), plus
759
+ // an explicit confirm token (#255 P1-8). ClawHub security review 2026.11.6
760
+ // (finding 2): a paired device token used to be enough to drop protection
761
+ // for EVERYONE - any LAN device that self-paired via auto-pair could reset
762
+ // the controller to L0. Reset is now a controller-host action only; remote
763
+ // owners revoke devices individually or re-enable from the host.
752
764
  export async function handleSecurityResetRequest(ctx) {
753
765
  const { req, res, deps, peer } = ctx;
754
766
  const state = deps.getTeamState();
755
767
  const auth = authenticateDeviceToken(state, extractDeviceToken(req));
756
- if (!auth && !(peer?.loopback ?? false)) {
757
- sendUnauthorized(res);
768
+ if (!(peer?.loopback ?? false)) {
769
+ sendJson(res, 403, {
770
+ error: "forbidden",
771
+ hint: "Security reset is a controller-host action (loopback only); remote devices cannot drop protection for everyone. Revoke devices individually or run the reset from the controller host.",
772
+ });
758
773
  return;
759
774
  }
760
775
  const body = await parseJsonBody(req);
@@ -12,7 +12,7 @@ import { getActiveRoles, resolveActiveRoleSkills } from "../profile-loader.js";
12
12
  import { buildRepoSyncInfo } from "../git-collaboration.js";
13
13
  import { buildTeamClawProjectWorkspacePath, resolveTeamClawProjectsDir, resolveTeamClawWorkspaceDir, } from "../openclaw-workspace.js";
14
14
  import { refreshControllerRepoState } from "./repo-routes.js";
15
- import { appendTaskExecutionEvent, broadcastTaskExecutionEvent, buildTaskExecutionIdentity, normalizeControllerIntakeSessionKey, recordTaskExecutionEvent, resetTaskForFreshAttempt, serializeTask, withWorkerDispatchToken, } from "./task-execution.js";
15
+ import { appendTaskExecutionEvent, broadcastTaskExecutionEvent, buildTaskExecutionIdentity, cancelTaskExecution, normalizeControllerIntakeSessionKey, recordTaskExecutionEvent, resetTaskForFreshAttempt, serializeTask, withWorkerDispatchToken, } from "./task-execution.js";
16
16
  const MAX_RECENT_TASK_CONTEXT = 3;
17
17
  const MAX_TASK_CONTEXT_SUMMARY_CHARS = 500;
18
18
  export function summarizeTaskForAssignment(task) {
@@ -227,7 +227,7 @@ export function buildConsolidatedPatternsContext() {
227
227
  return "";
228
228
  }
229
229
  }
230
- export function revertTaskAssignment(taskId, workerId, deps) {
230
+ export function revertTaskAssignment(taskId, workerId, deps, options) {
231
231
  const { updateTeamState, wsServer } = deps;
232
232
  let revertEvent;
233
233
  const state = updateTeamState((s) => {
@@ -238,6 +238,13 @@ export function revertTaskAssignment(taskId, workerId, deps) {
238
238
  if (task.assignedWorkerId === workerId) {
239
239
  task.status = "pending";
240
240
  task.assignedWorkerId = undefined;
241
+ // #5740 (ggcode, 2026-11-17): optional assignment hold so a reverted
242
+ // claim-eligibility retry does not immediately re-dispatch (outage
243
+ // churn); the heartbeat-driven auto-assign passes retry after expiry.
244
+ if (options?.holdMs && options.holdMs > 0) {
245
+ task.assignmentHoldCount = (task.assignmentHoldCount ?? 0) + 1;
246
+ task.assignmentHoldUntil = Date.now() + options.holdMs;
247
+ }
241
248
  task.updatedAt = Date.now();
242
249
  revertEvent = appendTaskExecutionEvent(task, {
243
250
  type: "error",
@@ -267,6 +274,27 @@ export function revertTaskAssignment(taskId, workerId, deps) {
267
274
  }
268
275
  return updatedTask;
269
276
  }
277
+ /** #5740 (ggcode): assignment hold after a reverted claim-eligibility check -
278
+ * 20s doubling per consecutive failure, capped at 160s, so a network blip
279
+ * costs one ~20s wait while a sustained outage retries at a bounded cadence
280
+ * instead of assign/cancel churn (and never bypasses the conflict gate). */
281
+ export function claimEligibilityHoldMs(consecutiveFailures) {
282
+ const capped = Math.min(Math.max(consecutiveFailures, 1), 4);
283
+ return Math.min(20_000 * 2 ** (capped - 1), 160_000);
284
+ }
285
+ /** #5740 (ggcode): any conclusive claim outcome (claimed, stood down, or a
286
+ * WRITE failure that legitimately continues unclaimed) ends the retry cycle -
287
+ * reset the backoff so a future blip starts at the base hold again. */
288
+ export function clearAssignmentHold(taskId, deps) {
289
+ deps.updateTeamState((s) => {
290
+ const task = s.tasks[taskId];
291
+ if (task && (task.assignmentHoldUntil !== undefined || task.assignmentHoldCount !== undefined)) {
292
+ delete task.assignmentHoldUntil;
293
+ delete task.assignmentHoldCount;
294
+ task.updatedAt = Date.now();
295
+ }
296
+ });
297
+ }
270
298
  export async function dispatchTaskToWorker(taskId, worker, deps) {
271
299
  const { getTeamState, logger, updateTeamState } = deps;
272
300
  const state = getTeamState();
@@ -479,6 +507,9 @@ export async function runAutoAssignRound(deps, preferredWorkerId, attemptedPairs
479
507
  const candidateAssignments = (await taskRouter
480
508
  .autoAssignPendingTasks(state.tasks, state.workers))
481
509
  .filter(({ task, worker }) => !attemptedPairs.has(`${task.id}:${worker.id}`))
510
+ // #5740 (ggcode): a task reverted by a failed claim-eligibility check
511
+ // sits out its exponential assignment hold before re-entering candidacy.
512
+ .filter(({ task }) => !(typeof task.assignmentHoldUntil === "number" && task.assignmentHoldUntil > Date.now()))
482
513
  .filter(({ task }) => {
483
514
  const root = taskWriteRoot(task);
484
515
  return !(root && busyWriteRoots.has(root));
@@ -499,6 +530,99 @@ export async function runAutoAssignRound(deps, preferredWorkerId, attemptedPairs
499
530
  assignedRole: nextAssignment.task.assignedRole,
500
531
  });
501
532
  if (updatedTask?.status === "assigned" && updatedTask.assignedWorkerId === nextAssignment.worker.id) {
533
+ // #claim-dequeue (2026-11-15): the GitHub claim happens HERE, at
534
+ // dequeue - after the fresh conflict check (assignees / external
535
+ // comments since enqueue) inside claimTaskAtDequeue. Non-takeOwnership
536
+ // tasks are a no-op there.
537
+ // #5740 (ggcode, 2026-11-17): an ELIGIBILITY-CHECK failure (network)
538
+ // must revert the assignment - the conflict gate never ran, so the
539
+ // task may not proceed. Back to pending; the next auto-assign pass
540
+ // re-checks (a blip costs ~20s, an outage loops at cadence instead of
541
+ // bypassing the gate). Write-phase claim failures still continue
542
+ // unclaimed per the original 2026-11-15 semantics.
543
+ deps.getTeamAutoScheduler?.()?.claimTaskAtDequeue(updatedTask).then((claim) => {
544
+ if (claim?.reason === "issue closed") {
545
+ // #5818: the claim check VERDICTED against the task - the issue was
546
+ // closed between enqueue and dequeue. That is terminal (no retry
547
+ // helps); running the leg anyway burned a full 8-minute worker on
548
+ // a closed issue (live: 952e7471). Cancel the dispatched execution
549
+ // and terminalize the task as cancelled - NOT back to pending (a
550
+ // pending task would redispatch; the sweep will not re-candidate a
551
+ // closed issue, but the queue entry would keep firing).
552
+ logger.warn(`Controller: issue closed before dispatch for ${updatedTask.id} - cancelling task`);
553
+ void (async () => {
554
+ await cancelTaskExecution(updatedTask.id, nextAssignment.worker.id, "target issue closed (#5818)", deps);
555
+ deps.updateTeamState((s) => {
556
+ const t = s.tasks[updatedTask.id];
557
+ if (!t)
558
+ return;
559
+ t.status = "failed";
560
+ t.error = "Cancelled: target issue was closed before dispatch (#5818) - no work performed.";
561
+ t.updatedAt = Date.now();
562
+ // #5825: cancelTaskExecution never resets the worker record,
563
+ // and cancelling also suppresses the worker-side completion
564
+ // report - so nothing ever flipped the seat idle. Release here
565
+ // (same shape as the normal completion path) or the worker
566
+ // stays orphan-busy forever (live: 2 busy, 1 in_progress).
567
+ const w = s.workers[nextAssignment.worker.id];
568
+ if (w && w.currentTaskId === updatedTask.id) {
569
+ w.status = "idle";
570
+ w.currentTaskId = undefined;
571
+ }
572
+ });
573
+ wsServer.broadcastUpdate({ type: "task:updated", data: serializeTask(deps.getTeamState()?.tasks[updatedTask.id] ?? updatedTask) });
574
+ })().catch(() => { });
575
+ }
576
+ else if (claim?.retryEligibility) {
577
+ logger.warn(`Controller: claim eligibility check failed for ${updatedTask.id} - reverting assignment to retry`);
578
+ // Unlike the #191 dispatch-failure path, the dispatch SUCCEEDED
579
+ // here: cancel the already-dispatched execution before reverting
580
+ // so the orphaned run cannot keep executing (and PATCH the task
581
+ // back to in_progress) while the controller re-queues it. The
582
+ // exponential assignment hold bounds the outage retry cadence.
583
+ void (async () => {
584
+ await cancelTaskExecution(updatedTask.id, nextAssignment.worker.id, "claim eligibility retry (#5740)", deps);
585
+ const failures = (deps.getTeamState()?.tasks[updatedTask.id]?.assignmentHoldCount ?? 0) + 1;
586
+ revertTaskAssignment(updatedTask.id, nextAssignment.worker.id, deps, {
587
+ holdMs: claimEligibilityHoldMs(failures),
588
+ });
589
+ })().catch(() => { });
590
+ }
591
+ else if (claim?.reason === "external activity" || claim?.reason === "assignees present") {
592
+ // #5823: stand-down verdicts are TERMINAL like issue-closed (the
593
+ // seat/owner is not going away; retrying cannot help) - the old
594
+ // else-branch only cleared the hold and the leg ran to completion
595
+ // on an issue another seat owns (live: the #5819 self-fix leg
596
+ // stood down at 21:24 yet kept executing at 21:38). Same treatment
597
+ // as #5818: cancel the dispatched execution, terminalize with the
598
+ // stand-down reason, no dead-letter count.
599
+ logger.warn(`Controller: claim stood down (${claim.reason}) for ${updatedTask.id} - cancelling task`);
600
+ void (async () => {
601
+ await cancelTaskExecution(updatedTask.id, nextAssignment.worker.id, `claim stand-down: ${claim.reason} (#5823)`, deps);
602
+ deps.updateTeamState((s) => {
603
+ const t = s.tasks[updatedTask.id];
604
+ if (!t)
605
+ return;
606
+ t.status = "failed";
607
+ t.error = `Cancelled: claim stood down (${claim.reason}) - another seat/owner owns the issue (#5823). No work performed.`;
608
+ t.updatedAt = Date.now();
609
+ // #5825: same orphan-busy release as the #5818 branch above.
610
+ const w = s.workers[nextAssignment.worker.id];
611
+ if (w && w.currentTaskId === updatedTask.id) {
612
+ w.status = "idle";
613
+ w.currentTaskId = undefined;
614
+ }
615
+ });
616
+ clearAssignmentHold(updatedTask.id, deps);
617
+ wsServer.broadcastUpdate({ type: "task:updated", data: serializeTask(deps.getTeamState()?.tasks[updatedTask.id] ?? updatedTask) });
618
+ })().catch(() => { });
619
+ }
620
+ else {
621
+ // Claim attempt concluded definitively (claimed / stood down /
622
+ // WRITE failure continuing unclaimed): end the retry cycle.
623
+ clearAssignmentHold(updatedTask.id, deps);
624
+ }
625
+ }).catch(() => { });
502
626
  wsServer.broadcastUpdate({ type: "task:updated", data: serializeTask(updatedTask) });
503
627
  logger.info(`Controller: auto-assigned pending task ${updatedTask.id} to ${nextAssignment.worker.id}`);
504
628
  assignedTasks.push(updatedTask);
@@ -166,6 +166,19 @@ export function taskRequiresMeaningfulProjectChangeGate(task) {
166
166
  if (/(审计|审核|验证|复检|复查|确认|测试|检查)/u.test(text)) {
167
167
  return false;
168
168
  }
169
+ // #5719 (ggcode, 2026-11-16): analysis-family tasks deliver their product
170
+ // in the result/comment, not in files - perf forensics, research,
171
+ // diagnostics, triage. The write-verb regex below matches their issue
172
+ // CONTEXT ("fix the growth", "add instrumentation") even though the task
173
+ // itself only investigates; a file-change gate on them is a 100% false
174
+ // no-op (live: takeOwnership #5701 completed with jsonl evidence in the
175
+ // claim comment, gate failed it, write-back went terminal, requeue loop).
176
+ if (/\b(perf|profile|investigat|diagnos|research|analy[sz]|evidence|forensic|triage|observ)\b/u.test(text)) {
177
+ return false;
178
+ }
179
+ if (/(性能|取证|调研|分析|诊断|排查|观察)/u.test(text)) {
180
+ return false;
181
+ }
169
182
  return /\b(implement|build|fix|rework|update|add|enhanc|deliver|write|create)\b/u.test(text);
170
183
  }
171
184
  export function projectHasMeaningfulDeliverableEvidence(task, contract) {
@@ -221,10 +234,22 @@ export function projectHasMeaningfulFileChanges(task, contract) {
221
234
  // Collaboration contract: write tasks deliver in a dedicated worktree.
222
235
  // An mtime scan is the wrong test there (committed files keep old mtimes
223
236
  // and the gate may run before the flush) - ask git instead: does HEAD carry
224
- // commits beyond the remote refs?
237
+ // commits beyond the task's BASE branch?
225
238
  if (task.projectDir.includes("__task-")) {
239
+ // #5654 (ggcode, 2026-11-15): the old probe counted UNPUSHED commits
240
+ // (`HEAD --not --remotes`). A worker that pushes its branch BEFORE
241
+ // submitting - the encouraged flow since the #5651 rebase-delivery path -
242
+ // always drained to 0 and got rejected as a no-op (live d4ddd1bd:
243
+ // delivered + pushed a3638d1da, gate said 0, task failed + issue
244
+ // reopened). Substantive means HEAD carries commits beyond the BASE
245
+ // branch (origin/<default>), whether or not they were already pushed.
246
+ let base = "origin/main";
247
+ try {
248
+ base = execFileSync("git", ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], { cwd: projectRoot }).toString().trim() || base;
249
+ }
250
+ catch { /* no origin/HEAD - conventional fallback above */ }
226
251
  try {
227
- const out = execFileSync("git", ["rev-list", "--count", "HEAD", "--not", "--remotes"], { cwd: projectRoot }).toString();
252
+ const out = execFileSync("git", ["rev-list", "--count", "HEAD", "--not", base], { cwd: projectRoot }).toString();
228
253
  return Number(out.trim()) > 0;
229
254
  }
230
255
  catch {
@@ -285,9 +310,15 @@ export function allowsNoChangeCompletion(task, contract, resultText) {
285
310
  || /\b(go test|go vet|npm test|pnpm test|yarn test|pytest|cargo test|verified|verification|passes|all tests pass|no remaining)\b/u.test(evidenceText);
286
311
  const noChangeIsExpected = /\b(qa|audit|review|verify|verification|validate|test|retest|confirm|check)\b/u.test(taskText)
287
312
  || /(审计|审核|验证|复检|复查|确认|测试|检查)/u.test(taskText)
313
+ // #5719: analysis-family work products live in the result itself.
314
+ || /\b(perf|profile|investigat|diagnos|research|analy[sz]|evidence|forensic|triage|observ)\b/u.test(taskText)
315
+ || /(性能|取证|调研|分析|诊断|排查|观察)/u.test(taskText)
288
316
  || /\b(already fixed|already resolved|no further changes|no code changes|no file changes|no additional changes|verified existing fix)\b/u.test(evidenceText)
289
317
  || /(已修复|已解决|无需改动|无需修改|没有额外修改|无需额外变更|只需验证)/u.test(evidenceText);
290
- return hasVerificationEvidence && noChangeIsExpected;
318
+ // #5719: for analysis-family tasks the substantive result text IS the
319
+ // verification evidence (metrics, traces, conclusions).
320
+ const analysisFamily = /\b(perf|profile|investigat|diagnos|research|analy[sz]|evidence|forensic|triage|observ)\b/u.test(taskText) || /(性能|取证|调研|分析|诊断|排查|观察)/u.test(taskText);
321
+ return (hasVerificationEvidence || (analysisFamily && resultText.trim().length > 200)) && noChangeIsExpected;
291
322
  }
292
323
  export function applyTaskResult(taskId, result, error, deps) {
293
324
  const { logger, updateTeamState, wsServer } = deps;