@teamclaws/teamclaw 2026.8.0 → 2026.11.0

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 (149) hide show
  1. package/cli.mjs +46 -15
  2. package/dist/api.js +1 -0
  3. package/dist/index.js +325 -0
  4. package/dist/src/config.js +412 -0
  5. package/dist/src/controller/clarification-routes.js +315 -0
  6. package/dist/src/controller/controller-capacity.js +14 -0
  7. package/dist/src/controller/controller-intake.js +895 -0
  8. package/dist/src/controller/controller-planning.js +813 -0
  9. package/dist/src/controller/controller-runs.js +175 -0
  10. package/dist/src/controller/controller-service.js +624 -0
  11. package/dist/src/controller/controller-tools.js +587 -0
  12. package/dist/src/controller/delivery-report.js +458 -0
  13. package/dist/src/controller/github-auth.js +564 -0
  14. package/dist/src/controller/http-server.js +284 -0
  15. package/dist/src/controller/kickoff-orchestrator.js +246 -0
  16. package/dist/src/controller/managed-gateway-process.js +286 -0
  17. package/dist/src/controller/message-delivery.js +28 -0
  18. package/dist/src/controller/message-router.js +38 -0
  19. package/dist/src/controller/message-routes.js +114 -0
  20. package/dist/src/controller/orchestration-manifest.js +151 -0
  21. package/dist/src/controller/preview-manager.js +586 -0
  22. package/dist/src/controller/preview-proxy.js +98 -0
  23. package/dist/src/controller/profile-switch.js +289 -0
  24. package/dist/src/controller/project-registry.js +294 -0
  25. package/dist/src/controller/prompt-injector.js +197 -0
  26. package/dist/src/controller/repo-routes.js +63 -0
  27. package/dist/src/controller/role-inference.js +246 -0
  28. package/dist/src/controller/route-table.js +1353 -0
  29. package/dist/src/controller/task-assignment.js +508 -0
  30. package/dist/src/controller/task-cleanup.js +258 -0
  31. package/dist/src/controller/task-execution.js +240 -0
  32. package/dist/src/controller/task-results.js +461 -0
  33. package/dist/src/controller/task-router.js +137 -0
  34. package/dist/src/controller/task-routes.js +703 -0
  35. package/dist/src/controller/teamauto-routes.js +124 -0
  36. package/dist/src/controller/tunnel-manager.js +548 -0
  37. package/dist/src/controller/ui-assets.js +68 -0
  38. package/dist/src/controller/websocket.js +42 -0
  39. package/dist/src/controller/worker-provisioning.js +1674 -0
  40. package/dist/src/controller/worker-routes.js +188 -0
  41. package/dist/src/discovery.js +86 -0
  42. package/dist/src/git-collaboration.js +694 -0
  43. package/dist/src/identity.js +132 -0
  44. package/dist/src/install-defaults.js +1 -0
  45. package/dist/src/interaction-contracts.js +531 -0
  46. package/dist/src/networking.js +91 -0
  47. package/dist/src/openclaw-workspace.js +925 -0
  48. package/dist/src/profile-loader.js +486 -0
  49. package/dist/src/profiles/banking.json +178 -0
  50. package/dist/src/profiles/crossborder-ecom.json +253 -0
  51. package/dist/src/profiles/insurance.json +157 -0
  52. package/dist/src/profiles/knowledge/hs-structure.md +97 -0
  53. package/dist/src/profiles/knowledge/incoterms-2020.md +188 -0
  54. package/dist/src/profiles/knowledge/vat-principles.md +85 -0
  55. package/dist/src/profiles/schema.json +201 -0
  56. package/dist/src/profiles/securities.json +137 -0
  57. package/dist/src/profiles/software-rd.json +264 -0
  58. package/dist/src/profiles/trading-co.json +200 -0
  59. package/dist/src/prompt-policy.js +386 -0
  60. package/dist/src/protocol.js +58 -0
  61. package/dist/src/role-ids.js +29 -0
  62. package/dist/src/roles.js +390 -0
  63. package/dist/src/session-roles.js +14 -0
  64. package/dist/src/state.js +361 -0
  65. package/dist/src/task-executor.js +1023 -0
  66. package/dist/src/teamauto/github-client.js +210 -0
  67. package/dist/src/teamauto/norms.js +85 -0
  68. package/dist/src/teamauto/repo-sync.js +423 -0
  69. package/dist/src/teamauto/scanner.js +207 -0
  70. package/dist/src/teamauto/schedule.js +123 -0
  71. package/dist/src/teamauto/scheduler.js +907 -0
  72. package/dist/src/teamauto/store.js +133 -0
  73. package/dist/src/types.js +290 -0
  74. package/dist/src/ui/app.js +4860 -0
  75. package/dist/src/ui/assets/teamclaw-app-icon.png +0 -0
  76. package/dist/src/ui/github-login.html +296 -0
  77. package/dist/src/ui/index.html +447 -0
  78. package/dist/src/ui/style.css +2805 -0
  79. package/dist/src/worker/http-handler.js +146 -0
  80. package/dist/src/worker/message-queue.js +24 -0
  81. package/dist/src/worker/prompt-injector.js +78 -0
  82. package/dist/src/worker/skill-installer.js +255 -0
  83. package/dist/src/worker/tools.js +541 -0
  84. package/dist/src/worker/worker-service.js +307 -0
  85. package/dist/src/workspace-browser.js +269 -0
  86. package/openclaw.plugin.json +28 -1
  87. package/package.json +3 -2
  88. package/src/config.ts +33 -2
  89. package/src/controller/clarification-routes.ts +404 -0
  90. package/src/controller/controller-intake.ts +1113 -0
  91. package/src/controller/controller-planning.ts +1029 -0
  92. package/src/controller/controller-runs.ts +239 -0
  93. package/src/controller/controller-service.ts +295 -41
  94. package/src/controller/controller-tools.ts +11 -7
  95. package/src/controller/http-server.ts +294 -6971
  96. package/src/controller/kickoff-orchestrator.ts +70 -7
  97. package/src/controller/message-delivery.ts +49 -0
  98. package/src/controller/message-routes.ts +137 -0
  99. package/src/controller/orchestration-manifest.ts +6 -29
  100. package/src/controller/preview-proxy.ts +127 -0
  101. package/src/controller/profile-switch.ts +366 -0
  102. package/src/controller/project-registry.ts +361 -0
  103. package/src/controller/prompt-injector.ts +23 -8
  104. package/src/controller/repo-routes.ts +91 -0
  105. package/src/controller/role-inference.ts +260 -22
  106. package/src/controller/route-table.ts +1616 -0
  107. package/src/controller/task-assignment.ts +618 -0
  108. package/src/controller/task-cleanup.ts +344 -0
  109. package/src/controller/task-execution.ts +356 -0
  110. package/src/controller/task-results.ts +544 -0
  111. package/src/controller/task-router.ts +98 -6
  112. package/src/controller/task-routes.ts +812 -0
  113. package/src/controller/teamauto-routes.ts +121 -0
  114. package/src/controller/ui-assets.ts +70 -0
  115. package/src/controller/websocket.ts +13 -1
  116. package/src/controller/worker-provisioning.ts +32 -4
  117. package/src/controller/worker-routes.ts +241 -0
  118. package/src/identity.ts +3 -2
  119. package/src/interaction-contracts.ts +7 -7
  120. package/src/openclaw-workspace.ts +44 -18
  121. package/src/profile-loader.ts +650 -0
  122. package/src/profiles/banking.json +178 -0
  123. package/src/profiles/crossborder-ecom.json +253 -0
  124. package/src/profiles/insurance.json +157 -0
  125. package/src/profiles/knowledge/hs-structure.md +97 -0
  126. package/src/profiles/knowledge/incoterms-2020.md +188 -0
  127. package/src/profiles/knowledge/vat-principles.md +85 -0
  128. package/src/profiles/schema.json +201 -0
  129. package/src/profiles/securities.json +137 -0
  130. package/src/profiles/software-rd.json +264 -0
  131. package/src/profiles/trading-co.json +200 -0
  132. package/src/prompt-policy.ts +27 -13
  133. package/src/role-ids.ts +31 -0
  134. package/src/roles.ts +60 -14
  135. package/src/session-roles.ts +14 -0
  136. package/src/state.ts +236 -9
  137. package/src/task-executor.ts +7 -18
  138. package/src/teamauto/github-client.ts +21 -0
  139. package/src/teamauto/repo-sync.ts +246 -6
  140. package/src/teamauto/scanner.ts +47 -13
  141. package/src/teamauto/scheduler.ts +259 -16
  142. package/src/teamauto/store.ts +12 -0
  143. package/src/types.ts +133 -16
  144. package/src/ui/app.js +592 -24
  145. package/src/ui/index.html +44 -11
  146. package/src/ui/style.css +194 -0
  147. package/src/worker/prompt-injector.ts +48 -8
  148. package/src/worker/skill-installer.ts +3 -1
  149. package/src/worker/worker-service.ts +83 -3
@@ -0,0 +1,618 @@
1
+ // PR-C of issue #204 (http-server monolith split): the task assignment
2
+ // pipeline (assignment context builders, worker dispatch, revert, and the
3
+ // issue-#191 gated auto-assign loop) extracted verbatim from
4
+ // controller/http-server.ts. Zero behavior change - callers pass the same
5
+ // deps object as before. This module must NEVER import http-server (the
6
+ // reverse edge exists: http-server -> task-assignment); autoAssignPendingTasks
7
+ // stays exported because controller-service.ts triggers it after startup
8
+ // reconciliation.
9
+ import fs from "node:fs";
10
+ import path from "node:path";
11
+ import type { PluginLogger } from "../../api.js";
12
+ import type {
13
+ PluginConfig,
14
+ RepoSyncInfo,
15
+ RoleId,
16
+ TaskAssignmentPayload,
17
+ TaskExecutionEvent,
18
+ TaskInfo,
19
+ TeamState,
20
+ WorkerInfo,
21
+ } from "../types.js";
22
+ import { getActiveRoles, resolveActiveRoleSkills } from "../profile-loader.js";
23
+ import { buildRepoSyncInfo } from "../git-collaboration.js";
24
+ import {
25
+ buildTeamClawProjectWorkspacePath,
26
+ resolveTeamClawProjectsDir,
27
+ resolveTeamClawWorkspaceDir,
28
+ } from "../openclaw-workspace.js";
29
+ import { refreshControllerRepoState } from "./repo-routes.js";
30
+ import {
31
+ appendTaskExecutionEvent,
32
+ broadcastTaskExecutionEvent,
33
+ buildTaskExecutionIdentity,
34
+ normalizeControllerIntakeSessionKey,
35
+ recordTaskExecutionEvent,
36
+ resetTaskForFreshAttempt,
37
+ serializeTask,
38
+ } from "./task-execution.js";
39
+ import type { TaskRouter } from "./task-router.js";
40
+ import type { ControllerTaskDomainDeps } from "./task-execution.js";
41
+
42
+ const MAX_RECENT_TASK_CONTEXT = 3;
43
+ const MAX_TASK_CONTEXT_SUMMARY_CHARS = 500;
44
+
45
+ export function summarizeTaskForAssignment(task: TaskInfo): string {
46
+ const lastExecutionMessage = task.execution?.events[task.execution.events.length - 1]?.message;
47
+ const contractSummary = task.resultContract
48
+ ? [
49
+ task.resultContract.summary,
50
+ ...task.resultContract.deliverables.slice(0, 3).map((deliverable) => `${deliverable.kind}: ${deliverable.value}`),
51
+ ].join(" | ")
52
+ : "";
53
+ const raw = contractSummary || task.result || task.progress || lastExecutionMessage || task.description || "";
54
+ const normalized = raw.replace(/\s+/g, " ").trim();
55
+ if (!normalized) {
56
+ return "No upstream summary available.";
57
+ }
58
+ if (normalized.length <= MAX_TASK_CONTEXT_SUMMARY_CHARS) {
59
+ return normalized;
60
+ }
61
+ return `${normalized.slice(0, MAX_TASK_CONTEXT_SUMMARY_CHARS).trimEnd()}…`;
62
+ }
63
+
64
+ export function buildRecentCompletedTaskContext(task: TaskInfo, state: TeamState | null): string {
65
+ if (!state) {
66
+ return "";
67
+ }
68
+
69
+ // Only include tasks from the same session/project to avoid cross-project contamination.
70
+ // Tasks sharing the same controllerSessionKey belong to the same user requirement.
71
+ const sameSession = task.controllerSessionKey
72
+ ? (candidate: TaskInfo) => candidate.controllerSessionKey === task.controllerSessionKey
73
+ : () => true; // If no session key, fall back to all completed tasks (legacy behavior)
74
+
75
+ const recentCompletedTasks = Object.values(state.tasks)
76
+ .filter((candidate) => candidate.id !== task.id && candidate.status === "completed")
77
+ .filter(sameSession)
78
+ .filter((candidate) => (candidate.completedAt ?? candidate.updatedAt) <= task.createdAt)
79
+ .sort((a, b) => (b.completedAt ?? b.updatedAt) - (a.completedAt ?? a.updatedAt))
80
+ .slice(0, MAX_RECENT_TASK_CONTEXT)
81
+ .reverse();
82
+
83
+ if (recentCompletedTasks.length === 0) {
84
+ return "";
85
+ }
86
+
87
+ return [
88
+ "## Recent Completed Team Deliverables",
89
+ "Use these upstream outputs before requesting clarification.",
90
+ "If a summary references a filename or task ID, search the shared workspace for it first.",
91
+ "Do not try to inspect another worker's OpenClaw session or session key directly; those sessions are isolated per worker.",
92
+ ...recentCompletedTasks.map((candidate) => {
93
+ const roleLabel = candidate.assignedRole
94
+ ? (getActiveRoles().find((role) => role.id === candidate.assignedRole)?.label ?? candidate.assignedRole)
95
+ : "Unassigned";
96
+ return `- [${candidate.id}] ${candidate.title} (${roleLabel}): ${summarizeTaskForAssignment(candidate)}`;
97
+ }),
98
+ ].join("\n");
99
+ }
100
+
101
+ export function buildRecommendedSkillsContext(task: TaskInfo): string {
102
+ const recommendedSkills = resolveActiveRoleSkills(task.assignedRole, task.recommendedSkills ?? []);
103
+ if (recommendedSkills.length === 0) {
104
+ return "";
105
+ }
106
+
107
+ return [
108
+ "## Recommended Skills",
109
+ "- Prefer these skill slugs for this task when relevant:",
110
+ ...recommendedSkills.map((skill) => ` - ${skill}`),
111
+ "- Before starting, search/install missing recommended skills in the current workspace when the runtime supports it.",
112
+ "- Prefer exact ClawHub/OpenClaw skill slugs over vague descriptions whenever possible.",
113
+ ].join("\n");
114
+ }
115
+
116
+ export function buildTaskContextSnapshot(task: TaskInfo, state: TeamState | null): TaskAssignmentPayload["teamContext"] | undefined {
117
+ if (!state || !task.controllerSessionKey) {
118
+ return undefined;
119
+ }
120
+ const normalizedSessionKey = normalizeControllerIntakeSessionKey(task.controllerSessionKey);
121
+ const summarize = (candidate: TaskInfo) => ({
122
+ id: candidate.id,
123
+ title: candidate.title,
124
+ assignedRole: candidate.assignedRole,
125
+ status: candidate.status,
126
+ summary: summarizeTaskForAssignment(candidate),
127
+ });
128
+ const sameSessionTasks = Object.values(state.tasks)
129
+ .filter((candidate) => candidate.id !== task.id)
130
+ .filter((candidate) => normalizeControllerIntakeSessionKey(candidate.controllerSessionKey) === normalizedSessionKey);
131
+ const latestRun = Object.values(state.controllerRuns)
132
+ .filter((run) => normalizeControllerIntakeSessionKey(run.sessionKey) === normalizedSessionKey)
133
+ .sort((a, b) => b.updatedAt - a.updatedAt)[0];
134
+ return {
135
+ requirementSummary: latestRun?.manifest?.requirementSummary || latestRun?.request,
136
+ projectName: latestRun?.manifest?.projectName,
137
+ requiredRoles: latestRun?.manifest?.requiredRoles,
138
+ activeTasks: sameSessionTasks.filter((candidate) => candidate.status === "assigned" || candidate.status === "in_progress").slice(0, 8).map(summarize),
139
+ blockedTasks: sameSessionTasks.filter((candidate) => candidate.status === "blocked").slice(0, 6).map(summarize),
140
+ recentCompletedTasks: sameSessionTasks
141
+ .filter((candidate) => candidate.status === "completed")
142
+ .sort((a, b) => (b.completedAt ?? b.updatedAt) - (a.completedAt ?? a.updatedAt))
143
+ .slice(0, 8)
144
+ .map(summarize),
145
+ pendingClarifications: Object.values(state.clarifications)
146
+ .filter((clarification) => clarification.status === "pending")
147
+ .filter((clarification) => normalizeControllerIntakeSessionKey(clarification.controllerSessionKey) === normalizedSessionKey)
148
+ .slice(0, 5)
149
+ .map((clarification) => ({
150
+ question: clarification.question,
151
+ blockingReason: clarification.blockingReason,
152
+ })),
153
+ answeredClarifications: Object.values(state.clarifications)
154
+ .filter((clarification) => clarification.status === "answered" && clarification.answer)
155
+ .filter((clarification) =>
156
+ clarification.taskId === task.id
157
+ || normalizeControllerIntakeSessionKey(clarification.controllerSessionKey) === normalizedSessionKey,
158
+ )
159
+ .sort((a, b) => (b.answeredAt ?? b.updatedAt ?? 0) - (a.answeredAt ?? a.updatedAt ?? 0))
160
+ .slice(0, 5)
161
+ .map((clarification) => ({
162
+ question: clarification.question,
163
+ answer: clarification.answer || "",
164
+ answeredBy: clarification.answeredBy,
165
+ blockingReason: clarification.blockingReason,
166
+ })),
167
+ handoffPlan: latestRun?.manifest?.handoffPlan,
168
+ notes: latestRun?.manifest?.notes,
169
+ kickoffSummary: latestRun?.manifest?.kickoffPlan?.summary,
170
+ };
171
+ }
172
+
173
+ export function buildTaskAssignmentDescription(task: TaskInfo, state: TeamState | null, repoInfo?: RepoSyncInfo): string {
174
+ const parts = [task.description];
175
+ const projectContext = buildProjectDirectoryContext(task.projectDir);
176
+ if (projectContext) {
177
+ parts.push("", projectContext);
178
+ }
179
+ const recommendedSkillsContext = buildRecommendedSkillsContext(task);
180
+ if (recommendedSkillsContext) {
181
+ parts.push("", recommendedSkillsContext);
182
+ }
183
+ const patternsContext = buildConsolidatedPatternsContext();
184
+ if (patternsContext) {
185
+ parts.push("", patternsContext);
186
+ }
187
+ const recentContext = buildRecentCompletedTaskContext(task, state);
188
+ if (recentContext) {
189
+ parts.push("", recentContext);
190
+ }
191
+ if (repoInfo?.enabled) {
192
+ parts.push("", buildRepoTaskContext(repoInfo));
193
+ }
194
+ return parts.join("\n");
195
+ }
196
+
197
+ export function buildProjectDirectoryContext(projectDir?: string): string | null {
198
+ if (!projectDir) {
199
+ return null;
200
+ }
201
+ const workspaceRelativePath = buildTeamClawProjectWorkspacePath(projectDir);
202
+ const absoluteProjectPath = path.join(resolveTeamClawProjectsDir(), projectDir).replace(/\\/gu, "/");
203
+ return [
204
+ "## Authoritative Project Paths",
205
+ `- Workspace-relative project path: \`${workspaceRelativePath}/\``,
206
+ `- Absolute project path: \`${absoluteProjectPath}/\``,
207
+ "- If the task description mentions any other workspace path, treat it as stale text from an older layout.",
208
+ "- Resolve project-local files (for example `ARCHITECTURE.md`, `README.md`, `package.json`, `data/...`) inside the authoritative project path above.",
209
+ ].join("\n");
210
+ }
211
+
212
+ export function buildRepoTaskContext(repoInfo: RepoSyncInfo): string {
213
+ const lines = [
214
+ "## TeamClaw Git Collaboration",
215
+ "- TeamClaw manages a git-backed project workspace for this task.",
216
+ `- Sync mode: ${repoInfo.mode}.`,
217
+ `- Default branch: ${repoInfo.defaultBranch}.`,
218
+ ];
219
+
220
+ if (repoInfo.headCommit) {
221
+ const headSummary = repoInfo.headSummary ? ` "${repoInfo.headSummary}"` : "";
222
+ lines.push(`- Current HEAD: ${repoInfo.headCommit}${headSummary}.`);
223
+ }
224
+
225
+ lines.push("- TeamClaw syncs the workspace checkout before task execution when needed.");
226
+ lines.push("- Treat the current workspace as the canonical repo checkout; do not delete `.git` or replace the repo with ad-hoc archives.");
227
+ return lines.join("\n");
228
+ }
229
+
230
+ export function scheduleProvisioningReconcile(deps: ControllerTaskDomainDeps, reason: string): void {
231
+ void deps.workerProvisioningManager?.requestReconcile(reason);
232
+ }
233
+
234
+ /** Collaboration contract helpers: at most ONE active write task per repo checkout. */
235
+ export function taskWriteRoot(task: TaskInfo): string | null {
236
+ if (task.writeMode === "read-only" || !task.projectDir) { return null; }
237
+ return task.projectDir.split("__task-")[0] ?? task.projectDir;
238
+ }
239
+
240
+ export function activeWriteRoots(state: TeamState): Set<string> {
241
+ const roots = new Set<string>();
242
+ for (const t of Object.values(state.tasks)) {
243
+ if (t.status !== "assigned" && t.status !== "in_progress") { continue; }
244
+ const root = taskWriteRoot(t);
245
+ if (root) { roots.add(root); }
246
+ }
247
+ return roots;
248
+ }
249
+
250
+ export function buildConsolidatedPatternsContext(): string {
251
+ try {
252
+ const workspaceDir = resolveTeamClawWorkspaceDir();
253
+ const patternsFile = path.join(workspaceDir, "memory", "patterns.md");
254
+ const content = fs.readFileSync(patternsFile, "utf8").trim();
255
+ // Only inject if there are actual patterns (more than just the header)
256
+ const lines = content.split("\n").filter((l: string) => l.startsWith("- "));
257
+ if (lines.length === 0) {
258
+ return "";
259
+ }
260
+ return [
261
+ "## Discovered Codebase Patterns",
262
+ "Previous workers discovered these reusable patterns. Apply them where relevant:",
263
+ ...lines,
264
+ ].join("\n");
265
+ } catch {
266
+ return "";
267
+ }
268
+ }
269
+
270
+ export function revertTaskAssignment(taskId: string, workerId: string, deps: ControllerTaskDomainDeps): TaskInfo | undefined {
271
+ const { updateTeamState, wsServer } = deps;
272
+ let revertEvent: TaskExecutionEvent | undefined;
273
+
274
+ const state = updateTeamState((s) => {
275
+ const task = s.tasks[taskId];
276
+ if (!task) {
277
+ return;
278
+ }
279
+
280
+ if (task.assignedWorkerId === workerId) {
281
+ task.status = "pending";
282
+ task.assignedWorkerId = undefined;
283
+ task.updatedAt = Date.now();
284
+ revertEvent = appendTaskExecutionEvent(task, {
285
+ type: "error",
286
+ phase: "assignment_reverted",
287
+ source: "controller",
288
+ message: `Assignment to ${workerId} was reverted; task returned to pending.`,
289
+ });
290
+ }
291
+
292
+ const worker = s.workers[workerId];
293
+ if (worker?.currentTaskId === taskId) {
294
+ if (worker.status !== "offline") {
295
+ worker.status = "idle";
296
+ }
297
+ worker.currentTaskId = undefined;
298
+ }
299
+
300
+ });
301
+
302
+ const updatedTask = state.tasks[taskId];
303
+ if (updatedTask) {
304
+ if (revertEvent) {
305
+ broadcastTaskExecutionEvent(taskId, updatedTask, revertEvent, deps);
306
+ }
307
+ wsServer.broadcastUpdate({ type: "task:updated", data: serializeTask(updatedTask) });
308
+ void autoAssignPendingTasks(deps).catch(() => {
309
+ // Best-effort retry path; assignment failure is already surfaced via task state.
310
+ });
311
+ scheduleProvisioningReconcile(deps, `assignment-reverted:${taskId}`);
312
+ }
313
+ return updatedTask;
314
+ }
315
+
316
+ export async function dispatchTaskToWorker(
317
+ taskId: string,
318
+ worker: WorkerInfo,
319
+ deps: ControllerTaskDomainDeps,
320
+ ): Promise<void> {
321
+ const { getTeamState, logger, updateTeamState } = deps;
322
+ const state = getTeamState();
323
+ const task = state?.tasks[taskId];
324
+ if (!task) {
325
+ throw new Error(`task ${taskId} not found`);
326
+ }
327
+
328
+ // Ensure project directory exists
329
+ if (task.projectDir) {
330
+ const projectPath = path.join(resolveTeamClawProjectsDir(), task.projectDir);
331
+ try { fs.mkdirSync(projectPath, { recursive: true }); } catch { /* best-effort */ }
332
+ }
333
+
334
+ // Collaboration contract: WRITE tasks execute in a task-scoped git worktree
335
+ // (branch teamclaw/task-<id>) so parallel roles never share a dirty checkout;
336
+ // delivery happens via push + PR in the write-back reconciler.
337
+ let assignmentProjectDir = task.projectDir;
338
+ if (task.writeMode === "write" && task.projectDir?.startsWith("teamauto/") && !task.projectDir.includes("__task-")) {
339
+ const scheduler = deps.getTeamAutoScheduler?.();
340
+ if (scheduler) {
341
+ const repoId = task.projectDir.slice("teamauto/".length).replace(/__/g, "/");
342
+ try {
343
+ assignmentProjectDir = await scheduler.ensureWriteWorktree(repoId, taskId);
344
+ updateTeamState((s) => {
345
+ const t = s.tasks[taskId];
346
+ if (t) { t.projectDir = assignmentProjectDir; }
347
+ });
348
+ logger.info(`Controller: write task ${taskId} -> worktree projects/${assignmentProjectDir}`);
349
+ } catch (err) {
350
+ logger.warn(`Controller: worktree setup failed for ${taskId}, falling back to shared checkout: ${String(err)}`);
351
+ }
352
+ }
353
+ }
354
+
355
+ const sharedWorkspace = deps.workerProvisioningManager?.isSharedWorkspaceWorker(worker.id)
356
+ || false;
357
+ const repoState = await refreshControllerRepoState(deps);
358
+ const repoInfo = buildRepoSyncInfo(repoState, sharedWorkspace);
359
+ const description = buildTaskAssignmentDescription(task, state ?? null, repoInfo);
360
+ const recommendedSkills = resolveActiveRoleSkills(task.assignedRole, task.recommendedSkills ?? []);
361
+ // Resume support: reuse the interrupted execution's session so the worker
362
+ // continues the same persisted OpenClaw conversation instead of starting over.
363
+ const executionIdentity = (task.checkpoint?.sessionKey)
364
+ ? { executionSessionKey: task.checkpoint.sessionKey, executionIdempotencyKey: buildTaskExecutionIdentity(task.id, worker.id).executionIdempotencyKey }
365
+ : buildTaskExecutionIdentity(task.id, worker.id);
366
+ const assignment: TaskAssignmentPayload = {
367
+ taskId: task.id,
368
+ title: task.title,
369
+ description,
370
+ priority: task.priority,
371
+ recommendedSkills,
372
+ projectDir: assignmentProjectDir,
373
+ executionSessionKey: executionIdentity.executionSessionKey,
374
+ executionIdempotencyKey: executionIdentity.executionIdempotencyKey,
375
+ checkpoint: task.checkpoint,
376
+ resumeAttempt: task.resumeAttempt,
377
+ repo: repoInfo,
378
+ teamContext: buildTaskContextSnapshot(task, state ?? null),
379
+ };
380
+
381
+ const res = await fetch(`${worker.url}/api/v1/tasks/assign`, {
382
+ method: "POST",
383
+ headers: { "Content-Type": "application/json" },
384
+ body: JSON.stringify(assignment),
385
+ });
386
+
387
+ if (!res.ok) {
388
+ throw new Error(`worker ${worker.id} responded with ${res.status}`);
389
+ }
390
+ }
391
+
392
+ export async function assignTaskToWorker(
393
+ taskId: string,
394
+ worker: WorkerInfo,
395
+ deps: ControllerTaskDomainDeps,
396
+ options?: {
397
+ assignedRole?: RoleId;
398
+ },
399
+ ): Promise<TaskInfo | undefined> {
400
+ const { logger, updateTeamState } = deps;
401
+ let assignmentApplied = false;
402
+
403
+ updateTeamState((s) => {
404
+ const task = s.tasks[taskId];
405
+ const targetWorker = s.workers[worker.id];
406
+ if (!task || !targetWorker) {
407
+ return;
408
+ }
409
+ if (targetWorker.status !== "idle") {
410
+ return;
411
+ }
412
+ const canAssignCurrentTask =
413
+ task.status === "pending" ||
414
+ (task.status === "assigned" && task.assignedWorkerId === worker.id);
415
+ if (!canAssignCurrentTask) {
416
+ return;
417
+ }
418
+
419
+ task.status = "assigned";
420
+ task.assignedWorkerId = worker.id;
421
+ if (options?.assignedRole) {
422
+ task.assignedRole = options.assignedRole;
423
+ }
424
+ resetTaskForFreshAttempt(task);
425
+ task.updatedAt = Date.now();
426
+
427
+ targetWorker.status = "busy";
428
+ targetWorker.currentTaskId = taskId;
429
+ assignmentApplied = true;
430
+ });
431
+
432
+ if (!assignmentApplied) {
433
+ return deps.getTeamState()?.tasks[taskId];
434
+ }
435
+
436
+ try {
437
+ await dispatchTaskToWorker(taskId, worker, deps);
438
+ } catch (err) {
439
+ logger.warn(`Controller: failed to dispatch task ${taskId} to ${worker.id}: ${String(err)}`);
440
+ recordTaskExecutionEvent(taskId, {
441
+ type: "error",
442
+ phase: "dispatch_failed",
443
+ source: "controller",
444
+ message: `Failed to dispatch task to ${worker.id}: ${String(err)}`,
445
+ workerId: worker.id,
446
+ role: options?.assignedRole ?? worker.role,
447
+ }, deps);
448
+ return revertTaskAssignment(taskId, worker.id, deps);
449
+ }
450
+
451
+ recordTaskExecutionEvent(taskId, {
452
+ type: "lifecycle",
453
+ phase: "assigned",
454
+ source: "controller",
455
+ message: `Assigned to ${worker.label || worker.id}.`,
456
+ workerId: worker.id,
457
+ role: options?.assignedRole ?? worker.role,
458
+ }, deps);
459
+
460
+ return deps.getTeamState()?.tasks[taskId];
461
+ }
462
+
463
+ // ── Issue #191: auto-assign re-entrancy gate ─────────────────────────────────
464
+ //
465
+ // revertTaskAssignment (dispatch failure path) fires a nested
466
+ // `void autoAssignPendingTasks(deps)`. Before the gate, each nested call ran
467
+ // concurrently with its OWN attemptedPairs set: it re-attempted the pair that
468
+ // had just failed, reverted again, and spawned another nested round - with
469
+ // unreachable workers the retry tree grew 2^n dispatch attempts (observed as
470
+ // a 4GB OOM). The gate keeps ONE round in flight per controller deps and
471
+ // defers nested triggers to a single follow-up round that SHARES the failed
472
+ // pairs, collapsing the storm to linear work. Keyed weakly on the deps object
473
+ // so separate controller instances (and separate test scenarios) never share
474
+ // gate state.
475
+ type AutoAssignGate = {
476
+ inFlight: boolean;
477
+ /** Follow-up round queued by a nested trigger; carries that trigger's preferredWorkerId hint. */
478
+ rerunQueued: { preferredWorkerId: string | undefined } | null;
479
+ attemptedPairs: Set<string>;
480
+ };
481
+
482
+ const autoAssignGates = new WeakMap<ControllerTaskDomainDeps, AutoAssignGate>();
483
+
484
+ export function getAutoAssignGate(deps: ControllerTaskDomainDeps): AutoAssignGate {
485
+ let gate = autoAssignGates.get(deps);
486
+ if (!gate) {
487
+ gate = { inFlight: false, rerunQueued: null, attemptedPairs: new Set() };
488
+ autoAssignGates.set(deps, gate);
489
+ }
490
+ return gate;
491
+ }
492
+
493
+ export async function autoAssignPendingTasks(
494
+ deps: ControllerTaskDomainDeps,
495
+ preferredWorkerId?: string,
496
+ ): Promise<TaskInfo[]> {
497
+ const gate = getAutoAssignGate(deps);
498
+ if (gate.inFlight) {
499
+ // Nested trigger (revert path, concurrent register/heartbeat, ...):
500
+ // never start a parallel round. Queue exactly one follow-up; it re-reads
501
+ // the live state, so nothing observable is lost - only the storm is.
502
+ // The follow-up carries the nested trigger's preferredWorkerId hint
503
+ // (worker register/heartbeat triggers pass theirs; it only biases which
504
+ // candidate is attempted first). A later id-less trigger (revert path)
505
+ // must not erase a hint that is already queued; a later trigger WITH an
506
+ // id wins as the most recent signal about where capacity appeared.
507
+ if (gate.rerunQueued) {
508
+ if (preferredWorkerId !== undefined) {
509
+ gate.rerunQueued.preferredWorkerId = preferredWorkerId;
510
+ }
511
+ } else {
512
+ gate.rerunQueued = { preferredWorkerId };
513
+ }
514
+ return [];
515
+ }
516
+ gate.inFlight = true;
517
+ try {
518
+ return await runAutoAssignRound(deps, preferredWorkerId, gate.attemptedPairs);
519
+ } finally {
520
+ gate.inFlight = false;
521
+ if (gate.rerunQueued) {
522
+ const rerun = gate.rerunQueued;
523
+ gate.rerunQueued = null;
524
+ void autoAssignPendingTasks(deps, rerun.preferredWorkerId).catch(() => {
525
+ // Best-effort follow-up round; assignment failures already surface
526
+ // via task state (same policy as the fire-and-forget call sites).
527
+ });
528
+ } else {
529
+ // The round settled with no deferred work: forget the attempted (and
530
+ // possibly failed) pairs so future rounds may try them again - e.g.
531
+ // after an unreachable worker recovers or a new task is submitted.
532
+ gate.attemptedPairs.clear();
533
+ }
534
+ }
535
+ }
536
+
537
+ export async function runAutoAssignRound(
538
+ deps: ControllerTaskDomainDeps,
539
+ preferredWorkerId: string | undefined,
540
+ attemptedPairs: Set<string>,
541
+ ): Promise<TaskInfo[]> {
542
+ const { getTeamState, taskRouter, wsServer, logger, config } = deps;
543
+ const assignedTasks: TaskInfo[] = [];
544
+ const maxConcurrent = config.maxConcurrentTasks;
545
+
546
+ // Phase 2.1 (design 2.3 concurrency matrix): while a profile switch
547
+ // transition is active, never dispatch new work - pending tasks belong to
548
+ // the outgoing team and are sealed into its archive.
549
+ if (getTeamState()?.transition) {
550
+ return assignedTasks;
551
+ }
552
+
553
+ while (true) {
554
+ const state = getTeamState();
555
+ if (!state) {
556
+ break;
557
+ }
558
+
559
+ // Throttle: count currently in-progress tasks and respect maxConcurrentTasks
560
+ const inProgressCount = Object.values(state.tasks).filter(
561
+ (t) => t.status === "in_progress",
562
+ ).length;
563
+ if (inProgressCount >= maxConcurrent) {
564
+ logger.debug?.(
565
+ `Controller: skipping auto-assign — ${inProgressCount} tasks in_progress (max ${maxConcurrent})`,
566
+ );
567
+ break;
568
+ }
569
+
570
+ // Collaboration contract: serialize write tasks per repo checkout - a
571
+ // second writer on the same root waits until the active one settles.
572
+ const busyWriteRoots = activeWriteRoots(state);
573
+ // Phase 2.5 wiring: the router is async because unconfident tasks may
574
+ // first escalate to the injected LLM role judge (cached per task).
575
+ const candidateAssignments = (await taskRouter
576
+ .autoAssignPendingTasks(state.tasks, state.workers))
577
+ .filter(({ task, worker }) => !attemptedPairs.has(`${task.id}:${worker.id}`))
578
+ .filter(({ task }) => {
579
+ const root = taskWriteRoot(task);
580
+ return !(root && busyWriteRoots.has(root));
581
+ });
582
+
583
+ const nextAssignment = (
584
+ (preferredWorkerId
585
+ ? candidateAssignments.find(({ worker }) => worker.id === preferredWorkerId)
586
+ : undefined)
587
+ ?? candidateAssignments[0]
588
+ );
589
+
590
+ if (!nextAssignment) {
591
+ scheduleProvisioningReconcile(deps, preferredWorkerId
592
+ ? `auto-assign-wait:${preferredWorkerId}`
593
+ : "auto-assign-wait");
594
+ break;
595
+ }
596
+
597
+ const pairKey = `${nextAssignment.task.id}:${nextAssignment.worker.id}`;
598
+ attemptedPairs.add(pairKey);
599
+
600
+ const updatedTask = await assignTaskToWorker(nextAssignment.task.id, nextAssignment.worker, deps, {
601
+ assignedRole: nextAssignment.task.assignedRole,
602
+ });
603
+
604
+ if (updatedTask?.status === "assigned" && updatedTask.assignedWorkerId === nextAssignment.worker.id) {
605
+ wsServer.broadcastUpdate({ type: "task:updated", data: serializeTask(updatedTask) });
606
+ logger.info(
607
+ `Controller: auto-assigned pending task ${updatedTask.id} to ${nextAssignment.worker.id}`,
608
+ );
609
+ assignedTasks.push(updatedTask);
610
+ }
611
+ }
612
+
613
+ scheduleProvisioningReconcile(deps, preferredWorkerId
614
+ ? `auto-assign:${preferredWorkerId}`
615
+ : "auto-assign");
616
+
617
+ return assignedTasks;
618
+ }