@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,1029 @@
1
+ // PR-C of issue #204 (http-server monolith split): the controller planning
2
+ // domain - manifest binding/backfill, fallback role+title heuristics,
3
+ // controller-managed task creation, supplemental human-context forwarding,
4
+ // follow-up/parallel-help message building, and delivery-report completion
5
+ // checks - extracted verbatim from controller/http-server.ts. Zero behavior
6
+ // change. This module must NEVER import http-server (the reverse edge
7
+ // exists: http-server -> controller-planning); the intake orchestration
8
+ // (controller-intake.ts) calls into these, never the other way round.
9
+ import type { PluginLogger } from "../../api.js";
10
+ import type {
11
+ ControllerOrchestrationManifest,
12
+ ControllerRunInfo,
13
+ ControllerRunSource,
14
+ PluginConfig,
15
+ RoleId,
16
+ TaskInfo,
17
+ TaskPriority,
18
+ TeamMessage,
19
+ TeamState,
20
+ WorkerTaskResultContract,
21
+ } from "../types.js";
22
+ import { generateId } from "../protocol.js";
23
+ import { ensureTeamMessageContract } from "../interaction-contracts.js";
24
+ import {
25
+ getActiveDefaultRole,
26
+ getActiveRoles,
27
+ normalizeRecommendedSkills,
28
+ resolveActiveRoleSkills,
29
+ } from "../profile-loader.js";
30
+ import {
31
+ deriveProjectSlug,
32
+ deriveStableProjectKey,
33
+ } from "../openclaw-workspace.js";
34
+ import { generateDeliveryReport, isSessionComplete } from "./delivery-report.js";
35
+ import { refreshControllerRepoState } from "./repo-routes.js";
36
+ import {
37
+ normalizeControllerIntakeSessionKey,
38
+ recordTaskExecutionEvent,
39
+ serializeTask,
40
+ } from "./task-execution.js";
41
+ import {
42
+ appendControllerRunEvent,
43
+ updateControllerRun,
44
+ } from "./controller-runs.js";
45
+ import { autoAssignPendingTasks } from "./task-assignment.js";
46
+ import {
47
+ resolveProjectIdentityForSession,
48
+ syncProjectRegistryEntry,
49
+ } from "./project-registry.js";
50
+ import { deliverMessageToWorker } from "./message-delivery.js";
51
+ import type { ControllerTaskDomainDeps } from "./task-execution.js";
52
+
53
+ export function collectTaskIds(state: TeamState | null): Set<string> {
54
+ return new Set(Object.keys(state?.tasks ?? {}));
55
+ }
56
+
57
+ export function normalizeControllerTaskMatchText(input: unknown): string {
58
+ return typeof input === "string" ? input.replace(/\s+/g, " ").trim().toLowerCase() : "";
59
+ }
60
+
61
+ export function taskMatchesManifestCreatedTask(
62
+ task: TaskInfo,
63
+ manifestTask: ControllerOrchestrationManifest["createdTasks"][number],
64
+ ): boolean {
65
+ if (normalizeControllerTaskMatchText(task.title) !== normalizeControllerTaskMatchText(manifestTask.title)) {
66
+ return false;
67
+ }
68
+ if (manifestTask.assignedRole && task.assignedRole && manifestTask.assignedRole !== task.assignedRole) {
69
+ return false;
70
+ }
71
+ if (manifestTask.assignedRole && !task.assignedRole) {
72
+ return false;
73
+ }
74
+ return task.createdBy === "controller";
75
+ }
76
+
77
+ export function scoreControllerTaskBindingCandidate(task: TaskInfo): number {
78
+ switch (task.status) {
79
+ case "pending":
80
+ return 6;
81
+ case "assigned":
82
+ return 5;
83
+ case "in_progress":
84
+ return 4;
85
+ case "review":
86
+ return 3;
87
+ case "blocked":
88
+ return 2;
89
+ case "completed":
90
+ return 1;
91
+ case "failed":
92
+ default:
93
+ return 0;
94
+ }
95
+ }
96
+
97
+ export function reconcileControllerManifestTaskBindings(
98
+ sessionKey: string,
99
+ createdTaskIds: string[],
100
+ manifest: ControllerOrchestrationManifest | undefined,
101
+ controllerRunId: string,
102
+ deps: ControllerTaskDomainDeps,
103
+ ): { taskIds: string[]; linkedTaskIds: string[] } {
104
+ if (!manifest || manifest.createdTasks.length === 0) {
105
+ return { taskIds: createdTaskIds, linkedTaskIds: [] };
106
+ }
107
+
108
+ const normalizedSessionKey = normalizeControllerIntakeSessionKey(sessionKey);
109
+ const linkedTaskIds: string[] = [];
110
+
111
+ deps.updateTeamState((state) => {
112
+ const usedTaskIds = new Set(createdTaskIds);
113
+ for (const manifestTask of manifest.createdTasks) {
114
+ const existingTaskId = Array.from(usedTaskIds).find((taskId) => {
115
+ const task = state.tasks[taskId];
116
+ return !!task && taskMatchesManifestCreatedTask(task, manifestTask);
117
+ });
118
+ const matchedTask = existingTaskId
119
+ ? state.tasks[existingTaskId]
120
+ : Object.values(state.tasks)
121
+ .filter((task) => !usedTaskIds.has(task.id))
122
+ .filter((task) => taskMatchesManifestCreatedTask(task, manifestTask))
123
+ .sort((left, right) => {
124
+ const scoreDelta = scoreControllerTaskBindingCandidate(right) - scoreControllerTaskBindingCandidate(left);
125
+ if (scoreDelta !== 0) {
126
+ return scoreDelta;
127
+ }
128
+ return right.updatedAt - left.updatedAt;
129
+ })[0];
130
+
131
+ if (!matchedTask) {
132
+ continue;
133
+ }
134
+
135
+ if (matchedTask.controllerSessionKey !== normalizedSessionKey) {
136
+ matchedTask.controllerSessionKey = normalizedSessionKey;
137
+ }
138
+ matchedTask.controllerRunId = controllerRunId;
139
+ if (!usedTaskIds.has(matchedTask.id)) {
140
+ usedTaskIds.add(matchedTask.id);
141
+ linkedTaskIds.push(matchedTask.id);
142
+ }
143
+ }
144
+ });
145
+
146
+ return {
147
+ taskIds: Array.from(new Set([...createdTaskIds, ...linkedTaskIds])),
148
+ linkedTaskIds,
149
+ };
150
+ }
151
+
152
+ export function tagControllerCreatedTasks(
153
+ taskIdsBeforeRun: Set<string>,
154
+ controllerRunId: string,
155
+ sessionKey: string,
156
+ deps: ControllerTaskDomainDeps,
157
+ ): string[] {
158
+ const normalizedSessionKey = normalizeControllerIntakeSessionKey(sessionKey);
159
+ const taggedTaskIds: string[] = [];
160
+ deps.updateTeamState((state) => {
161
+ for (const task of Object.values(state.tasks)) {
162
+ if (taskIdsBeforeRun.has(task.id)) {
163
+ continue;
164
+ }
165
+ if (task.createdBy !== "controller") {
166
+ continue;
167
+ }
168
+ task.controllerRunId = controllerRunId;
169
+ if (!task.controllerSessionKey) {
170
+ task.controllerSessionKey = normalizedSessionKey;
171
+ }
172
+ if (normalizeControllerIntakeSessionKey(task.controllerSessionKey) !== normalizedSessionKey) {
173
+ continue;
174
+ }
175
+ taggedTaskIds.push(task.id);
176
+ }
177
+ });
178
+ return taggedTaskIds;
179
+ }
180
+
181
+ export function resolveControllerWorkflowSessionKey(task: TaskInfo, state: TeamState | null): string | undefined {
182
+ if (task.controllerSessionKey) {
183
+ return normalizeControllerIntakeSessionKey(task.controllerSessionKey);
184
+ }
185
+ if (!state || task.createdBy !== "controller") {
186
+ return undefined;
187
+ }
188
+
189
+ const sortedRuns = Object.values(state.controllerRuns)
190
+ .sort((left, right) => right.updatedAt - left.updatedAt);
191
+
192
+ const directRun = sortedRuns.find((run) =>
193
+ run.sourceTaskId === task.id || run.createdTaskIds.includes(task.id),
194
+ );
195
+ if (directRun) {
196
+ return normalizeControllerIntakeSessionKey(directRun.sessionKey);
197
+ }
198
+
199
+ const manifestRun = sortedRuns.find((run) =>
200
+ run.manifest?.createdTasks.some((manifestTask) => taskMatchesManifestCreatedTask(task, manifestTask)),
201
+ );
202
+ return manifestRun ? normalizeControllerIntakeSessionKey(manifestRun.sessionKey) : undefined;
203
+ }
204
+
205
+ export function buildControllerManifestEventMessage(manifest: ControllerOrchestrationManifest): string {
206
+ const parts = [
207
+ `Structured orchestration manifest recorded.`,
208
+ `roles=${manifest.requiredRoles.join(", ") || "none"}`,
209
+ `created=${manifest.createdTasks.length}`,
210
+ `deferred=${manifest.deferredTasks.length}`,
211
+ ];
212
+ if (manifest.clarificationsNeeded) {
213
+ parts.push(`clarifications=${manifest.clarificationQuestions.length}`);
214
+ }
215
+ if (manifest.requirementFullyComplete) {
216
+ parts.push("requirementFullyComplete=true");
217
+ }
218
+ return parts.join(" ");
219
+ }
220
+
221
+ export function buildControllerManifestReply(
222
+ manifest: ControllerOrchestrationManifest | undefined,
223
+ createdTaskIds: string[],
224
+ state: TeamState | null,
225
+ fallbackReply: string,
226
+ ): string {
227
+ if (!manifest) {
228
+ const warning = "Warning: controller did not submit a structured orchestration manifest for this run.";
229
+ return fallbackReply ? `${fallbackReply}\n\n${warning}` : warning;
230
+ }
231
+
232
+ const actualCreatedTasks = createdTaskIds
233
+ .map((taskId) => state?.tasks?.[taskId])
234
+ .filter((task): task is TaskInfo => !!task);
235
+
236
+ const lines: string[] = [
237
+ `Requirement summary: ${manifest.requirementSummary}`,
238
+ `Required roles: ${manifest.requiredRoles.join(", ") || "none"}`,
239
+ ];
240
+
241
+ if (actualCreatedTasks.length > 0) {
242
+ lines.push("", "Created execution-ready tasks:");
243
+ for (const task of actualCreatedTasks) {
244
+ const roleLabel = task.assignedRole ? ` (${task.assignedRole})` : "";
245
+ lines.push(`- [${task.id}] ${task.title}${roleLabel}`);
246
+ }
247
+ } else if (manifest.createdTasks.length > 0) {
248
+ lines.push("", "Manifest planned created tasks:");
249
+ for (const task of manifest.createdTasks) {
250
+ const roleLabel = task.assignedRole ? ` (${task.assignedRole})` : "";
251
+ lines.push(`- ${task.title}${roleLabel}: ${task.expectedOutcome}`);
252
+ }
253
+ } else {
254
+ lines.push("", "Created execution-ready tasks: none.");
255
+ }
256
+
257
+ if (manifest.deferredTasks.length > 0) {
258
+ lines.push("", "Deferred tasks:");
259
+ for (const task of manifest.deferredTasks) {
260
+ const roleLabel = task.assignedRole ? ` (${task.assignedRole})` : "";
261
+ lines.push(`- ${task.title}${roleLabel}: blocked by ${task.blockedBy}; create when ${task.whenReady}`);
262
+ }
263
+ }
264
+
265
+ if (manifest.clarificationsNeeded) {
266
+ lines.push("", "Clarifications needed:");
267
+ for (const question of manifest.clarificationQuestions) {
268
+ lines.push(`- ${question}`);
269
+ }
270
+ }
271
+
272
+ // ── Team Kickoff Meeting (brief note; full details rendered in UI) ───
273
+ if (manifest.kickoffPlan?.assessments?.length) {
274
+ const kp = manifest.kickoffPlan;
275
+ const needed = kp.assessments.filter((a) => a.needed).length;
276
+ lines.push(
277
+ "",
278
+ `Team Kickoff Meeting: ${kp.assessments.length} roles assessed, ${needed} confirmed needed. See the Kickoff Meeting panel in the dashboard for full discussion details.`,
279
+ );
280
+ }
281
+
282
+ if (manifest.handoffPlan) {
283
+ lines.push("", `Handoff plan: ${manifest.handoffPlan}`);
284
+ }
285
+ if (manifest.notes) {
286
+ lines.push("", `Notes: ${manifest.notes}`);
287
+ }
288
+ if (manifest.createdTasks.length !== createdTaskIds.length) {
289
+ lines.push(
290
+ "",
291
+ `Warning: manifest declared ${manifest.createdTasks.length} created task(s), but TeamClaw recorded ${createdTaskIds.length}.`,
292
+ );
293
+ }
294
+
295
+ return lines.join("\n");
296
+ }
297
+
298
+ export function summarizeManifestExpectedOutcome(task: TaskInfo): string {
299
+ const raw = task.result || task.progress || task.description || "";
300
+ const normalized = raw.replace(/\s+/g, " ").trim();
301
+ if (!normalized) {
302
+ return "Produce the concrete deliverable described by this task and report the result back to the controller.";
303
+ }
304
+ if (normalized.length <= 180) {
305
+ return normalized;
306
+ }
307
+ return `${normalized.slice(0, 180).trimEnd()}…`;
308
+ }
309
+
310
+ export function inferManifestRolesFromText(text: string): RoleId[] {
311
+ const normalized = text.toLowerCase();
312
+ const roleIds: RoleId[] = [];
313
+ for (const role of getActiveRoles()) {
314
+ if (normalized.includes(role.id) || normalized.includes(role.label.toLowerCase())) {
315
+ roleIds.push(role.id);
316
+ }
317
+ }
318
+ return roleIds;
319
+ }
320
+
321
+ export function inferClarificationQuestionsFromReply(text: string): string[] {
322
+ const candidates = text
323
+ .split(/\n+/)
324
+ .map((line) => line.trim())
325
+ .filter((line) => line.includes("?"))
326
+ .map((line) => line.replace(/^[-*]\s*/, ""))
327
+ .filter(Boolean);
328
+ return Array.from(new Set(candidates)).slice(0, 5);
329
+ }
330
+
331
+ export function buildBackfilledControllerManifest(
332
+ request: string,
333
+ rawReply: string,
334
+ createdTaskIds: string[],
335
+ state: TeamState | null,
336
+ ): ControllerOrchestrationManifest {
337
+ const actualCreatedTasks = createdTaskIds
338
+ .map((taskId) => state?.tasks?.[taskId])
339
+ .filter((task): task is TaskInfo => !!task);
340
+ const inferredRoles = new Set<RoleId>();
341
+ for (const task of actualCreatedTasks) {
342
+ if (task.assignedRole) {
343
+ inferredRoles.add(task.assignedRole);
344
+ }
345
+ }
346
+ for (const roleId of inferManifestRolesFromText(rawReply)) {
347
+ inferredRoles.add(roleId);
348
+ }
349
+ for (const roleId of inferManifestRolesFromText(request)) {
350
+ inferredRoles.add(roleId);
351
+ }
352
+ // When no roles could be inferred at all, default the first-pass requirement analysis
353
+ // to architect rather than developer. This keeps repository analysis, feasibility
354
+ // assessment, and technical decomposition out of implementation-only developer tasks.
355
+ if (inferredRoles.size === 0) {
356
+ inferredRoles.add("architect");
357
+ }
358
+ const clarificationQuestions = inferClarificationQuestionsFromReply(rawReply);
359
+ return {
360
+ version: "1.0",
361
+ projectName: actualCreatedTasks.find((task) => task.projectId)?.projectId,
362
+ requirementSummary: request.replace(/\s+/g, " ").trim() || "Controller requirement summary unavailable.",
363
+ requiredRoles: Array.from(inferredRoles),
364
+ clarificationsNeeded: clarificationQuestions.length > 0 && actualCreatedTasks.length === 0,
365
+ clarificationQuestions,
366
+ clarificationSchemas: clarificationQuestions.map((question) => ({
367
+ kind: "text",
368
+ title: question,
369
+ required: true,
370
+ placeholder: "Provide the missing information",
371
+ })),
372
+ createdTasks: actualCreatedTasks.map((task) => ({
373
+ title: task.title,
374
+ assignedRole: task.assignedRole,
375
+ expectedOutcome: summarizeManifestExpectedOutcome(task),
376
+ })),
377
+ deferredTasks: [],
378
+ handoffPlan: actualCreatedTasks.length > 0
379
+ ? "Assigned workers should complete the created execution-ready tasks, report progress, and let the controller schedule downstream work after prerequisites are satisfied."
380
+ : undefined,
381
+ notes: "Backfilled by the controller because the model did not submit the required structured manifest.",
382
+ };
383
+ }
384
+
385
+ export function looksLikeSoftwareRequirement(request: string): boolean {
386
+ const normalized = request.toLowerCase();
387
+ return /(api|backend|frontend|fastapi|react|vue|node|python|typescript|javascript|sql|database|service|app|web|mobile|docker|kubernetes|deploy|stderr|stdout|logging|logger|log file|config|yaml|json|cli|command|build|test|compile|bug|fix|output|file|repo|repository|code|测试|系统|平台|接口|服务|数据库|应用|前端|后端|日志|输出|文件|配置|命令|编译|构建|修复|代码|仓库)/.test(normalized);
388
+ }
389
+
390
+ export function looksLikeManualExecutionClarification(question: string): boolean {
391
+ const normalized = question.toLowerCase();
392
+ return /(请先|请运行|请执行|请重试|请重新编译|请复现|run\b|rerun\b|retry\b|rebuild\b|recompile\b|git pull\b|go build\b|npm test\b|pnpm test\b|yarn test\b|pytest\b|cargo test\b|是否仍然|does it still|still crash|still fail)/i.test(normalized);
393
+ }
394
+
395
+ export function extractExecutableFollowUpFromClarification(question: string): string | null {
396
+ const trimmed = String(question || "").trim();
397
+ if (!trimmed || !looksLikeManualExecutionClarification(trimmed)) {
398
+ return null;
399
+ }
400
+ const normalized = trimmed.replace(/\s+/g, " ").trim();
401
+ return [
402
+ "Continue the same requirement by executing the obvious validation or rebuild step yourself instead of asking the human to run it manually.",
403
+ `Requested follow-up verification: ${normalized}`,
404
+ "Run the needed build/test/repro steps inside the project workspace, inspect the real outcome, and then either fix the issue or report the verified blocker with concrete evidence.",
405
+ ].join("\n\n");
406
+ }
407
+
408
+ export function isArchitectureFirstRequirement(request: string): boolean {
409
+ const normalized = request.toLowerCase();
410
+ return /(analy[sz]e|analysis|assess|feasibility|architecture|architect|design|plan|decompose|migration|port|rewrite|refactor|audit|review|repo|repository|codebase|golang|go\b|typescript|可行性|评估|架构|设计|分析|拆分|迁移|移植|重写|审计|仓库|代码库)/.test(normalized);
411
+ }
412
+
413
+ export function chooseFallbackAssignedRole(manifest: ControllerOrchestrationManifest, request: string): RoleId {
414
+ const requiredRoles = manifest.requiredRoles;
415
+ const implementationLikeRequest = looksLikeSoftwareRequirement(request) && !isArchitectureFirstRequirement(request);
416
+ if (requiredRoles.length === 1 && requiredRoles[0] === "architect" && implementationLikeRequest) {
417
+ return "developer";
418
+ }
419
+ if (requiredRoles.length === 0) {
420
+ return isArchitectureFirstRequirement(request) ? "architect" : "developer";
421
+ }
422
+ if (isArchitectureFirstRequirement(request)) {
423
+ if (requiredRoles.includes("architect")) {
424
+ return "architect";
425
+ }
426
+ if (requiredRoles.includes("pm")) {
427
+ return "pm";
428
+ }
429
+ }
430
+ if (requiredRoles.includes("developer") && requiredRoles.length === 1) {
431
+ return "developer";
432
+ }
433
+ return requiredRoles[0] ?? (isArchitectureFirstRequirement(request) ? "architect" : "developer");
434
+ }
435
+
436
+ export function buildFallbackControllerTaskTitle(request: string, assignedRole?: RoleId): string {
437
+ const firstMeaningfulLine = request
438
+ .split(/\n+/)
439
+ .map((line) => line.replace(/^#+\s*/, "").trim())
440
+ .find(Boolean);
441
+ if (firstMeaningfulLine) {
442
+ const normalized = firstMeaningfulLine.replace(/^需求[::]?\s*/, "").trim();
443
+ if (normalized.length > 0) {
444
+ const capped = normalized.slice(0, 72).trim();
445
+ return /[\u4e00-\u9fff]/.test(capped)
446
+ ? `实现${capped}`
447
+ : `Implement ${capped}`;
448
+ }
449
+ }
450
+ if (assignedRole === "architect") {
451
+ return "Analyze the repository and produce an architecture/feasibility plan";
452
+ }
453
+ return assignedRole === getActiveDefaultRole()
454
+ ? "Implement the requested software deliverable"
455
+ : `Perform the requested ${assignedRole || "software"} work`;
456
+ }
457
+
458
+ export function looksLikeSupplementalHumanContextUpdate(request: string): boolean {
459
+ const normalized = request.toLowerCase();
460
+ const hasEndpointOrCredentialHint = /(apikey|api key|token|credential|endpoint|base url|provider|model list|models接口|连接信息|兼容接口|供应商|可用模型)/i.test(request);
461
+ const urlCount = (request.match(/https?:\/\//gi) || []).length;
462
+ const looksLikeFreshImplementationAsk = /(implement|build|create|write|develop|fix|refactor|design|架构|设计|实现|开发|修复|重构|创建)/i.test(normalized);
463
+ return !looksLikeFreshImplementationAsk && (hasEndpointOrCredentialHint || urlCount >= 2);
464
+ }
465
+
466
+ export function getActiveTasksForSupplementalHumanContext(
467
+ controllerRunId: string,
468
+ sessionKey: string,
469
+ manifest: ControllerOrchestrationManifest,
470
+ state: TeamState | null,
471
+ ): TaskInfo[] {
472
+ const normalizedSessionKey = normalizeControllerIntakeSessionKey(sessionKey);
473
+ const runProjectDir = state?.controllerRuns?.[controllerRunId]?.projectDir;
474
+ const requiredRoles = new Set(manifest.requiredRoles);
475
+ return Object.values(state?.tasks ?? {})
476
+ .filter((task) => task.status === "assigned" || task.status === "in_progress" || task.status === "review")
477
+ .filter((task) => normalizeControllerIntakeSessionKey(task.controllerSessionKey) === normalizedSessionKey)
478
+ .filter((task) => !runProjectDir || task.projectDir === runProjectDir)
479
+ .filter((task) => requiredRoles.size === 0 || (task.assignedRole ? requiredRoles.has(task.assignedRole) : false))
480
+ .sort((left, right) => {
481
+ const leftScore = left.status === "in_progress" ? 2 : left.status === "assigned" ? 1 : 0;
482
+ const rightScore = right.status === "in_progress" ? 2 : right.status === "assigned" ? 1 : 0;
483
+ if (leftScore !== rightScore) {
484
+ return rightScore - leftScore;
485
+ }
486
+ return right.updatedAt - left.updatedAt;
487
+ });
488
+ }
489
+
490
+ export async function forwardSupplementalHumanContextToActiveTasks(
491
+ controllerRunId: string,
492
+ sessionKey: string,
493
+ request: string,
494
+ manifest: ControllerOrchestrationManifest,
495
+ deps: ControllerTaskDomainDeps,
496
+ ): Promise<string[]> {
497
+ if (!looksLikeSupplementalHumanContextUpdate(request)) {
498
+ return [];
499
+ }
500
+ const state = deps.getTeamState();
501
+ const targetTasks = getActiveTasksForSupplementalHumanContext(controllerRunId, sessionKey, manifest, state);
502
+ if (targetTasks.length === 0) {
503
+ return [];
504
+ }
505
+
506
+ const createdAt = Date.now();
507
+ const messages: TeamMessage[] = targetTasks.map((task) => ({
508
+ id: generateId(),
509
+ from: "human-intake",
510
+ to: task.assignedWorkerId,
511
+ toRole: task.assignedRole,
512
+ type: "direct",
513
+ content: request,
514
+ contract: ensureTeamMessageContract(null, {
515
+ type: "direct",
516
+ content: request,
517
+ toRole: task.assignedRole,
518
+ taskId: task.id,
519
+ intent: "update",
520
+ needsResponse: false,
521
+ }),
522
+ taskId: task.id,
523
+ createdAt,
524
+ }));
525
+
526
+ deps.updateTeamState((teamState) => {
527
+ teamState.messages.push(...messages);
528
+ });
529
+
530
+ for (const message of messages) {
531
+ recordTaskExecutionEvent(message.taskId!, {
532
+ type: "progress",
533
+ phase: "human_context_forwarded",
534
+ source: "controller",
535
+ status: "running",
536
+ message: "Human provided supplemental context for this task. Review task messages for the new details.",
537
+ }, deps);
538
+ deps.wsServer.broadcastUpdate({ type: "message:new", data: message });
539
+ if (message.to) {
540
+ const worker = deps.getTeamState()?.workers?.[message.to];
541
+ if (worker && worker.status !== "offline") {
542
+ try {
543
+ await deliverMessageToWorker(worker, message, deps);
544
+ } catch (err) {
545
+ deps.logger.warn(`Controller: failed to forward supplemental context to ${worker.id}: ${String(err)}`);
546
+ }
547
+ }
548
+ }
549
+ }
550
+
551
+ manifest.notes = manifest.notes
552
+ ? `${manifest.notes} TeamClaw forwarded this human intake as supplemental context to active task(s): ${targetTasks.map((task) => task.id).join(", ")}.`
553
+ : `TeamClaw forwarded this human intake as supplemental context to active task(s): ${targetTasks.map((task) => task.id).join(", ")}.`;
554
+ updateControllerRun(controllerRunId, deps, (run) => {
555
+ run.manifest = manifest;
556
+ appendControllerRunEvent(run, {
557
+ type: "warning",
558
+ phase: "context_forwarded",
559
+ source: "controller",
560
+ status: "running",
561
+ sessionKey,
562
+ message: `Forwarded supplemental human context to active task(s): ${targetTasks.map((task) => task.id).join(", ")}`,
563
+ });
564
+ });
565
+ return targetTasks.map((task) => task.id);
566
+ }
567
+
568
+ export async function createControllerManagedTask(
569
+ input: {
570
+ title: string;
571
+ description: string;
572
+ priority?: TaskPriority;
573
+ assignedRole?: RoleId;
574
+ createdBy: string;
575
+ controllerRunId?: string;
576
+ controllerSessionKey?: string;
577
+ projectName?: string;
578
+ recommendedSkills?: string[];
579
+ },
580
+ deps: ControllerTaskDomainDeps,
581
+ ): Promise<TaskInfo | undefined> {
582
+ const taskId = generateId();
583
+ const now = Date.now();
584
+ const repoState = await refreshControllerRepoState(deps);
585
+ const normalizedSessionKey = input.createdBy === "controller" && input.controllerSessionKey
586
+ ? normalizeControllerIntakeSessionKey(input.controllerSessionKey)
587
+ : undefined;
588
+
589
+ const inheritedProject = normalizedSessionKey
590
+ ? resolveProjectIdentityForSession(normalizedSessionKey, deps.getTeamState())
591
+ : undefined;
592
+ const explicitProjectId = deriveStableProjectKey(input.projectName ?? "");
593
+ const projectId = inheritedProject?.projectId ?? (explicitProjectId || undefined);
594
+ const projectDir = inheritedProject?.projectDir ?? projectId ?? deriveProjectSlug(input.title);
595
+
596
+ const normalizedRecommendedSkills = normalizeRecommendedSkills(input.recommendedSkills ?? []);
597
+ const task: TaskInfo = {
598
+ id: taskId,
599
+ title: input.title,
600
+ description: input.description,
601
+ status: "pending",
602
+ priority: input.priority ?? "medium",
603
+ assignedRole: input.assignedRole,
604
+ createdBy: input.createdBy,
605
+ recommendedSkills: normalizedRecommendedSkills.length > 0 ? normalizedRecommendedSkills : undefined,
606
+ controllerRunId: input.createdBy === "controller" ? input.controllerRunId : undefined,
607
+ controllerSessionKey: normalizedSessionKey,
608
+ projectId,
609
+ projectDir,
610
+ createdAt: now,
611
+ updatedAt: now,
612
+ };
613
+
614
+ deps.updateTeamState((state) => {
615
+ const project = syncProjectRegistryEntry(state, {
616
+ projectId: task.projectId,
617
+ projectDir: task.projectDir,
618
+ aliases: [input.projectName, task.projectId],
619
+ summary: task.title,
620
+ updatedAt: now,
621
+ });
622
+ task.projectId = project.projectId;
623
+ task.projectDir = project.projectDir;
624
+ state.tasks[taskId] = task;
625
+ });
626
+ recordTaskExecutionEvent(taskId, {
627
+ type: "lifecycle",
628
+ phase: "created",
629
+ source: "controller",
630
+ status: "pending",
631
+ message: `Task created by ${input.createdBy}.`,
632
+ role: input.assignedRole,
633
+ }, deps);
634
+ if (repoState?.enabled) {
635
+ recordTaskExecutionEvent(taskId, {
636
+ type: "lifecycle",
637
+ phase: "repo_ready",
638
+ source: "controller",
639
+ status: "pending",
640
+ message: repoState.remoteReady && repoState.remoteUrl
641
+ ? `Git collaboration ready on ${repoState.defaultBranch} with remote ${repoState.remoteUrl}.`
642
+ : `Git collaboration ready on ${repoState.defaultBranch} using controller-managed bundle sync.`,
643
+ role: input.assignedRole,
644
+ }, deps);
645
+ }
646
+ if (normalizedRecommendedSkills.length > 0) {
647
+ recordTaskExecutionEvent(taskId, {
648
+ type: "lifecycle",
649
+ phase: "skills_recommended",
650
+ source: "controller",
651
+ status: "pending",
652
+ message: `Recommended skills: ${normalizedRecommendedSkills.join(", ")}`,
653
+ role: input.assignedRole,
654
+ }, deps);
655
+ }
656
+
657
+ await autoAssignPendingTasks(deps);
658
+
659
+ const updatedTask = deps.getTeamState()?.tasks[taskId];
660
+ deps.wsServer.broadcastUpdate({ type: "task:created", data: serializeTask(updatedTask) });
661
+ return updatedTask;
662
+ }
663
+
664
+ export async function maybeBackfillExecutionReadyTask(
665
+ controllerRunId: string,
666
+ sessionKey: string,
667
+ request: string,
668
+ manifest: ControllerOrchestrationManifest,
669
+ deps: ControllerTaskDomainDeps,
670
+ options?: {
671
+ source?: ControllerRunSource;
672
+ },
673
+ ): Promise<string[]> {
674
+ if (manifest.createdTasks.length > 0 || manifest.clarificationsNeeded || manifest.requirementFullyComplete) {
675
+ return [];
676
+ }
677
+ if (options?.source === "task_follow_up") {
678
+ return [];
679
+ }
680
+ const likelyTechnicalRequest = looksLikeSoftwareRequirement(request)
681
+ || manifest.requiredRoles.length > 0
682
+ || /code|repo|repository|日志|输出|文件|配置|命令|修复|实现|修改/.test(request.toLowerCase());
683
+ if (!likelyTechnicalRequest) {
684
+ return [];
685
+ }
686
+ const forwardedTaskIds = await forwardSupplementalHumanContextToActiveTasks(
687
+ controllerRunId,
688
+ sessionKey,
689
+ request,
690
+ manifest,
691
+ deps,
692
+ );
693
+ if (forwardedTaskIds.length > 0) {
694
+ return [];
695
+ }
696
+
697
+ const assignedRole = chooseFallbackAssignedRole(manifest, request);
698
+ const task = await createControllerManagedTask({
699
+ title: buildFallbackControllerTaskTitle(request, assignedRole),
700
+ description: request,
701
+ assignedRole,
702
+ createdBy: "controller",
703
+ controllerRunId,
704
+ controllerSessionKey: sessionKey,
705
+ recommendedSkills: resolveActiveRoleSkills(assignedRole, []),
706
+ }, deps);
707
+ if (!task) {
708
+ return [];
709
+ }
710
+
711
+ manifest.createdTasks = [{
712
+ title: task.title,
713
+ assignedRole: task.assignedRole,
714
+ expectedOutcome: summarizeManifestExpectedOutcome(task),
715
+ }];
716
+ manifest.notes = manifest.notes
717
+ ? `${manifest.notes} Controller synthesized a fallback execution-ready task because the model returned no created tasks.`
718
+ : "Controller synthesized a fallback execution-ready task because the model returned no created tasks.";
719
+ updateControllerRun(controllerRunId, deps, (run) => {
720
+ run.manifest = manifest;
721
+ appendControllerRunEvent(run, {
722
+ type: "warning",
723
+ phase: "task_backfilled",
724
+ source: "controller",
725
+ status: "running",
726
+ sessionKey,
727
+ message: `Controller synthesized fallback task ${task.id} (${task.assignedRole || "unassigned"}).`,
728
+ });
729
+ });
730
+ return [task.id];
731
+ }
732
+
733
+ export function ensureControllerManifest(
734
+ controllerRunId: string,
735
+ sessionKey: string,
736
+ request: string,
737
+ rawReply: string,
738
+ createdTaskIds: string[],
739
+ deps: ControllerTaskDomainDeps,
740
+ ): ControllerOrchestrationManifest {
741
+ const currentState = deps.getTeamState();
742
+ const existingManifest = currentState?.controllerRuns?.[controllerRunId]?.manifest;
743
+ if (existingManifest) {
744
+ return existingManifest;
745
+ }
746
+
747
+ const manifest = buildBackfilledControllerManifest(request, rawReply, createdTaskIds, currentState);
748
+ updateControllerRun(controllerRunId, deps, (run) => {
749
+ run.manifest = manifest;
750
+ appendControllerRunEvent(run, {
751
+ type: "warning",
752
+ phase: "manifest_backfilled",
753
+ source: "controller",
754
+ status: "running",
755
+ sessionKey,
756
+ message: "Controller did not submit a structured manifest; TeamClaw backfilled a minimal manifest from the recorded run state.",
757
+ });
758
+ });
759
+ return manifest;
760
+ }
761
+
762
+ export function buildControllerFollowUpMessage(task: TaskInfo, state: TeamState | null): string {
763
+ const parts = [
764
+ `A controller-created TeamClaw task has ${task.status === "failed" ? "failed" : "completed"}.`,
765
+ `Task ID: ${task.id}`,
766
+ `Title: ${task.title}`,
767
+ task.assignedRole ? `Role: ${task.assignedRole}` : "",
768
+ "",
769
+ "## Original Task",
770
+ task.description || "No task description was recorded.",
771
+ ];
772
+
773
+ if (task.result) {
774
+ parts.push("", "## Task Result", task.result);
775
+ }
776
+ const resultContractSection = buildResultContractSection(task);
777
+ if (resultContractSection) {
778
+ parts.push("", resultContractSection);
779
+ }
780
+ if (task.error) {
781
+ parts.push("", "## Task Error", task.error);
782
+ }
783
+
784
+ // Include preview URLs so the controller can present them to the human
785
+ if (task.resultContract?.deliverables) {
786
+ const liveDeliverables = task.resultContract.deliverables.filter((d) => d.liveUrl);
787
+ if (liveDeliverables.length > 0) {
788
+ parts.push("", "## Live Previews");
789
+ for (const d of liveDeliverables) {
790
+ parts.push(`- ${d.summary || d.value}: ${d.liveUrl}`);
791
+ }
792
+ }
793
+ }
794
+
795
+ // Inject prior manifest context (deferred tasks, clarification questions) so the
796
+ // controller knows the original plan and can advance it
797
+ if (state) {
798
+ const sessionKey = task.controllerSessionKey;
799
+ if (sessionKey) {
800
+ const priorRuns = Object.values(state.controllerRuns)
801
+ .filter((run) => normalizeControllerIntakeSessionKey(run.sessionKey) === normalizeControllerIntakeSessionKey(sessionKey) && run.manifest)
802
+ .sort((a, b) => b.updatedAt - a.updatedAt);
803
+
804
+ // Collect deferred tasks from the latest manifest that had them
805
+ const latestWithDeferred = priorRuns.find((run) => run.manifest!.deferredTasks && run.manifest!.deferredTasks.length > 0);
806
+ if (latestWithDeferred?.manifest?.deferredTasks) {
807
+ parts.push("", "## Prior Orchestration Plan (Deferred Tasks)");
808
+ parts.push("These tasks were identified in the original plan but deferred until prerequisites were met:");
809
+ for (const dt of latestWithDeferred.manifest.deferredTasks) {
810
+ const blockedBy = dt.blockedBy ? ` [blocked by: ${dt.blockedBy}]` : "";
811
+ parts.push(`- ${dt.title} (${dt.assignedRole || "any"})${blockedBy}`);
812
+ }
813
+ }
814
+
815
+ // Collect only still-pending clarification questions for this session.
816
+ const pendingClarifications = Object.values(state.clarifications)
817
+ .filter((clarification) =>
818
+ clarification.status === "pending"
819
+ && normalizeControllerIntakeSessionKey(clarification.controllerSessionKey) === normalizeControllerIntakeSessionKey(sessionKey),
820
+ )
821
+ .sort((a, b) => b.updatedAt - a.updatedAt);
822
+ const priorQuestions = pendingClarifications
823
+ .map((clarification) => clarification.question)
824
+ .filter(Boolean);
825
+ if (priorQuestions.length > 0) {
826
+ parts.push("", "## Prior Clarification Questions (from earlier runs)");
827
+ for (const q of priorQuestions.slice(0, 5)) {
828
+ parts.push(`- ${q}`);
829
+ }
830
+ }
831
+ }
832
+ }
833
+
834
+ parts.push(
835
+ "",
836
+ "## Controller Follow-up",
837
+ "Continue orchestrating this same requirement.",
838
+ "Review the current TeamClaw state before acting.",
839
+ "Create only the next execution-ready task(s) whose prerequisites are now satisfied.",
840
+ "For any large-scale requirement, prefer parallel fan-out over serial mega-phases: if multiple independent developer workstreams are ready, create all of them now instead of a single umbrella developer task.",
841
+ "Decompose developer work by module or subsystem with clear file ownership and interfaces so multiple developer workers can collaborate safely in parallel.",
842
+ "Use TeamClaw's available same-role capacity: create multiple developer tasks when the work can proceed concurrently rather than forcing one developer to carry the whole rewrite alone.",
843
+ "Do not duplicate tasks that already exist, are active, or are already completed.",
844
+ "If this task produced a web application with a live preview URL, include it in your reply so the human can verify the result.",
845
+ "If all planned phases are complete and no follow-ups remain, set requirementFullyComplete=true in the manifest and provide a final delivery summary.",
846
+ "If no additional task should be created yet, reply briefly and stop.",
847
+ );
848
+
849
+ return parts.filter(Boolean).join("\n");
850
+ }
851
+
852
+ export function buildControllerParallelHelpMessage(
853
+ task: TaskInfo,
854
+ state: TeamState | null,
855
+ input: {
856
+ requestedBy: string;
857
+ requestedByRole?: RoleId;
858
+ targetRole?: RoleId;
859
+ reason: string;
860
+ requestedWorkerCount?: number;
861
+ suggestedWorkstreams: string[];
862
+ },
863
+ ): string {
864
+ const targetRole = input.targetRole || input.requestedByRole || task.assignedRole || "developer";
865
+ return [
866
+ buildControllerFollowUpMessage(task, state),
867
+ "",
868
+ "## Parallel Help Request",
869
+ `Current worker ${input.requestedBy} has asked TeamClaw to expand parallel help for role ${targetRole}.`,
870
+ input.requestedByRole ? `Requesting worker role: ${input.requestedByRole}` : "",
871
+ typeof input.requestedWorkerCount === "number"
872
+ ? `Desired same-role worker capacity for this requirement: ${input.requestedWorkerCount}`
873
+ : "",
874
+ `Why more parallel help is needed: ${input.reason}`,
875
+ input.suggestedWorkstreams.length > 0
876
+ ? `Suggested parallel workstreams:\n${input.suggestedWorkstreams.map((item) => `- ${item}`).join("\n")}`
877
+ : "",
878
+ "If the suggested workstreams are genuinely independent, create multiple execution-ready tasks for that role now instead of keeping one giant serial task.",
879
+ "Reuse active tasks when possible, but if no matching tasks already exist, fan out the work into distinct module- or subsystem-scoped tasks that can run concurrently.",
880
+ ].filter(Boolean).join("\n");
881
+ }
882
+
883
+ export async function maybeConvertControllerClarificationToExecutionTask(
884
+ controllerRunId: string,
885
+ sessionKey: string,
886
+ manifest: ControllerOrchestrationManifest,
887
+ deps: ControllerTaskDomainDeps,
888
+ ): Promise<string[]> {
889
+ const candidateQuestion = (manifest.clarificationQuestions || []).find((entry) => looksLikeManualExecutionClarification(entry));
890
+ const followUpDescription = candidateQuestion ? extractExecutableFollowUpFromClarification(candidateQuestion) : null;
891
+ if (!candidateQuestion || !followUpDescription) {
892
+ return [];
893
+ }
894
+
895
+ const assignedRole = chooseFallbackAssignedRole(manifest, followUpDescription);
896
+ const task = await createControllerManagedTask({
897
+ title: buildFallbackControllerTaskTitle(candidateQuestion, assignedRole),
898
+ description: followUpDescription,
899
+ assignedRole,
900
+ createdBy: "controller",
901
+ controllerRunId,
902
+ controllerSessionKey: sessionKey,
903
+ recommendedSkills: resolveActiveRoleSkills(assignedRole, []),
904
+ }, deps);
905
+ if (!task) {
906
+ return [];
907
+ }
908
+
909
+ manifest.createdTasks = [{
910
+ title: task.title,
911
+ assignedRole: task.assignedRole,
912
+ expectedOutcome: summarizeManifestExpectedOutcome(task),
913
+ }];
914
+ manifest.clarificationsNeeded = false;
915
+ manifest.clarificationQuestions = manifest.clarificationQuestions.filter((entry) => entry !== candidateQuestion);
916
+ if (Array.isArray(manifest.clarificationSchemas)) {
917
+ manifest.clarificationSchemas = manifest.clarificationSchemas.filter((schema) => schema.title !== candidateQuestion);
918
+ }
919
+ manifest.notes = manifest.notes
920
+ ? `${manifest.notes} TeamClaw converted a manual-action clarification into execution task ${task.id} so the team can perform the validation itself.`
921
+ : `TeamClaw converted a manual-action clarification into execution task ${task.id} so the team can perform the validation itself.`;
922
+ updateControllerRun(controllerRunId, deps, (run) => {
923
+ run.manifest = manifest;
924
+ appendControllerRunEvent(run, {
925
+ type: "warning",
926
+ phase: "clarification_converted_to_task",
927
+ source: "controller",
928
+ status: "running",
929
+ sessionKey,
930
+ message: `Controller converted a manual-action clarification into execution task ${task.id}.`,
931
+ });
932
+ });
933
+ return [task.id];
934
+ }
935
+
936
+ export async function checkAndGenerateReport(task: TaskInfo, deps: ControllerTaskDomainDeps): Promise<void> {
937
+ const sessionKey = task.controllerSessionKey;
938
+ if (!sessionKey) return;
939
+
940
+ const state = deps.getTeamState();
941
+ if (!state) return;
942
+
943
+ if (!isSessionComplete(sessionKey, state, normalizeControllerIntakeSessionKey)) return;
944
+
945
+ const report = generateDeliveryReport(sessionKey, state, normalizeControllerIntakeSessionKey);
946
+ if (!report) return;
947
+
948
+ // Check if we already generated a report for this session
949
+ const existingReport = state.reports?.[report.id];
950
+ if (existingReport) return;
951
+
952
+ // Store a lightweight record in state (full report is generated on demand from live state)
953
+ deps.updateTeamState((s) => {
954
+ if (!s.reports) s.reports = {};
955
+ s.reports[report.id] = {
956
+ id: report.id,
957
+ sessionKey: report.sessionKey,
958
+ generatedAt: report.generatedAt,
959
+ projectName: report.projectName,
960
+ requirementSummary: report.requirementSummary,
961
+ status: report.status,
962
+ taskCount: report.taskCount,
963
+ deliverableCount: report.deliverables.length,
964
+ previewCount: report.deliverables.filter((d) => d.previewUrl).length,
965
+ };
966
+ });
967
+
968
+ const reportUrl = `/api/v1/reports/${encodeURIComponent(sessionKey)}`;
969
+ deps.wsServer.broadcastUpdate({
970
+ type: "report:ready",
971
+ data: { sessionKey, reportUrl, projectName: report.projectName, status: report.status },
972
+ });
973
+ deps.logger.info(`Controller: delivery report generated for session ${sessionKey}: ${reportUrl}`);
974
+ }
975
+
976
+ export function buildResultContractSection(task: TaskInfo): string {
977
+ const contract = task.resultContract;
978
+ if (!contract) {
979
+ return "";
980
+ }
981
+
982
+ const lines = [
983
+ "## Structured Result Contract",
984
+ `Outcome: ${contract.outcome}`,
985
+ `Summary: ${contract.summary}`,
986
+ ];
987
+ if (contract.deliverables.length > 0) {
988
+ lines.push("Deliverables:");
989
+ for (const deliverable of contract.deliverables) {
990
+ const summary = deliverable.summary ? ` — ${deliverable.summary}` : "";
991
+ lines.push(`- ${deliverable.kind}: ${deliverable.value}${summary}`);
992
+ }
993
+ }
994
+ if (contract.keyPoints.length > 0) {
995
+ lines.push("Key points:");
996
+ for (const keyPoint of contract.keyPoints) {
997
+ lines.push(`- ${keyPoint}`);
998
+ }
999
+ }
1000
+ if (contract.blockers.length > 0) {
1001
+ lines.push("Blockers:");
1002
+ for (const blocker of contract.blockers) {
1003
+ lines.push(`- ${blocker}`);
1004
+ }
1005
+ }
1006
+ if (contract.followUps.length > 0) {
1007
+ lines.push("Suggested follow-ups:");
1008
+ for (const followUp of contract.followUps) {
1009
+ const roleLabel = followUp.targetRole ? ` (${followUp.targetRole})` : "";
1010
+ lines.push(`- ${followUp.type}${roleLabel}: ${followUp.reason}`);
1011
+ }
1012
+ }
1013
+ if (contract.questions.length > 0) {
1014
+ lines.push("Open questions:");
1015
+ for (const question of contract.questions) {
1016
+ lines.push(`- ${question}`);
1017
+ }
1018
+ }
1019
+ if (contract.notes) {
1020
+ lines.push(`Notes: ${contract.notes}`);
1021
+ }
1022
+ if (contract.discoveredPatterns && contract.discoveredPatterns.length > 0) {
1023
+ lines.push("Discovered patterns:");
1024
+ for (const pattern of contract.discoveredPatterns) {
1025
+ lines.push(`- ${pattern}`);
1026
+ }
1027
+ }
1028
+ return lines.join("\n");
1029
+ }