@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.
- package/cli.mjs +318 -17
- package/dist/index.js +54 -32
- package/dist/src/config.js +57 -2
- package/dist/src/controller/auth-routes.js +129 -0
- package/dist/src/controller/clarification-routes.js +315 -0
- package/dist/src/controller/controller-intake.js +895 -0
- package/dist/src/controller/controller-planning.js +814 -0
- package/dist/src/controller/controller-routes.js +195 -0
- package/dist/src/controller/controller-runs.js +175 -0
- package/dist/src/controller/controller-service.js +338 -50
- package/dist/src/controller/controller-tools.js +14 -7
- package/dist/src/controller/github-auth.js +2 -1
- package/dist/src/controller/http-server.js +290 -6003
- package/dist/src/controller/kickoff-orchestrator.js +33 -43
- package/dist/src/controller/message-delivery.js +31 -0
- package/dist/src/controller/message-routes.js +114 -0
- package/dist/src/controller/orchestration-manifest.js +11 -93
- package/dist/src/controller/preview-manager.js +51 -3
- package/dist/src/controller/preview-proxy.js +98 -0
- package/dist/src/controller/profile-switch.js +309 -0
- package/dist/src/controller/project-registry.js +294 -0
- package/dist/src/controller/prompt-injector.js +19 -9
- package/dist/src/controller/provisioning/backend-contract.js +9 -0
- package/dist/src/controller/provisioning/container-shared.js +64 -0
- package/dist/src/controller/provisioning/docker.js +214 -0
- package/dist/src/controller/provisioning/kubernetes.js +244 -0
- package/dist/src/controller/provisioning/plugin-root.js +41 -0
- package/dist/src/controller/provisioning/process-supervisor.js +190 -0
- package/dist/src/controller/provisioning-config.js +239 -0
- package/dist/src/controller/repo-routes.js +129 -0
- package/dist/src/controller/report-routes.js +56 -0
- package/dist/src/controller/role-inference.js +231 -20
- package/dist/src/controller/route-table.js +375 -0
- package/dist/src/controller/security.js +775 -0
- package/dist/src/controller/status-routes.js +287 -0
- package/dist/src/controller/task-assignment.js +511 -0
- package/dist/src/controller/task-cleanup.js +258 -0
- package/dist/src/controller/task-execution.js +271 -0
- package/dist/src/controller/task-results.js +471 -0
- package/dist/src/controller/task-router.js +74 -4
- 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 +41 -8
- package/dist/src/controller/tunnel-routes.js +225 -0
- package/dist/src/controller/ui-assets.js +68 -0
- package/dist/src/controller/websocket.js +6 -2
- package/dist/src/controller/webui-routes.js +49 -0
- package/dist/src/controller/worker-provisioning.js +69 -953
- package/dist/src/controller/worker-routes.js +188 -0
- package/dist/src/controller/workflow-routes.js +407 -0
- package/dist/src/controller/workspace-routes.js +200 -0
- package/dist/src/git-collaboration.js +4 -9
- package/dist/src/identity.js +15 -3
- package/dist/src/interaction-contracts.js +7 -7
- package/dist/src/openclaw-workspace.js +40 -18
- package/dist/src/profile-loader.js +604 -0
- package/dist/src/profiles/banking.json +202 -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 +281 -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 +42 -17
- package/dist/src/protocol.js +66 -3
- package/dist/src/role-ids.js +29 -0
- package/dist/src/roles.js +54 -13
- package/dist/src/session-roles.js +14 -0
- package/dist/src/shared/clarification-schema.js +65 -0
- package/dist/src/shared/github-auth.js +15 -0
- package/dist/src/shared/kickoff-prompt.js +37 -0
- package/dist/src/shared/utils.js +47 -0
- package/dist/src/state.js +275 -11
- package/dist/src/task-executor.js +7 -17
- package/dist/src/teamauto/github-client.js +18 -0
- package/dist/src/teamauto/repo-sync.js +228 -6
- package/dist/src/teamauto/scanner.js +40 -12
- package/dist/src/teamauto/scheduler.js +231 -12
- package/dist/src/types.js +77 -16
- package/dist/src/ui/app.js +1434 -82
- package/dist/src/ui/github-login.html +1 -0
- package/dist/src/ui/index.html +144 -45
- package/dist/src/ui/style.css +194 -0
- package/dist/src/worker/http-handler.js +59 -0
- package/dist/src/worker/prompt-injector.js +44 -8
- package/dist/src/worker/skill-installer.js +6 -10
- package/dist/src/worker/tools.js +20 -10
- package/dist/src/worker/worker-service.js +93 -7
- package/index.ts +61 -32
- package/openclaw.plugin.json +50 -2
- package/package.json +3 -2
- package/src/config.ts +57 -2
- package/src/controller/auth-routes.ts +157 -0
- package/src/controller/clarification-routes.ts +404 -0
- package/src/controller/controller-intake.ts +1113 -0
- package/src/controller/controller-planning.ts +1037 -0
- package/src/controller/controller-routes.ts +237 -0
- package/src/controller/controller-runs.ts +239 -0
- package/src/controller/controller-service.ts +422 -50
- package/src/controller/controller-tools.ts +16 -9
- package/src/controller/github-auth.ts +28 -63
- package/src/controller/http-server.ts +336 -6964
- package/src/controller/kickoff-orchestrator.ts +69 -45
- package/src/controller/message-delivery.ts +52 -0
- package/src/controller/message-routes.ts +137 -0
- package/src/controller/orchestration-manifest.ts +14 -100
- package/src/controller/preview-manager.ts +53 -3
- package/src/controller/preview-proxy.ts +127 -0
- package/src/controller/profile-switch.ts +396 -0
- package/src/controller/project-registry.ts +361 -0
- package/src/controller/prompt-injector.ts +23 -8
- package/src/controller/provisioning/backend-contract.ts +51 -0
- package/src/controller/provisioning/container-shared.ts +84 -0
- package/src/controller/provisioning/docker.ts +260 -0
- package/src/controller/provisioning/kubernetes.ts +263 -0
- package/src/controller/provisioning/plugin-root.ts +42 -0
- package/src/controller/provisioning/process-supervisor.ts +214 -0
- package/src/controller/provisioning-config.ts +289 -0
- package/src/controller/repo-routes.ts +163 -0
- package/src/controller/report-routes.ts +64 -0
- package/src/controller/role-inference.ts +260 -22
- package/src/controller/route-table.ts +597 -0
- package/src/controller/security.ts +899 -0
- package/src/controller/status-routes.ts +354 -0
- package/src/controller/task-assignment.ts +622 -0
- package/src/controller/task-cleanup.ts +344 -0
- package/src/controller/task-execution.ts +399 -0
- package/src/controller/task-results.ts +556 -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/tunnel-manager.ts +45 -8
- package/src/controller/tunnel-routes.ts +231 -0
- package/src/controller/ui-assets.ts +70 -0
- package/src/controller/websocket.ts +32 -4
- package/src/controller/webui-routes.ts +55 -0
- package/src/controller/worker-provisioning.ts +83 -1121
- package/src/controller/worker-routes.ts +241 -0
- package/src/controller/workflow-routes.ts +498 -0
- package/src/controller/workspace-routes.ts +222 -0
- package/src/git-collaboration.ts +4 -9
- package/src/identity.ts +16 -3
- package/src/interaction-contracts.ts +7 -7
- package/src/openclaw-workspace.ts +44 -18
- package/src/profile-loader.ts +816 -0
- package/src/profiles/banking.json +202 -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 +281 -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 +44 -17
- package/src/protocol.ts +72 -2
- package/src/role-ids.ts +31 -0
- package/src/roles.ts +60 -14
- package/src/session-roles.ts +14 -0
- package/src/shared/clarification-schema.ts +81 -0
- package/src/shared/github-auth.ts +92 -0
- package/src/shared/kickoff-prompt.ts +47 -0
- package/src/shared/utils.ts +51 -0
- package/src/state.ts +326 -10
- package/src/task-executor.ts +7 -18
- package/src/teamauto/github-client.ts +23 -1
- package/src/teamauto/repo-sync.ts +248 -7
- package/src/teamauto/scanner.ts +47 -13
- package/src/teamauto/scheduler.ts +261 -17
- package/src/teamauto/store.ts +12 -0
- package/src/types.ts +263 -17
- package/src/ui/app.js +1434 -82
- package/src/ui/github-login.html +1 -0
- package/src/ui/index.html +144 -45
- package/src/ui/style.css +194 -0
- package/src/worker/http-handler.ts +64 -1
- package/src/worker/prompt-injector.ts +48 -8
- package/src/worker/skill-installer.ts +6 -10
- package/src/worker/tools.ts +21 -10
- package/src/worker/worker-service.ts +101 -7
|
@@ -0,0 +1,812 @@
|
|
|
1
|
+
// PR-C of issue #204 (http-server monolith split): the task CRUD/lifecycle
|
|
2
|
+
// route handlers lifted verbatim from the inline dispatch blocks in
|
|
3
|
+
// controller/http-server.ts (task create/list/get/patch/delete, execution
|
|
4
|
+
// detail, manual assign, handoff, checkpoint, result contract, result,
|
|
5
|
+
// execution events, parallel help). Zero behavior change - the route shells
|
|
6
|
+
// in http-server keep the method+pathname matches and call these handlers
|
|
7
|
+
// with the same deps object as before. This module must NEVER import
|
|
8
|
+
// http-server (the reverse edge exists: http-server -> task-routes); the
|
|
9
|
+
// domain helpers arrive from the sibling PR-C modules below.
|
|
10
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
11
|
+
import type {
|
|
12
|
+
TaskExecutionEvent,
|
|
13
|
+
TaskExecutionEventInput,
|
|
14
|
+
TaskInfo,
|
|
15
|
+
TaskPriority,
|
|
16
|
+
TaskStatus,
|
|
17
|
+
WorkerInfo,
|
|
18
|
+
WorkerProgressContract,
|
|
19
|
+
} from "../types.js";
|
|
20
|
+
import { generateId, parseJsonBody, sendError, sendJson } from "../protocol.js";
|
|
21
|
+
import { normalizeRecommendedSkills, validateActiveRoleId } from "../profile-loader.js";
|
|
22
|
+
import { deriveProjectSlug, deriveStableProjectKey } from "../openclaw-workspace.js";
|
|
23
|
+
import {
|
|
24
|
+
backfillWorkerProgressContract,
|
|
25
|
+
enrichDeliverablesWithPreviewInference,
|
|
26
|
+
normalizeTaskHandoffContract,
|
|
27
|
+
normalizeWorkerProgressContract,
|
|
28
|
+
normalizeWorkerTaskResultContract,
|
|
29
|
+
} from "../interaction-contracts.js";
|
|
30
|
+
import { refreshControllerRepoState } from "./repo-routes.js";
|
|
31
|
+
import {
|
|
32
|
+
appendTaskExecutionEvent,
|
|
33
|
+
broadcastTaskExecutionEvent,
|
|
34
|
+
buildTaskExecutionSummary,
|
|
35
|
+
canAcceptWorkerUpdate,
|
|
36
|
+
cancelTaskExecution,
|
|
37
|
+
mapTaskStatusToExecutionStatus,
|
|
38
|
+
normalizeControllerIntakeSessionKey,
|
|
39
|
+
recordTaskExecutionEvent,
|
|
40
|
+
resetTaskForFreshAttempt,
|
|
41
|
+
serializeTask,
|
|
42
|
+
type ControllerTaskDomainDeps,
|
|
43
|
+
} from "./task-execution.js";
|
|
44
|
+
import {
|
|
45
|
+
assignTaskToWorker,
|
|
46
|
+
autoAssignPendingTasks,
|
|
47
|
+
scheduleProvisioningReconcile,
|
|
48
|
+
} from "./task-assignment.js";
|
|
49
|
+
import {
|
|
50
|
+
resolveProjectIdentityForSession,
|
|
51
|
+
syncProjectRegistryEntry,
|
|
52
|
+
} from "./project-registry.js";
|
|
53
|
+
import { buildEmptyTaskCleanupSummary, deleteTaskCascade } from "./task-cleanup.js";
|
|
54
|
+
import {
|
|
55
|
+
allowsNoChangeCompletion,
|
|
56
|
+
applyTaskResult,
|
|
57
|
+
buildEffectiveTaskResultContract,
|
|
58
|
+
consolidateDiscoveredPatterns,
|
|
59
|
+
ensureTaskResultContract,
|
|
60
|
+
enrichWithFilesystemHtmlScan,
|
|
61
|
+
filterStaleDeliverables,
|
|
62
|
+
projectHasMeaningfulFileChanges,
|
|
63
|
+
taskRequiresMeaningfulProjectChangeGate,
|
|
64
|
+
} from "./task-results.js";
|
|
65
|
+
import { requestTaskClarification } from "./clarification-routes.js";
|
|
66
|
+
import {
|
|
67
|
+
buildControllerParallelHelpMessage,
|
|
68
|
+
resolveControllerWorkflowSessionKey,
|
|
69
|
+
} from "./controller-planning.js";
|
|
70
|
+
import {
|
|
71
|
+
ControllerIntakeSwitchInProgressError,
|
|
72
|
+
runControllerIntake,
|
|
73
|
+
} from "./controller-intake.js";
|
|
74
|
+
import {
|
|
75
|
+
buildStartupReadinessMessage,
|
|
76
|
+
shouldBlockControllerUntilProvisioningReady,
|
|
77
|
+
} from "./worker-routes.js";
|
|
78
|
+
import {
|
|
79
|
+
buildControllerNoWorkersMessage,
|
|
80
|
+
shouldBlockControllerWithoutWorkers,
|
|
81
|
+
} from "./controller-capacity.js";
|
|
82
|
+
|
|
83
|
+
// Same value as the SWITCH_TASK_SUBMISSION_RETRY_AFTER_SECONDS constant the
|
|
84
|
+
// dispatch layer keeps in http-server.ts (PR-B precedent: the lifted preview
|
|
85
|
+
// proxy keeps its own copy of the prefix const; the shells keep an identical
|
|
86
|
+
// copy for the startsWith match).
|
|
87
|
+
const SWITCH_TASK_SUBMISSION_RETRY_AFTER_SECONDS = 5;
|
|
88
|
+
|
|
89
|
+
// POST /api/v1/tasks
|
|
90
|
+
export async function handleTaskCreateRequest(deps: ControllerTaskDomainDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
|
|
91
|
+
const { getTeamState, updateTeamState, wsServer } = deps;
|
|
92
|
+
const body = await parseJsonBody(req);
|
|
93
|
+
const title = typeof body.title === "string" ? body.title : "";
|
|
94
|
+
const description = typeof body.description === "string" ? body.description : "";
|
|
95
|
+
const priority = typeof body.priority === "string" ? body.priority as TaskPriority : "medium";
|
|
96
|
+
const assignedRole = validateActiveRoleId(body.assignedRole);
|
|
97
|
+
const createdBy = typeof body.createdBy === "string" ? body.createdBy : "boss";
|
|
98
|
+
const controllerSessionKey = createdBy === "controller" && typeof body.controllerSessionKey === "string" && body.controllerSessionKey.trim()
|
|
99
|
+
? normalizeControllerIntakeSessionKey(body.controllerSessionKey)
|
|
100
|
+
: undefined;
|
|
101
|
+
const explicitProjectName = typeof body.projectName === "string" && body.projectName.trim()
|
|
102
|
+
? deriveStableProjectKey(body.projectName)
|
|
103
|
+
: undefined;
|
|
104
|
+
const recommendedSkills = normalizeRecommendedSkills(
|
|
105
|
+
Array.isArray(body.recommendedSkills) ? body.recommendedSkills.map((entry) => String(entry ?? "")) : [],
|
|
106
|
+
);
|
|
107
|
+
|
|
108
|
+
if (!title) {
|
|
109
|
+
sendError(res, 400, "title is required");
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
if (createdBy === "controller") {
|
|
113
|
+
const readinessGate = shouldBlockControllerUntilProvisioningReady(deps, getTeamState());
|
|
114
|
+
if (readinessGate.blocked && readinessGate.readiness) {
|
|
115
|
+
sendError(res, 503, buildStartupReadinessMessage(readinessGate.readiness));
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
if (createdBy === "controller" && shouldBlockControllerWithoutWorkers(deps.config, getTeamState())) {
|
|
120
|
+
sendError(res, 409, buildControllerNoWorkersMessage());
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const taskId = generateId();
|
|
125
|
+
const now = Date.now();
|
|
126
|
+
const repoState = await refreshControllerRepoState(deps);
|
|
127
|
+
|
|
128
|
+
const inheritedProject = controllerSessionKey
|
|
129
|
+
? resolveProjectIdentityForSession(controllerSessionKey, getTeamState())
|
|
130
|
+
: undefined;
|
|
131
|
+
const projectId = inheritedProject?.projectId ?? (explicitProjectName || undefined);
|
|
132
|
+
const projectDir = inheritedProject?.projectDir ?? projectId ?? deriveProjectSlug(title);
|
|
133
|
+
|
|
134
|
+
const task: TaskInfo = {
|
|
135
|
+
id: taskId,
|
|
136
|
+
title,
|
|
137
|
+
description,
|
|
138
|
+
status: "pending",
|
|
139
|
+
priority,
|
|
140
|
+
assignedRole,
|
|
141
|
+
createdBy,
|
|
142
|
+
recommendedSkills: recommendedSkills.length > 0 ? recommendedSkills : undefined,
|
|
143
|
+
controllerRunId: undefined,
|
|
144
|
+
controllerSessionKey,
|
|
145
|
+
projectId,
|
|
146
|
+
projectDir,
|
|
147
|
+
createdAt: now,
|
|
148
|
+
updatedAt: now,
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
updateTeamState((s) => {
|
|
152
|
+
const project = syncProjectRegistryEntry(s, {
|
|
153
|
+
projectId: task.projectId,
|
|
154
|
+
projectDir: task.projectDir,
|
|
155
|
+
aliases: [explicitProjectName, task.projectId],
|
|
156
|
+
summary: task.title,
|
|
157
|
+
updatedAt: now,
|
|
158
|
+
});
|
|
159
|
+
task.projectId = project.projectId;
|
|
160
|
+
task.projectDir = project.projectDir;
|
|
161
|
+
s.tasks[taskId] = task;
|
|
162
|
+
});
|
|
163
|
+
recordTaskExecutionEvent(taskId, {
|
|
164
|
+
type: "lifecycle",
|
|
165
|
+
phase: "created",
|
|
166
|
+
source: "controller",
|
|
167
|
+
status: "pending",
|
|
168
|
+
message: `Task created by ${createdBy}.`,
|
|
169
|
+
role: assignedRole,
|
|
170
|
+
}, deps);
|
|
171
|
+
if (repoState?.enabled) {
|
|
172
|
+
recordTaskExecutionEvent(taskId, {
|
|
173
|
+
type: "lifecycle",
|
|
174
|
+
phase: "repo_ready",
|
|
175
|
+
source: "controller",
|
|
176
|
+
status: "pending",
|
|
177
|
+
message: repoState.remoteReady && repoState.remoteUrl
|
|
178
|
+
? `Git collaboration ready on ${repoState.defaultBranch} with remote ${repoState.remoteUrl}.`
|
|
179
|
+
: `Git collaboration ready on ${repoState.defaultBranch} using controller-managed bundle sync.`,
|
|
180
|
+
role: assignedRole,
|
|
181
|
+
}, deps);
|
|
182
|
+
}
|
|
183
|
+
if (recommendedSkills.length > 0) {
|
|
184
|
+
recordTaskExecutionEvent(taskId, {
|
|
185
|
+
type: "lifecycle",
|
|
186
|
+
phase: "skills_recommended",
|
|
187
|
+
source: "controller",
|
|
188
|
+
status: "pending",
|
|
189
|
+
message: `Recommended skills: ${recommendedSkills.join(", ")}`,
|
|
190
|
+
role: assignedRole,
|
|
191
|
+
}, deps);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
await autoAssignPendingTasks(deps);
|
|
195
|
+
|
|
196
|
+
const updatedTask = getTeamState()?.tasks[taskId];
|
|
197
|
+
wsServer.broadcastUpdate({ type: "task:created", data: serializeTask(updatedTask) });
|
|
198
|
+
sendJson(res, 201, { task: serializeTask(updatedTask) });
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// GET /api/v1/tasks
|
|
202
|
+
export async function handleTaskListRequest(deps: ControllerTaskDomainDeps, res: ServerResponse): Promise<void> {
|
|
203
|
+
const { getTeamState } = deps;
|
|
204
|
+
const state = getTeamState();
|
|
205
|
+
const tasks = state ? Object.values(state.tasks).map((task) => serializeTask(task)) : [];
|
|
206
|
+
sendJson(res, 200, { tasks });
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// GET /api/v1/tasks/:id
|
|
210
|
+
export async function handleTaskGetRequest(deps: ControllerTaskDomainDeps, res: ServerResponse, pathname: string): Promise<void> {
|
|
211
|
+
const { getTeamState } = deps;
|
|
212
|
+
const taskId = pathname.split("/").pop()!;
|
|
213
|
+
const state = getTeamState();
|
|
214
|
+
const task = state?.tasks[taskId];
|
|
215
|
+
if (!task) {
|
|
216
|
+
sendError(res, 404, "Task not found");
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
sendJson(res, 200, { task: serializeTask(task) });
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// DELETE /api/v1/tasks/:id
|
|
223
|
+
export async function handleTaskDeleteRequest(deps: ControllerTaskDomainDeps, res: ServerResponse, pathname: string): Promise<void> {
|
|
224
|
+
const { getTeamState } = deps;
|
|
225
|
+
const taskId = pathname.split("/").pop()!;
|
|
226
|
+
const summary = buildEmptyTaskCleanupSummary();
|
|
227
|
+
const deleted = await deleteTaskCascade(taskId, deps, summary);
|
|
228
|
+
if (!deleted) {
|
|
229
|
+
sendError(res, 404, "Task not found");
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
const stillExists = !!getTeamState()?.tasks[taskId];
|
|
233
|
+
if (stillExists) {
|
|
234
|
+
sendError(res, 409, "Task cleanup could not be confirmed");
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
sendJson(res, 200, {
|
|
238
|
+
status: "deleted",
|
|
239
|
+
confirmed: true,
|
|
240
|
+
taskId,
|
|
241
|
+
cleanup: summary,
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// GET /api/v1/tasks/:id/execution
|
|
246
|
+
export async function handleTaskExecutionGetRequest(deps: ControllerTaskDomainDeps, res: ServerResponse, pathname: string): Promise<void> {
|
|
247
|
+
const { getTeamState } = deps;
|
|
248
|
+
const taskId = pathname.split("/")[4]!;
|
|
249
|
+
const state = getTeamState();
|
|
250
|
+
const task = state?.tasks[taskId];
|
|
251
|
+
if (!task) {
|
|
252
|
+
sendError(res, 404, "Task not found");
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
const clarifications = state
|
|
257
|
+
? Object.values(state.clarifications)
|
|
258
|
+
.filter((item) => item.taskId === taskId)
|
|
259
|
+
.sort((left, right) => left.createdAt - right.createdAt)
|
|
260
|
+
: [];
|
|
261
|
+
const messages = state
|
|
262
|
+
? state.messages
|
|
263
|
+
.filter((message) => message.taskId === taskId)
|
|
264
|
+
.sort((left, right) => left.createdAt - right.createdAt)
|
|
265
|
+
: [];
|
|
266
|
+
|
|
267
|
+
sendJson(res, 200, {
|
|
268
|
+
task: serializeTask(task, true),
|
|
269
|
+
messages,
|
|
270
|
+
clarifications,
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// PATCH /api/v1/tasks/:id
|
|
275
|
+
export async function handleTaskPatchRequest(deps: ControllerTaskDomainDeps, req: IncomingMessage, res: ServerResponse, pathname: string): Promise<void> {
|
|
276
|
+
const { updateTeamState, wsServer } = deps;
|
|
277
|
+
const taskId = pathname.split("/").pop()!;
|
|
278
|
+
const body = await parseJsonBody(req);
|
|
279
|
+
let statusEvent: TaskExecutionEvent | undefined;
|
|
280
|
+
let progressEvent: TaskExecutionEvent | undefined;
|
|
281
|
+
let progressContract: WorkerProgressContract | undefined;
|
|
282
|
+
|
|
283
|
+
const state = updateTeamState((s) => {
|
|
284
|
+
const task = s.tasks[taskId];
|
|
285
|
+
if (!task) return;
|
|
286
|
+
const previousStatus = task.status;
|
|
287
|
+
const previousProgress = task.progress;
|
|
288
|
+
const previousProgressContract = task.progressContract;
|
|
289
|
+
if (typeof body.status === "string") task.status = body.status as TaskStatus;
|
|
290
|
+
if (typeof body.progress === "string") task.progress = body.progress as string;
|
|
291
|
+
if (typeof body.priority === "string") task.priority = body.priority as TaskPriority;
|
|
292
|
+
const nextAssignedRole = validateActiveRoleId(body.assignedRole);
|
|
293
|
+
if (nextAssignedRole) task.assignedRole = nextAssignedRole;
|
|
294
|
+
if (Array.isArray(body.recommendedSkills)) {
|
|
295
|
+
const recommendedSkills = normalizeRecommendedSkills(
|
|
296
|
+
body.recommendedSkills.map((entry: unknown) => String(entry ?? "")),
|
|
297
|
+
);
|
|
298
|
+
task.recommendedSkills = recommendedSkills.length > 0 ? recommendedSkills : undefined;
|
|
299
|
+
}
|
|
300
|
+
progressContract = normalizeWorkerProgressContract(body.progressContract)
|
|
301
|
+
?? (typeof body.progress === "string" ? backfillWorkerProgressContract(body.progress, typeof body.status === "string" ? body.status : undefined) : undefined);
|
|
302
|
+
if (progressContract) {
|
|
303
|
+
task.progressContract = progressContract;
|
|
304
|
+
task.progress = task.progress || progressContract.summary;
|
|
305
|
+
}
|
|
306
|
+
task.updatedAt = Date.now();
|
|
307
|
+
|
|
308
|
+
if (typeof body.status === "string" && body.status !== previousStatus) {
|
|
309
|
+
statusEvent = appendTaskExecutionEvent(task, {
|
|
310
|
+
type: "lifecycle",
|
|
311
|
+
phase: `status_${task.status}`,
|
|
312
|
+
source: "controller",
|
|
313
|
+
status: mapTaskStatusToExecutionStatus(task.status, task.execution?.status),
|
|
314
|
+
message: `Task status updated to ${task.status}.`,
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
if (typeof body.progress === "string" && body.progress !== previousProgress) {
|
|
318
|
+
progressEvent = appendTaskExecutionEvent(task, {
|
|
319
|
+
type: "progress",
|
|
320
|
+
phase: "progress_reported",
|
|
321
|
+
source: "worker",
|
|
322
|
+
status: task.status === "in_progress" || task.status === "review" ? "running" : undefined,
|
|
323
|
+
message: body.progress as string,
|
|
324
|
+
});
|
|
325
|
+
} else if (progressContract && JSON.stringify(progressContract) !== JSON.stringify(previousProgressContract)) {
|
|
326
|
+
progressEvent = appendTaskExecutionEvent(task, {
|
|
327
|
+
type: "progress",
|
|
328
|
+
phase: "progress_contract_reported",
|
|
329
|
+
source: "worker",
|
|
330
|
+
status: task.status === "in_progress" || task.status === "review" ? "running" : undefined,
|
|
331
|
+
message: progressContract.summary,
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
});
|
|
335
|
+
|
|
336
|
+
const updatedTask = state.tasks[taskId];
|
|
337
|
+
if (updatedTask) {
|
|
338
|
+
if (statusEvent) {
|
|
339
|
+
broadcastTaskExecutionEvent(taskId, updatedTask, statusEvent, deps);
|
|
340
|
+
}
|
|
341
|
+
if (progressEvent) {
|
|
342
|
+
broadcastTaskExecutionEvent(taskId, updatedTask, progressEvent, deps);
|
|
343
|
+
}
|
|
344
|
+
wsServer.broadcastUpdate({ type: "task:updated", data: serializeTask(updatedTask) });
|
|
345
|
+
}
|
|
346
|
+
sendJson(res, 200, { task: serializeTask(updatedTask) });
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
// POST /api/v1/tasks/:id/assign
|
|
350
|
+
export async function handleTaskAssignRequest(deps: ControllerTaskDomainDeps, req: IncomingMessage, res: ServerResponse, pathname: string): Promise<void> {
|
|
351
|
+
const { getTeamState, taskRouter, wsServer } = deps;
|
|
352
|
+
const taskId = pathname.split("/")[4]!;
|
|
353
|
+
const body = await parseJsonBody(req);
|
|
354
|
+
const workerId = typeof body.workerId === "string" ? body.workerId : undefined;
|
|
355
|
+
const targetRole = validateActiveRoleId(body.targetRole);
|
|
356
|
+
|
|
357
|
+
const state = getTeamState();
|
|
358
|
+
if (!state?.tasks[taskId]) {
|
|
359
|
+
sendError(res, 404, "Task not found");
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
let targetWorker: WorkerInfo | null = null;
|
|
364
|
+
if (workerId && state.workers[workerId]) {
|
|
365
|
+
targetWorker = state.workers[workerId]!;
|
|
366
|
+
} else {
|
|
367
|
+
const taskForRouting = targetRole
|
|
368
|
+
? { ...state.tasks[taskId], assignedRole: targetRole }
|
|
369
|
+
: state.tasks[taskId];
|
|
370
|
+
targetWorker = taskRouter.routeTask(taskForRouting, state.workers);
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
if (!targetWorker) {
|
|
374
|
+
sendError(res, 404, "No available worker for this task");
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
const updatedTask = await assignTaskToWorker(taskId, targetWorker, deps, {
|
|
379
|
+
assignedRole: targetRole,
|
|
380
|
+
});
|
|
381
|
+
wsServer.broadcastUpdate({ type: "task:updated", data: serializeTask(updatedTask) });
|
|
382
|
+
sendJson(res, 200, { task: serializeTask(updatedTask), worker: targetWorker });
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
// POST /api/v1/tasks/:id/handoff
|
|
386
|
+
export async function handleTaskHandoffRequest(deps: ControllerTaskDomainDeps, req: IncomingMessage, res: ServerResponse, pathname: string): Promise<void> {
|
|
387
|
+
const { logger, getTeamState, taskRouter, updateTeamState, wsServer } = deps;
|
|
388
|
+
const taskId = pathname.split("/")[4]!;
|
|
389
|
+
const body = await parseJsonBody(req);
|
|
390
|
+
const targetRole = validateActiveRoleId(body.targetRole);
|
|
391
|
+
const handoffContract = normalizeTaskHandoffContract(body.contract, {
|
|
392
|
+
targetRole,
|
|
393
|
+
reason: typeof body.reason === "string" ? body.reason : targetRole ? `The next step should move to ${targetRole}.` : "The task needs a new assignee.",
|
|
394
|
+
summary: typeof body.summary === "string" ? body.summary : undefined,
|
|
395
|
+
expectedNextStep: typeof body.expectedNextStep === "string" ? body.expectedNextStep : undefined,
|
|
396
|
+
artifacts: [],
|
|
397
|
+
});
|
|
398
|
+
|
|
399
|
+
const state = getTeamState();
|
|
400
|
+
if (!state?.tasks[taskId]) {
|
|
401
|
+
sendError(res, 404, "Task not found");
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
const previousWorkerId = state.tasks[taskId].assignedWorkerId;
|
|
406
|
+
const avoidPreviousManagedWorker = Boolean(
|
|
407
|
+
previousWorkerId && deps.workerProvisioningManager?.hasManagedWorker(previousWorkerId),
|
|
408
|
+
);
|
|
409
|
+
|
|
410
|
+
updateTeamState((s) => {
|
|
411
|
+
const task = s.tasks[taskId];
|
|
412
|
+
task.status = "pending";
|
|
413
|
+
task.assignedWorkerId = undefined;
|
|
414
|
+
task.assignedRole = targetRole ?? task.assignedRole;
|
|
415
|
+
task.lastHandoff = handoffContract;
|
|
416
|
+
resetTaskForFreshAttempt(task);
|
|
417
|
+
task.updatedAt = Date.now();
|
|
418
|
+
|
|
419
|
+
// Free old worker
|
|
420
|
+
if (previousWorkerId && s.workers[previousWorkerId]) {
|
|
421
|
+
const previousWorker = s.workers[previousWorkerId];
|
|
422
|
+
if (previousWorker.status !== "offline") {
|
|
423
|
+
previousWorker.status = "idle";
|
|
424
|
+
}
|
|
425
|
+
previousWorker.currentTaskId = undefined;
|
|
426
|
+
}
|
|
427
|
+
});
|
|
428
|
+
|
|
429
|
+
await cancelTaskExecution(taskId, previousWorkerId, "handoff", deps);
|
|
430
|
+
if (avoidPreviousManagedWorker && previousWorkerId) {
|
|
431
|
+
try {
|
|
432
|
+
await deps.workerProvisioningManager?.onWorkerRemoved(
|
|
433
|
+
previousWorkerId,
|
|
434
|
+
`handoff for ${taskId} requested a fresh managed worker`,
|
|
435
|
+
);
|
|
436
|
+
} catch (err) {
|
|
437
|
+
logger.warn(`Controller: failed to retire previous managed worker ${previousWorkerId}: ${String(err)}`);
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
// Try auto-assign to new role
|
|
442
|
+
const newState = getTeamState()!;
|
|
443
|
+
const routingWorkers = avoidPreviousManagedWorker && previousWorkerId
|
|
444
|
+
? Object.fromEntries(Object.entries(newState.workers).filter(([workerId]) => workerId !== previousWorkerId))
|
|
445
|
+
: newState.workers;
|
|
446
|
+
const worker = taskRouter.routeTask(newState.tasks[taskId], routingWorkers);
|
|
447
|
+
if (worker) {
|
|
448
|
+
await assignTaskToWorker(taskId, worker, deps, { assignedRole: targetRole });
|
|
449
|
+
} else {
|
|
450
|
+
scheduleProvisioningReconcile(deps, `handoff:${taskId}`);
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
const updatedTask = getTeamState()?.tasks[taskId];
|
|
454
|
+
recordTaskExecutionEvent(taskId, {
|
|
455
|
+
type: "lifecycle",
|
|
456
|
+
phase: "handoff",
|
|
457
|
+
source: "controller",
|
|
458
|
+
message: targetRole
|
|
459
|
+
? `Task handed off and re-routed to role ${targetRole}: ${handoffContract.summary}`
|
|
460
|
+
: `Task handed off for re-routing: ${handoffContract.summary}`,
|
|
461
|
+
role: targetRole,
|
|
462
|
+
}, deps);
|
|
463
|
+
wsServer.broadcastUpdate({ type: "task:updated", data: serializeTask(updatedTask) });
|
|
464
|
+
sendJson(res, 200, { task: serializeTask(updatedTask) });
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// POST /api/v1/tasks/:id/checkpoint
|
|
468
|
+
export async function handleTaskCheckpointRequest(deps: ControllerTaskDomainDeps, req: IncomingMessage, res: ServerResponse, pathname: string): Promise<void> {
|
|
469
|
+
const { updateTeamState } = deps;
|
|
470
|
+
const taskId = pathname.split("/")[4];
|
|
471
|
+
let body: Record<string, unknown> = {};
|
|
472
|
+
try { body = await parseJsonBody(req); } catch { sendError(res, 400, "invalid JSON body"); return; }
|
|
473
|
+
const lastAssistantMessage = typeof body.lastAssistantMessage === "string" ? body.lastAssistantMessage.slice(0, 8000) : "";
|
|
474
|
+
const progressNote = typeof body.progressNote === "string" ? body.progressNote.slice(0, 1000) : "";
|
|
475
|
+
const sessionKey = typeof body.sessionKey === "string" ? body.sessionKey : "";
|
|
476
|
+
if (!lastAssistantMessage && !progressNote) {
|
|
477
|
+
sendError(res, 400, "lastAssistantMessage or progressNote is required");
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
480
|
+
const updated = updateTeamState((s) => {
|
|
481
|
+
const task = s.tasks[taskId];
|
|
482
|
+
if (!task) { return; }
|
|
483
|
+
const prev = task.checkpoint;
|
|
484
|
+
const notes = [...(prev?.progressNotes ?? [])];
|
|
485
|
+
if (progressNote && !notes.includes(progressNote)) { notes.push(progressNote); }
|
|
486
|
+
task.checkpoint = {
|
|
487
|
+
updatedAt: Date.now(),
|
|
488
|
+
attempt: prev?.attempt ?? 0,
|
|
489
|
+
sessionKey: sessionKey || prev?.sessionKey || "",
|
|
490
|
+
lastAssistantMessage: lastAssistantMessage || prev?.lastAssistantMessage || "",
|
|
491
|
+
progressNotes: notes.slice(-10),
|
|
492
|
+
};
|
|
493
|
+
task.updatedAt = Date.now();
|
|
494
|
+
});
|
|
495
|
+
const task = updated?.tasks[taskId];
|
|
496
|
+
if (!task) { sendError(res, 404, "task not found"); return; }
|
|
497
|
+
sendJson(res, 200, { ok: true, updatedAt: task.checkpoint?.updatedAt });
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
// POST /api/v1/tasks/:id/result-contract
|
|
501
|
+
export async function handleTaskResultContractRequest(deps: ControllerTaskDomainDeps, req: IncomingMessage, res: ServerResponse, pathname: string): Promise<void> {
|
|
502
|
+
const { logger, getTeamState, updateTeamState } = deps;
|
|
503
|
+
const taskId = pathname.split("/")[4]!;
|
|
504
|
+
const body = await parseJsonBody(req);
|
|
505
|
+
const contract = normalizeWorkerTaskResultContract(body.contract ?? body.resultContract);
|
|
506
|
+
const workerId = typeof body.workerId === "string" ? body.workerId : undefined;
|
|
507
|
+
const currentTask = getTeamState()?.tasks[taskId];
|
|
508
|
+
if (!currentTask) {
|
|
509
|
+
sendError(res, 404, "Task not found");
|
|
510
|
+
return;
|
|
511
|
+
}
|
|
512
|
+
if (!contract) {
|
|
513
|
+
sendError(res, 400, "result contract is required");
|
|
514
|
+
return;
|
|
515
|
+
}
|
|
516
|
+
if (workerId && !canAcceptWorkerUpdate(currentTask, workerId)) {
|
|
517
|
+
logger.info(`Controller: ignoring stale result contract for ${taskId} from ${workerId}`);
|
|
518
|
+
sendJson(res, 202, { status: "ignored", reason: "stale-worker-result-contract" });
|
|
519
|
+
return;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
const state = updateTeamState((teamState) => {
|
|
523
|
+
const task = teamState.tasks[taskId];
|
|
524
|
+
if (!task) {
|
|
525
|
+
return;
|
|
526
|
+
}
|
|
527
|
+
task.resultContract = filterStaleDeliverables(contract, task.projectDir);
|
|
528
|
+
task.updatedAt = Date.now();
|
|
529
|
+
// Enrich deliverables with preview inference so PreviewManager can auto-launch.
|
|
530
|
+
// Workers typically don't include artifactType/previewCommand in their contracts.
|
|
531
|
+
const existingResult = task.result ?? "";
|
|
532
|
+
let enriched = enrichDeliverablesWithPreviewInference(task.resultContract, existingResult);
|
|
533
|
+
if (!enriched) {
|
|
534
|
+
enriched = enrichWithFilesystemHtmlScan(contract, task.projectDir);
|
|
535
|
+
}
|
|
536
|
+
if (enriched) {
|
|
537
|
+
task.resultContract = enriched;
|
|
538
|
+
}
|
|
539
|
+
});
|
|
540
|
+
recordTaskExecutionEvent(taskId, {
|
|
541
|
+
type: "output",
|
|
542
|
+
phase: "result_contract_recorded",
|
|
543
|
+
source: "worker",
|
|
544
|
+
status: contract.outcome === "failed" ? "failed" : "running",
|
|
545
|
+
message: contract.summary,
|
|
546
|
+
workerId,
|
|
547
|
+
role: currentTask.assignedRole,
|
|
548
|
+
}, deps);
|
|
549
|
+
consolidateDiscoveredPatterns(contract, taskId, currentTask.assignedRole, logger);
|
|
550
|
+
sendJson(res, 201, { task: serializeTask(state.tasks[taskId]) });
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
// POST /api/v1/tasks/:id/result
|
|
554
|
+
export async function handleTaskResultRequest(deps: ControllerTaskDomainDeps, req: IncomingMessage, res: ServerResponse, pathname: string): Promise<void> {
|
|
555
|
+
const { logger, getTeamState, updateTeamState } = deps;
|
|
556
|
+
const taskId = pathname.split("/")[4]!;
|
|
557
|
+
const body = await parseJsonBody(req);
|
|
558
|
+
const result = typeof body.result === "string" ? body.result : "";
|
|
559
|
+
let error = typeof body.error === "string" ? body.error : undefined;
|
|
560
|
+
const workerId = typeof body.workerId === "string" ? body.workerId : undefined;
|
|
561
|
+
const currentTask = getTeamState()?.tasks[taskId];
|
|
562
|
+
if (!currentTask) {
|
|
563
|
+
sendError(res, 404, "Task not found");
|
|
564
|
+
return;
|
|
565
|
+
}
|
|
566
|
+
if (workerId && !canAcceptWorkerUpdate(currentTask, workerId)) {
|
|
567
|
+
logger.info(`Controller: ignoring stale task result for ${taskId} from ${workerId}`);
|
|
568
|
+
sendJson(res, 202, { status: "ignored", reason: "stale-worker-result" });
|
|
569
|
+
return;
|
|
570
|
+
}
|
|
571
|
+
const previousWorkerId = getTeamState()?.tasks[taskId]?.assignedWorkerId;
|
|
572
|
+
|
|
573
|
+
const submittedContract = normalizeWorkerTaskResultContract(body.contract ?? body.resultContract);
|
|
574
|
+
if (submittedContract) {
|
|
575
|
+
updateTeamState((teamState) => {
|
|
576
|
+
const task = teamState.tasks[taskId];
|
|
577
|
+
if (!task) {
|
|
578
|
+
return;
|
|
579
|
+
}
|
|
580
|
+
task.resultContract = submittedContract;
|
|
581
|
+
});
|
|
582
|
+
recordTaskExecutionEvent(taskId, {
|
|
583
|
+
type: "output",
|
|
584
|
+
phase: "result_contract_recorded",
|
|
585
|
+
source: "worker",
|
|
586
|
+
status: error ? "failed" : "running",
|
|
587
|
+
message: submittedContract.summary,
|
|
588
|
+
workerId,
|
|
589
|
+
role: currentTask.assignedRole,
|
|
590
|
+
}, deps);
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
const effectiveContract = buildEffectiveTaskResultContract(currentTask, result, error, submittedContract ?? undefined);
|
|
594
|
+
|
|
595
|
+
if (!error && effectiveContract.outcome === "blocked") {
|
|
596
|
+
updateTeamState((teamState) => {
|
|
597
|
+
const task = teamState.tasks[taskId];
|
|
598
|
+
if (!task) {
|
|
599
|
+
return;
|
|
600
|
+
}
|
|
601
|
+
task.resultContract = effectiveContract;
|
|
602
|
+
task.updatedAt = Date.now();
|
|
603
|
+
});
|
|
604
|
+
if (!submittedContract) {
|
|
605
|
+
recordTaskExecutionEvent(taskId, {
|
|
606
|
+
type: "lifecycle",
|
|
607
|
+
phase: "result_contract_backfilled",
|
|
608
|
+
source: "controller",
|
|
609
|
+
message: "Worker did not submit a structured result contract; TeamClaw backfilled one from the recorded task result.",
|
|
610
|
+
workerId: currentTask.assignedWorkerId,
|
|
611
|
+
role: currentTask.assignedRole,
|
|
612
|
+
}, deps);
|
|
613
|
+
}
|
|
614
|
+
const requested = await requestTaskClarification({
|
|
615
|
+
taskId,
|
|
616
|
+
requestedBy: workerId ?? "worker",
|
|
617
|
+
requestedByWorkerId: workerId,
|
|
618
|
+
requestedByRole: currentTask.assignedRole,
|
|
619
|
+
question: effectiveContract.questions[0]
|
|
620
|
+
?? "This task is blocked and needs a human decision before work can continue. What should TeamClaw do next?",
|
|
621
|
+
blockingReason: effectiveContract.blockers[0] ?? effectiveContract.summary,
|
|
622
|
+
context: [
|
|
623
|
+
effectiveContract.notes,
|
|
624
|
+
result.trim(),
|
|
625
|
+
effectiveContract.keyPoints.length > 0
|
|
626
|
+
? `Worker-provided commands/details:\n${effectiveContract.keyPoints.join("\n")}`
|
|
627
|
+
: "",
|
|
628
|
+
].filter(Boolean).join("\n\n"),
|
|
629
|
+
}, deps);
|
|
630
|
+
if (requested.status === "missing-task") {
|
|
631
|
+
sendError(res, 404, "Task not found");
|
|
632
|
+
return;
|
|
633
|
+
}
|
|
634
|
+
if (requested.status === "conflict") {
|
|
635
|
+
sendError(res, 409, "Cannot request clarification for a completed task");
|
|
636
|
+
return;
|
|
637
|
+
}
|
|
638
|
+
sendJson(res, requested.status === "already-pending" ? 200 : 201, {
|
|
639
|
+
status: requested.status,
|
|
640
|
+
clarification: requested.clarification,
|
|
641
|
+
task: serializeTask(requested.task),
|
|
642
|
+
});
|
|
643
|
+
return;
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
const gatedTask = getTeamState()?.tasks[taskId];
|
|
647
|
+
if (
|
|
648
|
+
!error
|
|
649
|
+
&& gatedTask
|
|
650
|
+
&& taskRequiresMeaningfulProjectChangeGate(gatedTask)
|
|
651
|
+
&& !projectHasMeaningfulFileChanges(gatedTask, effectiveContract)
|
|
652
|
+
&& !allowsNoChangeCompletion(gatedTask, submittedContract ?? undefined, result)
|
|
653
|
+
) {
|
|
654
|
+
error = "Task reported completion but no meaningful project file changes were detected in the assigned project directory.";
|
|
655
|
+
recordTaskExecutionEvent(taskId, {
|
|
656
|
+
type: "warning",
|
|
657
|
+
phase: "completion_gate",
|
|
658
|
+
source: "controller",
|
|
659
|
+
status: "failed",
|
|
660
|
+
message: error,
|
|
661
|
+
workerId,
|
|
662
|
+
role: gatedTask.assignedRole,
|
|
663
|
+
}, deps);
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
const updatedTask = applyTaskResult(taskId, result, error, deps);
|
|
667
|
+
ensureTaskResultContract(taskId, result, error, deps);
|
|
668
|
+
if (!error) {
|
|
669
|
+
deps.previewManager?.syncTaskPreviews(taskId).catch((err) => {
|
|
670
|
+
logger.warn(`Controller: failed to sync previews for ${taskId}: ${String(err)}`);
|
|
671
|
+
});
|
|
672
|
+
}
|
|
673
|
+
if (!workerId || workerId !== previousWorkerId) {
|
|
674
|
+
await cancelTaskExecution(taskId, previousWorkerId, "manual result submission", deps);
|
|
675
|
+
}
|
|
676
|
+
sendJson(res, 200, { task: serializeTask(getTeamState()?.tasks[taskId] ?? updatedTask) });
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
// POST /api/v1/tasks/:id/execution
|
|
680
|
+
export async function handleTaskExecutionEventRequest(deps: ControllerTaskDomainDeps, req: IncomingMessage, res: ServerResponse, pathname: string): Promise<void> {
|
|
681
|
+
const { logger, getTeamState } = deps;
|
|
682
|
+
const taskId = pathname.split("/")[4]!;
|
|
683
|
+
const body = await parseJsonBody(req);
|
|
684
|
+
const type = typeof body.type === "string" ? body.type : "";
|
|
685
|
+
const message = typeof body.message === "string" ? body.message : "";
|
|
686
|
+
const workerId = typeof body.workerId === "string" ? body.workerId : undefined;
|
|
687
|
+
const currentTask = getTeamState()?.tasks[taskId];
|
|
688
|
+
|
|
689
|
+
if (!type || !message) {
|
|
690
|
+
sendError(res, 400, "type and message are required");
|
|
691
|
+
return;
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
if (!currentTask) {
|
|
695
|
+
sendError(res, 404, "Task not found");
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
if (workerId && !canAcceptWorkerUpdate(currentTask, workerId)) {
|
|
700
|
+
logger.info(`Controller: ignoring stale execution event for ${taskId} from ${workerId}`);
|
|
701
|
+
sendJson(res, 202, { status: "ignored", reason: "stale-worker-event" });
|
|
702
|
+
return;
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
const recorded = recordTaskExecutionEvent(taskId, {
|
|
706
|
+
type: type as TaskExecutionEventInput["type"],
|
|
707
|
+
message,
|
|
708
|
+
createdAt: typeof body.createdAt === "number" ? body.createdAt : undefined,
|
|
709
|
+
phase: typeof body.phase === "string" ? body.phase : undefined,
|
|
710
|
+
source: typeof body.source === "string" ? body.source as TaskExecutionEventInput["source"] : undefined,
|
|
711
|
+
stream: typeof body.stream === "string" ? body.stream : undefined,
|
|
712
|
+
role: validateActiveRoleId(body.role),
|
|
713
|
+
workerId,
|
|
714
|
+
runId: typeof body.runId === "string" ? body.runId : undefined,
|
|
715
|
+
sessionKey: typeof body.sessionKey === "string" ? body.sessionKey : undefined,
|
|
716
|
+
status: typeof body.status === "string" ? body.status as TaskExecutionEventInput["status"] : undefined,
|
|
717
|
+
}, deps);
|
|
718
|
+
|
|
719
|
+
if (!recorded.task || !recorded.event) {
|
|
720
|
+
sendError(res, 404, "Task not found");
|
|
721
|
+
return;
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
// When a result contract is backfilled, the task is effectively complete —
|
|
725
|
+
// trigger preview sync so that any web-app deliverables get previewed.
|
|
726
|
+
if (recorded.event?.phase === "result_contract_backfilled") {
|
|
727
|
+
deps.previewManager?.syncTaskPreviews(taskId).catch((err) => {
|
|
728
|
+
logger.warn(`Controller: failed to sync previews for ${taskId}: ${String(err)}`);
|
|
729
|
+
});
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
sendJson(res, 201, {
|
|
733
|
+
task: serializeTask(recorded.task),
|
|
734
|
+
execution: buildTaskExecutionSummary(recorded.task.execution),
|
|
735
|
+
event: recorded.event,
|
|
736
|
+
});
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
// POST /api/v1/tasks/:id/parallel-help
|
|
740
|
+
export async function handleTaskParallelHelpRequest(deps: ControllerTaskDomainDeps, req: IncomingMessage, res: ServerResponse, pathname: string): Promise<void> {
|
|
741
|
+
const { getTeamState } = deps;
|
|
742
|
+
const taskId = pathname.split("/")[4]!;
|
|
743
|
+
const body = await parseJsonBody(req);
|
|
744
|
+
const currentTask = getTeamState()?.tasks[taskId];
|
|
745
|
+
if (!currentTask) {
|
|
746
|
+
sendError(res, 404, "Task not found");
|
|
747
|
+
return;
|
|
748
|
+
}
|
|
749
|
+
const requestedBy = typeof body.requestedBy === "string" ? body.requestedBy : "";
|
|
750
|
+
const reason = typeof body.reason === "string" ? body.reason.trim() : "";
|
|
751
|
+
const requestedByRole = validateActiveRoleId(body.requestedByRole);
|
|
752
|
+
const targetRole = validateActiveRoleId(body.targetRole);
|
|
753
|
+
const requestedWorkerCount = typeof body.requestedWorkerCount === "number"
|
|
754
|
+
? Math.max(2, Math.min(10, Math.floor(body.requestedWorkerCount)))
|
|
755
|
+
: undefined;
|
|
756
|
+
const suggestedWorkstreams = Array.isArray(body.suggestedWorkstreams)
|
|
757
|
+
? body.suggestedWorkstreams.map((entry: unknown) => String(entry ?? "").trim()).filter(Boolean)
|
|
758
|
+
: [];
|
|
759
|
+
if (!requestedBy || !reason) {
|
|
760
|
+
sendError(res, 400, "requestedBy and reason are required");
|
|
761
|
+
return;
|
|
762
|
+
}
|
|
763
|
+
const sessionKey = resolveControllerWorkflowSessionKey(currentTask, getTeamState());
|
|
764
|
+
if (!sessionKey) {
|
|
765
|
+
sendError(res, 409, "Task is not linked to a controller session");
|
|
766
|
+
return;
|
|
767
|
+
}
|
|
768
|
+
recordTaskExecutionEvent(taskId, {
|
|
769
|
+
type: "progress",
|
|
770
|
+
phase: "parallel_help_requested",
|
|
771
|
+
source: "worker",
|
|
772
|
+
message: `Worker requested more ${targetRole || requestedByRole || currentTask.assignedRole || "developer"} capacity for parallel work: ${reason}`,
|
|
773
|
+
workerId: requestedBy,
|
|
774
|
+
role: requestedByRole,
|
|
775
|
+
}, deps);
|
|
776
|
+
try {
|
|
777
|
+
const result = await runControllerIntake(
|
|
778
|
+
buildControllerParallelHelpMessage(currentTask, getTeamState(), {
|
|
779
|
+
requestedBy,
|
|
780
|
+
requestedByRole,
|
|
781
|
+
targetRole,
|
|
782
|
+
reason,
|
|
783
|
+
requestedWorkerCount,
|
|
784
|
+
suggestedWorkstreams,
|
|
785
|
+
}),
|
|
786
|
+
sessionKey,
|
|
787
|
+
deps,
|
|
788
|
+
{
|
|
789
|
+
source: "task_follow_up",
|
|
790
|
+
sourceTaskId: currentTask.id,
|
|
791
|
+
sourceTaskTitle: currentTask.title,
|
|
792
|
+
},
|
|
793
|
+
);
|
|
794
|
+
sendJson(res, 201, result);
|
|
795
|
+
} catch (err) {
|
|
796
|
+
if (err instanceof ControllerIntakeSwitchInProgressError) {
|
|
797
|
+
// Backstop for the race between the URL-level gate and the intake
|
|
798
|
+
// entry; same 503 + Retry-After shape as the gate.
|
|
799
|
+
res.setHeader("Retry-After", String(SWITCH_TASK_SUBMISSION_RETRY_AFTER_SECONDS));
|
|
800
|
+
sendJson(res, 503, {
|
|
801
|
+
error: err.message,
|
|
802
|
+
retryAfterSeconds: SWITCH_TASK_SUBMISSION_RETRY_AFTER_SECONDS,
|
|
803
|
+
transition: {
|
|
804
|
+
phase: err.transition.phase,
|
|
805
|
+
targetProfileId: err.transition.targetProfileId,
|
|
806
|
+
},
|
|
807
|
+
});
|
|
808
|
+
return;
|
|
809
|
+
}
|
|
810
|
+
throw err;
|
|
811
|
+
}
|
|
812
|
+
}
|