@teamclaws/teamclaw 2026.11.6 → 2026.11.8

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 (43) hide show
  1. package/README.md +17 -11
  2. package/dist/src/config.js +3 -3
  3. package/dist/src/controller/http-server.js +18 -6
  4. package/dist/src/controller/managed-gateway-process.js +17 -1
  5. package/dist/src/controller/preview-proxy.js +55 -8
  6. package/dist/src/controller/provisioning/process-supervisor.js +11 -0
  7. package/dist/src/controller/route-table.js +2 -2
  8. package/dist/src/controller/security.js +85 -17
  9. package/dist/src/controller/task-assignment.js +62 -1
  10. package/dist/src/controller/task-routes.js +39 -2
  11. package/dist/src/controller/tunnel-manager.js +11 -0
  12. package/dist/src/controller/tunnel-routes.js +11 -0
  13. package/dist/src/controller/workspace-routes.js +16 -2
  14. package/dist/src/teamauto/github-client.js +19 -0
  15. package/dist/src/teamauto/repo-sync.js +96 -22
  16. package/dist/src/teamauto/scheduler.js +458 -36
  17. package/dist/src/teamauto/store.js +125 -3
  18. package/dist/src/types.js +5 -3
  19. package/dist/src/ui/app.js +2 -2
  20. package/dist/src/worker/worker-service.js +13 -1
  21. package/dist/src/workspace-browser.js +14 -0
  22. package/openclaw.plugin.json +5 -5
  23. package/package.json +4 -2
  24. package/src/config.ts +3 -3
  25. package/src/controller/http-server.ts +19 -5
  26. package/src/controller/managed-gateway-process.ts +17 -1
  27. package/src/controller/preview-proxy.ts +54 -8
  28. package/src/controller/provisioning/process-supervisor.ts +11 -0
  29. package/src/controller/route-table.ts +2 -2
  30. package/src/controller/security.ts +90 -17
  31. package/src/controller/task-assignment.ts +58 -1
  32. package/src/controller/task-routes.ts +39 -1
  33. package/src/controller/tunnel-manager.ts +12 -1
  34. package/src/controller/tunnel-routes.ts +11 -0
  35. package/src/controller/workspace-routes.ts +17 -2
  36. package/src/teamauto/github-client.ts +21 -1
  37. package/src/teamauto/repo-sync.ts +85 -21
  38. package/src/teamauto/scheduler.ts +434 -33
  39. package/src/teamauto/store.ts +133 -3
  40. package/src/types.ts +9 -7
  41. package/src/ui/app.js +2 -2
  42. package/src/worker/worker-service.ts +15 -1
  43. package/src/workspace-browser.ts +15 -0
@@ -211,6 +211,40 @@ export function classifySecurityPeer(ip: string | undefined, viaTunnel: boolean)
211
211
  };
212
212
  }
213
213
 
214
+ /**
215
+ * ClawHub security review 2026.11.7 (finding 1): every request that rode
216
+ * through the Cloudflare edge carries CF-Connecting-IP / CF-Ray (added by
217
+ * the edge, not by cloudflared or the client). The managed tunnel suffixes
218
+ * in tunnel-manager catch *.teamclaw.dev / *.trycloudflare.com by Host,
219
+ * but a SELF-HOSTED tunnel serves a custom hostname, so its traffic used to
220
+ * classify as a plain loopback peer and inherit trusted-host access even
221
+ * while device protection was on. Treating edge-marked requests as tunnel
222
+ * traffic closes that: a forged CF header only ever DOWNGRADES the caller
223
+ * (tunnel peers are never loopback/LAN), never grants anything.
224
+ */
225
+ export function hasCloudflareEdgeHeaders(req: { headers: Record<string, unknown> }): boolean {
226
+ const h = req.headers;
227
+ return Boolean(h["cf-connecting-ip"] || h["cf-ray"] || h["cf-worker"]);
228
+ }
229
+
230
+ /** Origin policy for browser WebSocket upgrades (review 2026.11.7 finding 3). */
231
+ export function isAllowedWebSocketOrigin(req: { headers: Record<string, unknown> }): boolean {
232
+ const origin = req.headers.origin;
233
+ if (typeof origin !== "string" || !origin.trim()) {
234
+ return true; // non-browser clients (CLI, workers, curl) send no Origin
235
+ }
236
+ const host = typeof req.headers.host === "string" ? req.headers.host : "";
237
+ if (!host) {
238
+ return false;
239
+ }
240
+ try {
241
+ const u = new URL(origin);
242
+ return (u.protocol === "http:" || u.protocol === "https:") && u.host.toLowerCase() === host.toLowerCase();
243
+ } catch {
244
+ return false;
245
+ }
246
+ }
247
+
214
248
  // ---------------------------------------------------------------------------
215
249
  // State helpers
216
250
  // ---------------------------------------------------------------------------
@@ -370,6 +404,8 @@ export type SecurityMiddlewareDeps = {
370
404
  logger: PluginLogger;
371
405
  getTeamState: () => TeamState | null;
372
406
  updateTeamState: (updater: (state: TeamState) => void) => TeamState;
407
+ /** Active tunnel mode ("self-hosted" means tunnel visitors must hold a device token, not a gate cookie). */
408
+ tunnelMode?: () => "managed" | "self-hosted" | "quick" | null;
373
409
  };
374
410
 
375
411
  export type SecurityMiddleware = (req: IncomingMessage, res: ServerResponse, pathname: string, peer: SecurityPeer) => boolean;
@@ -487,7 +523,13 @@ export function createSecurityMiddleware(deps: SecurityMiddlewareDeps): Security
487
523
  // visitor can never obtain a pairing code, so protection-on would just
488
524
  // kill the tunnel with an unanswerable 401 (user design ruling
489
525
  // 2026-11-12). LAN peers remain the pairing boundary.
490
- if (peer.loopback || peer.viaTunnel) {
526
+ // ClawHub security review 2026.11.7 (finding 1): that exemption only
527
+ // holds for GATED tunnels (*.teamclaw.dev / quick tunnels whose visitors
528
+ // carry the gate cookie). A SELF-HOSTED tunnel has no gate token and a
529
+ // custom hostname, so its visitors must authenticate like any other
530
+ // remote peer - otherwise "protection on" protected nothing there.
531
+ const selfHostedTunnel = peer.viaTunnel && deps.tunnelMode?.() === "self-hosted";
532
+ if ((peer.loopback || peer.viaTunnel) && !selfHostedTunnel) {
491
533
  const authAny = authenticateDeviceToken(state, extractDeviceToken(req));
492
534
  if (authAny) touchDeviceLastSeen(deps, authAny.device.id);
493
535
  return true;
@@ -517,13 +559,43 @@ export function createSecurityMiddleware(deps: SecurityMiddlewareDeps): Security
517
559
  export type WebSocketUpgradeGuardDeps = SecurityMiddlewareDeps & {
518
560
  isTunnelHost: (host: string | undefined) => boolean;
519
561
  gateAllows?: (req: { headers: Record<string, unknown> }) => boolean;
562
+ /** Full-request tunnel classification (Host suffix OR Cloudflare edge headers); wins over isTunnelHost. */
563
+ viaTunnelRequest?: (req: { headers: Record<string, unknown> }) => boolean;
520
564
  };
521
565
 
522
566
  export function createWebSocketUpgradeGuard(deps: WebSocketUpgradeGuardDeps): (req: IncomingMessage) => boolean {
523
567
  return function verifyUpgrade(req: IncomingMessage): boolean {
524
- const viaTunnel = deps.isTunnelHost(typeof req.headers.host === "string" ? req.headers.host : undefined);
568
+ const viaTunnel = deps.viaTunnelRequest
569
+ ? deps.viaTunnelRequest(req)
570
+ : deps.isTunnelHost(typeof req.headers.host === "string" ? req.headers.host : undefined);
525
571
  const peer = classifySecurityPeer(req.socket.remoteAddress, viaTunnel);
526
572
  const state = deps.getTeamState();
573
+ // ClawHub security review 2026.11.7 (finding 3): browsers always send
574
+ // Origin on WebSocket upgrades; a cross-site page could otherwise open
575
+ // /ws with the victim's session cookie and read the live event stream.
576
+ // Only the controller's own origin (same host) may upgrade; non-browser
577
+ // clients without an Origin header are unaffected.
578
+ if (!isAllowedWebSocketOrigin(req)) {
579
+ deps.logger.warn(`Controller: rejected WebSocket upgrade from ${peer.ip} with cross-site Origin ${String(req.headers.origin)}`);
580
+ return false;
581
+ }
582
+ const selfHostedTunnel = peer.viaTunnel && deps.tunnelMode?.() === "self-hosted";
583
+ // ClawHub security review 2026.11.6 (finding 3): the tunnel gate must
584
+ // run BEFORE the protection-off allowance. The HTTP path enforces
585
+ // gateAllows for every tunnel request regardless of device protection
586
+ // (http-server.ts), so a protection-off controller still gates its HTTP
587
+ // surface - but this guard used to return true first, which left /ws as
588
+ // the one tunnel surface a gate-cookie-less visitor could subscribe to
589
+ // (task/message/clarification event stream). Same layering as HTTP now.
590
+ // Self-hosted tunnels (2026.11.7 finding 1) have no gate cookie: their
591
+ // visitors fall through to the device-token check below instead.
592
+ if (peer.viaTunnel && !selfHostedTunnel) {
593
+ if (!deps.gateAllows || !deps.gateAllows(req)) {
594
+ deps.logger.warn(`Controller: rejected WebSocket upgrade from ${peer.ip} (via tunnel, no gate cookie)`);
595
+ return false;
596
+ }
597
+ return true;
598
+ }
527
599
  if (!isProtectionOn(state)) {
528
600
  recordNonLanPeerSignal(deps, state, peer, "/ws");
529
601
  return true;
@@ -536,13 +608,8 @@ export function createWebSocketUpgradeGuard(deps: WebSocketUpgradeGuardDeps): (r
536
608
  if (peer.loopback) {
537
609
  return true;
538
610
  }
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
- }
611
+ // Gated-tunnel upgrades were handled above (gate cookie). Self-hosted
612
+ // tunnel upgrades land here and authenticate with a device token.
546
613
  let token = extractDeviceToken(req);
547
614
  if (!token) {
548
615
  const url = new URL(req.url ?? "/ws", `http://${req.headers.host ?? "localhost"}`);
@@ -792,10 +859,10 @@ export async function handleSecurityPairAutoRequest(ctx: RouteContext): Promise<
792
859
  });
793
860
  return;
794
861
  }
795
- if ((deps.config.security?.autoPair ?? true) !== true) {
862
+ if ((deps.config.security?.autoPair ?? false) !== true) {
796
863
  sendJson(res, 403, {
797
864
  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\"}.",
865
+ 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
866
  });
800
867
  return;
801
868
  }
@@ -828,7 +895,7 @@ export async function handleSecurityGetRequest(ctx: RouteContext): Promise<void>
828
895
  protection: isProtectionOn(state),
829
896
  devices: (security?.devices ?? []).map(serializeDevice),
830
897
  ...(active ? { pairingCode: { expiresAt: active.expiresAt, purpose: active.purpose } } : {}),
831
- autoPair: deps.config.security?.autoPair ?? true,
898
+ autoPair: deps.config.security?.autoPair ?? false,
832
899
  });
833
900
  }
834
901
 
@@ -857,15 +924,21 @@ export async function handleSecurityDeviceDeleteRequest(ctx: RouteContext): Prom
857
924
  sendJson(res, 200, { ok: true, revoked: deviceId, revokedSelf, protection });
858
925
  }
859
926
 
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.
927
+ // POST /api/v1/security/reset - LOOPBACK ONLY (anti-lockout hatch), plus
928
+ // an explicit confirm token (#255 P1-8). ClawHub security review 2026.11.6
929
+ // (finding 2): a paired device token used to be enough to drop protection
930
+ // for EVERYONE - any LAN device that self-paired via auto-pair could reset
931
+ // the controller to L0. Reset is now a controller-host action only; remote
932
+ // owners revoke devices individually or re-enable from the host.
863
933
  export async function handleSecurityResetRequest(ctx: RouteContext): Promise<void> {
864
934
  const { req, res, deps, peer } = ctx;
865
935
  const state = deps.getTeamState();
866
936
  const auth = authenticateDeviceToken(state, extractDeviceToken(req));
867
- if (!auth && !(peer?.loopback ?? false)) {
868
- sendUnauthorized(res);
937
+ if (!(peer?.loopback ?? false)) {
938
+ sendJson(res, 403, {
939
+ error: "forbidden",
940
+ 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.",
941
+ });
869
942
  return;
870
943
  }
871
944
  const body = await parseJsonBody(req);
@@ -656,7 +656,37 @@ export async function runAutoAssignRound(
656
656
  // bypassing the gate). Write-phase claim failures still continue
657
657
  // unclaimed per the original 2026-11-15 semantics.
658
658
  deps.getTeamAutoScheduler?.()?.claimTaskAtDequeue(updatedTask).then((claim) => {
659
- if (claim?.retryEligibility) {
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) {
660
690
  logger.warn(`Controller: claim eligibility check failed for ${updatedTask.id} - reverting assignment to retry`);
661
691
  // Unlike the #191 dispatch-failure path, the dispatch SUCCEEDED
662
692
  // here: cancel the already-dispatched execution before reverting
@@ -670,6 +700,33 @@ export async function runAutoAssignRound(
670
700
  holdMs: claimEligibilityHoldMs(failures),
671
701
  });
672
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(() => {});
673
730
  } else {
674
731
  // Claim attempt concluded definitively (claimed / stood down /
675
732
  // WRITE failure continuing unclaimed): end the retry cycle.
@@ -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 {
@@ -579,7 +580,7 @@ export async function handleTaskResultRequest(deps: ControllerTaskDomainDeps, re
579
580
  const { logger, getTeamState, updateTeamState } = deps;
580
581
  const taskId = pathname.split("/")[4]!;
581
582
  const body = await parseJsonBody(req);
582
- const result = typeof body.result === "string" ? body.result : "";
583
+ let result = typeof body.result === "string" ? body.result : "";
583
584
  let error = typeof body.error === "string" ? body.error : undefined;
584
585
  const workerId = typeof body.workerId === "string" ? body.workerId : undefined;
585
586
  const currentTask = getTeamState()?.tasks[taskId];
@@ -668,6 +669,43 @@ export async function handleTaskResultRequest(deps: ControllerTaskDomainDeps, re
668
669
  }
669
670
 
670
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
+ }
671
709
  if (
672
710
  !error
673
711
  && gatedTask
@@ -193,7 +193,7 @@ function gateCookieValue(gateToken: string, tunnelId: string): string {
193
193
  return createHash("sha256").update(`${gateToken}:${tunnelId}`).digest("hex").slice(0, 32);
194
194
  }
195
195
 
196
- export function createTunnelManager(deps: { logger: PluginLogger; localPort: number }) {
196
+ export function createTunnelManager(deps: { logger: PluginLogger; localPort: number; isProtectionOn?: () => boolean }) {
197
197
  const { logger } = deps;
198
198
  let child: ChildProcess | null = null;
199
199
  let handle: TunnelHandle | null = null;
@@ -470,6 +470,17 @@ export function createTunnelManager(deps: { logger: PluginLogger; localPort: num
470
470
  if (handle) return handle;
471
471
  const st = readTunnelState();
472
472
  if (!st || st.tunnelId === "quick") return null; // one-off, not recoverable
473
+ // ClawHub security review 2026.11.6 (finding 4): a self-hosted tunnel's
474
+ // custom hostname never matches the built-in gate suffixes, so its
475
+ // traffic arrives as a loopback peer and inherits trusted-host access.
476
+ // Device protection is the only thing standing between that public
477
+ // ingress and the API - do not reconnect one while protection is off;
478
+ // drop the stale state so the owner re-enables deliberately.
479
+ if (st.tunnelId === "self-hosted" && deps.isProtectionOn && !deps.isProtectionOn()) {
480
+ 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");
481
+ clearTunnelState();
482
+ return null;
483
+ }
473
484
  const bin = findCloudflared();
474
485
  if (!bin) {
475
486
  logger.warn("TeamClaw tunnel: previous share found but cloudflared is not installed; not recovering");
@@ -194,6 +194,17 @@ export function createTunnelManagementRoutes(tunnelManager: TunnelManager, deps:
194
194
  if (!tunnelStartAllowedFrom(req, res)) {
195
195
  return;
196
196
  }
197
+ // ClawHub security review 2026.11.6 (finding 4): a self-hosted
198
+ // tunnel's custom hostname is outside the built-in gate, so its
199
+ // requests arrive as trusted loopback peers. Without device
200
+ // protection that is unauthenticated public access to the API.
201
+ if (!isProtectionOn(deps.getTeamState())) {
202
+ sendJson(res, 409, {
203
+ error: "device protection must be enabled before starting a self-hosted tunnel",
204
+ 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.",
205
+ });
206
+ return;
207
+ }
197
208
  logger.info(`TeamClaw tunnel: start-self-hosted requested (${tunnelCaller(req)})`);
198
209
  let token = "";
199
210
  try {
@@ -29,6 +29,9 @@ function workspaceRequestErrorMessage(err: unknown): string {
29
29
  return err instanceof Error ? err.message : "Workspace request failed";
30
30
  }
31
31
 
32
+ // Active content the raw route must sandbox on direct navigation (finding 6).
33
+ const ACTIVE_CONTENT_TYPES = new Set(["text/html; charset=utf-8", "image/svg+xml"]);
34
+
32
35
  function workspaceStatusRoute(ctx: RouteContext): void {
33
36
  const { res } = ctx;
34
37
  sendJson(res, 200, {
@@ -193,7 +196,15 @@ async function workspaceRawFileRoute(ctx: RouteContext): Promise<void> {
193
196
  try {
194
197
  const relativePath = decodeURIComponent(rawPathname);
195
198
  const file = await readWorkspaceRawFile(relativePath);
196
- res.writeHead(200, {
199
+ // ClawHub security review 2026.11.6 (finding 6): HTML/SVG served with
200
+ // their active MIME type under the controller origin execute with the
201
+ // owner's session on DIRECT navigation (the preview iframe's sandbox
202
+ // attribute does not travel with the "Open Raw" link). A response-level
203
+ // CSP sandbox without allow-same-origin gives the document an opaque
204
+ // origin even on top-level navigation: scripts may run (the preview
205
+ // already allows that) but cannot read controller cookies or call
206
+ // /api/v1/* same-origin. Mirrors the iframe flags byte for byte.
207
+ const headers: Record<string, string> = {
197
208
  "Content-Type": file.contentType,
198
209
  "Cache-Control": "no-store",
199
210
  // Issue #23 security review follow-up: honor a CORS origin the
@@ -202,7 +213,11 @@ async function workspaceRawFileRoute(ctx: RouteContext): Promise<void> {
202
213
  // historical "*" byte for byte (shared helper, see protocol.ts).
203
214
  "Access-Control-Allow-Origin": pinnedCorsAllowOrigin(res),
204
215
  "X-Content-Type-Options": "nosniff",
205
- });
216
+ };
217
+ if (ACTIVE_CONTENT_TYPES.has(file.contentType)) {
218
+ headers["Content-Security-Policy"] = "sandbox allow-scripts allow-forms";
219
+ }
220
+ res.writeHead(200, headers);
206
221
  res.end(file.content);
207
222
  } catch (err) {
208
223
  sendError(res, workspaceRequestErrorStatus(err), workspaceRequestErrorMessage(err));
@@ -215,6 +215,25 @@ export function createGithubClient(auth: GithubAuthManager) {
215
215
  });
216
216
  },
217
217
 
218
+ /** #5785: PRs (any state) whose head is exactly this branch - the
219
+ * PR-face evidence surface. The settle audit asks "did this WRITE task's
220
+ * PR ever come into existence", which no comment surface can answer (an
221
+ * issue direct-post masks the missing PR). Mirrors the sentinel's
222
+ * pulls?head= REST probe. */
223
+ async listPullsByHead(owner: string, repo: string, branch: string): Promise<Array<{ number: number; state: string; htmlUrl: string }>> {
224
+ const { data } = await request("GET", `/repos/${owner}/${repo}/pulls?head=${encodeURIComponent(`${owner}:${branch}`)}&state=all&per_page=10`);
225
+ if (!Array.isArray(data)) {
226
+ return [];
227
+ }
228
+ return (data as Record<string, unknown>[])
229
+ .map((raw) => ({
230
+ number: Number(raw.number ?? 0),
231
+ state: String(raw.state ?? ""),
232
+ htmlUrl: String(raw.html_url ?? ""),
233
+ }))
234
+ .filter((p) => p.number > 0);
235
+ },
236
+
218
237
  async listCommits(owner: string, repo: string, sinceSha: string): Promise<{ sha: string; message: string }[]> {
219
238
  const suffix = sinceSha ? `?sha=${encodeURIComponent(sinceSha)}` : "?per_page=20";
220
239
  void suffix;
@@ -297,13 +316,14 @@ export function createGithubClient(auth: GithubAuthManager) {
297
316
 
298
317
  /** #claim-dequeue: comments on an issue since a timestamp, for the
299
318
  * dequeue-time external-collaboration check (authors + times only). */
300
- async getIssueCommentsSince(owner: string, repo: string, issueNumber: number, sinceIso: string): Promise<Array<{ user: string; createdAt: string }>> {
319
+ async getIssueCommentsSince(owner: string, repo: string, issueNumber: number, sinceIso: string): Promise<Array<{ user: string; createdAt: string; body: string }>> {
301
320
  try {
302
321
  const { data } = await request("GET", `/repos/${owner}/${repo}/issues/${issueNumber}/comments?since=${encodeURIComponent(sinceIso)}&per_page=20`);
303
322
  if (!Array.isArray(data)) return [];
304
323
  return (data as Record<string, unknown>[]).map((c) => ({
305
324
  user: String((c.user as { login?: string } | undefined)?.login ?? ""),
306
325
  createdAt: String(c.created_at ?? ""),
326
+ body: String(c.body ?? ""),
307
327
  })).filter((c) => c.user);
308
328
  } catch {
309
329
  return []; // listing failed - degrade to assignee check only
@@ -155,17 +155,51 @@ export function createRepoSync(auth: GithubAuthManager, logger: { warn: (m: stri
155
155
  await run(["checkout", "-B", name], dir);
156
156
  }
157
157
 
158
+ /** #5815: deliverable must mean commits beyond the REMOTE base tip. A
159
+ * stale local baseline makes a zero-commit branch look deliverable; the
160
+ * PR then 422s (zero diff) deterministically six times. */
161
+ async function branchHasCommits(dir: string, defaultBranch?: string, cloneUrl?: string): Promise<boolean> {
162
+ if (!defaultBranch) return false;
163
+ try {
164
+ if (cloneUrl) {
165
+ const authed = await tokenizedUrl(cloneUrl);
166
+ await run(["fetch", authed, defaultBranch], dir).catch(() => {});
167
+ } else {
168
+ await run(["fetch", "origin", defaultBranch], dir).catch(() => {});
169
+ }
170
+ const out = await run(["rev-list", "--count", `origin/${defaultBranch}..HEAD`], dir);
171
+ return Number(out.trim()) > 0;
172
+ } catch {
173
+ return false;
174
+ }
175
+ }
176
+
177
+ /** #5815: is the branch an ancestor of the remote base (zero-diff shape)? */
178
+ async function branchIsAncestorOfRemoteBase(dir: string, branch: string, defaultBranch: string): Promise<boolean> {
179
+ await run(["fetch", "origin", defaultBranch], dir).catch(() => {});
180
+ const head = (await run(["rev-parse", `origin/${branch}`], dir).catch(() => "")).trim();
181
+ const base = (await run(["rev-parse", `origin/${defaultBranch}`], dir).catch(() => "")).trim();
182
+ if (!head || !base) return false;
183
+ return run(["merge-base", "--is-ancestor", head, base], dir).then(() => true, () => false);
184
+ }
185
+
186
+ /** #5788: does the branch exist on the remote? (422 disambiguation probe) */
187
+ async function branchExistsRemotely(dir: string, branch: string): Promise<boolean> {
188
+ const out = await run(["ls-remote", "origin", `refs/heads/${branch}`], dir).catch(() => "");
189
+ return out.trim().length > 0;
190
+ }
191
+
158
192
  async function commitAll(dir: string, message: string, authorName: string, authorEmail: string): Promise<boolean> {
159
193
  const status = await run(["status", "--porcelain"], dir);
160
194
  if (!status.trim()) {
161
195
  return false;
162
196
  }
163
197
  await run(["add", "-A"], dir);
164
- await run(["-c", `user.name=${authorName}`, "-c", `user.email=${authorEmail}`, "commit", "-m", message], dir);
198
+ await run(["-c", `user.name=${authorName}`, "-c", `user.email=${authorEmail}`, "-c", "core.hooksPath=", "commit", "-m", message], dir);
165
199
  return true;
166
200
  }
167
201
 
168
- async function pushBranch(repoId: string, dir: string, cloneUrl: string, branch: string): Promise<{ alreadyDelivered: boolean }> {
202
+ async function pushBranch(repoId: string, dir: string, cloneUrl: string, branch: string, onPushError?: (msg: string) => void): Promise<{ alreadyDelivered: boolean }> {
169
203
  const authed = await tokenizedUrl(cloneUrl);
170
204
  // #stale-base follow-up: the remote task branch may ALREADY carry the
171
205
  // delivery (previous incarnation pushed it; the PR got merged). Blindly
@@ -187,10 +221,25 @@ export function createRepoSync(auth: GithubAuthManager, logger: { warn: (m: stri
187
221
  } catch { /* branch absent remotely or fetch failed - plain push below */ }
188
222
  try {
189
223
  await run(["push", authed, `HEAD:refs/heads/${branch}`], dir);
224
+ // #5788: verify the push LANDED - a "successful" push whose ref is
225
+ // missing remotely (auth edge, proxy quirk) strands the branch exactly
226
+ // like a failed one, and createPR would 422 on the missing head.
227
+ const ls = await run(["ls-remote", authed, `refs/heads/${branch}`], dir).catch(() => "");
228
+ const localHead = (await run(["rev-parse", "HEAD"], dir)).trim();
229
+ if (ls && localHead && !ls.includes(localHead)) {
230
+ const msg = `post-push ref verification failed: remote refs/heads/${branch} does not contain local HEAD ${localHead.slice(0, 8)}`;
231
+ logger.warn(`TeamAuto: ${msg}`);
232
+ try { onPushError?.(msg); } catch { /* observability only */ }
233
+ throw new Error(msg);
234
+ }
190
235
  return { alreadyDelivered: false };
191
236
  } catch (err) {
192
237
  const msg = err instanceof Error ? err.message : String(err);
193
238
  logger.warn(`TeamAuto: push failed for ${repoId}#${branch}: ${msg}`);
239
+ // #5788: the push leg was the ONLY delivery step with zero activity
240
+ // surface - its failure only ever showed as downstream createPR 422
241
+ // noise (two stranded self-fix legs). Surface it via the callback.
242
+ try { onPushError?.(msg); } catch { /* observability only */ }
194
243
  // #5651 (ggcode, 2026-11-15): a NON-FAST-FORWARD rejection is
195
244
  // deterministic - the generic retry ladder burned 6 attempts / ~25min
196
245
  // on it twice (#5268 family). The task branch is exclusively ours, so
@@ -299,13 +348,14 @@ export function createRepoSync(auth: GithubAuthManager, logger: { warn: (m: stri
299
348
  // wtName carries the teamauto/ level for the REL path; the physical dir is
300
349
  // a SIBLING of the base checkout (path.join would nest teamauto/ twice).
301
350
  const wtPath = path.join(path.dirname(base), path.basename(wtName));
302
- if (!(await fs.access(path.join(wtPath, ".git")).then(() => true, () => false))) {
351
+ const wtExists = await fs.access(path.join(wtPath, ".git")).then(() => true, () => false);
352
+ if (!wtExists) {
303
353
  // #stale-base (user report 2026-11-14): ensureCloned (fetch + reset to
304
354
  // the default-branch tip) only ran at BIND time (learnNorms), so the
305
355
  // base checkout's HEAD drifted days behind origin/main and EVERY new
306
356
  // task worktree branched from stale code. Refresh the base right
307
357
  // before creating a new branch off it - same fetch+reset as
308
- // ensureCloned. Existing worktrees (resume path) are left untouched.
358
+ // ensureCloned.
309
359
  if (defaultBranch && cloneUrl) {
310
360
  try {
311
361
  const authed = await tokenizedUrl(cloneUrl);
@@ -317,6 +367,36 @@ export function createRepoSync(auth: GithubAuthManager, logger: { warn: (m: stri
317
367
  }
318
368
  await run(["worktree", "add", "-b", taskBranchName(taskId), wtPath, "HEAD"], base);
319
369
  logger.warn(`TeamAuto: worktree ${wtName} (branch ${taskBranchName(taskId)}) for ${taskId}`);
370
+ } else {
371
+ // #resume-sync (user 2026-11-18): a RESUMED task (retry / review
372
+ // follow-up) used to continue on the ORIGINAL base untouched - the
373
+ // comment above explicitly left resume paths stale. On repos that
374
+ // move fast, a worktree alive for hours is guaranteed behind, all
375
+ // retried work lands on a superseded base, and the divergence only
376
+ // surfaces at push (single-shot #5651 rebase self-heal or dead
377
+ // letter). Sync BEFORE resuming: fetch the main tree, count how far
378
+ // behind this branch is, rebase when behind (dirty trees via
379
+ // autostash). Best-effort: on any failure we continue on the current
380
+ // base exactly as before - delivery-time self-heal still applies.
381
+ try {
382
+ await run(["fetch", "origin", "+refs/heads/main:refs/remotes/origin/main"], base).catch(async () => {
383
+ const db = defaultBranch || (await run(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], base).then((o) => o.trim(), () => ""));
384
+ if (db) await run(["fetch", "origin", `+refs/heads/${db}:refs/remotes/origin/${db}`], base);
385
+ });
386
+ const behindOut = await run(["rev-list", "--count", "HEAD..origin/main"], wtPath).catch(() => "");
387
+ const behind = Number(behindOut.trim()) || 0;
388
+ if (behind > 0) {
389
+ logger.warn(`TeamAuto: resume-sync ${repoId}#${taskId}: branch is ${behind} commit(s) behind main - rebasing before work continues`);
390
+ try {
391
+ await run(["rebase", "--autostash", "origin/main"], wtPath);
392
+ } catch (rebaseErr) {
393
+ await run(["rebase", "--abort"], wtPath).catch(() => {});
394
+ logger.warn(`TeamAuto: resume-sync rebase failed for ${repoId}#${taskId} (continuing on current base; delivery-time self-heal applies): ${rebaseErr instanceof Error ? rebaseErr.message : String(rebaseErr)}`);
395
+ }
396
+ }
397
+ } catch (err) {
398
+ logger.warn(`TeamAuto: resume-sync skipped for ${repoId}#${taskId}: ${err instanceof Error ? err.message : String(err)}`);
399
+ }
320
400
  }
321
401
  // Refresh the in-use sentinel on create AND resume (#173 follow-up 2).
322
402
  await writeTaskLock(wtPath);
@@ -533,23 +613,7 @@ export function createRepoSync(auth: GithubAuthManager, logger: { warn: (m: stri
533
613
  return taskWorktreeDirName(repoId, taskId);
534
614
  }
535
615
 
536
- /** True when HEAD has commits beyond the base branch (worktree delivery). */
537
- async function branchHasCommits(dir: string, baseBranch: string): Promise<boolean> {
538
- try {
539
- const out = await run(["rev-list", "--count", "HEAD", "--not", baseBranch], dir);
540
- return Number(out.trim()) > 0;
541
- } catch {
542
- // Base branch name unknown/unfetched - fall back to diff against first parent chain
543
- try {
544
- const root = await run(["rev-list", "--max-parents=0", "HEAD"], dir);
545
- return root.trim().length > 0;
546
- } catch {
547
- return false;
548
- }
549
- }
550
- }
551
-
552
- return { ensureCloned, currentSha, recentCommitMessages, readFileIfPresent, safeRepoPath, createWorkBranch, commitAll, pushBranch, ensureTaskWorktree, removeTaskWorktree, safeRemoveTaskWorktree, gcTaskWorktrees, taskWorktreeRelDir, taskBranchName, branchHasCommits, repoDir };
616
+ return { ensureCloned, currentSha, recentCommitMessages, readFileIfPresent, safeRepoPath, createWorkBranch, commitAll, pushBranch, branchExistsRemotely, branchIsAncestorOfRemoteBase, ensureTaskWorktree, removeTaskWorktree, safeRemoveTaskWorktree, gcTaskWorktrees, taskWorktreeRelDir, taskBranchName, branchHasCommits, repoDir };
553
617
  }
554
618
 
555
619
  export type TeamAutoRepoSync = ReturnType<typeof createRepoSync>;