@teamclaws/teamclaw 2026.8.1 → 2026.11.1

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 (184) hide show
  1. package/cli.mjs +318 -17
  2. package/dist/index.js +54 -32
  3. package/dist/src/config.js +57 -2
  4. package/dist/src/controller/auth-routes.js +129 -0
  5. package/dist/src/controller/clarification-routes.js +315 -0
  6. package/dist/src/controller/controller-intake.js +895 -0
  7. package/dist/src/controller/controller-planning.js +814 -0
  8. package/dist/src/controller/controller-routes.js +195 -0
  9. package/dist/src/controller/controller-runs.js +175 -0
  10. package/dist/src/controller/controller-service.js +338 -50
  11. package/dist/src/controller/controller-tools.js +14 -7
  12. package/dist/src/controller/github-auth.js +2 -1
  13. package/dist/src/controller/http-server.js +290 -6003
  14. package/dist/src/controller/kickoff-orchestrator.js +33 -43
  15. package/dist/src/controller/message-delivery.js +31 -0
  16. package/dist/src/controller/message-routes.js +114 -0
  17. package/dist/src/controller/orchestration-manifest.js +11 -93
  18. package/dist/src/controller/preview-manager.js +51 -3
  19. package/dist/src/controller/preview-proxy.js +98 -0
  20. package/dist/src/controller/profile-switch.js +309 -0
  21. package/dist/src/controller/project-registry.js +294 -0
  22. package/dist/src/controller/prompt-injector.js +19 -9
  23. package/dist/src/controller/provisioning/backend-contract.js +9 -0
  24. package/dist/src/controller/provisioning/container-shared.js +64 -0
  25. package/dist/src/controller/provisioning/docker.js +214 -0
  26. package/dist/src/controller/provisioning/kubernetes.js +244 -0
  27. package/dist/src/controller/provisioning/plugin-root.js +41 -0
  28. package/dist/src/controller/provisioning/process-supervisor.js +190 -0
  29. package/dist/src/controller/provisioning-config.js +239 -0
  30. package/dist/src/controller/repo-routes.js +129 -0
  31. package/dist/src/controller/report-routes.js +56 -0
  32. package/dist/src/controller/role-inference.js +231 -20
  33. package/dist/src/controller/route-table.js +375 -0
  34. package/dist/src/controller/security.js +775 -0
  35. package/dist/src/controller/status-routes.js +287 -0
  36. package/dist/src/controller/task-assignment.js +511 -0
  37. package/dist/src/controller/task-cleanup.js +258 -0
  38. package/dist/src/controller/task-execution.js +271 -0
  39. package/dist/src/controller/task-results.js +471 -0
  40. package/dist/src/controller/task-router.js +74 -4
  41. package/dist/src/controller/task-routes.js +703 -0
  42. package/dist/src/controller/teamauto-routes.js +124 -0
  43. package/dist/src/controller/tunnel-manager.js +41 -8
  44. package/dist/src/controller/tunnel-routes.js +225 -0
  45. package/dist/src/controller/ui-assets.js +68 -0
  46. package/dist/src/controller/websocket.js +6 -2
  47. package/dist/src/controller/webui-routes.js +49 -0
  48. package/dist/src/controller/worker-provisioning.js +69 -953
  49. package/dist/src/controller/worker-routes.js +188 -0
  50. package/dist/src/controller/workflow-routes.js +407 -0
  51. package/dist/src/controller/workspace-routes.js +200 -0
  52. package/dist/src/git-collaboration.js +4 -9
  53. package/dist/src/identity.js +15 -3
  54. package/dist/src/interaction-contracts.js +7 -7
  55. package/dist/src/openclaw-workspace.js +40 -18
  56. package/dist/src/profile-loader.js +604 -0
  57. package/dist/src/profiles/banking.json +202 -0
  58. package/dist/src/profiles/crossborder-ecom.json +253 -0
  59. package/dist/src/profiles/insurance.json +157 -0
  60. package/dist/src/profiles/knowledge/hs-structure.md +97 -0
  61. package/dist/src/profiles/knowledge/incoterms-2020.md +188 -0
  62. package/dist/src/profiles/knowledge/vat-principles.md +85 -0
  63. package/dist/src/profiles/schema.json +281 -0
  64. package/dist/src/profiles/securities.json +137 -0
  65. package/dist/src/profiles/software-rd.json +264 -0
  66. package/dist/src/profiles/trading-co.json +200 -0
  67. package/dist/src/prompt-policy.js +42 -17
  68. package/dist/src/protocol.js +66 -3
  69. package/dist/src/role-ids.js +29 -0
  70. package/dist/src/roles.js +54 -13
  71. package/dist/src/session-roles.js +14 -0
  72. package/dist/src/shared/clarification-schema.js +65 -0
  73. package/dist/src/shared/github-auth.js +15 -0
  74. package/dist/src/shared/kickoff-prompt.js +37 -0
  75. package/dist/src/shared/utils.js +47 -0
  76. package/dist/src/state.js +275 -11
  77. package/dist/src/task-executor.js +7 -17
  78. package/dist/src/teamauto/github-client.js +18 -0
  79. package/dist/src/teamauto/repo-sync.js +228 -6
  80. package/dist/src/teamauto/scanner.js +40 -12
  81. package/dist/src/teamauto/scheduler.js +231 -12
  82. package/dist/src/types.js +77 -16
  83. package/dist/src/ui/app.js +1434 -82
  84. package/dist/src/ui/github-login.html +1 -0
  85. package/dist/src/ui/index.html +144 -45
  86. package/dist/src/ui/style.css +194 -0
  87. package/dist/src/worker/http-handler.js +59 -0
  88. package/dist/src/worker/prompt-injector.js +44 -8
  89. package/dist/src/worker/skill-installer.js +6 -10
  90. package/dist/src/worker/tools.js +20 -10
  91. package/dist/src/worker/worker-service.js +93 -7
  92. package/index.ts +61 -32
  93. package/openclaw.plugin.json +50 -2
  94. package/package.json +3 -2
  95. package/src/config.ts +57 -2
  96. package/src/controller/auth-routes.ts +157 -0
  97. package/src/controller/clarification-routes.ts +404 -0
  98. package/src/controller/controller-intake.ts +1113 -0
  99. package/src/controller/controller-planning.ts +1037 -0
  100. package/src/controller/controller-routes.ts +237 -0
  101. package/src/controller/controller-runs.ts +239 -0
  102. package/src/controller/controller-service.ts +422 -50
  103. package/src/controller/controller-tools.ts +16 -9
  104. package/src/controller/github-auth.ts +28 -63
  105. package/src/controller/http-server.ts +336 -6964
  106. package/src/controller/kickoff-orchestrator.ts +69 -45
  107. package/src/controller/message-delivery.ts +52 -0
  108. package/src/controller/message-routes.ts +137 -0
  109. package/src/controller/orchestration-manifest.ts +14 -100
  110. package/src/controller/preview-manager.ts +53 -3
  111. package/src/controller/preview-proxy.ts +127 -0
  112. package/src/controller/profile-switch.ts +396 -0
  113. package/src/controller/project-registry.ts +361 -0
  114. package/src/controller/prompt-injector.ts +23 -8
  115. package/src/controller/provisioning/backend-contract.ts +51 -0
  116. package/src/controller/provisioning/container-shared.ts +84 -0
  117. package/src/controller/provisioning/docker.ts +260 -0
  118. package/src/controller/provisioning/kubernetes.ts +263 -0
  119. package/src/controller/provisioning/plugin-root.ts +42 -0
  120. package/src/controller/provisioning/process-supervisor.ts +214 -0
  121. package/src/controller/provisioning-config.ts +289 -0
  122. package/src/controller/repo-routes.ts +163 -0
  123. package/src/controller/report-routes.ts +64 -0
  124. package/src/controller/role-inference.ts +260 -22
  125. package/src/controller/route-table.ts +597 -0
  126. package/src/controller/security.ts +899 -0
  127. package/src/controller/status-routes.ts +354 -0
  128. package/src/controller/task-assignment.ts +622 -0
  129. package/src/controller/task-cleanup.ts +344 -0
  130. package/src/controller/task-execution.ts +399 -0
  131. package/src/controller/task-results.ts +556 -0
  132. package/src/controller/task-router.ts +98 -6
  133. package/src/controller/task-routes.ts +812 -0
  134. package/src/controller/teamauto-routes.ts +121 -0
  135. package/src/controller/tunnel-manager.ts +45 -8
  136. package/src/controller/tunnel-routes.ts +231 -0
  137. package/src/controller/ui-assets.ts +70 -0
  138. package/src/controller/websocket.ts +32 -4
  139. package/src/controller/webui-routes.ts +55 -0
  140. package/src/controller/worker-provisioning.ts +83 -1121
  141. package/src/controller/worker-routes.ts +241 -0
  142. package/src/controller/workflow-routes.ts +498 -0
  143. package/src/controller/workspace-routes.ts +222 -0
  144. package/src/git-collaboration.ts +4 -9
  145. package/src/identity.ts +16 -3
  146. package/src/interaction-contracts.ts +7 -7
  147. package/src/openclaw-workspace.ts +44 -18
  148. package/src/profile-loader.ts +816 -0
  149. package/src/profiles/banking.json +202 -0
  150. package/src/profiles/crossborder-ecom.json +253 -0
  151. package/src/profiles/insurance.json +157 -0
  152. package/src/profiles/knowledge/hs-structure.md +97 -0
  153. package/src/profiles/knowledge/incoterms-2020.md +188 -0
  154. package/src/profiles/knowledge/vat-principles.md +85 -0
  155. package/src/profiles/schema.json +281 -0
  156. package/src/profiles/securities.json +137 -0
  157. package/src/profiles/software-rd.json +264 -0
  158. package/src/profiles/trading-co.json +200 -0
  159. package/src/prompt-policy.ts +44 -17
  160. package/src/protocol.ts +72 -2
  161. package/src/role-ids.ts +31 -0
  162. package/src/roles.ts +60 -14
  163. package/src/session-roles.ts +14 -0
  164. package/src/shared/clarification-schema.ts +81 -0
  165. package/src/shared/github-auth.ts +92 -0
  166. package/src/shared/kickoff-prompt.ts +47 -0
  167. package/src/shared/utils.ts +51 -0
  168. package/src/state.ts +326 -10
  169. package/src/task-executor.ts +7 -18
  170. package/src/teamauto/github-client.ts +23 -1
  171. package/src/teamauto/repo-sync.ts +248 -7
  172. package/src/teamauto/scanner.ts +47 -13
  173. package/src/teamauto/scheduler.ts +261 -17
  174. package/src/teamauto/store.ts +12 -0
  175. package/src/types.ts +263 -17
  176. package/src/ui/app.js +1434 -82
  177. package/src/ui/github-login.html +1 -0
  178. package/src/ui/index.html +144 -45
  179. package/src/ui/style.css +194 -0
  180. package/src/worker/http-handler.ts +64 -1
  181. package/src/worker/prompt-injector.ts +48 -8
  182. package/src/worker/skill-installer.ts +6 -10
  183. package/src/worker/tools.ts +21 -10
  184. package/src/worker/worker-service.ts +101 -7
@@ -1,4 +1,8 @@
1
1
  import { randomBytes } from "node:crypto";
2
+ // Phase 2.3/2.5 (cross-review adopted suggestion): manual-proposal roles
3
+ // validate against the ACTIVE profile and default to its defaultRole instead
4
+ // of hardcoded software role literals.
5
+ import { getActiveDefaultRole, validateActiveRoleId } from "../profile-loader.js";
2
6
  import { createGithubClient } from "./github-client.js";
3
7
  import { learnNorms, renderNormsBlock } from "./norms.js";
4
8
  import { createRepoSync, teamAutoProjectDir } from "./repo-sync.js";
@@ -53,6 +57,28 @@ export function sweepBackoffMinutes(failures) {
53
57
  export function sweepRetryDueAt(failures, lastErrorAt) {
54
58
  return lastErrorAt + sweepBackoffMinutes(failures) * 60_000;
55
59
  }
60
+ /**
61
+ * Issue #24: max write-back delivery attempts before the entry is marked
62
+ * terminally failed (failedAt) and never retried again.
63
+ */
64
+ export const TEAMAUTO_WRITEBACK_MAX_ATTEMPTS = 6;
65
+ /**
66
+ * Issue #24: write-back retry backoff - 1 minute after the 1st failure,
67
+ * doubling per attempt, capped at 2 hours. Over
68
+ * TEAMAUTO_WRITEBACK_MAX_ATTEMPTS attempts this spaces transient GitHub API
69
+ * failures (secondary rate limits, 5xx, token refresh races) across roughly
70
+ * an hour before giving up, instead of the pre-fix behavior (sticky error
71
+ * with no retry/no visibility, then a 20s hammer once the self-heal landed).
72
+ */
73
+ export const WRITEBACK_RETRY_BASE_MS = 60_000;
74
+ export const WRITEBACK_RETRY_MAX_MS = 2 * 60 * 60_000;
75
+ export function writebackBackoffMs(attempts) {
76
+ return Math.min(WRITEBACK_RETRY_BASE_MS * 2 ** Math.max(0, attempts - 1), WRITEBACK_RETRY_MAX_MS);
77
+ }
78
+ /** Epoch ms when a failed write-back becomes due for its next retry. */
79
+ export function writebackRetryDueAt(attempts, lastErrorAt) {
80
+ return lastErrorAt + writebackBackoffMs(attempts);
81
+ }
56
82
  /** Auto-pauses (set by the sweep catch block) are cooldowns; user pauses are not. */
57
83
  export function isAutoPause(reason) {
58
84
  return !!reason && reason.startsWith("sweep failed:");
@@ -63,8 +89,88 @@ export function createTeamAutoScheduler(deps) {
63
89
  pushTeamAutoActivity(store, entry);
64
90
  deps.onActivity?.(entry);
65
91
  }
92
+ /**
93
+ * Issue #24: a failed write-back used to be a sticky `error` field whose
94
+ * only trace was one warn log line - the completed task's result never
95
+ * reached GitHub and nothing surfaced it. Centralized failure handling:
96
+ * persist the failure (attempts/backoff), expose it in the activity feed,
97
+ * and give up terminally (failedAt) once attempts are exhausted or the
98
+ * caller flags the failure undeliverable.
99
+ */
100
+ function markWritebackFailure(store, entry, message, options = {}) {
101
+ entry.error = message;
102
+ entry.attempts = (entry.attempts ?? 0) + 1;
103
+ entry.lastErrorAt = Date.now();
104
+ entry.nextAttemptAt = writebackRetryDueAt(entry.attempts, entry.lastErrorAt);
105
+ const gaveUp = options.terminal === true || entry.attempts >= TEAMAUTO_WRITEBACK_MAX_ATTEMPTS;
106
+ if (gaveUp && !entry.doneAt) {
107
+ entry.failedAt = Date.now();
108
+ recordActivity(store, {
109
+ at: Date.now(),
110
+ repoId: entry.repoId,
111
+ kind: "writeback",
112
+ text: `failed permanently after ${entry.attempts} attempt(s) (${entry.action} #${entry.targetId ?? "-"}, task ${entry.taskId}): ${message}`,
113
+ });
114
+ logger.warn(`TeamAuto: write-back ${entry.taskId} (${entry.repoId} ${entry.action} #${entry.targetId ?? "-"}) gave up after ${entry.attempts} attempts: ${message}`);
115
+ return;
116
+ }
117
+ recordActivity(store, {
118
+ at: Date.now(),
119
+ repoId: entry.repoId,
120
+ kind: "writeback",
121
+ text: `failed (attempt ${entry.attempts}/${TEAMAUTO_WRITEBACK_MAX_ATTEMPTS}, retry in ~${Math.max(1, Math.round(writebackBackoffMs(entry.attempts) / 60_000))}min) (${entry.action} #${entry.targetId ?? "-"}): ${message}`,
122
+ });
123
+ logger.warn(`TeamAuto: writeback failed (${entry.repoId} ${entry.action} #${entry.targetId ?? "-"}): ${message}`);
124
+ }
125
+ /**
126
+ * Issue #24: write-back delivery stats surfaced through getStatus() so the
127
+ * repos endpoint, the teamclaw_teamauto_status tool, and the activity feed
128
+ * can see stuck/failed deliveries instead of only warn logs.
129
+ */
130
+ function summarizeWritebacks(store) {
131
+ const open = store.writebacks.filter((w) => !w.doneAt);
132
+ const failed = open.filter((w) => w.failedAt);
133
+ const errored = open.filter((w) => w.error && !w.failedAt);
134
+ const lastErrorEntry = open
135
+ .filter((w) => w.error)
136
+ .sort((a, b) => (b.lastErrorAt ?? 0) - (a.lastErrorAt ?? 0))[0];
137
+ return {
138
+ pending: open.length - failed.length - errored.length,
139
+ errored: errored.length,
140
+ failed: failed.length,
141
+ lastError: lastErrorEntry
142
+ ? {
143
+ taskId: lastErrorEntry.taskId,
144
+ repoId: lastErrorEntry.repoId,
145
+ action: lastErrorEntry.action,
146
+ targetId: lastErrorEntry.targetId,
147
+ attempts: lastErrorEntry.attempts ?? 0,
148
+ terminal: Boolean(lastErrorEntry.failedAt),
149
+ at: lastErrorEntry.lastErrorAt ?? null,
150
+ message: lastErrorEntry.error,
151
+ }
152
+ : null,
153
+ };
154
+ }
66
155
  const client = createGithubClient(auth);
67
156
  const sync = createRepoSync(auth, logger);
157
+ // #173 follow-up 5: squash-merge delivery oracle for worktree GC. After a
158
+ // squash merge + branch deletion the task commits are unreachable from
159
+ // origin/<default>, so the rev-list own-count never drains and the worktree
160
+ // is retained forever. Positive proof = a merged PR whose head tip is exactly
161
+ // the worktree's HEAD. Every failure path resolves false (fail toward keep).
162
+ const squashDeliveryOracle = async (repoId, taskId, headTip) => {
163
+ try {
164
+ const [owner, name] = repoId.split("/");
165
+ if (!owner || !name) {
166
+ return false;
167
+ }
168
+ return await client.prHeadDelivered(owner, name, sync.taskBranchName(taskId), headTip);
169
+ }
170
+ catch {
171
+ return false;
172
+ }
173
+ };
68
174
  const timers = new Map();
69
175
  const sweeping = new Set();
70
176
  let running = false;
@@ -374,6 +480,8 @@ export function createTeamAutoScheduler(deps) {
374
480
  ].join("\n"),
375
481
  status: "pending",
376
482
  priority: candidate.kind === "takeOwnership" ? "high" : "medium",
483
+ // Candidate.role is RoleId since Phase 2.3 debt item 4 (scanner role
484
+ // set derives from the active team profile) - no cast needed.
377
485
  assignedRole: candidate.role,
378
486
  writeMode: candidate.writeMode === "write" ? "write" : "read-only",
379
487
  createdBy: "teamauto",
@@ -400,12 +508,17 @@ export function createTeamAutoScheduler(deps) {
400
508
  throw new Error(`${repoId} not bound`);
401
509
  }
402
510
  const kind = input.kind === "takeOwnership" || input.kind === "issueReview" || input.kind === "prReview" || input.kind === "fullReview" ? input.kind : "issueReview";
511
+ // Cross-review adopted suggestion: the caller-supplied role is untrusted
512
+ // input - validate it against the ACTIVE profile (drops unknown and
513
+ // not-in-this-profile ids) and fall back to the profile defaultRole
514
+ // instead of the old hardcoded "developer"/"architect" software literals.
515
+ const role = validateActiveRoleId(input.role) ?? getActiveDefaultRole();
403
516
  const candidate = {
404
517
  repoId,
405
518
  key: `${repoId}#manual-${Date.now()}`,
406
519
  kind,
407
520
  number: 0,
408
- role: (input.role || (kind === "takeOwnership" ? "developer" : "architect")),
521
+ role,
409
522
  writeMode: input.writeMode ?? (kind === "takeOwnership" ? "write" : "read-only"),
410
523
  title: input.title.slice(0, 120),
411
524
  reason: "manual proposal from agent tool",
@@ -430,6 +543,7 @@ export function createTeamAutoScheduler(deps) {
430
543
  // never deliver - drop them instead of accumulating forever.
431
544
  if (state0) {
432
545
  const before = s.writebacks.length;
546
+ const deadOnes = [];
433
547
  s.writebacks = s.writebacks.filter((w) => {
434
548
  if (w.doneAt) {
435
549
  return true;
@@ -438,25 +552,50 @@ export function createTeamAutoScheduler(deps) {
438
552
  const dead = !t || (t.status === "failed" && !t.result);
439
553
  if (dead) {
440
554
  logger.warn(`TeamAuto: dropping dead write-back ${w.taskId} (${t ? "task failed without result" : "task missing"})`);
555
+ deadOnes.push(w);
441
556
  }
442
557
  return !dead;
443
558
  });
444
559
  if (s.writebacks.length !== before) {
445
560
  await saveTeamAutoStore(s);
446
561
  }
562
+ // Live-verified gap (mw5aun1l, 2026-11-07): this drop path fires for
563
+ // failed-without-result tasks BEFORE the pending loop below, so the
564
+ // terminal worktree cleanup there never ran for them - the single
565
+ // largest leak source. Safety-clean here too (same contract). The
566
+ // filter callback cannot await, hence the post-filter pass.
567
+ for (const w of deadOnes) {
568
+ const t = state0.tasks[w.taskId];
569
+ if (t && t.writeMode === "write" && t.projectDir?.includes("__task-")) {
570
+ const r = await sync.safeRemoveTaskWorktree(w.repoId, w.taskId, squashDeliveryOracle);
571
+ if (r.removed) {
572
+ // #173 follow-up 4: positive removal line - without it a successful
573
+ // terminal cleanup is invisible in logs (only kept/failed logged).
574
+ logger.warn(`TeamAuto: terminal task ${w.taskId} worktree removed (${r.reason})`);
575
+ }
576
+ else if (!r.reason.includes("already gone")) {
577
+ logger.warn(`TeamAuto: terminal task ${w.taskId} worktree kept: ${r.reason}`);
578
+ }
579
+ }
580
+ }
447
581
  }
448
582
  // Self-heal: an entry whose task later COMPLETED with a result (e.g. the
449
583
  // completion gate rejected an early submission, then a retry succeeded)
450
584
  // must be retried - a sticky error here would silently drop delivery.
585
+ // Issue #24: the retry now respects the per-entry backoff (nextAttemptAt)
586
+ // so a failing write-back no longer hammers GitHub on every 20s pass;
587
+ // legacy entries without a nextAttemptAt (pre-#24 stores) retry once
588
+ // immediately and then enter the normal backoff ladder. Terminally
589
+ // failed entries (failedAt) are never retried again.
451
590
  for (const w of s.writebacks) {
452
- if (w.error && !w.doneAt && state0) {
591
+ if (w.error && !w.doneAt && !w.failedAt && state0) {
453
592
  const t = state0.tasks[w.taskId];
454
- if (t && t.status === "completed" && t.result) {
593
+ if (t && t.status === "completed" && t.result && (w.nextAttemptAt ?? 0) <= Date.now()) {
455
594
  w.error = null;
456
595
  }
457
596
  }
458
597
  }
459
- const pending = s.writebacks.filter((w) => !w.doneAt && !w.error);
598
+ const pending = s.writebacks.filter((w) => !w.doneAt && !w.error && !w.failedAt);
460
599
  if (!pending.length) {
461
600
  return;
462
601
  }
@@ -473,7 +612,27 @@ export function createTeamAutoScheduler(deps) {
473
612
  const [owner, name] = entry.repoId.split("/");
474
613
  try {
475
614
  if (task.status === "failed" || !task.result) {
476
- entry.error = task.status === "failed" ? (task.error ?? "task failed") : "task completed without a textual result";
615
+ // Undeliverable in every future pass: a failed task never gains a
616
+ // result, and "completed without result" cannot recover either.
617
+ // Mark terminal (issue #24) so the entry is counted, surfaced via
618
+ // activity/stats, and never pointlessly retried. Failed-without-
619
+ // result entries are additionally dropped by the dead-letter pass
620
+ // on the next reconcile.
621
+ markWritebackFailure(s, entry, task.status === "failed" ? (task.error ?? "task failed") : "task completed without a textual result", { terminal: true });
622
+ // Terminal write task: its dispatch-time worktree has no delivery
623
+ // path left - remove it when the worker never produced deliverable
624
+ // commits (safety-checked, undelivered work is retained + logged).
625
+ if (task.writeMode === "write" && task.projectDir?.includes("__task-")) {
626
+ const r = await sync.safeRemoveTaskWorktree(entry.repoId, task.id, squashDeliveryOracle);
627
+ if (r.removed) {
628
+ // #173 follow-up 4: positive removal line - symmetric with the
629
+ // boot-GC path which logs both directions.
630
+ logger.warn(`TeamAuto: terminal task ${task.id} worktree removed (${r.reason})`);
631
+ }
632
+ else if (!r.reason.includes("already gone")) {
633
+ logger.warn(`TeamAuto: terminal task ${task.id} worktree kept: ${r.reason}`);
634
+ }
635
+ }
477
636
  }
478
637
  else {
479
638
  const role = (task.assignedRole ?? "qa");
@@ -503,8 +662,7 @@ export function createTeamAutoScheduler(deps) {
503
662
  await sync.removeTaskWorktree(repoId, task.id);
504
663
  }
505
664
  catch (prErr) {
506
- entry.error = `worktree PR delivery failed: ${prErr instanceof Error ? prErr.message : String(prErr)}`;
507
- logger.warn(`TeamAuto: ${entry.error} (${task.id})`);
665
+ markWritebackFailure(s, entry, `worktree PR delivery failed: ${prErr instanceof Error ? prErr.message : String(prErr)}`);
508
666
  }
509
667
  }
510
668
  if (entry.action === "issueComment" && entry.targetId) {
@@ -557,16 +715,20 @@ export function createTeamAutoScheduler(deps) {
557
715
  }
558
716
  }
559
717
  else {
560
- entry.error = `unsupported action ${entry.action}`;
718
+ markWritebackFailure(s, entry, `unsupported action ${entry.action}`, { terminal: true });
561
719
  }
562
720
  if (writebackDone) {
563
- recordActivity(s, { at: Date.now(), repoId: entry.repoId, kind: "writeback", text: `${entry.action} #${entry.targetId ?? "-"} ok (${task.id})` });
721
+ // Delivery succeeded: clear any transient failure state so a
722
+ // partially-failed entry (e.g. PR opened on an earlier retry)
723
+ // does not linger in the errored/failed stats (issue #24).
724
+ entry.error = null;
725
+ entry.failedAt = null;
726
+ recordActivity(s, { at: Date.now(), repoId: entry.repoId, kind: "writeback", text: `${entry.action} #${entry.targetId ?? "-"} ok (${task.id}${entry.attempts ? `, after ${entry.attempts} failed attempt(s)` : ""})` });
564
727
  }
565
728
  }
566
729
  }
567
730
  catch (err) {
568
- entry.error = err instanceof Error ? err.message : String(err);
569
- logger.warn(`TeamAuto: writeback failed (${entry.repoId} ${entry.action} #${entry.targetId ?? "-"}): ${entry.error}`);
731
+ markWritebackFailure(s, entry, err instanceof Error ? err.message : String(err));
570
732
  }
571
733
  void repo;
572
734
  }
@@ -653,6 +815,60 @@ export function createTeamAutoScheduler(deps) {
653
815
  void reconcileWritebacks();
654
816
  }, 20_000);
655
817
  writebackTimer.unref?.();
818
+ // Boot reconciliation: heal leftover task worktrees whose task is
819
+ // terminal (or gone entirely) - the pre-cleanup backlog never shrinks
820
+ // on its own. Safety-checked: undelivered work is kept and logged.
821
+ void (async () => {
822
+ try {
823
+ // #173 follow-up 3: with getTeamState() === null the isTerminal
824
+ // predicate below classifies EVERY task as terminal - boot GC must
825
+ // not run blind over an unloaded team state (fails toward skip).
826
+ if (!deps.getTeamState()) {
827
+ logger.warn("TeamAuto: worktree GC skipped (team state unavailable)");
828
+ return;
829
+ }
830
+ let removed = 0;
831
+ let retained = 0;
832
+ let stale = 0;
833
+ const retainedDetails = [];
834
+ for (const repo of s.repos) {
835
+ if (!repo.enabled)
836
+ continue;
837
+ const isTerminal = (taskId) => {
838
+ const t = deps.getTeamState()?.tasks[taskId];
839
+ if (t && t.status !== "completed" && t.status !== "failed")
840
+ return false;
841
+ // Review F1: a terminal task with a pending write-back (push
842
+ // ok / PR failed, 20s-retry window) still needs its worktree -
843
+ // the retry delivers the PR from the surviving branch. Do not
844
+ // GC until the write-back settles (doneAt or dropped). Issue
845
+ // #24: terminally failed write-backs (failedAt) count as settled
846
+ // too - safeRemoveTaskWorktree still retains unpushed work.
847
+ return !s.writebacks.some((w) => w.taskId === taskId && !w.doneAt && !w.failedAt);
848
+ };
849
+ const r = await sync.gcTaskWorktrees(repo.id, isTerminal, squashDeliveryOracle);
850
+ removed += r.removed.length;
851
+ retained += r.retained.length;
852
+ stale += r.stale;
853
+ retainedDetails.push(...r.retained.map((x) => `${x.taskId}: ${x.reason}`));
854
+ }
855
+ if (removed || retained || stale) {
856
+ // #173 follow-up 4: per-task retain reasons recorded as activity
857
+ // (PR #167 promised "outcome logged + recorded as activity"); the
858
+ // stale count surfaces dir-gone-but-branch-kept leaks too.
859
+ const detail = retainedDetails.length
860
+ ? `; ${retainedDetails.slice(0, 10).join("; ")}${retainedDetails.length > 10 ? `; +${retainedDetails.length - 10} more` : ""}`
861
+ : "";
862
+ const stalePart = stale ? `, stale ${stale}` : "";
863
+ recordActivity(s, { at: Date.now(), repoId: "*", kind: "task", text: `worktree GC: removed ${removed}, retained ${retained} (undelivered${detail})${stalePart}` });
864
+ await saveTeamAutoStore(s);
865
+ logger.warn(`TeamAuto: worktree GC removed ${removed}, retained ${retained}${stalePart}`);
866
+ }
867
+ }
868
+ catch (err) {
869
+ logger.warn(`TeamAuto: worktree GC failed: ${err instanceof Error ? err.message : String(err)}`);
870
+ }
871
+ })();
656
872
  }
657
873
  async function stop() {
658
874
  running = false;
@@ -667,7 +883,10 @@ export function createTeamAutoScheduler(deps) {
667
883
  }
668
884
  async function getStatus() {
669
885
  const s = await ensureStore();
670
- return { repos: s.repos, budget: s.budget, activity: s.activity ?? [] };
886
+ // Issue #24: failed/stuck write-back deliveries are part of the status
887
+ // payload (repos endpoint + teamclaw_teamauto_status tool) instead of
888
+ // being invisible outside warn logs.
889
+ return { repos: s.repos, budget: s.budget, activity: s.activity ?? [], writebacks: summarizeWritebacks(s) };
671
890
  }
672
891
  async function getActivity() {
673
892
  const s = await ensureStore();
package/dist/src/types.js CHANGED
@@ -1,5 +1,14 @@
1
1
  import { TEAMCLAW_PUBLISHED_RUNTIME_IMAGE } from "./install-defaults.js";
2
- import { DEFAULT_GITHUB_CLIENT_ID } from "./controller/github-auth.js";
2
+ import { DEFAULT_GITHUB_CLIENT_ID } from "./shared/github-auth.js";
3
+ // Safe value import: roles.js only pulls prompt-policy.js -> openclaw-workspace.js
4
+ // at runtime (its types.js import is type-only), so no module cycle is formed.
5
+ import { DEFAULT_ROLE } from "./roles.js";
6
+ import { validateRoleId, validateRoleIdList } from "./roles.js";
7
+ import { ROLE_IDS } from "./roles.js";
8
+ // Phase 1.6: profile-loader has no runtime edge back into this module (its
9
+ // types.js import is type-only), so the software-rd baseline id stays a
10
+ // single literal shared with the loader.
11
+ import { SOFTWARE_RD_PROFILE_ID } from "./profile-loader.js";
3
12
  function parseRoleModelOverrides(raw) {
4
13
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
5
14
  return undefined;
@@ -7,8 +16,9 @@ function parseRoleModelOverrides(raw) {
7
16
  const result = {};
8
17
  let hasAny = false;
9
18
  for (const [key, value] of Object.entries(raw)) {
10
- if (VALID_ROLES.includes(key) && typeof value === "string" && value.trim()) {
11
- result[key] = value.trim();
19
+ const roleKey = validateRoleId(key);
20
+ if (roleKey && typeof value === "string" && value.trim()) {
21
+ result[roleKey] = value.trim();
12
22
  hasAny = true;
13
23
  }
14
24
  }
@@ -21,15 +31,47 @@ export function parsePluginConfig(raw = {}) {
21
31
  const port = typeof raw.port === "number" && raw.port > 0 && raw.port < 65536
22
32
  ? raw.port
23
33
  : 9527;
24
- const role = typeof raw.role === "string" && VALID_ROLES.includes(raw.role)
25
- ? raw.role
26
- : "developer";
34
+ // Issue #27: explicit listen-host override for the worker HTTP server.
35
+ // Empty/absent keeps the default policy (loopback on hosts, all interfaces
36
+ // in containers) resolved in worker-service.ts.
37
+ const listenHost = typeof raw.listenHost === "string" && raw.listenHost.trim()
38
+ ? raw.listenHost.trim()
39
+ : undefined;
40
+ // Issue #27: 9527 is ALSO the controller's default port. A controller and a
41
+ // worker on the same host both defaulting to it collide with a confusing
42
+ // EADDRINUSE at startup. Only the same-host dual-process case is a problem -
43
+ // an external worker legitimately using 9527 must keep working - so this
44
+ // stays a parse-time warning, never an error.
45
+ if (mode === "worker" && port === 9527) {
46
+ console.warn("[teamclaw] config warning: worker mode uses port 9527, which is also the controller default. " +
47
+ "Running a controller and this worker on the same host will conflict (EADDRINUSE); set this worker's `port` config key to another value in that topology.");
48
+ }
49
+ // Issue #192 (Phase 3 prerequisite): lenient worker-side role parsing.
50
+ // The registry validateRoleId folded any unknown role string (e.g. a
51
+ // minimal-bank "credit-officer") to developer, so a worker provisioned
52
+ // under an industry profile registered with the WRONG role against its
53
+ // controller (mismatch or 400). A non-empty string role is now preserved
54
+ // as written - RoleId is an open branded string and this explicit cast is
55
+ // the documented way for non-seed ids to enter (see the RoleId ruling
56
+ // above) - and legitimacy is finally adjudicated by the controller's
57
+ // validateActiveRoleId at registration, where the ACTIVE profile is the
58
+ // single source of truth. DEFAULT_ROLE still applies only when the role
59
+ // is missing, not a string, or blank.
60
+ const role = typeof raw.role === "string" && raw.role.trim()
61
+ ? raw.role.trim()
62
+ : DEFAULT_ROLE;
27
63
  const controllerUrl = typeof raw.controllerUrl === "string"
28
64
  ? raw.controllerUrl.trim()
29
65
  : "";
30
66
  const teamName = typeof raw.teamName === "string" && raw.teamName.trim()
31
67
  ? raw.teamName.trim()
32
68
  : "TeamClaw";
69
+ // Phase 1.6: first-initialization bootstrap value. Existence of the id is
70
+ // checked by the controller startup chain (unknown ids fall back to the
71
+ // software-rd baseline with a warning); here we only normalize the shape.
72
+ const teamProfile = typeof raw.teamProfile === "string" && raw.teamProfile.trim()
73
+ ? raw.teamProfile.trim()
74
+ : SOFTWARE_RD_PROFILE_ID;
33
75
  const heartbeatIntervalMs = typeof raw.heartbeatIntervalMs === "number" && raw.heartbeatIntervalMs >= 1000
34
76
  ? raw.heartbeatIntervalMs
35
77
  : 10000;
@@ -37,6 +79,10 @@ export function parsePluginConfig(raw = {}) {
37
79
  const taskTimeoutMs = typeof raw.taskTimeoutMs === "number" && raw.taskTimeoutMs >= 1000
38
80
  ? raw.taskTimeoutMs
39
81
  : 600_000;
82
+ // Phase 2.1: graceful-drain budget for a team profile switch (design 2.3).
83
+ const teamSwitchDrainTimeoutMs = typeof raw.teamSwitchDrainTimeoutMs === "number" && raw.teamSwitchDrainTimeoutMs >= 1000
84
+ ? raw.teamSwitchDrainTimeoutMs
85
+ : 30_000;
40
86
  const gitEnabled = typeof raw.gitEnabled === "boolean" ? raw.gitEnabled : true;
41
87
  const gitRemoteUrl = typeof raw.gitRemoteUrl === "string"
42
88
  ? raw.gitRemoteUrl.trim()
@@ -59,6 +105,18 @@ export function parsePluginConfig(raw = {}) {
59
105
  const agentIsolationMode = typeof raw.agentIsolationMode === "string" && (raw.agentIsolationMode === "independent" || raw.agentIsolationMode === "main")
60
106
  ? raw.agentIsolationMode
61
107
  : "independent";
108
+ // Issue #23: security.autoPair defaults to true (L1 zero-input LAN
109
+ // pairing); only an explicit boolean false disables pair-auto.
110
+ const rawSecurity = raw.security;
111
+ const rawAutoPair = rawSecurity && typeof rawSecurity === "object" && !Array.isArray(rawSecurity)
112
+ ? rawSecurity.autoPair
113
+ : undefined;
114
+ const security = {
115
+ autoPair: typeof rawAutoPair === "boolean" ? rawAutoPair : true,
116
+ };
117
+ // Issue #23 (client wave): the paired device token, if this instance
118
+ // paired with a protected controller. Empty/absent keeps L0 behavior.
119
+ const securityToken = typeof raw.securityToken === "string" ? raw.securityToken.trim() : "";
62
120
  const rawWorkerProvisioningType = parseProvisioningType(raw.workerProvisioningType);
63
121
  const workerProvisioningDisabled = raw.workerProvisioningDisabled === true;
64
122
  // Legacy local installs often persisted workerProvisioningType="none" without
@@ -147,13 +205,16 @@ export function parsePluginConfig(raw = {}) {
147
205
  return {
148
206
  mode,
149
207
  port,
208
+ listenHost,
150
209
  role,
151
210
  controllerUrl,
152
211
  teamName,
212
+ teamProfile,
153
213
  heartbeatIntervalMs,
154
214
  processModel,
155
215
  roleModelOverrides: parseRoleModelOverrides(raw.roleModelOverrides),
156
216
  taskTimeoutMs,
217
+ teamSwitchDrainTimeoutMs,
157
218
  gitEnabled,
158
219
  gitRemoteUrl,
159
220
  gitDefaultBranch,
@@ -162,6 +223,8 @@ export function parsePluginConfig(raw = {}) {
162
223
  githubClientId,
163
224
  githubClientSecret,
164
225
  agentIsolationMode,
226
+ security,
227
+ securityToken,
165
228
  workerProvisioningType,
166
229
  workerProvisioningDisabled,
167
230
  workerProvisioningControllerUrl,
@@ -188,11 +251,9 @@ export function parsePluginConfig(raw = {}) {
188
251
  };
189
252
  }
190
253
  function parseRoleList(raw) {
191
- return Array.isArray(raw)
192
- ? [...new Set(raw
193
- .filter((entry) => typeof entry === "string" && VALID_ROLES.includes(entry))
194
- .map((entry) => entry))]
195
- : [];
254
+ // Phase 0.3: delegates to the shared validateRoleIdList guard in roles.ts
255
+ // (same filter + first-occurrence dedup semantics as before).
256
+ return validateRoleIdList(raw);
196
257
  }
197
258
  function parseProvisioningType(raw) {
198
259
  return typeof raw === "string" && VALID_PROVISIONING_TYPES.includes(raw)
@@ -236,8 +297,8 @@ const VALID_PROVISIONING_TYPES = [
236
297
  "docker",
237
298
  "kubernetes",
238
299
  ];
239
- const VALID_ROLES = [
240
- "pm", "architect", "developer", "qa",
241
- "release-engineer", "infra-engineer", "devops", "security-engineer",
242
- "designer", "marketing", "data-engineer",
243
- ];
300
+ // Not referenced at runtime anymore: role validation goes through
301
+ // validateRoleId/validateRoleIdList in roles.ts (Phase 0.3). Phase 1.2 folds
302
+ // the former hand-written copy into the registry: the value now derives from
303
+ // roles.ts ROLE_IDS so it can never drift from the single source of truth.
304
+ const VALID_ROLES = ROLE_IDS;