@teamclaws/teamclaw 2026.8.1 → 2026.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. package/cli.mjs +318 -17
  2. package/dist/index.js +54 -32
  3. package/dist/src/config.js +57 -2
  4. package/dist/src/controller/auth-routes.js +129 -0
  5. package/dist/src/controller/clarification-routes.js +315 -0
  6. package/dist/src/controller/controller-intake.js +895 -0
  7. package/dist/src/controller/controller-planning.js +814 -0
  8. package/dist/src/controller/controller-routes.js +195 -0
  9. package/dist/src/controller/controller-runs.js +175 -0
  10. package/dist/src/controller/controller-service.js +338 -50
  11. package/dist/src/controller/controller-tools.js +14 -7
  12. package/dist/src/controller/github-auth.js +2 -1
  13. package/dist/src/controller/http-server.js +290 -6003
  14. package/dist/src/controller/kickoff-orchestrator.js +33 -43
  15. package/dist/src/controller/message-delivery.js +31 -0
  16. package/dist/src/controller/message-routes.js +114 -0
  17. package/dist/src/controller/orchestration-manifest.js +11 -93
  18. package/dist/src/controller/preview-manager.js +51 -3
  19. package/dist/src/controller/preview-proxy.js +98 -0
  20. package/dist/src/controller/profile-switch.js +309 -0
  21. package/dist/src/controller/project-registry.js +294 -0
  22. package/dist/src/controller/prompt-injector.js +19 -9
  23. package/dist/src/controller/provisioning/backend-contract.js +9 -0
  24. package/dist/src/controller/provisioning/container-shared.js +64 -0
  25. package/dist/src/controller/provisioning/docker.js +214 -0
  26. package/dist/src/controller/provisioning/kubernetes.js +244 -0
  27. package/dist/src/controller/provisioning/plugin-root.js +41 -0
  28. package/dist/src/controller/provisioning/process-supervisor.js +190 -0
  29. package/dist/src/controller/provisioning-config.js +239 -0
  30. package/dist/src/controller/repo-routes.js +129 -0
  31. package/dist/src/controller/report-routes.js +56 -0
  32. package/dist/src/controller/role-inference.js +231 -20
  33. package/dist/src/controller/route-table.js +375 -0
  34. package/dist/src/controller/security.js +775 -0
  35. package/dist/src/controller/status-routes.js +287 -0
  36. package/dist/src/controller/task-assignment.js +511 -0
  37. package/dist/src/controller/task-cleanup.js +258 -0
  38. package/dist/src/controller/task-execution.js +271 -0
  39. package/dist/src/controller/task-results.js +471 -0
  40. package/dist/src/controller/task-router.js +74 -4
  41. package/dist/src/controller/task-routes.js +703 -0
  42. package/dist/src/controller/teamauto-routes.js +124 -0
  43. package/dist/src/controller/tunnel-manager.js +41 -8
  44. package/dist/src/controller/tunnel-routes.js +225 -0
  45. package/dist/src/controller/ui-assets.js +68 -0
  46. package/dist/src/controller/websocket.js +6 -2
  47. package/dist/src/controller/webui-routes.js +49 -0
  48. package/dist/src/controller/worker-provisioning.js +69 -953
  49. package/dist/src/controller/worker-routes.js +188 -0
  50. package/dist/src/controller/workflow-routes.js +407 -0
  51. package/dist/src/controller/workspace-routes.js +200 -0
  52. package/dist/src/git-collaboration.js +4 -9
  53. package/dist/src/identity.js +15 -3
  54. package/dist/src/interaction-contracts.js +7 -7
  55. package/dist/src/openclaw-workspace.js +40 -18
  56. package/dist/src/profile-loader.js +604 -0
  57. package/dist/src/profiles/banking.json +202 -0
  58. package/dist/src/profiles/crossborder-ecom.json +253 -0
  59. package/dist/src/profiles/insurance.json +157 -0
  60. package/dist/src/profiles/knowledge/hs-structure.md +97 -0
  61. package/dist/src/profiles/knowledge/incoterms-2020.md +188 -0
  62. package/dist/src/profiles/knowledge/vat-principles.md +85 -0
  63. package/dist/src/profiles/schema.json +281 -0
  64. package/dist/src/profiles/securities.json +137 -0
  65. package/dist/src/profiles/software-rd.json +264 -0
  66. package/dist/src/profiles/trading-co.json +200 -0
  67. package/dist/src/prompt-policy.js +42 -17
  68. package/dist/src/protocol.js +66 -3
  69. package/dist/src/role-ids.js +29 -0
  70. package/dist/src/roles.js +54 -13
  71. package/dist/src/session-roles.js +14 -0
  72. package/dist/src/shared/clarification-schema.js +65 -0
  73. package/dist/src/shared/github-auth.js +15 -0
  74. package/dist/src/shared/kickoff-prompt.js +37 -0
  75. package/dist/src/shared/utils.js +47 -0
  76. package/dist/src/state.js +275 -11
  77. package/dist/src/task-executor.js +7 -17
  78. package/dist/src/teamauto/github-client.js +18 -0
  79. package/dist/src/teamauto/repo-sync.js +228 -6
  80. package/dist/src/teamauto/scanner.js +40 -12
  81. package/dist/src/teamauto/scheduler.js +231 -12
  82. package/dist/src/types.js +77 -16
  83. package/dist/src/ui/app.js +1434 -82
  84. package/dist/src/ui/github-login.html +1 -0
  85. package/dist/src/ui/index.html +144 -45
  86. package/dist/src/ui/style.css +194 -0
  87. package/dist/src/worker/http-handler.js +59 -0
  88. package/dist/src/worker/prompt-injector.js +44 -8
  89. package/dist/src/worker/skill-installer.js +6 -10
  90. package/dist/src/worker/tools.js +20 -10
  91. package/dist/src/worker/worker-service.js +93 -7
  92. package/index.ts +61 -32
  93. package/openclaw.plugin.json +50 -2
  94. package/package.json +3 -2
  95. package/src/config.ts +57 -2
  96. package/src/controller/auth-routes.ts +157 -0
  97. package/src/controller/clarification-routes.ts +404 -0
  98. package/src/controller/controller-intake.ts +1113 -0
  99. package/src/controller/controller-planning.ts +1037 -0
  100. package/src/controller/controller-routes.ts +237 -0
  101. package/src/controller/controller-runs.ts +239 -0
  102. package/src/controller/controller-service.ts +422 -50
  103. package/src/controller/controller-tools.ts +16 -9
  104. package/src/controller/github-auth.ts +28 -63
  105. package/src/controller/http-server.ts +336 -6964
  106. package/src/controller/kickoff-orchestrator.ts +69 -45
  107. package/src/controller/message-delivery.ts +52 -0
  108. package/src/controller/message-routes.ts +137 -0
  109. package/src/controller/orchestration-manifest.ts +14 -100
  110. package/src/controller/preview-manager.ts +53 -3
  111. package/src/controller/preview-proxy.ts +127 -0
  112. package/src/controller/profile-switch.ts +396 -0
  113. package/src/controller/project-registry.ts +361 -0
  114. package/src/controller/prompt-injector.ts +23 -8
  115. package/src/controller/provisioning/backend-contract.ts +51 -0
  116. package/src/controller/provisioning/container-shared.ts +84 -0
  117. package/src/controller/provisioning/docker.ts +260 -0
  118. package/src/controller/provisioning/kubernetes.ts +263 -0
  119. package/src/controller/provisioning/plugin-root.ts +42 -0
  120. package/src/controller/provisioning/process-supervisor.ts +214 -0
  121. package/src/controller/provisioning-config.ts +289 -0
  122. package/src/controller/repo-routes.ts +163 -0
  123. package/src/controller/report-routes.ts +64 -0
  124. package/src/controller/role-inference.ts +260 -22
  125. package/src/controller/route-table.ts +597 -0
  126. package/src/controller/security.ts +899 -0
  127. package/src/controller/status-routes.ts +354 -0
  128. package/src/controller/task-assignment.ts +622 -0
  129. package/src/controller/task-cleanup.ts +344 -0
  130. package/src/controller/task-execution.ts +399 -0
  131. package/src/controller/task-results.ts +556 -0
  132. package/src/controller/task-router.ts +98 -6
  133. package/src/controller/task-routes.ts +812 -0
  134. package/src/controller/teamauto-routes.ts +121 -0
  135. package/src/controller/tunnel-manager.ts +45 -8
  136. package/src/controller/tunnel-routes.ts +231 -0
  137. package/src/controller/ui-assets.ts +70 -0
  138. package/src/controller/websocket.ts +32 -4
  139. package/src/controller/webui-routes.ts +55 -0
  140. package/src/controller/worker-provisioning.ts +83 -1121
  141. package/src/controller/worker-routes.ts +241 -0
  142. package/src/controller/workflow-routes.ts +498 -0
  143. package/src/controller/workspace-routes.ts +222 -0
  144. package/src/git-collaboration.ts +4 -9
  145. package/src/identity.ts +16 -3
  146. package/src/interaction-contracts.ts +7 -7
  147. package/src/openclaw-workspace.ts +44 -18
  148. package/src/profile-loader.ts +816 -0
  149. package/src/profiles/banking.json +202 -0
  150. package/src/profiles/crossborder-ecom.json +253 -0
  151. package/src/profiles/insurance.json +157 -0
  152. package/src/profiles/knowledge/hs-structure.md +97 -0
  153. package/src/profiles/knowledge/incoterms-2020.md +188 -0
  154. package/src/profiles/knowledge/vat-principles.md +85 -0
  155. package/src/profiles/schema.json +281 -0
  156. package/src/profiles/securities.json +137 -0
  157. package/src/profiles/software-rd.json +264 -0
  158. package/src/profiles/trading-co.json +200 -0
  159. package/src/prompt-policy.ts +44 -17
  160. package/src/protocol.ts +72 -2
  161. package/src/role-ids.ts +31 -0
  162. package/src/roles.ts +60 -14
  163. package/src/session-roles.ts +14 -0
  164. package/src/shared/clarification-schema.ts +81 -0
  165. package/src/shared/github-auth.ts +92 -0
  166. package/src/shared/kickoff-prompt.ts +47 -0
  167. package/src/shared/utils.ts +51 -0
  168. package/src/state.ts +326 -10
  169. package/src/task-executor.ts +7 -18
  170. package/src/teamauto/github-client.ts +23 -1
  171. package/src/teamauto/repo-sync.ts +248 -7
  172. package/src/teamauto/scanner.ts +47 -13
  173. package/src/teamauto/scheduler.ts +261 -17
  174. package/src/teamauto/store.ts +12 -0
  175. package/src/types.ts +263 -17
  176. package/src/ui/app.js +1434 -82
  177. package/src/ui/github-login.html +1 -0
  178. package/src/ui/index.html +144 -45
  179. package/src/ui/style.css +194 -0
  180. package/src/worker/http-handler.ts +64 -1
  181. package/src/worker/prompt-injector.ts +48 -8
  182. package/src/worker/skill-installer.ts +6 -10
  183. package/src/worker/tools.ts +21 -10
  184. package/src/worker/worker-service.ts +101 -7
@@ -0,0 +1,471 @@
1
+ // PR-C of issue #204 (http-server monolith split): the task result domain -
2
+ // result application (worker release, managed-worker retirement, workflow
3
+ // continuation), stale-deliverable filtering, filesystem HTML enrichment,
4
+ // the meaningful-project-change completion gate, result-contract
5
+ // backfill/effective-contract synthesis, and discovered-patterns
6
+ // consolidation - extracted verbatim from controller/http-server.ts. Zero
7
+ // behavior change. This module must NEVER import http-server (the reverse
8
+ // edge exists: http-server -> task-results).
9
+ import fs from "node:fs";
10
+ import path from "node:path";
11
+ import { execFileSync } from "node:child_process";
12
+ import { backfillWorkerTaskResultContract, enrichDeliverablesWithPreviewInference, } from "../interaction-contracts.js";
13
+ import { resolveTeamClawAgentWorkspaceRootDir, resolveTeamClawProjectsDir, resolveTeamClawWorkspaceDir, } from "../openclaw-workspace.js";
14
+ import { appendTaskExecutionEvent, broadcastTaskExecutionEvent, recordTaskExecutionEvent, serializeTask, } from "./task-execution.js";
15
+ import { autoAssignPendingTasks, scheduleProvisioningReconcile } from "./task-assignment.js";
16
+ import { checkAndGenerateReport } from "./controller-planning.js";
17
+ import { continueControllerWorkflow } from "./controller-intake.js";
18
+ // Design 2.4 workflow-chain routing: tasks carrying TaskInfo.workflow route
19
+ // their follow-up step deterministically from the template's conclusion
20
+ // branches (they are createdBy "workflow", so the generic controller LLM
21
+ // follow-up below never fires for them - the two continuations are disjoint).
22
+ import { continueWorkflowAfterTaskCompletion } from "./workflow-routes.js";
23
+ /**
24
+ * Filter deliverables that don't belong to the current task's project directory.
25
+ * This prevents cross-project contamination when the model references stale files
26
+ * from previous sessions visible in the shared workspace.
27
+ */
28
+ export function filterStaleDeliverables(contract, taskProjectDir) {
29
+ if (!taskProjectDir)
30
+ return contract;
31
+ // Normalize: "projects/foo-bar/" → "projects/foo-bar"
32
+ const normalizedDir = taskProjectDir.replace(/\/$/u, "");
33
+ const filtered = contract.deliverables.filter((d) => {
34
+ const val = (d.value ?? "").replace(/\/$/u, "");
35
+ if (!val)
36
+ return true; // keep notes/commands without paths
37
+ if (d.kind === "note" || d.kind === "command")
38
+ return true;
39
+ // Accept deliverables whose path contains the projectDir or is rooted in teamclaw/projects/{projectDir}
40
+ if (val.includes(normalizedDir))
41
+ return true;
42
+ // Accept relative paths that look like project-internal (no slashes or relative)
43
+ if (!val.includes("/") || val.startsWith("./"))
44
+ return true;
45
+ // Reject paths from other project directories
46
+ return false;
47
+ });
48
+ if (filtered.length === contract.deliverables.length)
49
+ return contract;
50
+ return { ...contract, deliverables: filtered };
51
+ }
52
+ /**
53
+ * Strategy 4: When text-based enrichment found no HTML file references,
54
+ * scan the workspace filesystem for HTML files and create a web-app deliverable.
55
+ * This handles workers that return abstract summaries without mentioning specific paths.
56
+ */
57
+ export function enrichWithFilesystemHtmlScan(contract, taskProjectDir) {
58
+ const existingWebApp = contract.deliverables.find((d) => d.artifactType === "web-app");
59
+ if (existingWebApp) {
60
+ const cwd = existingWebApp.previewCwd?.trim();
61
+ if (cwd && cwd !== "." && cwd !== "./") {
62
+ return null;
63
+ }
64
+ // Fall through — existing web-app has root previewCwd, try to improve it
65
+ }
66
+ let workspaceDir;
67
+ let openclawWorkspaceDir;
68
+ try {
69
+ workspaceDir = resolveTeamClawWorkspaceDir();
70
+ openclawWorkspaceDir = resolveTeamClawAgentWorkspaceRootDir();
71
+ }
72
+ catch {
73
+ return null;
74
+ }
75
+ // Recursively scan the workspace for HTML files (up to 3 levels deep)
76
+ const MAX_DEPTH = 3;
77
+ const htmlCandidates = [];
78
+ function scanDir(dir, depth) {
79
+ if (depth > MAX_DEPTH)
80
+ return;
81
+ let entries;
82
+ try {
83
+ entries = fs.readdirSync(dir, { withFileTypes: true });
84
+ }
85
+ catch {
86
+ return;
87
+ }
88
+ for (const entry of entries) {
89
+ if (entry.name.startsWith(".") || entry.name === "node_modules" || entry.name === ".git")
90
+ continue;
91
+ const fullPath = path.join(dir, entry.name);
92
+ if (entry.isDirectory()) {
93
+ scanDir(fullPath, depth + 1);
94
+ }
95
+ else if (entry.isFile() && (entry.name.endsWith(".html") || entry.name.endsWith(".htm"))) {
96
+ if (!entry.name.includes(".config.") && !entry.name.includes(".test.") && !entry.name.includes(".spec.")) {
97
+ htmlCandidates.push({ dirPath: dir, filename: entry.name });
98
+ }
99
+ }
100
+ }
101
+ }
102
+ // Scope scan to the task's project directory when available to avoid
103
+ // picking up stale HTML from unrelated projects.
104
+ const scanRoot = taskProjectDir
105
+ ? path.join(workspaceDir, taskProjectDir)
106
+ : workspaceDir;
107
+ if (taskProjectDir && !fs.existsSync(scanRoot)) {
108
+ return null;
109
+ }
110
+ scanDir(scanRoot, 0);
111
+ if (htmlCandidates.length === 0) {
112
+ return null;
113
+ }
114
+ // Use OpenClaw workspace root as base for relative paths (worker paths and
115
+ // preview manager both resolve relative to the OpenClaw workspace, not the
116
+ // TeamClaw subdirectory).
117
+ const candidate = htmlCandidates[0];
118
+ const relativeDir = path.relative(openclawWorkspaceDir, candidate.dirPath) || ".";
119
+ const normalizedDir = relativeDir.replace(/\\/gu, "/");
120
+ // Avoid adding a duplicate if a directory deliverable for this path already exists
121
+ const existingDir = contract.deliverables.find((d) => d.kind === "directory" && d.value.replace(/\\/gu, "/").replace(/\/$/u, "") === normalizedDir);
122
+ if (existingDir && existingDir.artifactType === "web-app" && existingWebApp?.previewCwd?.trim() !== ".") {
123
+ // Existing web-app already has a specific, non-root directory — leave it alone.
124
+ return null;
125
+ }
126
+ const newDeliverable = {
127
+ kind: "directory",
128
+ value: normalizedDir,
129
+ summary: `Web application at ${normalizedDir}`,
130
+ artifactType: "web-app",
131
+ previewCommand: "npx -y serve -l {PORT}",
132
+ previewCwd: normalizedDir,
133
+ previewReadyPath: "/",
134
+ };
135
+ const newDeliverables = [...contract.deliverables];
136
+ if (existingDir) {
137
+ // Update existing directory deliverable with web-app fields
138
+ const idx = newDeliverables.indexOf(existingDir);
139
+ // Always take the filesystem scan's directory path, which is more specific
140
+ newDeliverables[idx] = { ...existingDir, ...newDeliverable };
141
+ }
142
+ else {
143
+ newDeliverables.push(newDeliverable);
144
+ }
145
+ return { ...contract, deliverables: newDeliverables };
146
+ }
147
+ const MEANINGFUL_PROJECT_CHANGE_EXTENSIONS = new Set([
148
+ ".js", ".jsx", ".ts", ".tsx", ".json", ".html", ".css", ".scss", ".md", ".txt", ".yml", ".yaml",
149
+ ".go", ".mod", ".sum", ".py", ".rb", ".rs", ".java", ".kt", ".swift", ".c", ".cc", ".cpp", ".h", ".hpp",
150
+ ".cs", ".php", ".sh", ".bash", ".zsh", ".sql", ".toml", ".ini",
151
+ ]);
152
+ const IGNORED_PROJECT_CHANGE_DIRS = new Set([
153
+ "node_modules", ".git", "dist", "build", ".next", ".cache", "coverage", "tmp", "temp",
154
+ ]);
155
+ const IGNORED_PROJECT_CHANGE_FILES = new Set([
156
+ "package-lock.json", "pnpm-lock.yaml", "yarn.lock",
157
+ ]);
158
+ export function taskRequiresMeaningfulProjectChangeGate(task) {
159
+ if (task.assignedRole !== "developer" || !task.projectDir) {
160
+ return false;
161
+ }
162
+ const text = `${task.title}\n${task.description}`.toLowerCase();
163
+ if (/\b(qa|audit|review|verify|verification|validate|test|retest|confirm|check)\b/u.test(text)) {
164
+ return false;
165
+ }
166
+ if (/(审计|审核|验证|复检|复查|确认|测试|检查)/u.test(text)) {
167
+ return false;
168
+ }
169
+ return /\b(implement|build|fix|rework|update|add|enhanc|deliver|write|create)\b/u.test(text);
170
+ }
171
+ export function projectHasMeaningfulDeliverableEvidence(task, contract) {
172
+ if (!task.projectDir || !contract) {
173
+ return false;
174
+ }
175
+ const projectRoot = path.join(resolveTeamClawProjectsDir(), task.projectDir);
176
+ for (const deliverable of contract.deliverables) {
177
+ if (deliverable.kind !== "file" && deliverable.kind !== "directory") {
178
+ continue;
179
+ }
180
+ const rawValue = deliverable.value.trim().replace(/\\/g, "/");
181
+ if (!rawValue) {
182
+ continue;
183
+ }
184
+ const normalizedValue = rawValue.startsWith("projects/")
185
+ ? rawValue.slice("projects/".length)
186
+ : rawValue;
187
+ if (normalizedValue !== task.projectDir
188
+ && !normalizedValue.startsWith(`${task.projectDir}/`)) {
189
+ continue;
190
+ }
191
+ const relativePath = normalizedValue === task.projectDir
192
+ ? ""
193
+ : normalizedValue.slice(task.projectDir.length + 1);
194
+ const fullPath = relativePath ? path.join(projectRoot, relativePath) : projectRoot;
195
+ try {
196
+ const stats = fs.statSync(fullPath);
197
+ if (stats.isFile()) {
198
+ return true;
199
+ }
200
+ if (stats.isDirectory()) {
201
+ const entries = fs.readdirSync(fullPath, { withFileTypes: true });
202
+ if (entries.some((entry) => entry.isFile() || entry.isDirectory())) {
203
+ return true;
204
+ }
205
+ }
206
+ }
207
+ catch {
208
+ continue;
209
+ }
210
+ }
211
+ return false;
212
+ }
213
+ export function projectHasMeaningfulFileChanges(task, contract) {
214
+ if (!task.projectDir) {
215
+ return false;
216
+ }
217
+ const projectRoot = path.join(resolveTeamClawProjectsDir(), task.projectDir);
218
+ if (!fs.existsSync(projectRoot)) {
219
+ return false;
220
+ }
221
+ // Collaboration contract: write tasks deliver in a dedicated worktree.
222
+ // An mtime scan is the wrong test there (committed files keep old mtimes
223
+ // and the gate may run before the flush) - ask git instead: does HEAD carry
224
+ // commits beyond the remote refs?
225
+ if (task.projectDir.includes("__task-")) {
226
+ try {
227
+ const out = execFileSync("git", ["rev-list", "--count", "HEAD", "--not", "--remotes"], { cwd: projectRoot }).toString();
228
+ return Number(out.trim()) > 0;
229
+ }
230
+ catch {
231
+ return false;
232
+ }
233
+ }
234
+ const threshold = Math.max(task.startedAt ?? 0, task.createdAt ?? 0) - 1000;
235
+ const stack = [projectRoot];
236
+ while (stack.length > 0) {
237
+ const currentDir = stack.pop();
238
+ let entries;
239
+ try {
240
+ entries = fs.readdirSync(currentDir, { withFileTypes: true });
241
+ }
242
+ catch {
243
+ continue;
244
+ }
245
+ for (const entry of entries) {
246
+ if (entry.isDirectory()) {
247
+ if (!IGNORED_PROJECT_CHANGE_DIRS.has(entry.name)) {
248
+ stack.push(path.join(currentDir, entry.name));
249
+ }
250
+ continue;
251
+ }
252
+ if (!entry.isFile()) {
253
+ continue;
254
+ }
255
+ if (IGNORED_PROJECT_CHANGE_FILES.has(entry.name)) {
256
+ continue;
257
+ }
258
+ const ext = path.extname(entry.name).toLowerCase();
259
+ if (!MEANINGFUL_PROJECT_CHANGE_EXTENSIONS.has(ext)) {
260
+ continue;
261
+ }
262
+ const fullPath = path.join(currentDir, entry.name);
263
+ try {
264
+ const stats = fs.statSync(fullPath);
265
+ if (stats.mtimeMs >= threshold) {
266
+ return true;
267
+ }
268
+ }
269
+ catch {
270
+ continue;
271
+ }
272
+ }
273
+ }
274
+ return projectHasMeaningfulDeliverableEvidence(task, contract);
275
+ }
276
+ export function allowsNoChangeCompletion(task, contract, resultText) {
277
+ const taskText = `${task.title}\n${task.description}`.toLowerCase();
278
+ const evidenceText = [
279
+ contract?.summary ?? "",
280
+ contract?.notes ?? "",
281
+ ...(contract?.keyPoints ?? []),
282
+ resultText,
283
+ ].join("\n").toLowerCase();
284
+ const hasVerificationEvidence = (contract?.deliverables ?? []).some((deliverable) => deliverable.kind === "command" || deliverable.kind === "note")
285
+ || /\b(go test|go vet|npm test|pnpm test|yarn test|pytest|cargo test|verified|verification|passes|all tests pass|no remaining)\b/u.test(evidenceText);
286
+ const noChangeIsExpected = /\b(qa|audit|review|verify|verification|validate|test|retest|confirm|check)\b/u.test(taskText)
287
+ || /(审计|审核|验证|复检|复查|确认|测试|检查)/u.test(taskText)
288
+ || /\b(already fixed|already resolved|no further changes|no code changes|no file changes|no additional changes|verified existing fix)\b/u.test(evidenceText)
289
+ || /(已修复|已解决|无需改动|无需修改|没有额外修改|无需额外变更|只需验证)/u.test(evidenceText);
290
+ return hasVerificationEvidence && noChangeIsExpected;
291
+ }
292
+ export function applyTaskResult(taskId, result, error, deps) {
293
+ const { logger, updateTeamState, wsServer } = deps;
294
+ let completionEvent;
295
+ const state = updateTeamState((s) => {
296
+ const task = s.tasks[taskId];
297
+ if (!task)
298
+ return;
299
+ task.status = error ? "failed" : "completed";
300
+ task.result = result;
301
+ task.error = error;
302
+ task.completedAt = Date.now();
303
+ task.updatedAt = Date.now();
304
+ // Re-enrich deliverables now that the full result text is available.
305
+ if (!error && task.resultContract) {
306
+ // Filter out stale deliverables from other projects first
307
+ task.resultContract = filterStaleDeliverables(task.resultContract, task.projectDir);
308
+ let enriched = enrichDeliverablesWithPreviewInference(task.resultContract, result);
309
+ if (!enriched) {
310
+ // Text-based enrichment failed — scan the workspace filesystem for HTML files.
311
+ enriched = enrichWithFilesystemHtmlScan(task.resultContract, task.projectDir);
312
+ }
313
+ if (enriched) {
314
+ task.resultContract = enriched;
315
+ }
316
+ }
317
+ completionEvent = appendTaskExecutionEvent(task, {
318
+ type: error ? "error" : "lifecycle",
319
+ phase: error ? "result_failed" : "result_completed",
320
+ source: "controller",
321
+ status: error ? "failed" : "completed",
322
+ message: error ? `Task failed: ${error}` : "Task completed successfully.",
323
+ workerId: task.assignedWorkerId,
324
+ role: task.assignedRole,
325
+ });
326
+ if (task.assignedWorkerId && s.workers[task.assignedWorkerId]) {
327
+ const assignedWorker = s.workers[task.assignedWorkerId];
328
+ if (assignedWorker.status !== "offline") {
329
+ assignedWorker.status = "idle";
330
+ }
331
+ assignedWorker.currentTaskId = undefined;
332
+ }
333
+ });
334
+ const updatedTask = state.tasks[taskId];
335
+ if (updatedTask) {
336
+ if (completionEvent) {
337
+ broadcastTaskExecutionEvent(taskId, updatedTask, completionEvent, deps);
338
+ }
339
+ wsServer.broadcastUpdate({ type: "task:completed", data: serializeTask(updatedTask) });
340
+ logger.info(`Controller: task ${taskId} ${error ? "failed" : "completed"}`);
341
+ if (error && updatedTask.assignedWorkerId && deps.workerProvisioningManager?.hasManagedWorker(updatedTask.assignedWorkerId)) {
342
+ void deps.workerProvisioningManager.onWorkerRemoved(updatedTask.assignedWorkerId, `task ${taskId} failed; retiring managed worker before retry`).catch((err) => {
343
+ logger.warn(`Controller: failed to retire managed worker ${updatedTask.assignedWorkerId}: ${String(err)}`);
344
+ });
345
+ }
346
+ if (updatedTask.assignedWorkerId) {
347
+ void autoAssignPendingTasks(deps, updatedTask.assignedWorkerId).catch((err) => {
348
+ logger.warn(`Controller: failed to auto-assign pending tasks after result for ${taskId}: ${String(err)}`);
349
+ });
350
+ }
351
+ scheduleProvisioningReconcile(deps, `task-result:${taskId}`);
352
+ if (!error && updatedTask.workflow) {
353
+ void continueWorkflowAfterTaskCompletion(updatedTask, deps).catch((err) => {
354
+ logger.warn(`Controller: failed to continue workflow chain after ${taskId}: ${String(err)}`);
355
+ });
356
+ }
357
+ if (!error && updatedTask.createdBy === "controller") {
358
+ void continueControllerWorkflow(updatedTask, deps).catch((err) => {
359
+ logger.warn(`Controller: failed to continue intake workflow after ${taskId}: ${String(err)}`);
360
+ }).finally(() => {
361
+ // After the follow-up run completes (or if there was none), check session completion.
362
+ void checkAndGenerateReport(updatedTask, deps).catch(() => { });
363
+ });
364
+ }
365
+ else if (updatedTask.controllerSessionKey) {
366
+ // Non-controller tasks or failed tasks — still check session completion.
367
+ void checkAndGenerateReport(updatedTask, deps).catch(() => { });
368
+ }
369
+ }
370
+ return updatedTask;
371
+ }
372
+ export function ensureTaskResultContract(taskId, result, error, deps) {
373
+ const state = deps.getTeamState();
374
+ const currentTask = state?.tasks[taskId];
375
+ if (!currentTask) {
376
+ return undefined;
377
+ }
378
+ if (currentTask.resultContract) {
379
+ // Worker submitted a structured contract — but it may be missing preview
380
+ // fields (artifactType, previewCommand, etc.). Enrich deliverables
381
+ // so the PreviewManager can auto-launch previews.
382
+ let enriched = enrichDeliverablesWithPreviewInference(currentTask.resultContract, result);
383
+ if (!enriched) {
384
+ // Text-based enrichment failed — scan the workspace filesystem for HTML files.
385
+ enriched = enrichWithFilesystemHtmlScan(currentTask.resultContract, currentTask.projectDir);
386
+ }
387
+ if (enriched) {
388
+ deps.updateTeamState((teamState) => {
389
+ const task = teamState.tasks[taskId];
390
+ if (task) {
391
+ task.resultContract = enriched;
392
+ task.updatedAt = Date.now();
393
+ }
394
+ });
395
+ return enriched;
396
+ }
397
+ return currentTask.resultContract;
398
+ }
399
+ let contract = backfillWorkerTaskResultContract(currentTask, result, error);
400
+ if (!error) {
401
+ const enriched = enrichDeliverablesWithPreviewInference(contract, result)
402
+ ?? enrichWithFilesystemHtmlScan(contract, currentTask.projectDir);
403
+ if (enriched) {
404
+ contract = enriched;
405
+ }
406
+ }
407
+ deps.updateTeamState((teamState) => {
408
+ const task = teamState.tasks[taskId];
409
+ if (!task || task.resultContract) {
410
+ return;
411
+ }
412
+ task.resultContract = contract;
413
+ });
414
+ recordTaskExecutionEvent(taskId, {
415
+ type: "lifecycle",
416
+ phase: "result_contract_backfilled",
417
+ source: "controller",
418
+ message: "Worker did not submit a structured result contract; TeamClaw backfilled one from the recorded task result.",
419
+ workerId: currentTask.assignedWorkerId,
420
+ role: currentTask.assignedRole,
421
+ }, deps);
422
+ return contract;
423
+ }
424
+ export function buildEffectiveTaskResultContract(task, result, error, submittedContract) {
425
+ let contract = submittedContract
426
+ ? filterStaleDeliverables(submittedContract, task.projectDir)
427
+ : backfillWorkerTaskResultContract(task, result, error);
428
+ if (!error) {
429
+ const enriched = enrichDeliverablesWithPreviewInference(contract, result)
430
+ ?? enrichWithFilesystemHtmlScan(contract, task.projectDir);
431
+ if (enriched) {
432
+ contract = enriched;
433
+ }
434
+ }
435
+ return contract;
436
+ }
437
+ const MAX_PATTERNS_FILE_BYTES = 64 * 1024;
438
+ export function consolidateDiscoveredPatterns(contract, taskId, role, logger) {
439
+ const patterns = contract.discoveredPatterns;
440
+ if (!patterns || patterns.length === 0) {
441
+ return;
442
+ }
443
+ try {
444
+ const workspaceDir = resolveTeamClawWorkspaceDir();
445
+ const patternsFile = path.join(workspaceDir, "memory", "patterns.md");
446
+ fs.mkdirSync(path.join(workspaceDir, "memory"), { recursive: true });
447
+ let currentSize = 0;
448
+ try {
449
+ currentSize = fs.statSync(patternsFile).size;
450
+ }
451
+ catch {
452
+ // File doesn't exist yet; will be created by append.
453
+ }
454
+ if (currentSize > MAX_PATTERNS_FILE_BYTES) {
455
+ logger.info(`Controller: patterns.md already ${currentSize} bytes, skipping consolidation for ${taskId}`);
456
+ return;
457
+ }
458
+ const roleLabel = role ?? "unknown";
459
+ const timestamp = new Date().toISOString().slice(0, 10);
460
+ const section = [
461
+ "",
462
+ `## ${timestamp} — ${taskId} (${roleLabel})`,
463
+ ...patterns.map((p) => `- ${p}`),
464
+ ].join("\n") + "\n";
465
+ fs.appendFileSync(patternsFile, section, "utf8");
466
+ logger.info(`Controller: consolidated ${patterns.length} pattern(s) from ${taskId} into patterns.md`);
467
+ }
468
+ catch (err) {
469
+ logger.warn(`Controller: failed to consolidate patterns for ${taskId}: ${err instanceof Error ? err.message : String(err)}`);
470
+ }
471
+ }
@@ -1,8 +1,30 @@
1
- import { getRole } from "../roles.js";
1
+ // Phase 1.3: role labels come from the active TeamProfile.
2
+ import { getActiveRole } from "../profile-loader.js";
3
+ // Phase 2.5: bilingual tiered token inference (design 2.3) is the fast path
4
+ // for unassigned tasks; it returns null when it refuses to decide (tie or
5
+ // all-zero), which falls through to the legacy keyword matcher below.
6
+ import { inferTaskRole } from "./role-inference.js";
7
+ // Phase 2.5 wiring (design 2.3 "LLM 兜底", P2.5 follow-up): tasks the token
8
+ // fast path refuses to decide escalate to resolveTaskRoleWithLlmFallback
9
+ // (kickoff-orchestrator seam). The llmRoleJudge callback is injected by the
10
+ // controller assembly (controller-service wires it to the real controller
11
+ // LLM session; tests inject fakes) so this module stays free of LLM/runtime
12
+ // knowledge. Without a judge the escalation is skipped and unconfident tasks
13
+ // keep the legacy capability-matcher path - byte-for-byte the pre-wiring
14
+ // behavior (e.g. runtimes without an LLM subagent).
15
+ import { resolveTaskRoleWithLlmFallback } from "./kickoff-orchestrator.js";
2
16
  export class TaskRouter {
3
17
  logger;
4
- constructor(logger) {
18
+ llmRoleJudge;
19
+ /**
20
+ * LLM-judged role per task id, written at most once per task per process
21
+ * so a pending unconfident task never triggers repeat LLM calls across
22
+ * dispatch rounds. Pruned when the task disappears from state.
23
+ */
24
+ judgedRoles = new Map();
25
+ constructor(logger, options) {
5
26
  this.logger = logger;
27
+ this.llmRoleJudge = options?.llmRoleJudge;
6
28
  }
7
29
  routeTask(task, workers) {
8
30
  // First try exact role match with idle workers
@@ -14,12 +36,28 @@ export class TaskRouter {
14
36
  this.logger.info(`TaskRouter: no idle worker for explicitly assigned role ${task.assignedRole} on task ${task.id}; keeping task pending`);
15
37
  return null;
16
38
  }
39
+ // Phase 2.5 fast path: tiered bilingual token inference over the active
40
+ // profile's roles. A confident pick routes to that role's idle workers;
41
+ // when the inferred role has no idle worker we degrade to the legacy
42
+ // matcher instead of stranding the task (inference is a hint, the
43
+ // explicit assignedRole branch above is the decision that must wait).
44
+ // Phase 2.5 wiring: an LLM-judged role (cached from a previous dispatch
45
+ // round) fills in when the token fast path refuses to decide, with the
46
+ // same hint semantics as a confident inference.
47
+ const inferredRole = inferTaskRole(task) ?? this.judgedRoles.get(task.id);
48
+ if (inferredRole) {
49
+ const inferredCandidates = Object.values(workers).filter((w) => w.role === inferredRole && w.status === "idle");
50
+ if (inferredCandidates.length > 0) {
51
+ return inferredCandidates[0];
52
+ }
53
+ this.logger.info(`TaskRouter: inferred role ${inferredRole} has no idle worker on task ${task.id}; trying capability matching`);
54
+ }
17
55
  // Try keyword matching on capabilities
18
56
  const keywords = this.extractKeywords(task.description + " " + task.title);
19
57
  const scored = Object.values(workers)
20
58
  .filter((w) => w.status === "idle")
21
59
  .map((w) => {
22
- const roleDef = getRole(w.role);
60
+ const roleDef = getActiveRole(w.role);
23
61
  const capabilities = roleDef?.capabilities ?? [];
24
62
  const matchCount = keywords.filter((k) => capabilities.some((c) => c.includes(k) || k.includes(c))).length;
25
63
  return { worker: w, score: matchCount };
@@ -36,8 +74,32 @@ export class TaskRouter {
36
74
  }
37
75
  return null;
38
76
  }
39
- autoAssignPendingTasks(tasks, workers) {
77
+ async autoAssignPendingTasks(tasks, workers) {
40
78
  const pendingTasks = Object.values(tasks).filter((t) => t.status === "pending" || t.status === "assigned");
79
+ this.pruneJudgedRoles(tasks);
80
+ // Phase 2.5 wiring: escalate unassigned tasks the token fast path refuses
81
+ // to decide to the LLM judge, once per task (results cached above the
82
+ // routing call). The resolver degrades to the profile defaultRole when
83
+ // the judge fails, times out, or answers with a role outside the active
84
+ // profile. Skipped entirely when no judge is wired - pre-wiring behavior.
85
+ if (this.llmRoleJudge) {
86
+ await Promise.all(pendingTasks
87
+ .filter((task) => !task.assignedRole
88
+ && !this.judgedRoles.has(task.id)
89
+ && inferTaskRole(task) === null)
90
+ .map(async (task) => {
91
+ try {
92
+ const resolved = await resolveTaskRoleWithLlmFallback(task, {
93
+ llmRoleJudge: this.llmRoleJudge,
94
+ logger: this.logger,
95
+ });
96
+ this.judgedRoles.set(task.id, resolved);
97
+ }
98
+ catch (err) {
99
+ this.logger.warn(`TaskRouter: LLM role judge threw for task ${task.id} (${err instanceof Error ? err.message : String(err)}); keeping legacy routing for it`);
100
+ }
101
+ }));
102
+ }
41
103
  const assignments = [];
42
104
  for (const task of pendingTasks) {
43
105
  if (task.assignedWorkerId && workers[task.assignedWorkerId]) {
@@ -50,6 +112,14 @@ export class TaskRouter {
50
112
  }
51
113
  return assignments;
52
114
  }
115
+ /** Drop judged-role cache entries for tasks that no longer exist in state. */
116
+ pruneJudgedRoles(tasks) {
117
+ for (const taskId of this.judgedRoles.keys()) {
118
+ if (!tasks[taskId]) {
119
+ this.judgedRoles.delete(taskId);
120
+ }
121
+ }
122
+ }
53
123
  extractKeywords(text) {
54
124
  const common = new Set([
55
125
  "the", "a", "an", "and", "or", "but", "in", "on", "at", "to", "for",