@teamclaws/teamclaw 2026.11.4 → 2026.11.6

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 (47) hide show
  1. package/dist/src/controller/config-routes.js +7 -3
  2. package/dist/src/controller/controller-service.js +12 -1
  3. package/dist/src/controller/provisioning/container-shared.js +6 -1
  4. package/dist/src/controller/provisioning/docker.js +1 -1
  5. package/dist/src/controller/provisioning/kubernetes.js +1 -1
  6. package/dist/src/controller/provisioning/process-supervisor.js +12 -1
  7. package/dist/src/controller/provisioning-config.js +8 -0
  8. package/dist/src/controller/task-assignment.js +65 -2
  9. package/dist/src/controller/task-results.js +34 -3
  10. package/dist/src/controller/task-routes.js +24 -1
  11. package/dist/src/controller/worker-provisioning.js +35 -0
  12. package/dist/src/controller/worker-routes.js +21 -6
  13. package/dist/src/openclaw-workspace.js +39 -20
  14. package/dist/src/task-executor.js +44 -3
  15. package/dist/src/teamauto/github-client.js +88 -5
  16. package/dist/src/teamauto/repo-sync.js +90 -5
  17. package/dist/src/teamauto/scanner.js +22 -1
  18. package/dist/src/teamauto/scheduler.js +587 -182
  19. package/dist/src/teamauto/store.js +46 -0
  20. package/dist/src/teamauto/write-payload-guard.js +209 -0
  21. package/dist/src/types.js +6 -0
  22. package/dist/src/worker/tools.js +5 -0
  23. package/openclaw.plugin.json +1 -1
  24. package/package.json +1 -1
  25. package/src/controller/config-routes.ts +7 -3
  26. package/src/controller/controller-service.ts +12 -1
  27. package/src/controller/provisioning/backend-contract.ts +4 -0
  28. package/src/controller/provisioning/container-shared.ts +6 -1
  29. package/src/controller/provisioning/docker.ts +1 -1
  30. package/src/controller/provisioning/kubernetes.ts +1 -1
  31. package/src/controller/provisioning/process-supervisor.ts +12 -1
  32. package/src/controller/provisioning-config.ts +9 -0
  33. package/src/controller/task-assignment.ts +71 -1
  34. package/src/controller/task-results.ts +33 -3
  35. package/src/controller/task-routes.ts +25 -1
  36. package/src/controller/worker-provisioning.ts +35 -0
  37. package/src/controller/worker-routes.ts +21 -7
  38. package/src/openclaw-workspace.ts +43 -23
  39. package/src/task-executor.ts +46 -3
  40. package/src/teamauto/github-client.ts +83 -5
  41. package/src/teamauto/repo-sync.ts +100 -4
  42. package/src/teamauto/scanner.ts +23 -2
  43. package/src/teamauto/scheduler.ts +503 -106
  44. package/src/teamauto/store.ts +72 -0
  45. package/src/teamauto/write-payload-guard.ts +222 -0
  46. package/src/types.ts +21 -0
  47. package/src/worker/tools.ts +5 -0
@@ -273,19 +273,43 @@ export async function handleTaskExecutionGetRequest(deps: ControllerTaskDomainDe
273
273
 
274
274
  // PATCH /api/v1/tasks/:id
275
275
  export async function handleTaskPatchRequest(deps: ControllerTaskDomainDeps, req: IncomingMessage, res: ServerResponse, pathname: string): Promise<void> {
276
- const { updateTeamState, wsServer } = deps;
276
+ const { updateTeamState, wsServer, logger, getTeamState } = deps;
277
277
  const taskId = pathname.split("/").pop()!;
278
278
  const body = await parseJsonBody(req);
279
279
  let statusEvent: TaskExecutionEvent | undefined;
280
280
  let progressEvent: TaskExecutionEvent | undefined;
281
281
  let progressContract: WorkerProgressContract | undefined;
282
282
 
283
+ // #5740 (ggcode, 2026-11-17): worker progress PATCHes now carry workerId;
284
+ // when present, the same stale-worker guard as the result routes applies
285
+ // so a dispatched-but-reverted (orphaned) run cannot keep mutating the
286
+ // task it no longer owns.
287
+ const patchWorkerId = typeof body.workerId === "string" ? body.workerId : undefined;
288
+ if (patchWorkerId) {
289
+ const currentTask = getTeamState()?.tasks[taskId];
290
+ if (currentTask && !canAcceptWorkerUpdate(currentTask, patchWorkerId)) {
291
+ logger.info(`Controller: ignoring stale task patch for ${taskId} from ${patchWorkerId}`);
292
+ sendJson(res, 202, { status: "ignored", reason: "stale-worker-update" });
293
+ return;
294
+ }
295
+ }
296
+
283
297
  const state = updateTeamState((s) => {
284
298
  const task = s.tasks[taskId];
285
299
  if (!task) return;
286
300
  const previousStatus = task.status;
287
301
  const previousProgress = task.progress;
288
302
  const previousProgressContract = task.progressContract;
303
+ // #5740: a bare PATCH (no workerId, e.g. WebUI) must not flip a pending,
304
+ // unassigned task to in_progress - that is exactly the illegal
305
+ // unclaimed-execution state the claim gate exists to prevent. The
306
+ // progress text below still applies.
307
+ if (typeof body.status === "string"
308
+ && body.status === "in_progress"
309
+ && task.status === "pending"
310
+ && !task.assignedWorkerId) {
311
+ delete body.status;
312
+ }
289
313
  if (typeof body.status === "string") task.status = body.status as TaskStatus;
290
314
  if (typeof body.progress === "string") task.progress = body.progress as string;
291
315
  if (typeof body.priority === "string") task.priority = body.priority as TaskPriority;
@@ -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
 
@@ -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
  }
@@ -219,17 +240,46 @@ export function createGithubClient(auth: GithubAuthManager) {
219
240
  // ---- write side (require Contents/Issues/PR write on the App) ----
220
241
 
221
242
  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 } });
243
+ // #5704: LLM envelope frames must never land as comment bodies.
244
+ const safeBody = sanitizeGithubWriteBody(body, `issue comment ${owner}/${repo}#${issueNumber}`);
245
+ const { data } = await request("POST", `/repos/${owner}/${repo}/issues/${issueNumber}/comments`, { body: { body: safeBody } });
223
246
  return Number((data as { id?: number }).id ?? 0);
224
247
  },
225
248
 
226
249
  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 } });
250
+ // #5704: same write-channel guard on the PR review surface.
251
+ const safeBody = sanitizeGithubWriteBody(body, `pull review ${owner}/${repo}#${pullNumber}`);
252
+ await request("POST", `/repos/${owner}/${repo}/pulls/${pullNumber}/reviews`, { body: { event: "COMMENT", body: safeBody } });
253
+ },
254
+
255
+ /** #5660: normalized feedback bodies already on a PR - review bodies AND
256
+ * issue-style comments (a worker may post through either surface during
257
+ * its execution window while the write-back ladder delivers the same
258
+ * text moments later). Whitespace-collapsed so footer spacing cannot
259
+ * defeat the comparison. */
260
+ async getPullFeedbackBodies(owner: string, repo: string, pullNumber: number): Promise<string[]> {
261
+ const bodies: string[] = [];
262
+ const norm = (raw: unknown): string => String(raw ?? "").replace(/\s+/g, " ").trim();
263
+ try {
264
+ const { data } = await request("GET", `/repos/${owner}/${repo}/pulls/${pullNumber}/reviews?per_page=30`);
265
+ if (Array.isArray(data)) {
266
+ for (const r of data as Record<string, unknown>[]) bodies.push(norm(r.body));
267
+ }
268
+ } catch { /* reviews listing failed - degrade to comments-only check */ }
269
+ try {
270
+ const { data } = await request("GET", `/repos/${owner}/${repo}/issues/${pullNumber}/comments?per_page=30`);
271
+ if (Array.isArray(data)) {
272
+ for (const c of data as Record<string, unknown>[]) bodies.push(norm(c.body));
273
+ }
274
+ } catch { /* comments listing failed - degrade to reviews-only check */ }
275
+ return bodies.filter(Boolean);
228
276
  },
229
277
 
230
278
  async createIssue(owner: string, repo: string, title: string, body: string, labels?: string[]): Promise<number> {
279
+ // #5704: umbrella/section bodies get the same frame guard.
280
+ const safeBody = sanitizeGithubWriteBody(body, `create issue ${owner}/${repo}`);
231
281
  const { data } = await request("POST", `/repos/${owner}/${repo}/issues`, {
232
- body: { title, body, ...(labels?.length ? { labels } : {}) },
282
+ body: { title, body: safeBody, ...(labels?.length ? { labels } : {}) },
233
283
  });
234
284
  return Number((data as { number?: number }).number ?? 0);
235
285
  },
@@ -245,6 +295,31 @@ export function createGithubClient(auth: GithubAuthManager) {
245
295
  await request("DELETE", `/repos/${owner}/${repo}/issues/${issueNumber}/assignees`, { body: { assignees } });
246
296
  },
247
297
 
298
+ /** #claim-dequeue: comments on an issue since a timestamp, for the
299
+ * 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 }>> {
301
+ try {
302
+ const { data } = await request("GET", `/repos/${owner}/${repo}/issues/${issueNumber}/comments?since=${encodeURIComponent(sinceIso)}&per_page=20`);
303
+ if (!Array.isArray(data)) return [];
304
+ return (data as Record<string, unknown>[]).map((c) => ({
305
+ user: String((c.user as { login?: string } | undefined)?.login ?? ""),
306
+ createdAt: String(c.created_at ?? ""),
307
+ })).filter((c) => c.user);
308
+ } catch {
309
+ return []; // listing failed - degrade to assignee check only
310
+ }
311
+ },
312
+
313
+ async getIssueCommentBodies(owner: string, repo: string, issueNumber: number): Promise<string[]> {
314
+ try {
315
+ const { data } = await request("GET", `/repos/${owner}/${repo}/issues/${issueNumber}/comments?per_page=30`);
316
+ if (!Array.isArray(data)) return [];
317
+ return (data as Record<string, unknown>[]).map((c) => String(c.body ?? ""));
318
+ } catch {
319
+ return []; // listing failed - degrade to posting (duplicate risk < lost delivery)
320
+ }
321
+ },
322
+
248
323
  /** Fresh issue state for claim-time re-checks (#268): the scan-time
249
324
  * assignee snapshot is seconds stale by enqueue time - a human may have
250
325
  * self-assigned in between, and claiming over a human is worse than not
@@ -269,8 +344,11 @@ export function createGithubClient(auth: GithubAuthManager) {
269
344
 
270
345
  /** Open a PR from a task worktree branch (collaboration contract delivery). */
271
346
  async createPullRequest(owner: string, repo: string, head: string, base: string, title: string, body: string): Promise<{ number: number; url: string }> {
347
+ // #5704 case 3: a bare frame as the whole PR body consumed the deliverable
348
+ // surface (ggcode #5703) - guard the PR body like every other write.
349
+ const safeBody = sanitizeGithubWriteBody(body, `create PR ${owner}/${repo} head=${head}`);
272
350
  const { data } = await request("POST", `/repos/${owner}/${repo}/pulls`, {
273
- body: { title, head, base, body },
351
+ body: { title, head, base, body: safeBody },
274
352
  });
275
353
  const item = data as { number?: number; html_url?: string };
276
354
  return { number: Number(item.number ?? 0), url: String(item.html_url ?? "") };
@@ -26,6 +26,16 @@ export type TaskDeliveryOracle = (
26
26
  headTip: string,
27
27
  ) => Promise<boolean>;
28
28
 
29
+ /**
30
+ * #orphan-gc oracle: is the worktree's TARGET (issue/PR) closed? true =
31
+ * positively closed (the worktree is an orphan - even a dirty tree has no
32
+ * possible delivery), null/false = unknown or still open (fail toward keep).
33
+ */
34
+ export type TaskTargetClosedOracle = (
35
+ repoId: string,
36
+ taskId: string,
37
+ ) => Promise<boolean | null>;
38
+
29
39
  /** TaskInfo.projectDir slug for a bound repo (relative to the projects dir). */
30
40
  export function teamAutoProjectDir(repoId: string): string {
31
41
  return `teamauto/${repoSlugToDirName(repoId)}`;
@@ -155,12 +165,57 @@ export function createRepoSync(auth: GithubAuthManager, logger: { warn: (m: stri
155
165
  return true;
156
166
  }
157
167
 
158
- async function pushBranch(repoId: string, dir: string, cloneUrl: string, branch: string): Promise<void> {
168
+ async function pushBranch(repoId: string, dir: string, cloneUrl: string, branch: string): Promise<{ alreadyDelivered: boolean }> {
159
169
  const authed = await tokenizedUrl(cloneUrl);
170
+ // #stale-base follow-up: the remote task branch may ALREADY carry the
171
+ // delivery (previous incarnation pushed it; the PR got merged). Blindly
172
+ // pushing HEAD again is a permanent non-fast-forward (6x retry spam,
173
+ // task mwfzy51j 2026-11-14). Fetch the remote tip first: when local
174
+ // HEAD is an ancestor of it, the work is already on the remote - report
175
+ // instead of pushing.
176
+ try {
177
+ await run(["fetch", authed, `refs/heads/${branch}`], dir);
178
+ const remoteTip = (await run(["rev-parse", "FETCH_HEAD"], dir)).trim();
179
+ const localHead = (await run(["rev-parse", "HEAD"], dir)).trim();
180
+ if (remoteTip && localHead && remoteTip !== localHead) {
181
+ const ancestor = await run(["merge-base", "--is-ancestor", localHead, remoteTip], dir).then(() => true, () => false);
182
+ if (ancestor) {
183
+ logger.warn(`TeamAuto: ${repoId}#${branch} already delivered (remote tip ${remoteTip.slice(0, 8)} contains local ${localHead.slice(0, 8)}) - skipping push`);
184
+ return { alreadyDelivered: true };
185
+ }
186
+ }
187
+ } catch { /* branch absent remotely or fetch failed - plain push below */ }
160
188
  try {
161
189
  await run(["push", authed, `HEAD:refs/heads/${branch}`], dir);
190
+ return { alreadyDelivered: false };
162
191
  } catch (err) {
163
- logger.warn(`TeamAuto: push failed for ${repoId}#${branch}: ${err instanceof Error ? err.message : String(err)}`);
192
+ const msg = err instanceof Error ? err.message : String(err);
193
+ logger.warn(`TeamAuto: push failed for ${repoId}#${branch}: ${msg}`);
194
+ // #5651 (ggcode, 2026-11-15): a NON-FAST-FORWARD rejection is
195
+ // deterministic - the generic retry ladder burned 6 attempts / ~25min
196
+ // on it twice (#5268 family). The task branch is exclusively ours, so
197
+ // rebase onto the fetched remote tip and push ONCE more; if the rebase
198
+ // conflicts (base rewritten underneath us) give up immediately - the
199
+ // caller's failure path is the correct terminal state, not 5 more
200
+ // doomed retries of the same push.
201
+ const NON_FF = /non-fast-forward|behind its remote counterpart|fetch first|reject/i;
202
+ if (NON_FF.test(msg)) {
203
+ try {
204
+ logger.warn(`TeamAuto: non-fast-forward on ${repoId}#${branch} - rebasing onto remote tip and retrying once`);
205
+ await run(["rebase", "FETCH_HEAD"], dir);
206
+ await run(["push", authed, `HEAD:refs/heads/${branch}`], dir);
207
+ logger.warn(`TeamAuto: ${repoId}#${branch} delivered after rebase`);
208
+ return { alreadyDelivered: false };
209
+ } catch (rebaseErr) {
210
+ // Leave the worktree clean for the next pass: abort a half-done
211
+ // rebase so the retry (or dead-letter) sees a sane tree.
212
+ await run(["rebase", "--abort"], dir).catch(() => {});
213
+ const rmsg = rebaseErr instanceof Error ? rebaseErr.message : String(rebaseErr);
214
+ logger.warn(`TeamAuto: rebase self-heal failed for ${repoId}#${branch}: ${rmsg}`);
215
+ const permanent = new Error(`push rejected (non-fast-forward) and rebase self-heal failed: ${rmsg}`);
216
+ throw permanent;
217
+ }
218
+ }
164
219
  throw err;
165
220
  }
166
221
  }
@@ -238,13 +293,28 @@ export function createRepoSync(auth: GithubAuthManager, logger: { warn: (m: stri
238
293
  * branched from HEAD. Reuses an existing worktree (resume-safe) so the
239
294
  * checkpoint/retry path lands in the same tree.
240
295
  */
241
- async function ensureTaskWorktree(repoId: string, taskId: string): Promise<string> {
296
+ async function ensureTaskWorktree(repoId: string, taskId: string, defaultBranch?: string, cloneUrl?: string): Promise<string> {
242
297
  const base = await repoDir(repoId);
243
298
  const wtName = taskWorktreeDirName(repoId, taskId);
244
299
  // wtName carries the teamauto/ level for the REL path; the physical dir is
245
300
  // a SIBLING of the base checkout (path.join would nest teamauto/ twice).
246
301
  const wtPath = path.join(path.dirname(base), path.basename(wtName));
247
302
  if (!(await fs.access(path.join(wtPath, ".git")).then(() => true, () => false))) {
303
+ // #stale-base (user report 2026-11-14): ensureCloned (fetch + reset to
304
+ // the default-branch tip) only ran at BIND time (learnNorms), so the
305
+ // base checkout's HEAD drifted days behind origin/main and EVERY new
306
+ // task worktree branched from stale code. Refresh the base right
307
+ // before creating a new branch off it - same fetch+reset as
308
+ // ensureCloned. Existing worktrees (resume path) are left untouched.
309
+ if (defaultBranch && cloneUrl) {
310
+ try {
311
+ const authed = await tokenizedUrl(cloneUrl);
312
+ await run(["fetch", authed, defaultBranch], base);
313
+ await run(["reset", "--hard", "FETCH_HEAD"], base);
314
+ } catch (err) {
315
+ logger.warn(`TeamAuto: base refresh failed for ${repoId} (continuing on current HEAD): ${err instanceof Error ? err.message : String(err)}`);
316
+ }
317
+ }
248
318
  await run(["worktree", "add", "-b", taskBranchName(taskId), wtPath, "HEAD"], base);
249
319
  logger.warn(`TeamAuto: worktree ${wtName} (branch ${taskBranchName(taskId)}) for ${taskId}`);
250
320
  }
@@ -283,6 +353,8 @@ export function createRepoSync(auth: GithubAuthManager, logger: { warn: (m: stri
283
353
  repoId: string,
284
354
  taskId: string,
285
355
  deliveryOracle?: TaskDeliveryOracle,
356
+ targetClosedOracle?: TaskTargetClosedOracle,
357
+ isUnknownTask?: (taskId: string) => boolean,
286
358
  ): Promise<{ removed: boolean; reason: string }> {
287
359
  const base = await repoDir(repoId);
288
360
  const wtName = taskWorktreeDirName(repoId, taskId);
@@ -310,6 +382,28 @@ export function createRepoSync(auth: GithubAuthManager, logger: { warn: (m: stri
310
382
  if (inUsePid !== null) {
311
383
  return { removed: false, reason: `retained: in use by live process (pid ${inUsePid})` };
312
384
  }
385
+ // #gc3 (user policy 2026-11-14: "全删"): a worktree whose task has NO
386
+ // record left in team-state (task history pruned) can never be judged
387
+ // by delivery/target oracles and was retained forever. The owner
388
+ // ruled: delete outright, no archive. Still placed AFTER the in-use
389
+ // sentinel - a live foreign controller may be finishing work in it.
390
+ if (isUnknownTask?.(taskId)) {
391
+ await removeTaskWorktree(repoId, taskId);
392
+ return { removed: true, reason: "orphaned: no task record (delete policy)" };
393
+ }
394
+ // #orphan-gc: the target issue/PR is CLOSED - no delivery this worktree
395
+ // could ever produce would be wanted (the issue was fixed/rejected
396
+ // elsewhere, the PR superseded). This is the authoritative orphan
397
+ // signal: it overrides the dirty guard, because "uncommitted work"
398
+ // toward a closed target has no future. Placed AFTER the in-use check -
399
+ // a live foreign controller may still be finishing a delivery race.
400
+ if (targetClosedOracle) {
401
+ const closed = await targetClosedOracle(repoId, taskId).catch(() => null);
402
+ if (closed === true) {
403
+ await removeTaskWorktree(repoId, taskId);
404
+ return { removed: true, reason: "orphaned: target issue/PR closed (dirty tree dropped - no possible delivery)" };
405
+ }
406
+ }
313
407
  // #173 follow-up 1: the dirty guard must cover BOTH removal paths. The
314
408
  // tip-match branch used to remove without any dirty check, silently
315
409
  // destroying post-delivery worker edits (small window, but real).
@@ -368,6 +462,8 @@ export function createRepoSync(auth: GithubAuthManager, logger: { warn: (m: stri
368
462
  repoId: string,
369
463
  isTerminal: (taskId: string) => boolean,
370
464
  deliveryOracle?: TaskDeliveryOracle,
465
+ targetClosedOracle?: TaskTargetClosedOracle,
466
+ isUnknownTask?: (taskId: string) => boolean,
371
467
  ): Promise<{ removed: string[]; retained: { taskId: string; reason: string }[]; stale: number }> {
372
468
  const base = await repoDir(repoId);
373
469
  const siblings = path.dirname(base);
@@ -379,7 +475,7 @@ export function createRepoSync(auth: GithubAuthManager, logger: { warn: (m: stri
379
475
  const retained: { taskId: string; reason: string }[] = [];
380
476
  let stale = 0;
381
477
  const apply = async (taskId: string): Promise<void> => {
382
- const r = await safeRemoveTaskWorktree(repoId, taskId, deliveryOracle);
478
+ const r = await safeRemoveTaskWorktree(repoId, taskId, deliveryOracle, targetClosedOracle, isUnknownTask);
383
479
  if (r.removed) {
384
480
  removed.push(taskId);
385
481
  logger.warn(`TeamAuto: worktree GC removed ${taskId} (${r.reason})`);
@@ -9,7 +9,7 @@ import type { TeamAutoRepo } from "./store.js";
9
9
  * filters, idempotency via the `seen` cursor map).
10
10
  */
11
11
 
12
- export type CandidateKind = "issueReview" | "takeOwnership" | "prReview" | "fullReview";
12
+ export type CandidateKind = "issueReview" | "takeOwnership" | "prReview" | "fullReview" | "prRework";
13
13
 
14
14
  /**
15
15
  * Joint full-review section definitions: which review sections exist and
@@ -187,7 +187,28 @@ export async function sweepRepo(
187
187
  if ((repo.cursors.seen[key] ?? 0) >= updatedAtMs) {
188
188
  continue;
189
189
  }
190
- // See the issue-loop note: no first-sweep gate (deadlock source).
190
+ // #pr-rework (user 2026-11-15, live case ggcode#5653): OUR OWN open PRs
191
+ // were exempted below to avoid self-review loops - but that also made
192
+ // external review feedback (GO/NO GO, rework requests) DEAD: delivery
193
+ // write-back completes at PR creation, nothing ever re-picks the thread,
194
+ // and a NO GO'd PR sat idle 12h+ until a human coordinator intervened.
195
+ // Same-ecosystem communication IS the GitHub surface - close the loop:
196
+ // our own PR with fresh activity becomes a prRework task (the worker
197
+ // reads the review thread and continues in the original branch).
198
+ if (pull.head.startsWith("teamclaw/") && !pull.draft && repo.policy.actions.prRework) {
199
+ candidates.push({
200
+ repoId: repo.id,
201
+ key,
202
+ kind: "prRework",
203
+ number: pull.number,
204
+ role: "developer" as const,
205
+ writeMode: "write" as const,
206
+ title: truncate(`Rework from review: PR #${pull.number}: ${pull.title}`, 120),
207
+ reason: "our delivered PR received new review activity",
208
+ context: `Our delivery PR #${pull.number} received new review activity (comments/review/edits at ${pull.updated_at}).\nLink: ${pull.htmlUrl}\nHead branch: ${pull.head}\n\nRead the review thread on the PR, address the feedback, and push follow-up commits to the same branch.\n\nPR description:\n${truncate(pull.body, 2000)}`,
209
+ });
210
+ continue;
211
+ }
191
212
  // Skip our own PRs and drafts.
192
213
  if (pull.head.startsWith("teamclaw/") || pull.draft || TEAMCLAW_MARKER_RE.test(pull.title)) {
193
214
  continue;