@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
@@ -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 {
@@ -17,6 +17,7 @@
17
17
  // below keep their historical module path and signatures.
18
18
  import fs from "node:fs/promises";
19
19
  import net from "node:net";
20
+ import os from "node:os";
20
21
  import path from "node:path";
21
22
  import type { PluginLogger } from "../../api.js";
22
23
  import { generateId, generateLaunchToken, secretsEqual } from "../protocol.js";
@@ -103,6 +104,39 @@ export class WorkerProvisioningManager {
103
104
  constructor(deps: WorkerProvisioningManagerDeps) {
104
105
  this.deps = deps;
105
106
  this.backend = createProvisionerBackend(deps.config, deps.logger);
107
+ // #rate-limit-999 terminal fix: EMBEDDED workers (every in-gateway
108
+ // ProvisionedWorker - the common case) read the CONTROLLER's own agent
109
+ // scope (~/.openclaw/agents/teamclaw/agent/settings.json), not the
110
+ // per-worker state dirs the v2 fix stamped. That scope had been left at
111
+ // maxRetries=999 (the old config default), so embedded workers ground
112
+ // themselves to death retrying 429s. Heal it at startup - read-modify-
113
+ // write touching ONLY retry.provider.maxRetries, preserving other keys.
114
+ void this.healControllerAgentRetrySettings().catch((err) => {
115
+ deps.logger.warn?.(`Controller: failed to heal controller agent retry settings: ${String(err)}`);
116
+ });
117
+ }
118
+
119
+ private async healControllerAgentRetrySettings(): Promise<void> {
120
+ const stateRoot = process.env.OPENCLAW_STATE_DIR
121
+ ? process.env.OPENCLAW_STATE_DIR
122
+ : path.join(os.homedir(), ".openclaw");
123
+ const settingsPath = path.join(stateRoot, "agents", "teamclaw", "agent", "settings.json");
124
+ let current: Record<string, unknown> = {};
125
+ try {
126
+ current = JSON.parse(await fs.readFile(settingsPath, "utf8")) as Record<string, unknown>;
127
+ } catch { /* absent or unreadable - stamp fresh */ }
128
+ const retry = (current.retry && typeof current.retry === "object") ? current.retry as Record<string, unknown> : {};
129
+ const provider = (retry.provider && typeof retry.provider === "object") ? retry.provider as Record<string, unknown> : {};
130
+ if (provider.maxRetries === this.deps.config.workerRateLimitMaxRetries) {
131
+ return; // already correct
132
+ }
133
+ provider.maxRetries = this.deps.config.workerRateLimitMaxRetries;
134
+ retry.enabled = retry.enabled !== false;
135
+ retry.provider = provider;
136
+ current.retry = retry;
137
+ await fs.mkdir(path.dirname(settingsPath), { recursive: true }).catch(() => { /* exists */ });
138
+ await fs.writeFile(settingsPath, JSON.stringify(current, null, 2) + "\n", { encoding: "utf8", mode: 0o600 });
139
+ this.deps.logger.info?.(`Controller: healed controller agent retry scope - provider.maxRetries=${this.deps.config.workerRateLimitMaxRetries} (${settingsPath})`);
106
140
  }
107
141
 
108
142
  /** Update the actual controller port after the HTTP server binds. */
@@ -651,6 +685,7 @@ export class WorkerProvisioningManager {
651
685
  workspaceDir: getConfiguredWorkerWorkspaceDir(workerConfig),
652
686
  env: this.buildForwardedEnv(controllerUrl),
653
687
  configJson: `${JSON.stringify(workerConfig, null, 2)}\n`,
688
+ rateLimitMaxRetries: this.deps.config.workerRateLimitMaxRetries,
654
689
  });
655
690
 
656
691
  this.deps.updateTeamState((state) => {
@@ -147,18 +147,32 @@ export async function handleWorkerListRequest(deps: ControllerTaskDomainDeps, re
147
147
 
148
148
  // POST /api/v1/workers/:id/heartbeat
149
149
  export async function handleWorkerHeartbeatRequest(deps: ControllerTaskDomainDeps, req: IncomingMessage, res: ServerResponse, pathname: string): Promise<void> {
150
- const { updateTeamState } = deps;
150
+ const { updateTeamState, logger } = deps;
151
151
  const workerId = pathname.split("/")[4]!;
152
152
  const body = await parseJsonBody(req);
153
153
  const status = typeof body.status === "string" ? body.status as WorkerInfo["status"] : "idle";
154
- const currentTaskId = typeof body.currentTaskId === "string" ? body.currentTaskId : undefined;
155
-
154
+ const reportedTaskId = typeof body.currentTaskId === "string" ? body.currentTaskId : undefined;
155
+
156
+ // #busy-clamp (user report 2026-11-15: one QA worker visibly running TWO
157
+ // in-progress tasks): the registry must not TRUST a worker-reported idle
158
+ // while the SERVER has that worker bound to a task. A busy worker's
159
+ // heartbeat can lag its own truth (double-assigned before this fix, or a
160
+ // heartbeat fired between task boundaries) - honoring it flipped the
161
+ // registry to idle and the assigner re-picked the still-busy worker 14s
162
+ // later. Server-side assignment is the source of truth: busy + bound
163
+ // currentTaskId survives until the task itself settles (completion/failure
164
+ // paths clear it) or the worker reports THAT task id as done.
156
165
  updateTeamState((s) => {
157
- if (s.workers[workerId]) {
158
- s.workers[workerId].lastHeartbeat = Date.now();
159
- s.workers[workerId].status = status;
160
- s.workers[workerId].currentTaskId = currentTaskId;
166
+ if (!s.workers[workerId]) return;
167
+ const w = s.workers[workerId];
168
+ w.lastHeartbeat = Date.now();
169
+ const serverBusy = w.status === "busy" && Boolean(w.currentTaskId);
170
+ if (serverBusy && status === "idle" && reportedTaskId !== w.currentTaskId) {
171
+ logger.warn?.(`Controller: heartbeat from ${workerId} claimed idle while bound to ${w.currentTaskId} - clamping to busy (server truth wins)`);
172
+ return; // keep busy + currentTaskId; only lastHeartbeat updated
161
173
  }
174
+ w.status = status;
175
+ w.currentTaskId = reportedTaskId;
162
176
  });
163
177
  deps.workerProvisioningManager?.onWorkerHeartbeat(workerId, status);
164
178
 
@@ -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));
@@ -813,6 +813,41 @@ export async function updateTeamClawModelConfig(
813
813
  * pattern as updateTeamClawModelConfig). Only whitelisted fields are
814
814
  * touched; unknown keys in the existing plugin config are preserved.
815
815
  */
816
+ // #hot-reload (user report 2026-11-15 13:48): persisting these three
817
+ // numbers into the HOST openclaw.json (plugins.entries.teamclaw.config)
818
+ // made the host CONFIG WATCHER drain+reload the ENTIRE teamclaw plugin on
819
+ // every PATCH - in-flight tasks interrupted, all workers restarted, a 2s
820
+ // main-thread stall, and the reload itself frequently FAILED (controller
821
+ // service stop timeout) which rolled the change back: the update visibly
822
+ // "caused a gateway restart" and then "did not apply". Pure numeric caps
823
+ // never needed host-config semantics - persist to the plugin's OWN state
824
+ // (provisioning-hot-config.json beside team-state.json) and re-apply on
825
+ // controller start. No host file change -> no plugin reload ->真热更新。
826
+ function provisioningHotConfigPath(env: NodeJS.ProcessEnv = process.env, homedir: () => string = os.homedir): string {
827
+ const explicitStateDir = env.OPENCLAW_STATE_DIR?.trim();
828
+ const base = explicitStateDir
829
+ ? path.join(explicitStateDir, "plugins", "teamclaw")
830
+ : path.join(homedir(), ".openclaw", "plugins", "teamclaw");
831
+ return path.join(base, "provisioning-hot-config.json");
832
+ }
833
+
834
+ export async function loadProvisioningHotConfig(
835
+ env: NodeJS.ProcessEnv = process.env,
836
+ homedir: () => string = os.homedir,
837
+ ): Promise<Record<string, number> | null> {
838
+ try {
839
+ const raw = JSON5.parse(await fs.readFile(provisioningHotConfigPath(env, homedir), "utf8")) as Record<string, unknown>;
840
+ const out: Record<string, number> = {};
841
+ for (const key of ["workerProvisioningMinPerRole", "workerProvisioningMaxPerRole", "workerProvisioningIdleTtlMs"]) {
842
+ const v = raw[key];
843
+ if (typeof v === "number" && Number.isFinite(v)) out[key] = v;
844
+ }
845
+ return Object.keys(out).length > 0 ? out : null;
846
+ } catch {
847
+ return null; // absent/first run - host-config defaults stand
848
+ }
849
+ }
850
+
816
851
  export async function updateTeamClawProvisioningConfig(
817
852
  update: {
818
853
  workerProvisioningMinPerRole?: number;
@@ -823,34 +858,19 @@ export async function updateTeamClawProvisioningConfig(
823
858
  env: NodeJS.ProcessEnv = process.env,
824
859
  homedir: () => string = os.homedir,
825
860
  ): Promise<{ configPath: string }> {
826
- const configPath = resolveDefaultOpenClawConfigPath(env, homedir);
827
- let parsed: Record<string, unknown>;
861
+ const configPath = provisioningHotConfigPath(env, homedir);
862
+ let current: Record<string, unknown> = {};
828
863
  try {
829
- parsed = JSON5.parse(await fs.readFile(configPath, "utf8")) as Record<string, unknown>;
830
- if (!isRecord(parsed)) {
831
- throw new Error("host config is not an object");
832
- }
833
- } catch (err) {
834
- throw new Error(`failed to read host config at ${configPath}: ${err instanceof Error ? err.message : String(err)}`);
835
- }
836
-
837
- const plugins = isRecord(parsed.plugins) ? parsed.plugins : {};
838
- const pluginEntries = isRecord(plugins.entries) ? plugins.entries : {};
839
- const teamclawPlugin = isRecord(pluginEntries[TEAMCLAW_AGENT_ID]) ? pluginEntries[TEAMCLAW_AGENT_ID] : { enabled: true };
840
- const pluginConfig = isRecord((teamclawPlugin as { config?: unknown }).config)
841
- ? { ...(teamclawPlugin as { config: Record<string, unknown> }).config }
842
- : {};
864
+ current = JSON5.parse(await fs.readFile(configPath, "utf8")) as Record<string, unknown>;
865
+ } catch { /* absent - start fresh */ }
843
866
  for (const [key, value] of Object.entries(update)) {
844
867
  if (typeof value === "number" && Number.isFinite(value)) {
845
- pluginConfig[key] = value;
868
+ current[key] = value;
846
869
  }
847
870
  }
848
- pluginEntries[TEAMCLAW_AGENT_ID] = { ...teamclawPlugin, config: pluginConfig };
849
- plugins.entries = pluginEntries;
850
- parsed.plugins = plugins;
851
-
852
- await fs.writeFile(configPath, `${JSON.stringify(parsed, null, 2)}\n`, "utf8");
853
- logger?.warn?.("TeamClaw: worker provisioning config persisted (hot-reload applies to the running controller)");
871
+ await fs.mkdir(path.dirname(configPath), { recursive: true });
872
+ await fs.writeFile(configPath, `${JSON.stringify(current, null, 2)}\n`, "utf8");
873
+ logger?.warn?.(`TeamClaw: worker provisioning config persisted to plugin state (${configPath}) - no host-config change, no plugin reload`);
854
874
  return { configPath };
855
875
  }
856
876
 
@@ -89,7 +89,7 @@ export function createRoleTaskExecutor(deps: RoleTaskExecutorDeps) {
89
89
  ? roleDef.systemPrompt
90
90
  : `You are a ${role} in a virtual software team. Complete the assigned task.`;
91
91
 
92
- return async (taskDescription: string, assignment: TaskAssignmentPayload): Promise<TaskExecutorResult> => {
92
+ const executeOnce = async (taskDescription: string, assignment: TaskAssignmentPayload): Promise<TaskExecutorResult> => {
93
93
  const taskId = assignment.taskId;
94
94
  const sessionKey = getSessionKey(assignment);
95
95
  const idempotencyKey = getIdempotencyKey?.(assignment);
@@ -662,6 +662,31 @@ export function createRoleTaskExecutor(deps: RoleTaskExecutorDeps) {
662
662
  throw err;
663
663
  }
664
664
  };
665
+ // #5641 (user report 2026-11-15): the openclaw host's workspace-state guard
666
+ // THROWS BY CONTRACT ("retry workspace setup") when the shared workspace
667
+ // changes mid-preparation - e.g. the 02:00 fullReview batch racing the
668
+ // sweep's own repo sync. teamclaw used to surface that error straight to a
669
+ // terminal task failure (architect leg died in seconds, 3 days straight).
670
+ // Bounded retry honoring the host's retryable contract; the inner run is
671
+ // idempotent via idempotencyKey.
672
+ const RETRYABLE_WORKSPACE_GUARD = /Workspace filesystem changed while preparing state|WorkspaceAliasRepointed/;
673
+ return async (taskDescription: string, assignment: TaskAssignmentPayload): Promise<TaskExecutorResult> => {
674
+ const MAX_ATTEMPTS = 3;
675
+ const BACKOFF_MS = [5_000, 15_000];
676
+ for (let attempt = 1; ; attempt++) {
677
+ try {
678
+ return await executeOnce(taskDescription, assignment);
679
+ } catch (err) {
680
+ const msg = err instanceof Error ? err.message : String(err);
681
+ if (attempt < MAX_ATTEMPTS && RETRYABLE_WORKSPACE_GUARD.test(msg)) {
682
+ logger.warn(`TeamClaw: retryable workspace-state failure (attempt ${attempt}/${MAX_ATTEMPTS}) for task ${assignment.taskId}: ${msg.slice(0, 140)}`);
683
+ await delay(BACKOFF_MS[attempt - 1] ?? 15_000);
684
+ continue;
685
+ }
686
+ throw err;
687
+ }
688
+ }
689
+ };
665
690
  }
666
691
 
667
692
  function formatDuration(timeoutMs: number): string {
@@ -1106,7 +1131,7 @@ function buildAssistantTurnSnapshot(text: string, toolCalls: string[] = []): Ass
1106
1131
  };
1107
1132
  }
1108
1133
 
1109
- function extractLastAssistantTurn(messages: unknown[]): AssistantTurnSnapshot {
1134
+ export function extractLastAssistantTurn(messages: unknown[]): AssistantTurnSnapshot {
1110
1135
  const assistantMessages = messages.filter((message): message is { role?: unknown; content?: unknown } => {
1111
1136
  if (!message || typeof message !== "object") {
1112
1137
  return false;
@@ -1143,7 +1168,25 @@ function extractLastAssistantTurn(messages: unknown[]): AssistantTurnSnapshot {
1143
1168
  }
1144
1169
  }
1145
1170
 
1146
- return buildAssistantTurnSnapshot(JSON.stringify(lastAssistant));
1171
+ // Some transports hand the text block directly as the content object.
1172
+ if (
1173
+ !!lastAssistant.content
1174
+ && typeof lastAssistant.content === "object"
1175
+ && typeof (lastAssistant.content as { text?: unknown }).text === "string"
1176
+ ) {
1177
+ return buildAssistantTurnSnapshot((lastAssistant.content as { text: string }).text);
1178
+ }
1179
+
1180
+ // #5704 (ggcode, 2026-11-16): no recoverable text. The legacy fallback
1181
+ // serialized the whole message object, so an empty transport frame
1182
+ // (content:[] plus api/provider/usage metadata) reached GitHub verbatim
1183
+ // as the worker's "final reply" - comment bodies (ggcode #5699) and even
1184
+ // a whole PR body (#5703). Intended text lives ONLY in content (string,
1185
+ // text blocks, or a direct text object - all handled above); anything
1186
+ // else is frame metadata. Return empty text: the task completes without
1187
+ // a textual result and the write-back ladder surfaces that terminally
1188
+ // instead of posting frame JSON.
1189
+ return buildAssistantTurnSnapshot("");
1147
1190
  }
1148
1191
 
1149
1192
  function isRateLimitMessage(value: string): boolean {
@@ -1,5 +1,6 @@
1
1
  // Issue #226 W5: cross-subsystem contract lives in the shared layer now.
2
2
  import type { GithubAuthManager } from "../shared/github-auth.js";
3
+ import { sanitizeGithubWriteBody } from "./write-payload-guard.js";
3
4
 
4
5
  /**
5
6
  * Minimal GitHub REST client for TeamAuto: ETag-conditional GETs, light
@@ -73,7 +74,16 @@ export function createGithubClient(auth: GithubAuthManager) {
73
74
  if (options.body !== undefined) {
74
75
  headers["Content-Type"] = "application/json";
75
76
  }
76
- const etagKey = options.etagKey ? `${method} ${urlPath}` : undefined;
77
+ const etagKey = options.etagKey && !urlPath.includes("/issues?") ? `${method} ${urlPath}` : undefined;
78
+ // #5706 (ggcode, 2026-11-16): the ISSUE-SCAN URL must not use conditional
79
+ // requests. Live evidence: the gateway process received 304 for
80
+ // state=open&sort=updated&since=<cursor> while the byte-identical request
81
+ // (same etag, same plugin token) from a shell returned 200 with 13 items -
82
+ // GitHub's weak-validation on since-filtered, updated-sorted lists can
83
+ // serve a stale 304 to the long-lived process, starving EVERY sweep to
84
+ // "fetched 0" (three re-opened issues starved 3h, historical cases 4h20m).
85
+ // The scan fetches <=50 items; 304 savings are negligible. Pulls/commits
86
+ // and all write paths keep their etag handling.
77
87
  if (etagKey && options.etags?.[etagKey]) {
78
88
  headers["If-None-Match"] = options.etags[etagKey];
79
89
  }
@@ -90,6 +100,12 @@ export function createGithubClient(auth: GithubAuthManager) {
90
100
  }
91
101
  }
92
102
  if (response.status === 304) {
103
+ // #5706: a 304 on the ISSUE SCAN URL while the identical request from
104
+ // a shell (same etag) returns 200/12 items is the live divergence -
105
+ // log it loudly so the next sweep pins the layer.
106
+ if (urlPath.includes("/issues?")) {
107
+ console.warn(`[teamclaw#5706] issues scan 304: ${urlPath.slice(0, 140)}`);
108
+ }
93
109
  return { status: 304, data: null, notModified: true };
94
110
  }
95
111
  const text = await response.text();
@@ -107,6 +123,11 @@ export function createGithubClient(auth: GithubAuthManager) {
107
123
  }
108
124
  if (response.status >= 200 && response.status < 300) {
109
125
  etagCounters.hits += 1; // #267-3: "hits" = calls that returned fresh data (non-304 successes)
126
+ // #5706: empty-array 200s on the scan URL are suspicious in exactly
127
+ // the starvation scenario - make them visible.
128
+ if (urlPath.includes("/issues?") && Array.isArray(data) && data.length === 0) {
129
+ console.warn(`[teamclaw#5706] issues scan 200-but-EMPTY: ${urlPath.slice(0, 140)}`);
130
+ }
110
131
  }
111
132
  return { status: response.status, data, notModified: false };
112
133
  }
@@ -194,6 +215,25 @@ export function createGithubClient(auth: GithubAuthManager) {
194
215
  });
195
216
  },
196
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
+
197
237
  async listCommits(owner: string, repo: string, sinceSha: string): Promise<{ sha: string; message: string }[]> {
198
238
  const suffix = sinceSha ? `?sha=${encodeURIComponent(sinceSha)}` : "?per_page=20";
199
239
  void suffix;
@@ -219,17 +259,46 @@ export function createGithubClient(auth: GithubAuthManager) {
219
259
  // ---- write side (require Contents/Issues/PR write on the App) ----
220
260
 
221
261
  async postIssueComment(owner: string, repo: string, issueNumber: number, body: string): Promise<number> {
222
- const { data } = await request("POST", `/repos/${owner}/${repo}/issues/${issueNumber}/comments`, { body: { body } });
262
+ // #5704: LLM envelope frames must never land as comment bodies.
263
+ const safeBody = sanitizeGithubWriteBody(body, `issue comment ${owner}/${repo}#${issueNumber}`);
264
+ const { data } = await request("POST", `/repos/${owner}/${repo}/issues/${issueNumber}/comments`, { body: { body: safeBody } });
223
265
  return Number((data as { id?: number }).id ?? 0);
224
266
  },
225
267
 
226
268
  async postPullReviewComment(owner: string, repo: string, pullNumber: number, body: string): Promise<void> {
227
- await request("POST", `/repos/${owner}/${repo}/pulls/${pullNumber}/reviews`, { body: { event: "COMMENT", body } });
269
+ // #5704: same write-channel guard on the PR review surface.
270
+ const safeBody = sanitizeGithubWriteBody(body, `pull review ${owner}/${repo}#${pullNumber}`);
271
+ await request("POST", `/repos/${owner}/${repo}/pulls/${pullNumber}/reviews`, { body: { event: "COMMENT", body: safeBody } });
272
+ },
273
+
274
+ /** #5660: normalized feedback bodies already on a PR - review bodies AND
275
+ * issue-style comments (a worker may post through either surface during
276
+ * its execution window while the write-back ladder delivers the same
277
+ * text moments later). Whitespace-collapsed so footer spacing cannot
278
+ * defeat the comparison. */
279
+ async getPullFeedbackBodies(owner: string, repo: string, pullNumber: number): Promise<string[]> {
280
+ const bodies: string[] = [];
281
+ const norm = (raw: unknown): string => String(raw ?? "").replace(/\s+/g, " ").trim();
282
+ try {
283
+ const { data } = await request("GET", `/repos/${owner}/${repo}/pulls/${pullNumber}/reviews?per_page=30`);
284
+ if (Array.isArray(data)) {
285
+ for (const r of data as Record<string, unknown>[]) bodies.push(norm(r.body));
286
+ }
287
+ } catch { /* reviews listing failed - degrade to comments-only check */ }
288
+ try {
289
+ const { data } = await request("GET", `/repos/${owner}/${repo}/issues/${pullNumber}/comments?per_page=30`);
290
+ if (Array.isArray(data)) {
291
+ for (const c of data as Record<string, unknown>[]) bodies.push(norm(c.body));
292
+ }
293
+ } catch { /* comments listing failed - degrade to reviews-only check */ }
294
+ return bodies.filter(Boolean);
228
295
  },
229
296
 
230
297
  async createIssue(owner: string, repo: string, title: string, body: string, labels?: string[]): Promise<number> {
298
+ // #5704: umbrella/section bodies get the same frame guard.
299
+ const safeBody = sanitizeGithubWriteBody(body, `create issue ${owner}/${repo}`);
231
300
  const { data } = await request("POST", `/repos/${owner}/${repo}/issues`, {
232
- body: { title, body, ...(labels?.length ? { labels } : {}) },
301
+ body: { title, body: safeBody, ...(labels?.length ? { labels } : {}) },
233
302
  });
234
303
  return Number((data as { number?: number }).number ?? 0);
235
304
  },
@@ -245,6 +314,32 @@ export function createGithubClient(auth: GithubAuthManager) {
245
314
  await request("DELETE", `/repos/${owner}/${repo}/issues/${issueNumber}/assignees`, { body: { assignees } });
246
315
  },
247
316
 
317
+ /** #claim-dequeue: comments on an issue since a timestamp, for the
318
+ * dequeue-time external-collaboration check (authors + times only). */
319
+ async getIssueCommentsSince(owner: string, repo: string, issueNumber: number, sinceIso: string): Promise<Array<{ user: string; createdAt: string; body: string }>> {
320
+ try {
321
+ const { data } = await request("GET", `/repos/${owner}/${repo}/issues/${issueNumber}/comments?since=${encodeURIComponent(sinceIso)}&per_page=20`);
322
+ if (!Array.isArray(data)) return [];
323
+ return (data as Record<string, unknown>[]).map((c) => ({
324
+ user: String((c.user as { login?: string } | undefined)?.login ?? ""),
325
+ createdAt: String(c.created_at ?? ""),
326
+ body: String(c.body ?? ""),
327
+ })).filter((c) => c.user);
328
+ } catch {
329
+ return []; // listing failed - degrade to assignee check only
330
+ }
331
+ },
332
+
333
+ async getIssueCommentBodies(owner: string, repo: string, issueNumber: number): Promise<string[]> {
334
+ try {
335
+ const { data } = await request("GET", `/repos/${owner}/${repo}/issues/${issueNumber}/comments?per_page=30`);
336
+ if (!Array.isArray(data)) return [];
337
+ return (data as Record<string, unknown>[]).map((c) => String(c.body ?? ""));
338
+ } catch {
339
+ return []; // listing failed - degrade to posting (duplicate risk < lost delivery)
340
+ }
341
+ },
342
+
248
343
  /** Fresh issue state for claim-time re-checks (#268): the scan-time
249
344
  * assignee snapshot is seconds stale by enqueue time - a human may have
250
345
  * self-assigned in between, and claiming over a human is worse than not
@@ -269,8 +364,11 @@ export function createGithubClient(auth: GithubAuthManager) {
269
364
 
270
365
  /** Open a PR from a task worktree branch (collaboration contract delivery). */
271
366
  async createPullRequest(owner: string, repo: string, head: string, base: string, title: string, body: string): Promise<{ number: number; url: string }> {
367
+ // #5704 case 3: a bare frame as the whole PR body consumed the deliverable
368
+ // surface (ggcode #5703) - guard the PR body like every other write.
369
+ const safeBody = sanitizeGithubWriteBody(body, `create PR ${owner}/${repo} head=${head}`);
272
370
  const { data } = await request("POST", `/repos/${owner}/${repo}/pulls`, {
273
- body: { title, head, base, body },
371
+ body: { title, head, base, body: safeBody },
274
372
  });
275
373
  const item = data as { number?: number; html_url?: string };
276
374
  return { number: Number(item.number ?? 0), url: String(item.html_url ?? "") };