@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
@@ -155,22 +155,116 @@ 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<void> {
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);
204
+ // #stale-base follow-up: the remote task branch may ALREADY carry the
205
+ // delivery (previous incarnation pushed it; the PR got merged). Blindly
206
+ // pushing HEAD again is a permanent non-fast-forward (6x retry spam,
207
+ // task mwfzy51j 2026-11-14). Fetch the remote tip first: when local
208
+ // HEAD is an ancestor of it, the work is already on the remote - report
209
+ // instead of pushing.
210
+ try {
211
+ await run(["fetch", authed, `refs/heads/${branch}`], dir);
212
+ const remoteTip = (await run(["rev-parse", "FETCH_HEAD"], dir)).trim();
213
+ const localHead = (await run(["rev-parse", "HEAD"], dir)).trim();
214
+ if (remoteTip && localHead && remoteTip !== localHead) {
215
+ const ancestor = await run(["merge-base", "--is-ancestor", localHead, remoteTip], dir).then(() => true, () => false);
216
+ if (ancestor) {
217
+ logger.warn(`TeamAuto: ${repoId}#${branch} already delivered (remote tip ${remoteTip.slice(0, 8)} contains local ${localHead.slice(0, 8)}) - skipping push`);
218
+ return { alreadyDelivered: true };
219
+ }
220
+ }
221
+ } catch { /* branch absent remotely or fetch failed - plain push below */ }
170
222
  try {
171
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
+ }
235
+ return { alreadyDelivered: false };
172
236
  } catch (err) {
173
- logger.warn(`TeamAuto: push failed for ${repoId}#${branch}: ${err instanceof Error ? err.message : String(err)}`);
237
+ const msg = err instanceof Error ? err.message : String(err);
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 */ }
243
+ // #5651 (ggcode, 2026-11-15): a NON-FAST-FORWARD rejection is
244
+ // deterministic - the generic retry ladder burned 6 attempts / ~25min
245
+ // on it twice (#5268 family). The task branch is exclusively ours, so
246
+ // rebase onto the fetched remote tip and push ONCE more; if the rebase
247
+ // conflicts (base rewritten underneath us) give up immediately - the
248
+ // caller's failure path is the correct terminal state, not 5 more
249
+ // doomed retries of the same push.
250
+ const NON_FF = /non-fast-forward|behind its remote counterpart|fetch first|reject/i;
251
+ if (NON_FF.test(msg)) {
252
+ try {
253
+ logger.warn(`TeamAuto: non-fast-forward on ${repoId}#${branch} - rebasing onto remote tip and retrying once`);
254
+ await run(["rebase", "FETCH_HEAD"], dir);
255
+ await run(["push", authed, `HEAD:refs/heads/${branch}`], dir);
256
+ logger.warn(`TeamAuto: ${repoId}#${branch} delivered after rebase`);
257
+ return { alreadyDelivered: false };
258
+ } catch (rebaseErr) {
259
+ // Leave the worktree clean for the next pass: abort a half-done
260
+ // rebase so the retry (or dead-letter) sees a sane tree.
261
+ await run(["rebase", "--abort"], dir).catch(() => {});
262
+ const rmsg = rebaseErr instanceof Error ? rebaseErr.message : String(rebaseErr);
263
+ logger.warn(`TeamAuto: rebase self-heal failed for ${repoId}#${branch}: ${rmsg}`);
264
+ const permanent = new Error(`push rejected (non-fast-forward) and rebase self-heal failed: ${rmsg}`);
265
+ throw permanent;
266
+ }
267
+ }
174
268
  throw err;
175
269
  }
176
270
  }
@@ -248,15 +342,61 @@ export function createRepoSync(auth: GithubAuthManager, logger: { warn: (m: stri
248
342
  * branched from HEAD. Reuses an existing worktree (resume-safe) so the
249
343
  * checkpoint/retry path lands in the same tree.
250
344
  */
251
- async function ensureTaskWorktree(repoId: string, taskId: string): Promise<string> {
345
+ async function ensureTaskWorktree(repoId: string, taskId: string, defaultBranch?: string, cloneUrl?: string): Promise<string> {
252
346
  const base = await repoDir(repoId);
253
347
  const wtName = taskWorktreeDirName(repoId, taskId);
254
348
  // wtName carries the teamauto/ level for the REL path; the physical dir is
255
349
  // a SIBLING of the base checkout (path.join would nest teamauto/ twice).
256
350
  const wtPath = path.join(path.dirname(base), path.basename(wtName));
257
- 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) {
353
+ // #stale-base (user report 2026-11-14): ensureCloned (fetch + reset to
354
+ // the default-branch tip) only ran at BIND time (learnNorms), so the
355
+ // base checkout's HEAD drifted days behind origin/main and EVERY new
356
+ // task worktree branched from stale code. Refresh the base right
357
+ // before creating a new branch off it - same fetch+reset as
358
+ // ensureCloned.
359
+ if (defaultBranch && cloneUrl) {
360
+ try {
361
+ const authed = await tokenizedUrl(cloneUrl);
362
+ await run(["fetch", authed, defaultBranch], base);
363
+ await run(["reset", "--hard", "FETCH_HEAD"], base);
364
+ } catch (err) {
365
+ logger.warn(`TeamAuto: base refresh failed for ${repoId} (continuing on current HEAD): ${err instanceof Error ? err.message : String(err)}`);
366
+ }
367
+ }
258
368
  await run(["worktree", "add", "-b", taskBranchName(taskId), wtPath, "HEAD"], base);
259
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
+ }
260
400
  }
261
401
  // Refresh the in-use sentinel on create AND resume (#173 follow-up 2).
262
402
  await writeTaskLock(wtPath);
@@ -294,6 +434,7 @@ export function createRepoSync(auth: GithubAuthManager, logger: { warn: (m: stri
294
434
  taskId: string,
295
435
  deliveryOracle?: TaskDeliveryOracle,
296
436
  targetClosedOracle?: TaskTargetClosedOracle,
437
+ isUnknownTask?: (taskId: string) => boolean,
297
438
  ): Promise<{ removed: boolean; reason: string }> {
298
439
  const base = await repoDir(repoId);
299
440
  const wtName = taskWorktreeDirName(repoId, taskId);
@@ -321,6 +462,15 @@ export function createRepoSync(auth: GithubAuthManager, logger: { warn: (m: stri
321
462
  if (inUsePid !== null) {
322
463
  return { removed: false, reason: `retained: in use by live process (pid ${inUsePid})` };
323
464
  }
465
+ // #gc3 (user policy 2026-11-14: "全删"): a worktree whose task has NO
466
+ // record left in team-state (task history pruned) can never be judged
467
+ // by delivery/target oracles and was retained forever. The owner
468
+ // ruled: delete outright, no archive. Still placed AFTER the in-use
469
+ // sentinel - a live foreign controller may be finishing work in it.
470
+ if (isUnknownTask?.(taskId)) {
471
+ await removeTaskWorktree(repoId, taskId);
472
+ return { removed: true, reason: "orphaned: no task record (delete policy)" };
473
+ }
324
474
  // #orphan-gc: the target issue/PR is CLOSED - no delivery this worktree
325
475
  // could ever produce would be wanted (the issue was fixed/rejected
326
476
  // elsewhere, the PR superseded). This is the authoritative orphan
@@ -393,6 +543,7 @@ export function createRepoSync(auth: GithubAuthManager, logger: { warn: (m: stri
393
543
  isTerminal: (taskId: string) => boolean,
394
544
  deliveryOracle?: TaskDeliveryOracle,
395
545
  targetClosedOracle?: TaskTargetClosedOracle,
546
+ isUnknownTask?: (taskId: string) => boolean,
396
547
  ): Promise<{ removed: string[]; retained: { taskId: string; reason: string }[]; stale: number }> {
397
548
  const base = await repoDir(repoId);
398
549
  const siblings = path.dirname(base);
@@ -404,7 +555,7 @@ export function createRepoSync(auth: GithubAuthManager, logger: { warn: (m: stri
404
555
  const retained: { taskId: string; reason: string }[] = [];
405
556
  let stale = 0;
406
557
  const apply = async (taskId: string): Promise<void> => {
407
- const r = await safeRemoveTaskWorktree(repoId, taskId, deliveryOracle, targetClosedOracle);
558
+ const r = await safeRemoveTaskWorktree(repoId, taskId, deliveryOracle, targetClosedOracle, isUnknownTask);
408
559
  if (r.removed) {
409
560
  removed.push(taskId);
410
561
  logger.warn(`TeamAuto: worktree GC removed ${taskId} (${r.reason})`);
@@ -462,23 +613,7 @@ export function createRepoSync(auth: GithubAuthManager, logger: { warn: (m: stri
462
613
  return taskWorktreeDirName(repoId, taskId);
463
614
  }
464
615
 
465
- /** True when HEAD has commits beyond the base branch (worktree delivery). */
466
- async function branchHasCommits(dir: string, baseBranch: string): Promise<boolean> {
467
- try {
468
- const out = await run(["rev-list", "--count", "HEAD", "--not", baseBranch], dir);
469
- return Number(out.trim()) > 0;
470
- } catch {
471
- // Base branch name unknown/unfetched - fall back to diff against first parent chain
472
- try {
473
- const root = await run(["rev-list", "--max-parents=0", "HEAD"], dir);
474
- return root.trim().length > 0;
475
- } catch {
476
- return false;
477
- }
478
- }
479
- }
480
-
481
- 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 };
482
617
  }
483
618
 
484
619
  export type TeamAutoRepoSync = ReturnType<typeof createRepoSync>;
@@ -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;