@teamclaws/teamclaw 2026.11.6 → 2026.11.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +17 -11
  2. package/dist/src/config.js +3 -3
  3. package/dist/src/controller/http-server.js +2 -2
  4. package/dist/src/controller/managed-gateway-process.js +17 -1
  5. package/dist/src/controller/provisioning/process-supervisor.js +11 -0
  6. package/dist/src/controller/route-table.js +2 -2
  7. package/dist/src/controller/security.js +30 -15
  8. package/dist/src/controller/task-assignment.js +62 -1
  9. package/dist/src/controller/task-routes.js +39 -2
  10. package/dist/src/controller/tunnel-manager.js +11 -0
  11. package/dist/src/controller/tunnel-routes.js +11 -0
  12. package/dist/src/controller/workspace-routes.js +16 -2
  13. package/dist/src/teamauto/github-client.js +19 -0
  14. package/dist/src/teamauto/repo-sync.js +96 -22
  15. package/dist/src/teamauto/scheduler.js +458 -36
  16. package/dist/src/teamauto/store.js +125 -3
  17. package/dist/src/types.js +5 -3
  18. package/dist/src/ui/app.js +2 -2
  19. package/dist/src/worker/worker-service.js +13 -1
  20. package/dist/src/workspace-browser.js +14 -0
  21. package/openclaw.plugin.json +5 -5
  22. package/package.json +4 -2
  23. package/src/config.ts +3 -3
  24. package/src/controller/http-server.ts +2 -2
  25. package/src/controller/managed-gateway-process.ts +17 -1
  26. package/src/controller/provisioning/process-supervisor.ts +11 -0
  27. package/src/controller/route-table.ts +2 -2
  28. package/src/controller/security.ts +30 -15
  29. package/src/controller/task-assignment.ts +58 -1
  30. package/src/controller/task-routes.ts +39 -1
  31. package/src/controller/tunnel-manager.ts +12 -1
  32. package/src/controller/tunnel-routes.ts +11 -0
  33. package/src/controller/workspace-routes.ts +17 -2
  34. package/src/teamauto/github-client.ts +21 -1
  35. package/src/teamauto/repo-sync.ts +85 -21
  36. package/src/teamauto/scheduler.ts +434 -33
  37. package/src/teamauto/store.ts +133 -3
  38. package/src/types.ts +9 -7
  39. package/src/ui/app.js +2 -2
  40. package/src/worker/worker-service.ts +15 -1
  41. package/src/workspace-browser.ts +15 -0
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",
@@ -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;
@@ -134,6 +134,17 @@ export class ProcessProvisioner {
134
134
  OPENCLAW_STATE_DIR: stateDir,
135
135
  OPENCLAW_CONFIG_PATH: configPath,
136
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 } : {}),
137
148
  TEAMCLAW_WORKER_ID: spec.workerId,
138
149
  TEAMCLAW_LAUNCH_TOKEN: spec.launchToken,
139
150
  ...(spec.workspaceDir ? { TEAMCLAW_WORKSPACE_DIR: spec.workspaceDir } : {}),
@@ -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);
@@ -541,7 +541,39 @@ export async function runAutoAssignRound(deps, preferredWorkerId, attemptedPairs
541
541
  // bypassing the gate). Write-phase claim failures still continue
542
542
  // unclaimed per the original 2026-11-15 semantics.
543
543
  deps.getTeamAutoScheduler?.()?.claimTaskAtDequeue(updatedTask).then((claim) => {
544
- if (claim?.retryEligibility) {
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) {
545
577
  logger.warn(`Controller: claim eligibility check failed for ${updatedTask.id} - reverting assignment to retry`);
546
578
  // Unlike the #191 dispatch-failure path, the dispatch SUCCEEDED
547
579
  // here: cancel the already-dispatched execution before reverting
@@ -556,6 +588,35 @@ export async function runAutoAssignRound(deps, preferredWorkerId, attemptedPairs
556
588
  });
557
589
  })().catch(() => { });
558
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
+ }
559
620
  else {
560
621
  // Claim attempt concluded definitively (claimed / stood down /
561
622
  // WRITE failure continuing unclaimed): end the retry cycle.
@@ -10,7 +10,7 @@ import { buildEmptyTaskCleanupSummary, deleteTaskCascade } from "./task-cleanup.
10
10
  import { allowsNoChangeCompletion, applyTaskResult, buildEffectiveTaskResultContract, consolidateDiscoveredPatterns, ensureTaskResultContract, enrichWithFilesystemHtmlScan, filterStaleDeliverables, projectHasMeaningfulFileChanges, taskRequiresMeaningfulProjectChangeGate, } from "./task-results.js";
11
11
  import { requestTaskClarification } from "./clarification-routes.js";
12
12
  import { buildControllerParallelHelpMessage, resolveControllerWorkflowSessionKey, } from "./controller-planning.js";
13
- import { ControllerIntakeSwitchInProgressError, runControllerIntake, } from "./controller-intake.js";
13
+ import { ControllerIntakeSwitchInProgressError, isStillWaitingResponse, runControllerIntake, } from "./controller-intake.js";
14
14
  import { buildStartupReadinessMessage, shouldBlockControllerUntilProvisioningReady, } from "./worker-routes.js";
15
15
  import { buildControllerNoWorkersMessage, shouldBlockControllerWithoutWorkers, } from "./controller-capacity.js";
16
16
  // Same value as the SWITCH_TASK_SUBMISSION_RETRY_AFTER_SECONDS constant the
@@ -489,7 +489,7 @@ export async function handleTaskResultRequest(deps, req, res, pathname) {
489
489
  const { logger, getTeamState, updateTeamState } = deps;
490
490
  const taskId = pathname.split("/")[4];
491
491
  const body = await parseJsonBody(req);
492
- const result = typeof body.result === "string" ? body.result : "";
492
+ let result = typeof body.result === "string" ? body.result : "";
493
493
  let error = typeof body.error === "string" ? body.error : undefined;
494
494
  const workerId = typeof body.workerId === "string" ? body.workerId : undefined;
495
495
  const currentTask = getTeamState()?.tasks[taskId];
@@ -574,6 +574,43 @@ export async function handleTaskResultRequest(deps, req, res, pathname) {
574
574
  return;
575
575
  }
576
576
  const gatedTask = getTeamState()?.tasks[taskId];
577
+ // #5767 fourth hole: a worker that never produced work can "complete" by
578
+ // submitting the waiting SENTINEL as its result (live: f12efcdb completed
579
+ // with `TEAMCLAW_STILL_WAITING`). The sentinel means "not done yet" - it
580
+ // must never satisfy completion. Reject with an empty stored result so the
581
+ // failed-without-result semantics apply (terminal write-back, claim
582
+ // recovery re-opens the issue, the next sweep retries).
583
+ if (!error && gatedTask && isStillWaitingResponse(result)) {
584
+ 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.";
585
+ recordTaskExecutionEvent(taskId, {
586
+ type: "warning",
587
+ phase: "completion_gate",
588
+ source: "controller",
589
+ status: "failed",
590
+ message: error,
591
+ workerId,
592
+ role: gatedTask.assignedRole,
593
+ }, deps);
594
+ result = "";
595
+ }
596
+ // #5770 leg A: a MID-FLIGHT narration is not a final result either (live:
597
+ // "Tree is clean. Now implementing the fix - first the helper in ...").
598
+ // Present-progressive openers mean the work has NOT finished; accepting
599
+ // them completes a task with zero product. Reject like the sentinel -
600
+ // fresh attempt on the next sweep once the worker actually finishes.
601
+ if (!error && gatedTask && /\b(?:now|currently|next)\s+(?:implementing|working on|fixing|writing|adding|refactoring|investigating|starting)\b/i.test(result.slice(0, 400))) {
602
+ 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.";
603
+ recordTaskExecutionEvent(taskId, {
604
+ type: "warning",
605
+ phase: "completion_gate",
606
+ source: "controller",
607
+ status: "failed",
608
+ message: error,
609
+ workerId,
610
+ role: gatedTask.assignedRole,
611
+ }, deps);
612
+ result = "";
613
+ }
577
614
  if (!error
578
615
  && gatedTask
579
616
  && taskRequiresMeaningfulProjectChangeGate(gatedTask)
@@ -448,6 +448,17 @@ export function createTunnelManager(deps) {
448
448
  const st = readTunnelState();
449
449
  if (!st || st.tunnelId === "quick")
450
450
  return null; // one-off, not recoverable
451
+ // ClawHub security review 2026.11.6 (finding 4): a self-hosted tunnel's
452
+ // custom hostname never matches the built-in gate suffixes, so its
453
+ // traffic arrives as a loopback peer and inherits trusted-host access.
454
+ // Device protection is the only thing standing between that public
455
+ // ingress and the API - do not reconnect one while protection is off;
456
+ // drop the stale state so the owner re-enables deliberately.
457
+ if (st.tunnelId === "self-hosted" && deps.isProtectionOn && !deps.isProtectionOn()) {
458
+ logger.warn("TeamClaw tunnel: NOT recovering the previous self-hosted tunnel - device protection is off and a custom-domain tunnel bypasses the sharing gate; enable device pairing (POST /api/v1/security/enable) and start it again from the Tunnel page");
459
+ clearTunnelState();
460
+ return null;
461
+ }
451
462
  const bin = findCloudflared();
452
463
  if (!bin) {
453
464
  logger.warn("TeamClaw tunnel: previous share found but cloudflared is not installed; not recovering");
@@ -176,6 +176,17 @@ export function createTunnelManagementRoutes(tunnelManager, deps) {
176
176
  if (!tunnelStartAllowedFrom(req, res)) {
177
177
  return;
178
178
  }
179
+ // ClawHub security review 2026.11.6 (finding 4): a self-hosted
180
+ // tunnel's custom hostname is outside the built-in gate, so its
181
+ // requests arrive as trusted loopback peers. Without device
182
+ // protection that is unauthenticated public access to the API.
183
+ if (!isProtectionOn(deps.getTeamState())) {
184
+ sendJson(res, 409, {
185
+ error: "device protection must be enabled before starting a self-hosted tunnel",
186
+ hint: "A custom-domain tunnel bypasses the sharing gate (its hostname is not *.teamclaw.dev), so every request reaches this controller as a trusted local peer. Enable device pairing first (POST /api/v1/security/enable from the controller host), then start the tunnel. Managed (*.teamclaw.dev) tunnels are gate-protected and unaffected.",
187
+ });
188
+ return;
189
+ }
179
190
  logger.info(`TeamClaw tunnel: start-self-hosted requested (${tunnelCaller(req)})`);
180
191
  let token = "";
181
192
  try {
@@ -19,6 +19,8 @@ function workspaceRequestErrorStatus(err) {
19
19
  function workspaceRequestErrorMessage(err) {
20
20
  return err instanceof Error ? err.message : "Workspace request failed";
21
21
  }
22
+ // Active content the raw route must sandbox on direct navigation (finding 6).
23
+ const ACTIVE_CONTENT_TYPES = new Set(["text/html; charset=utf-8", "image/svg+xml"]);
22
24
  function workspaceStatusRoute(ctx) {
23
25
  const { res } = ctx;
24
26
  sendJson(res, 200, {
@@ -181,7 +183,15 @@ async function workspaceRawFileRoute(ctx) {
181
183
  try {
182
184
  const relativePath = decodeURIComponent(rawPathname);
183
185
  const file = await readWorkspaceRawFile(relativePath);
184
- res.writeHead(200, {
186
+ // ClawHub security review 2026.11.6 (finding 6): HTML/SVG served with
187
+ // their active MIME type under the controller origin execute with the
188
+ // owner's session on DIRECT navigation (the preview iframe's sandbox
189
+ // attribute does not travel with the "Open Raw" link). A response-level
190
+ // CSP sandbox without allow-same-origin gives the document an opaque
191
+ // origin even on top-level navigation: scripts may run (the preview
192
+ // already allows that) but cannot read controller cookies or call
193
+ // /api/v1/* same-origin. Mirrors the iframe flags byte for byte.
194
+ const headers = {
185
195
  "Content-Type": file.contentType,
186
196
  "Cache-Control": "no-store",
187
197
  // Issue #23 security review follow-up: honor a CORS origin the
@@ -190,7 +200,11 @@ async function workspaceRawFileRoute(ctx) {
190
200
  // historical "*" byte for byte (shared helper, see protocol.ts).
191
201
  "Access-Control-Allow-Origin": pinnedCorsAllowOrigin(res),
192
202
  "X-Content-Type-Options": "nosniff",
193
- });
203
+ };
204
+ if (ACTIVE_CONTENT_TYPES.has(file.contentType)) {
205
+ headers["Content-Security-Policy"] = "sandbox allow-scripts allow-forms";
206
+ }
207
+ res.writeHead(200, headers);
194
208
  res.end(file.content);
195
209
  }
196
210
  catch (err) {
@@ -160,6 +160,24 @@ export function createGithubClient(auth) {
160
160
  };
161
161
  });
162
162
  },
163
+ /** #5785: PRs (any state) whose head is exactly this branch - the
164
+ * PR-face evidence surface. The settle audit asks "did this WRITE task's
165
+ * PR ever come into existence", which no comment surface can answer (an
166
+ * issue direct-post masks the missing PR). Mirrors the sentinel's
167
+ * pulls?head= REST probe. */
168
+ async listPullsByHead(owner, repo, branch) {
169
+ const { data } = await request("GET", `/repos/${owner}/${repo}/pulls?head=${encodeURIComponent(`${owner}:${branch}`)}&state=all&per_page=10`);
170
+ if (!Array.isArray(data)) {
171
+ return [];
172
+ }
173
+ return data
174
+ .map((raw) => ({
175
+ number: Number(raw.number ?? 0),
176
+ state: String(raw.state ?? ""),
177
+ htmlUrl: String(raw.html_url ?? ""),
178
+ }))
179
+ .filter((p) => p.number > 0);
180
+ },
163
181
  async listCommits(owner, repo, sinceSha) {
164
182
  const suffix = sinceSha ? `?sha=${encodeURIComponent(sinceSha)}` : "?per_page=20";
165
183
  void suffix;
@@ -246,6 +264,7 @@ export function createGithubClient(auth) {
246
264
  return data.map((c) => ({
247
265
  user: String(c.user?.login ?? ""),
248
266
  createdAt: String(c.created_at ?? ""),
267
+ body: String(c.body ?? ""),
249
268
  })).filter((c) => c.user);
250
269
  }
251
270
  catch {