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