@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
@@ -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
@@ -231,7 +231,7 @@ export function createControllerHttpServer(deps: ControllerHttpDeps): http.Serve
231
231
  // structure below is unchanged from the pre-PR-D if/else chain.
232
232
  let tunnelManager = tunnelManagerSingleton;
233
233
  if (!tunnelManager) {
234
- tunnelManager = tunnelManagerSingleton = createTunnelManager({ logger, localPort: deps.config.port });
234
+ tunnelManager = tunnelManagerSingleton = createTunnelManager({ logger, localPort: deps.config.port, isProtectionOn: () => isProtectionOn(deps.getTeamState()) });
235
235
  }
236
236
  if (!tunnelRoutesSingleton) {
237
237
  tunnelRoutesSingleton = {
@@ -299,7 +299,7 @@ export function createControllerHttpServer(deps: ControllerHttpDeps): http.Serve
299
299
  // Boot reconciliation: reconnect a share persisted by a previous run
300
300
  // (gateway restart or kill -9) so the tunnel id and gate token survive.
301
301
  if (!tunnelManagerSingleton) {
302
- tunnelManagerSingleton = createTunnelManager({ logger, localPort: deps.config.port });
302
+ tunnelManagerSingleton = createTunnelManager({ logger, localPort: deps.config.port, isProtectionOn: () => isProtectionOn(deps.getTeamState()) });
303
303
  }
304
304
  void tunnelManagerSingleton.recover().catch((err) => {
305
305
  logger.warn(`TeamClaw tunnel: boot recovery failed: ${String(err)}`);
@@ -34,6 +34,18 @@ export function spawnManagedGatewayProcess(options: ManagedGatewaySpawnOptions):
34
34
  }
35
35
 
36
36
  export function spawnManagedCommandProcess(options: ManagedCommandSpawnOptions): ChildProcess {
37
+ // #terminal-activation guard: previewCommand is worker-influenced input
38
+ // (#237 W1) executed through the core sh -c wrapper. A prompt-injected
39
+ // `open`/osascript command hijacks LaunchServices and activates
40
+ // Terminal.app from the headless launchd context (reported live: default
41
+ // Terminal windows intermittently activating). Reject loudly - never
42
+ // silently - so the attempt is visible in logs.
43
+ const cmd = options.command.trim();
44
+ if (/^(open|osascript)\b/i.test(cmd) || /(^|[\s;&|])osascript\b/i.test(cmd) || /(^|\s)-a\s+Terminal\b/.test(cmd)) {
45
+ const reason = `blocked Terminal-activation command (preview contract violation): ${cmd.slice(0, 120)}`;
46
+ console.error(`[teamclaw] ${reason}`);
47
+ throw new Error(`[teamclaw] ${reason}`);
48
+ }
37
49
  const cwd = options.cwd ?? process.cwd();
38
50
  const child = spawn(process.execPath, buildManagedCommandWrapperArgs(options.command), {
39
51
  ...buildManagedProcessSpawnOptions({
@@ -251,9 +263,13 @@ const shutdownSignals = process.platform === "win32"
251
263
  ? ["SIGTERM", "SIGINT", "SIGBREAK"]
252
264
  : ["SIGTERM", "SIGINT", "SIGHUP", "SIGQUIT"];
253
265
  const shell = process.platform === "win32" ? "cmd.exe" : "sh";
266
+ // -c, NOT -lc: a LOGIN shell sources the user's profiles in a headless
267
+ // launchd context. Profile init scripts are interactive-session side-effect
268
+ // machines (open/LaunchServices hooks, TTY-needing helpers) and are the
269
+ // plausible amplifier behind intermittent Terminal.app activations.
254
270
  const shellArgs = process.platform === "win32"
255
271
  ? ["/d", "/s", "/c", command]
256
- : ["-lc", command];
272
+ : ["-c", command];
257
273
 
258
274
  let shuttingDown = false;
259
275
  let parentMonitor = null;
@@ -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
@@ -134,6 +145,17 @@ export class ProcessProvisioner implements WorkerProvisionerBackend {
134
145
  OPENCLAW_STATE_DIR: stateDir,
135
146
  OPENCLAW_CONFIG_PATH: configPath,
136
147
  OPENCLAW_SKIP_CANVAS_HOST: "1",
148
+ // #disk-hygiene (screenshot report 2026-11-19): worker go builds can
149
+ // accumulate gigabytes of go-build/go-link dirs in the HOME tmp when
150
+ // deployments want them on a scratch volume. Opt-in ONLY - hardcoded
151
+ // paths would break any deployment without that volume. When the
152
+ // operator sets TEAMCLAW_GOCACHE / TEAMCLAW_GOTMPDIR, they are
153
+ // forwarded as GOCACHE / GOTMPDIR (an externally-set GOCACHE already
154
+ // flows through ...process.env untouched and is never overridden);
155
+ // unset -> Go defaults apply exactly as before. Kept ABOVE the
156
+ // workspaceDir spread so the contract test's env-tail shape holds.
157
+ ...(process.env.TEAMCLAW_GOCACHE && !process.env.GOCACHE ? { GOCACHE: process.env.TEAMCLAW_GOCACHE } : {}),
158
+ ...(process.env.TEAMCLAW_GOTMPDIR && !process.env.GOTMPDIR ? { GOTMPDIR: process.env.TEAMCLAW_GOTMPDIR } : {}),
137
159
  TEAMCLAW_WORKER_ID: spec.workerId,
138
160
  TEAMCLAW_LAUNCH_TOKEN: spec.launchToken,
139
161
  ...(spec.workspaceDir ? { TEAMCLAW_WORKSPACE_DIR: spec.workspaceDir } : {}),
@@ -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);
@@ -575,8 +575,8 @@ export const controllerRouteTable: readonly RouteDef[] = [
575
575
  // pair/start- authenticated device or loopback (mints a fresh code,
576
576
  // invalidating the previous one)
577
577
  // pair - one-shot 60s code exchange -> {token, deviceId}
578
- // pair-auto - LAN peer + config.security.autoPair + protection on
579
- // reset - authenticated device or loopback (anti-lockout hatch)
578
+ // pair-auto - LAN peer + config.security.autoPair (opt-in) + protection on
579
+ // reset - loopback only (anti-lockout hatch; controller host action)
580
580
  // GET /security and DELETE /security/devices/:id are NOT exempt: the
581
581
  // middleware itself guarantees the caller holds a valid device token.
582
582
  { method: "POST", path: "/api/v1/security/enable", handler: handleSecurityEnableRequest },
@@ -524,6 +524,20 @@ export function createWebSocketUpgradeGuard(deps: WebSocketUpgradeGuardDeps): (r
524
524
  const viaTunnel = deps.isTunnelHost(typeof req.headers.host === "string" ? req.headers.host : undefined);
525
525
  const peer = classifySecurityPeer(req.socket.remoteAddress, viaTunnel);
526
526
  const state = deps.getTeamState();
527
+ // ClawHub security review 2026.11.6 (finding 3): the tunnel gate must
528
+ // run BEFORE the protection-off allowance. The HTTP path enforces
529
+ // gateAllows for every tunnel request regardless of device protection
530
+ // (http-server.ts), so a protection-off controller still gates its HTTP
531
+ // surface - but this guard used to return true first, which left /ws as
532
+ // the one tunnel surface a gate-cookie-less visitor could subscribe to
533
+ // (task/message/clarification event stream). Same layering as HTTP now.
534
+ if (peer.viaTunnel) {
535
+ if (!deps.gateAllows || !deps.gateAllows(req)) {
536
+ deps.logger.warn(`Controller: rejected WebSocket upgrade from ${peer.ip} (via tunnel, no gate cookie)`);
537
+ return false;
538
+ }
539
+ return true;
540
+ }
527
541
  if (!isProtectionOn(state)) {
528
542
  recordNonLanPeerSignal(deps, state, peer, "/ws");
529
543
  return true;
@@ -536,13 +550,8 @@ export function createWebSocketUpgradeGuard(deps: WebSocketUpgradeGuardDeps): (r
536
550
  if (peer.loopback) {
537
551
  return true;
538
552
  }
539
- // Tunnel-origin upgrades (cloudflared loopback + tunnel Host): the
540
- // visitor holds the GATE token, not a pairing token - same layering
541
- // as the HTTP gate (a device token here would be an unanswerable
542
- // wall, 8b03ed6). Verify the gate cookie instead.
543
- if (peer.viaTunnel && deps.gateAllows && deps.gateAllows(req)) {
544
- return true;
545
- }
553
+ // Tunnel-origin upgrades were handled above (gate cookie, never a pairing
554
+ // token - a device token here would be an unanswerable wall, 8b03ed6).
546
555
  let token = extractDeviceToken(req);
547
556
  if (!token) {
548
557
  const url = new URL(req.url ?? "/ws", `http://${req.headers.host ?? "localhost"}`);
@@ -792,10 +801,10 @@ export async function handleSecurityPairAutoRequest(ctx: RouteContext): Promise<
792
801
  });
793
802
  return;
794
803
  }
795
- if ((deps.config.security?.autoPair ?? true) !== true) {
804
+ if ((deps.config.security?.autoPair ?? false) !== true) {
796
805
  sendJson(res, 403, {
797
806
  error: "auto-pairing is disabled on this controller",
798
- hint: "The owner disabled security.autoPair; ask for a pairing code and POST /api/v1/security/pair {\"code\",\"kind\",\"name\"}.",
807
+ 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\"}.",
799
808
  });
800
809
  return;
801
810
  }
@@ -828,7 +837,7 @@ export async function handleSecurityGetRequest(ctx: RouteContext): Promise<void>
828
837
  protection: isProtectionOn(state),
829
838
  devices: (security?.devices ?? []).map(serializeDevice),
830
839
  ...(active ? { pairingCode: { expiresAt: active.expiresAt, purpose: active.purpose } } : {}),
831
- autoPair: deps.config.security?.autoPair ?? true,
840
+ autoPair: deps.config.security?.autoPair ?? false,
832
841
  });
833
842
  }
834
843
 
@@ -857,15 +866,21 @@ export async function handleSecurityDeviceDeleteRequest(ctx: RouteContext): Prom
857
866
  sendJson(res, 200, { ok: true, revoked: deviceId, revokedSelf, protection });
858
867
  }
859
868
 
860
- // POST /api/v1/security/reset - authenticated OR loopback (anti-lockout
861
- // hatch), plus an explicit confirm token (#255 P1-8): a paired device must
862
- // knowingly opt in, since the reset drops protection to L0 for EVERYONE.
869
+ // POST /api/v1/security/reset - LOOPBACK ONLY (anti-lockout hatch), plus
870
+ // an explicit confirm token (#255 P1-8). ClawHub security review 2026.11.6
871
+ // (finding 2): a paired device token used to be enough to drop protection
872
+ // for EVERYONE - any LAN device that self-paired via auto-pair could reset
873
+ // the controller to L0. Reset is now a controller-host action only; remote
874
+ // owners revoke devices individually or re-enable from the host.
863
875
  export async function handleSecurityResetRequest(ctx: RouteContext): Promise<void> {
864
876
  const { req, res, deps, peer } = ctx;
865
877
  const state = deps.getTeamState();
866
878
  const auth = authenticateDeviceToken(state, extractDeviceToken(req));
867
- if (!auth && !(peer?.loopback ?? false)) {
868
- sendUnauthorized(res);
879
+ if (!(peer?.loopback ?? false)) {
880
+ sendJson(res, 403, {
881
+ error: "forbidden",
882
+ 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.",
883
+ });
869
884
  return;
870
885
  }
871
886
  const body = await parseJsonBody(req);
@@ -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,94 @@ 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?.reason === "issue closed") {
660
+ // #5818: the claim check VERDICTED against the task - the issue was
661
+ // closed between enqueue and dequeue. That is terminal (no retry
662
+ // helps); running the leg anyway burned a full 8-minute worker on
663
+ // a closed issue (live: 952e7471). Cancel the dispatched execution
664
+ // and terminalize the task as cancelled - NOT back to pending (a
665
+ // pending task would redispatch; the sweep will not re-candidate a
666
+ // closed issue, but the queue entry would keep firing).
667
+ logger.warn(`Controller: issue closed before dispatch for ${updatedTask.id} - cancelling task`);
668
+ void (async () => {
669
+ await cancelTaskExecution(updatedTask.id, nextAssignment.worker.id, "target issue closed (#5818)", deps);
670
+ deps.updateTeamState((s) => {
671
+ const t = s.tasks[updatedTask.id];
672
+ if (!t) return;
673
+ t.status = "failed";
674
+ t.error = "Cancelled: target issue was closed before dispatch (#5818) - no work performed.";
675
+ t.updatedAt = Date.now();
676
+ // #5825: cancelTaskExecution never resets the worker record,
677
+ // and cancelling also suppresses the worker-side completion
678
+ // report - so nothing ever flipped the seat idle. Release here
679
+ // (same shape as the normal completion path) or the worker
680
+ // stays orphan-busy forever (live: 2 busy, 1 in_progress).
681
+ const w = s.workers[nextAssignment.worker.id];
682
+ if (w && w.currentTaskId === updatedTask.id) {
683
+ w.status = "idle";
684
+ w.currentTaskId = undefined;
685
+ }
686
+ });
687
+ wsServer.broadcastUpdate({ type: "task:updated", data: serializeTask(deps.getTeamState()?.tasks[updatedTask.id] ?? updatedTask) });
688
+ })().catch(() => {});
689
+ } else if (claim?.retryEligibility) {
690
+ logger.warn(`Controller: claim eligibility check failed for ${updatedTask.id} - reverting assignment to retry`);
691
+ // Unlike the #191 dispatch-failure path, the dispatch SUCCEEDED
692
+ // here: cancel the already-dispatched execution before reverting
693
+ // so the orphaned run cannot keep executing (and PATCH the task
694
+ // back to in_progress) while the controller re-queues it. The
695
+ // exponential assignment hold bounds the outage retry cadence.
696
+ void (async () => {
697
+ await cancelTaskExecution(updatedTask.id, nextAssignment.worker.id, "claim eligibility retry (#5740)", deps);
698
+ const failures = (deps.getTeamState()?.tasks[updatedTask.id]?.assignmentHoldCount ?? 0) + 1;
699
+ revertTaskAssignment(updatedTask.id, nextAssignment.worker.id, deps, {
700
+ holdMs: claimEligibilityHoldMs(failures),
701
+ });
702
+ })().catch(() => {});
703
+ } else if (claim?.reason === "external activity" || claim?.reason === "assignees present") {
704
+ // #5823: stand-down verdicts are TERMINAL like issue-closed (the
705
+ // seat/owner is not going away; retrying cannot help) - the old
706
+ // else-branch only cleared the hold and the leg ran to completion
707
+ // on an issue another seat owns (live: the #5819 self-fix leg
708
+ // stood down at 21:24 yet kept executing at 21:38). Same treatment
709
+ // as #5818: cancel the dispatched execution, terminalize with the
710
+ // stand-down reason, no dead-letter count.
711
+ logger.warn(`Controller: claim stood down (${claim.reason}) for ${updatedTask.id} - cancelling task`);
712
+ void (async () => {
713
+ await cancelTaskExecution(updatedTask.id, nextAssignment.worker.id, `claim stand-down: ${claim.reason} (#5823)`, deps);
714
+ deps.updateTeamState((s) => {
715
+ const t = s.tasks[updatedTask.id];
716
+ if (!t) return;
717
+ t.status = "failed";
718
+ t.error = `Cancelled: claim stood down (${claim.reason}) - another seat/owner owns the issue (#5823). No work performed.`;
719
+ t.updatedAt = Date.now();
720
+ // #5825: same orphan-busy release as the #5818 branch above.
721
+ const w = s.workers[nextAssignment.worker.id];
722
+ if (w && w.currentTaskId === updatedTask.id) {
723
+ w.status = "idle";
724
+ w.currentTaskId = undefined;
725
+ }
726
+ });
727
+ clearAssignmentHold(updatedTask.id, deps);
728
+ wsServer.broadcastUpdate({ type: "task:updated", data: serializeTask(deps.getTeamState()?.tasks[updatedTask.id] ?? updatedTask) });
729
+ })().catch(() => {});
730
+ } else {
731
+ // Claim attempt concluded definitively (claimed / stood down /
732
+ // WRITE failure continuing unclaimed): end the retry cycle.
733
+ clearAssignmentHold(updatedTask.id, deps);
734
+ }
735
+ }).catch(() => {});
609
736
  wsServer.broadcastUpdate({ type: "task:updated", data: serializeTask(updatedTask) });
610
737
  logger.info(
611
738
  `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(
@@ -69,6 +69,7 @@ import {
69
69
  } from "./controller-planning.js";
70
70
  import {
71
71
  ControllerIntakeSwitchInProgressError,
72
+ isStillWaitingResponse,
72
73
  runControllerIntake,
73
74
  } from "./controller-intake.js";
74
75
  import {
@@ -273,19 +274,43 @@ export async function handleTaskExecutionGetRequest(deps: ControllerTaskDomainDe
273
274
 
274
275
  // PATCH /api/v1/tasks/:id
275
276
  export async function handleTaskPatchRequest(deps: ControllerTaskDomainDeps, req: IncomingMessage, res: ServerResponse, pathname: string): Promise<void> {
276
- const { updateTeamState, wsServer } = deps;
277
+ const { updateTeamState, wsServer, logger, getTeamState } = deps;
277
278
  const taskId = pathname.split("/").pop()!;
278
279
  const body = await parseJsonBody(req);
279
280
  let statusEvent: TaskExecutionEvent | undefined;
280
281
  let progressEvent: TaskExecutionEvent | undefined;
281
282
  let progressContract: WorkerProgressContract | undefined;
282
283
 
284
+ // #5740 (ggcode, 2026-11-17): worker progress PATCHes now carry workerId;
285
+ // when present, the same stale-worker guard as the result routes applies
286
+ // so a dispatched-but-reverted (orphaned) run cannot keep mutating the
287
+ // task it no longer owns.
288
+ const patchWorkerId = typeof body.workerId === "string" ? body.workerId : undefined;
289
+ if (patchWorkerId) {
290
+ const currentTask = getTeamState()?.tasks[taskId];
291
+ if (currentTask && !canAcceptWorkerUpdate(currentTask, patchWorkerId)) {
292
+ logger.info(`Controller: ignoring stale task patch for ${taskId} from ${patchWorkerId}`);
293
+ sendJson(res, 202, { status: "ignored", reason: "stale-worker-update" });
294
+ return;
295
+ }
296
+ }
297
+
283
298
  const state = updateTeamState((s) => {
284
299
  const task = s.tasks[taskId];
285
300
  if (!task) return;
286
301
  const previousStatus = task.status;
287
302
  const previousProgress = task.progress;
288
303
  const previousProgressContract = task.progressContract;
304
+ // #5740: a bare PATCH (no workerId, e.g. WebUI) must not flip a pending,
305
+ // unassigned task to in_progress - that is exactly the illegal
306
+ // unclaimed-execution state the claim gate exists to prevent. The
307
+ // progress text below still applies.
308
+ if (typeof body.status === "string"
309
+ && body.status === "in_progress"
310
+ && task.status === "pending"
311
+ && !task.assignedWorkerId) {
312
+ delete body.status;
313
+ }
289
314
  if (typeof body.status === "string") task.status = body.status as TaskStatus;
290
315
  if (typeof body.progress === "string") task.progress = body.progress as string;
291
316
  if (typeof body.priority === "string") task.priority = body.priority as TaskPriority;
@@ -555,7 +580,7 @@ export async function handleTaskResultRequest(deps: ControllerTaskDomainDeps, re
555
580
  const { logger, getTeamState, updateTeamState } = deps;
556
581
  const taskId = pathname.split("/")[4]!;
557
582
  const body = await parseJsonBody(req);
558
- const result = typeof body.result === "string" ? body.result : "";
583
+ let result = typeof body.result === "string" ? body.result : "";
559
584
  let error = typeof body.error === "string" ? body.error : undefined;
560
585
  const workerId = typeof body.workerId === "string" ? body.workerId : undefined;
561
586
  const currentTask = getTeamState()?.tasks[taskId];
@@ -644,6 +669,43 @@ export async function handleTaskResultRequest(deps: ControllerTaskDomainDeps, re
644
669
  }
645
670
 
646
671
  const gatedTask = getTeamState()?.tasks[taskId];
672
+ // #5767 fourth hole: a worker that never produced work can "complete" by
673
+ // submitting the waiting SENTINEL as its result (live: f12efcdb completed
674
+ // with `TEAMCLAW_STILL_WAITING`). The sentinel means "not done yet" - it
675
+ // must never satisfy completion. Reject with an empty stored result so the
676
+ // failed-without-result semantics apply (terminal write-back, claim
677
+ // recovery re-opens the issue, the next sweep retries).
678
+ if (!error && gatedTask && isStillWaitingResponse(result)) {
679
+ error = "Task submitted the TEAMCLAW_STILL_WAITING placeholder as its result - the task is still waiting, not complete. Result discarded; the issue will be re-opened for the next sweep.";
680
+ recordTaskExecutionEvent(taskId, {
681
+ type: "warning",
682
+ phase: "completion_gate",
683
+ source: "controller",
684
+ status: "failed",
685
+ message: error,
686
+ workerId,
687
+ role: gatedTask.assignedRole,
688
+ }, deps);
689
+ result = "";
690
+ }
691
+ // #5770 leg A: a MID-FLIGHT narration is not a final result either (live:
692
+ // "Tree is clean. Now implementing the fix - first the helper in ...").
693
+ // Present-progressive openers mean the work has NOT finished; accepting
694
+ // them completes a task with zero product. Reject like the sentinel -
695
+ // fresh attempt on the next sweep once the worker actually finishes.
696
+ if (!error && gatedTask && /\b(?:now|currently|next)\s+(?:implementing|working on|fixing|writing|adding|refactoring|investigating|starting)\b/i.test(result.slice(0, 400))) {
697
+ error = "Task submitted a mid-flight narration (present-progressive) as its result - the work is still in progress, not complete. Result discarded; the issue will be re-opened for the next sweep.";
698
+ recordTaskExecutionEvent(taskId, {
699
+ type: "warning",
700
+ phase: "completion_gate",
701
+ source: "controller",
702
+ status: "failed",
703
+ message: error,
704
+ workerId,
705
+ role: gatedTask.assignedRole,
706
+ }, deps);
707
+ result = "";
708
+ }
647
709
  if (
648
710
  !error
649
711
  && gatedTask