@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,197 @@
1
+ // Phase 1.3: the advertised role set comes from the active TeamProfile.
2
+ import { getActiveDomainInstructions, getActiveRoles } from "../profile-loader.js";
3
+ import { buildControllerCompletionRules, buildControllerDisciplineRules, buildControllerEvidenceMemoryRules, buildControllerIntakeRules, buildControllerStructuredContractRules, buildControllerToolRules, buildControllerWorkflowRules, buildRoleOperatingRules, composePrompt, } from "../prompt-policy.js";
4
+ import { hasOnDemandWorkerProvisioning, shouldBlockControllerWithoutWorkers } from "./controller-capacity.js";
5
+ import { resolveTeamClawWorkspaceDir } from "../openclaw-workspace.js";
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+ export function createControllerPromptInjector(deps) {
9
+ return () => {
10
+ const state = deps.getTeamState();
11
+ const workers = Object.values(state?.workers ?? {});
12
+ const tasks = Object.values(state?.tasks ?? {});
13
+ const pendingTasks = tasks.filter((t) => t.status === "pending");
14
+ const activeTasks = tasks.filter((t) => t.status === "in_progress" || t.status === "assigned");
15
+ const blockedTasks = tasks.filter((t) => t.status === "blocked");
16
+ const completedTasks = tasks.filter((t) => t.status === "completed");
17
+ const pendingClarifications = Object.values(state?.clarifications ?? {}).filter((c) => c.status === "pending");
18
+ const canProvisionWithoutWorkers = hasOnDemandWorkerProvisioning(deps.config);
19
+ const parts = [
20
+ "## TeamClaw Controller Mode",
21
+ "You are the Team Controller and the first-pass requirements analyst for the human.",
22
+ "Treat human input as raw requirements unless it is already explicitly phrased as an execution-ready TeamClaw task.",
23
+ ...buildControllerToolRules(),
24
+ "",
25
+ "### Current Team Status",
26
+ ];
27
+ if (!state) {
28
+ parts.push("- Team state is not loaded yet; treat this as a fresh controller intake and establish execution-ready tasks from the human requirement.");
29
+ }
30
+ else if (workers.length === 0) {
31
+ if (shouldBlockControllerWithoutWorkers(deps.config, state)) {
32
+ parts.push("- No workers are registered and on-demand provisioning is disabled.");
33
+ parts.push("- Blocking rule: you may analyze the requirement and identify the needed roles, but do not create TeamClaw tasks yet.");
34
+ parts.push("- Do not start doing the worker-role work yourself. Tell the human to bring workers online or enable process/docker/kubernetes provisioning first.");
35
+ }
36
+ else {
37
+ parts.push("- No workers are registered yet, but on-demand provisioning is enabled.");
38
+ parts.push("- You may still create execution-ready TeamClaw tasks for the required roles; the controller will provision workers on demand.");
39
+ }
40
+ }
41
+ else {
42
+ for (const w of workers) {
43
+ const roleDef = getActiveRoles().find((r) => r.id === w.role);
44
+ const statusIcon = w.status === "idle" ? "[idle]" : w.status === "busy" ? "[busy]" : "[offline]";
45
+ const currentTask = w.currentTaskId ? ` (task: ${w.currentTaskId})` : "";
46
+ parts.push(`- ${roleDef?.icon ?? ""} ${w.label} (${w.id}) ${statusIcon}${currentTask}`);
47
+ }
48
+ }
49
+ parts.push("");
50
+ parts.push(`### Tasks Summary`);
51
+ parts.push(`- Pending: ${pendingTasks.length} | Active: ${activeTasks.length} | Blocked: ${blockedTasks.length} | Completed: ${completedTasks.length}`);
52
+ if (pendingClarifications.length > 0) {
53
+ parts.push("");
54
+ parts.push("Pending clarification requests:");
55
+ for (const clarification of pendingClarifications.slice(0, 10)) {
56
+ parts.push(`- Task ${clarification.taskId}: ${clarification.question}`);
57
+ }
58
+ }
59
+ if (pendingTasks.length > 0) {
60
+ parts.push("");
61
+ parts.push("Pending tasks:");
62
+ for (const t of pendingTasks.slice(0, 10)) {
63
+ parts.push(`- [${t.priority}] ${t.title} (role: ${t.assignedRole ?? "any"})`);
64
+ }
65
+ }
66
+ parts.push("");
67
+ parts.push("### Available Roles");
68
+ for (const role of getActiveRoles()) {
69
+ const skillLine = role.recommendedSkills.length > 0
70
+ ? ` Recommended skills: ${role.recommendedSkills.join(", ")}.`
71
+ : "";
72
+ parts.push(`- ${role.icon} ${role.label}: ${role.description}.${skillLine}`);
73
+ }
74
+ // Phase 2.4 (design 2.4): when the active profile carries industry
75
+ // guardrails, the controller's operating contract is replaced by them,
76
+ // assembled right after the role catalog (the controller-side analog of
77
+ // "after the role systemPrompt" on the worker pipeline). Profiles without
78
+ // domainInstructions (software-rd) inject nothing, so the controller
79
+ // prompt bytes are unchanged (Phase 1.7 golden).
80
+ const domainInstructions = getActiveDomainInstructions();
81
+ if (domainInstructions) {
82
+ parts.push(...buildRoleOperatingRules({
83
+ suggestedRoles: [],
84
+ recommendedSkills: [],
85
+ domainInstructions,
86
+ }));
87
+ }
88
+ // List existing projects so the controller can distinguish new vs. existing
89
+ parts.push("");
90
+ parts.push("### Existing Projects in Workspace");
91
+ const existingProjects = listExistingProjects(state);
92
+ if (existingProjects.length === 0) {
93
+ parts.push("- No existing projects yet.");
94
+ }
95
+ else {
96
+ for (const proj of existingProjects) {
97
+ parts.push(`- 📂 ${proj.dir}: ${proj.summary}`);
98
+ }
99
+ }
100
+ parts.push("");
101
+ parts.push("## New vs. Existing Project Detection");
102
+ parts.push("- Before creating tasks, determine if the user's request relates to an existing project listed above.");
103
+ parts.push("- If the request mentions a technology, feature, or project name that matches an existing project, treat it as an enhancement/bugfix for that project — reuse the same projectDir.");
104
+ parts.push("- If the request is clearly a new, unrelated requirement, create a fresh projectDir with a new projectName.");
105
+ parts.push("- When enhancing an existing project, include context about what already exists so the worker can extend rather than rebuild.");
106
+ parts.push("- NEVER let a worker's deliverables reference files from a different project. Each task's deliverables must be scoped to its own projectDir.");
107
+ parts.push(...buildControllerWorkflowRules());
108
+ parts.push("");
109
+ parts.push("## Team Kickoff Meeting (Collaborative Planning)");
110
+ parts.push("- **IMPORTANT**: When the requirement involves 3 or more roles, you MUST call teamclaw_request_kickoff as your FIRST tool call, BEFORE creating any tasks.");
111
+ parts.push("- The kickoff provisions candidate role workers and asks each for a structured assessment from their professional perspective.");
112
+ parts.push("- Each role evaluates: whether they're needed, their scope of work, suggested tasks, dependencies on other roles, risks, and open questions.");
113
+ parts.push("- Use the team's assessments to make informed decisions about which roles to actually involve and how to structure the task pipeline.");
114
+ parts.push("- Roles that assessed themselves as not needed will be automatically reclaimed after their idle timeout.");
115
+ parts.push("- Adaptive kickoff rules:");
116
+ parts.push(" - **Simple** (single clear task, 1 role): Skip kickoff, create task directly.");
117
+ parts.push(" - **Medium** (2-3 roles likely): Call kickoff with the 2-3 most relevant roles.");
118
+ parts.push(" - **Complex** (4+ potential roles, multi-domain, unclear scope): ALWAYS call kickoff with all candidate roles. Do NOT skip.");
119
+ parts.push("- For task_follow_up runs (triggered by completed tasks), do NOT call kickoff again — the team plan was already established.");
120
+ parts.push("- Example: 'Build an e-commerce platform' → complex (architect+developer+designer+qa+security) → MUST call teamclaw_request_kickoff first");
121
+ parts.push("");
122
+ parts.push("## Out-of-Scope Requests");
123
+ parts.push("- TeamClaw is a software development team. You handle: coding, architecture, design, testing, deployment, documentation, security review, and related technical work.");
124
+ parts.push("- Do not infer that the user lacks rights to work on a codebase just because it contains binaries, bundles, minified code, generated artifacts, proprietary branding, or unusual repository structure. Unless the user explicitly states a restriction, keep the decision technical rather than ownership-based.");
125
+ parts.push("- If the human asks for something clearly non-technical (cooking, weather, personal advice, general knowledge, creative writing unrelated to software), politely decline in your reply text AND still call teamclaw_submit_manifest with createdTasks=[], requiredRoles=[], and requirementSummary explaining why you declined.");
126
+ parts.push("- If the request is borderline (e.g. 'write a blog post about our API'), lean toward accepting it and assigning to the appropriate role (marketing, pm).");
127
+ parts.push("- REMEMBER: You must ALWAYS call teamclaw_submit_manifest, even when declining. The system cannot record your decision without it.");
128
+ parts.push("");
129
+ parts.push("## Clarification & Follow-up Awareness");
130
+ parts.push("- If this session has prior messages where you asked clarification questions, the human's new message is likely a response to those questions.");
131
+ parts.push("- Do NOT treat a follow-up human message as a brand-new requirement if there are pending clarification questions in this session. Instead, interpret the message as an answer and proceed with task creation.");
132
+ parts.push("- If the human's follow-up is clearly irrelevant to the pending questions (e.g. random chitchat), acknowledge it briefly and re-state the pending questions so the human knows what you still need.");
133
+ parts.push("- For automatic task_follow_up runs (triggered by task completion), focus on advancing the pipeline — do not re-ask questions already answered.");
134
+ parts.push("");
135
+ parts.push("## Deliverable Presentation");
136
+ parts.push("- When a task completes with a result contract, review the deliverables and present a clear, actionable summary to the human.");
137
+ parts.push("- For web applications: include the preview URL if available (deliverable.liveUrl). The human should be able to click and verify.");
138
+ parts.push("- For CLI tools: include the command to run with example arguments.");
139
+ parts.push("- For documents: highlight the key decisions or structure.");
140
+ parts.push("- When ALL tasks for the requirement are complete (requirementFullyComplete=true), provide a final delivery summary:");
141
+ parts.push(" - What was built (1-2 sentence overview)");
142
+ parts.push(" - How to access/run it (URLs, commands)");
143
+ parts.push(" - File locations (project directory)");
144
+ parts.push(" - Any caveats or next steps");
145
+ parts.push(...buildControllerStructuredContractRules());
146
+ parts.push(...buildControllerEvidenceMemoryRules());
147
+ parts.push(...buildControllerIntakeRules());
148
+ parts.push(...buildControllerDisciplineRules({ canProvisionWithoutWorkers }));
149
+ parts.push(...buildControllerCompletionRules());
150
+ return {
151
+ prependSystemContext: composePrompt(parts),
152
+ };
153
+ };
154
+ }
155
+ function listExistingProjects(state) {
156
+ const projects = [];
157
+ const seenDirs = new Set();
158
+ if (state) {
159
+ for (const project of Object.values(state.projects ?? {})) {
160
+ if (project.projectDir && !seenDirs.has(project.projectDir)) {
161
+ seenDirs.add(project.projectDir);
162
+ const aliases = project.aliases.filter(Boolean);
163
+ const aliasSummary = aliases.length > 0 ? `aliases: ${aliases.join(", ")}` : "";
164
+ const summary = [project.summary, aliasSummary].filter(Boolean).join(" | ") || "(registered project)";
165
+ projects.push({ dir: project.projectDir, summary });
166
+ }
167
+ }
168
+ for (const task of Object.values(state.tasks)) {
169
+ if (task.projectDir && !seenDirs.has(task.projectDir)) {
170
+ seenDirs.add(task.projectDir);
171
+ const summary = task.resultContract?.summary ?? task.title;
172
+ projects.push({ dir: task.projectDir, summary });
173
+ }
174
+ }
175
+ }
176
+ // Also scan the filesystem for project directories not tracked in state
177
+ try {
178
+ const workspaceDir = resolveTeamClawWorkspaceDir();
179
+ const projectsRoot = path.join(workspaceDir, "projects");
180
+ if (fs.existsSync(projectsRoot)) {
181
+ const entries = fs.readdirSync(projectsRoot, { withFileTypes: true });
182
+ for (const entry of entries) {
183
+ if (entry.isDirectory() && !entry.name.startsWith(".")) {
184
+ const fullDir = `projects/${entry.name}`;
185
+ if (!seenDirs.has(entry.name) && !seenDirs.has(fullDir)) {
186
+ seenDirs.add(fullDir);
187
+ projects.push({ dir: fullDir, summary: "(discovered on filesystem)" });
188
+ }
189
+ }
190
+ }
191
+ }
192
+ }
193
+ catch {
194
+ // Workspace not available — skip filesystem scan
195
+ }
196
+ return projects.slice(0, 20);
197
+ }
@@ -0,0 +1,63 @@
1
+ import { sendJson, sendError } from "../protocol.js";
2
+ import { getActiveProfile } from "../profile-loader.js";
3
+ import { ensureControllerGitRepo, exportControllerGitBundle } from "../git-collaboration.js";
4
+ export async function refreshControllerRepoState(deps) {
5
+ // Phase 2.3: the ACTIVE PROFILE's git switch outranks the legacy config
6
+ // knob here - refreshing (or stamping) repo state for a profile that
7
+ // declared git off would re-introduce exactly the repo field the switch
8
+ // omitted for it (design 2.3: banking keeps no repo initialization). All
9
+ // callers already treat null as "no repo" (same as config gitEnabled off).
10
+ if (!deps.config.gitEnabled || !getActiveProfile().capabilities.git) {
11
+ return null;
12
+ }
13
+ try {
14
+ const repo = await ensureControllerGitRepo(deps.config, deps.logger);
15
+ if (repo) {
16
+ deps.updateTeamState((s) => {
17
+ s.repo = repo;
18
+ });
19
+ }
20
+ return repo;
21
+ }
22
+ catch (err) {
23
+ const message = err instanceof Error ? err.message : String(err);
24
+ deps.logger.warn(`Controller: failed to refresh git repo state: ${message}`);
25
+ deps.updateTeamState((s) => {
26
+ if (s.repo?.enabled) {
27
+ s.repo = {
28
+ ...s.repo,
29
+ error: message,
30
+ lastPreparedAt: Date.now(),
31
+ };
32
+ }
33
+ });
34
+ return deps.getTeamState()?.repo ?? null;
35
+ }
36
+ }
37
+ // GET /api/v1/repo
38
+ export async function handleRepoStatusRequest(deps, res) {
39
+ const repo = await refreshControllerRepoState(deps);
40
+ if (!repo?.enabled) {
41
+ sendJson(res, 200, { enabled: false });
42
+ return;
43
+ }
44
+ sendJson(res, 200, { repo });
45
+ }
46
+ // GET /api/v1/repo/bundle
47
+ export async function handleRepoBundleRequest(deps, res) {
48
+ try {
49
+ const exported = await exportControllerGitBundle(deps.config, deps.logger);
50
+ res.writeHead(200, {
51
+ "Content-Type": "application/octet-stream",
52
+ "Content-Length": exported.data.byteLength,
53
+ "Content-Disposition": `attachment; filename="${exported.filename}"`,
54
+ "Access-Control-Allow-Origin": "*",
55
+ "Access-Control-Allow-Methods": "GET, POST, PATCH, DELETE, OPTIONS",
56
+ "Access-Control-Allow-Headers": "Content-Type",
57
+ });
58
+ res.end(exported.data);
59
+ }
60
+ catch (err) {
61
+ sendError(res, 503, err instanceof Error ? err.message : String(err));
62
+ }
63
+ }
@@ -0,0 +1,246 @@
1
+ // Phase 1.3: inference candidates come from the active TeamProfile.
2
+ import { getActiveRoles } from "../profile-loader.js";
3
+ /**
4
+ * Minimum length for ASCII (latin letter / digit) tokens. Two-character
5
+ * tokens such as "qa", "pm", "ci", "ui" are meaningful role identifiers and
6
+ * must participate in scoring. The previous `length > 2` filter dropped them.
7
+ */
8
+ const ASCII_TOKEN_MIN_LENGTH = 2;
9
+ /**
10
+ * Minimum length for CJK run tokens, in characters. Single CJK characters
11
+ * are too ambiguous to score on; runs of two or more characters are kept.
12
+ */
13
+ const CJK_TOKEN_MIN_LENGTH = 2;
14
+ const ASCII_TOKEN_PATTERN = /[a-z0-9]+/g;
15
+ // A token made purely of ASCII letters/digits (all tokens the pattern above
16
+ // extracts). Such tokens match as STANDALONE WORDS, never as substrings of a
17
+ // longer ASCII word: "data" must not hit "database", "test" must not hit
18
+ // "testing", "pm" must not hit "npm". Multi-word phrases ("software
19
+ // architect") and CJK runs keep whole-phrase containment semantics.
20
+ const ASCII_WORD_TOKEN_PATTERN = /^[a-z0-9]+$/;
21
+ // CJK Unified Ideographs, Extension A, and CJK Compatibility Ideographs.
22
+ const CJK_RUN_PATTERN = /[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]+/g;
23
+ // ---------------------------------------------------------------------------
24
+ // Phase 2.5 tiered scoring (vertical-team-profiles-design.md section 2.3).
25
+ //
26
+ // Token hits are weighted by their SOURCE tier:
27
+ // labelZh full phrase > label full phrase > id/label word > capability word
28
+ // ("labelZh 完整词 > 高区分度业务词 > 泛化词"). Weights are integers so the
29
+ // fallback margin below is measured in whole tiers or whole token hits.
30
+ // ---------------------------------------------------------------------------
31
+ const WEIGHT_LABELZH_PHRASE = 8;
32
+ const WEIGHT_LABEL_PHRASE = 6;
33
+ const WEIGHT_ID_LABEL_WORD = 3;
34
+ const WEIGHT_CAPABILITY_WORD = 1;
35
+ /**
36
+ * Rarity stopword threshold (design 2.3): a token that appears in MORE THAN
37
+ * one third of the active profile's roles discriminates nothing
38
+ * ("分析/管理/合规 全员命中等于没命中") and is dropped from scoring entirely.
39
+ * Computed per inference call over the active role set, so a token that is
40
+ * generic in one profile (合规 in banking) can stay distinctive in another.
41
+ */
42
+ const RARITY_STOPWORD_FRACTION = 1 / 3;
43
+ /**
44
+ * LLM-fallback margin (design 2.3): the token fast path is confident only
45
+ * when the runner-up scores strictly below the winner by at least this much.
46
+ * Any tie (margin < 1) escalates to the LLM fallback instead of the old
47
+ * "并列取数组靠前" registry-order determinism. The value is 1 - not higher -
48
+ * because the design's own high-distinctiveness examples (反洗钱→aml-analyst,
49
+ * 贷审→approver) are single capability-tier hits with margin exactly 1 and
50
+ * must stay on the fast path.
51
+ */
52
+ const LLM_FALLBACK_SCORE_MARGIN = 1;
53
+ function isAsciiAlphanumeric(char) {
54
+ if (!char) {
55
+ return false;
56
+ }
57
+ return (char >= "0" && char <= "9") || (char >= "a" && char <= "z");
58
+ }
59
+ /**
60
+ * Check whether a pure-ASCII word token occurs in `text` as a standalone
61
+ * word rather than inside a longer ASCII word. Plain substring containment
62
+ * would misroute texts like "npm install fails" to the "pm" role, "build a
63
+ * guide page" to the "ui" role, or (Phase 2.5 regression found in testing)
64
+ * "Design the database schema" to the data-engineer role via "data" inside
65
+ * "database". Non-ASCII neighbours (CJK characters, punctuation, string
66
+ * boundaries, hyphens in kebab ids) still count as boundaries, so "qa"
67
+ * matches inside "处理QA登录问题" after lowercasing.
68
+ */
69
+ function asciiWordTokenInText(token, text) {
70
+ let index = text.indexOf(token);
71
+ while (index !== -1) {
72
+ const boundedBefore = !isAsciiAlphanumeric(text[index - 1]);
73
+ const boundedAfter = !isAsciiAlphanumeric(text[index + token.length]);
74
+ if (boundedBefore && boundedAfter) {
75
+ return true;
76
+ }
77
+ index = text.indexOf(token, index + 1);
78
+ }
79
+ return false;
80
+ }
81
+ function tokenInText(token, text) {
82
+ if (ASCII_WORD_TOKEN_PATTERN.test(token)) {
83
+ return asciiWordTokenInText(token, text);
84
+ }
85
+ return text.includes(token);
86
+ }
87
+ /**
88
+ * Extract scoring tokens from one role-facing string (id, label, capability).
89
+ *
90
+ * Two kinds of tokens are produced:
91
+ * - ASCII alphanumeric runs of at least 2 characters ("qa", "deployment").
92
+ * - Contiguous CJK runs of at least 2 characters ("核保", "架构设计"), kept
93
+ * whole: `text.includes(token)` then has exact-phrase semantics and cannot
94
+ * produce crossing-window false positives.
95
+ */
96
+ export function extractRoleTokens(entry) {
97
+ const lowered = entry.toLowerCase();
98
+ const tokens = [];
99
+ for (const match of lowered.matchAll(ASCII_TOKEN_PATTERN)) {
100
+ if (match[0].length >= ASCII_TOKEN_MIN_LENGTH) {
101
+ tokens.push(match[0]);
102
+ }
103
+ }
104
+ for (const match of lowered.matchAll(CJK_RUN_PATTERN)) {
105
+ if (match[0].length >= CJK_TOKEN_MIN_LENGTH) {
106
+ tokens.push(match[0]);
107
+ }
108
+ }
109
+ return tokens;
110
+ }
111
+ /** Scoring units of one role: token/phrase -> its highest source-tier weight. */
112
+ function buildRoleScoringUnits(role) {
113
+ const units = new Map();
114
+ const put = (token, weight) => {
115
+ const current = units.get(token);
116
+ if (current === undefined || weight > current) {
117
+ units.set(token, weight);
118
+ }
119
+ };
120
+ const labelZh = typeof role.labelZh === "string" ? role.labelZh.trim().toLowerCase() : "";
121
+ if (labelZh) {
122
+ put(labelZh, WEIGHT_LABELZH_PHRASE);
123
+ for (const token of extractRoleTokens(labelZh)) {
124
+ put(token, WEIGHT_ID_LABEL_WORD);
125
+ }
126
+ }
127
+ const label = role.label.trim().toLowerCase();
128
+ if (label) {
129
+ put(label, WEIGHT_LABEL_PHRASE);
130
+ }
131
+ for (const entry of [role.id, role.label]) {
132
+ for (const token of extractRoleTokens(entry)) {
133
+ put(token, WEIGHT_ID_LABEL_WORD);
134
+ }
135
+ }
136
+ for (const capability of role.capabilities) {
137
+ for (const token of extractRoleTokens(capability)) {
138
+ put(token, WEIGHT_CAPABILITY_WORD);
139
+ }
140
+ }
141
+ return units;
142
+ }
143
+ /**
144
+ * Rank the active profile's roles against the task text with tiered,
145
+ * rarity-adjusted token scoring and report the confidence verdict.
146
+ *
147
+ * Pure function: no LLM calls. Callers that need a decision when
148
+ * `needsLlmFallback` is true own the fallback (see
149
+ * resolveTaskRoleWithLlmFallback in kickoff-orchestrator.ts).
150
+ */
151
+ export function inferTaskRoleWithConfidence(task) {
152
+ if (task.assignedRole) {
153
+ return {
154
+ role: task.assignedRole,
155
+ runnerUp: null,
156
+ topScore: 0,
157
+ runnerUpScore: 0,
158
+ topScoreMinusRunnerUp: 0,
159
+ needsLlmFallback: false,
160
+ reason: "assigned",
161
+ };
162
+ }
163
+ const roles = getActiveRoles();
164
+ const text = `${task.title} ${task.description}`.toLowerCase();
165
+ const unitMaps = roles.map((role) => buildRoleScoringUnits(role));
166
+ // Rarity stopwords over the active profile's role set: token -> number of
167
+ // roles carrying it at any tier.
168
+ const documentFrequency = new Map();
169
+ for (const units of unitMaps) {
170
+ for (const token of units.keys()) {
171
+ documentFrequency.set(token, (documentFrequency.get(token) ?? 0) + 1);
172
+ }
173
+ }
174
+ const stopwordCount = roles.length * RARITY_STOPWORD_FRACTION;
175
+ const isStopword = (token) => (documentFrequency.get(token) ?? 0) > stopwordCount;
176
+ let bestRole = null;
177
+ let bestScore = 0;
178
+ let runnerUpRole = null;
179
+ let runnerUpScore = 0;
180
+ roles.forEach((role, index) => {
181
+ let score = 0;
182
+ for (const [token, weight] of unitMaps[index]) {
183
+ if (isStopword(token)) {
184
+ continue;
185
+ }
186
+ if (tokenInText(token, text)) {
187
+ score += weight;
188
+ }
189
+ }
190
+ if (score > bestScore) {
191
+ runnerUpRole = bestRole;
192
+ runnerUpScore = bestScore;
193
+ bestRole = role.id;
194
+ bestScore = score;
195
+ }
196
+ else if (score > runnerUpScore) {
197
+ runnerUpRole = role.id;
198
+ runnerUpScore = score;
199
+ }
200
+ });
201
+ if (bestScore <= 0) {
202
+ return {
203
+ role: null,
204
+ runnerUp: null,
205
+ topScore: 0,
206
+ runnerUpScore: 0,
207
+ topScoreMinusRunnerUp: 0,
208
+ needsLlmFallback: true,
209
+ reason: "all-zero",
210
+ };
211
+ }
212
+ const margin = bestScore - runnerUpScore;
213
+ if (margin < LLM_FALLBACK_SCORE_MARGIN) {
214
+ return {
215
+ role: bestRole,
216
+ runnerUp: runnerUpRole,
217
+ topScore: bestScore,
218
+ runnerUpScore,
219
+ topScoreMinusRunnerUp: margin,
220
+ needsLlmFallback: true,
221
+ reason: "tie",
222
+ };
223
+ }
224
+ return {
225
+ role: bestRole,
226
+ runnerUp: runnerUpRole,
227
+ topScore: bestScore,
228
+ runnerUpScore,
229
+ topScoreMinusRunnerUp: margin,
230
+ needsLlmFallback: false,
231
+ reason: "confident",
232
+ };
233
+ }
234
+ /**
235
+ * Infer the most appropriate role for a task based on text analysis.
236
+ *
237
+ * If `task.assignedRole` is already set, returns it directly. Otherwise the
238
+ * tiered token fast path decides only when it is confident (design 2.3): a
239
+ * tie between the top two roles - the old "并列取数组靠前" registry-order
240
+ * determinism - or an all-zero scoreboard returns `null` so the caller can
241
+ * escalate to the controller LLM fallback (or its own default role).
242
+ */
243
+ export function inferTaskRole(task) {
244
+ const verdict = inferTaskRoleWithConfidence(task);
245
+ return verdict.needsLlmFallback ? null : verdict.role;
246
+ }