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