@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,64 @@
1
+ // Issue #226 W2 (route-table carve-up): the delivery-report / health route
2
+ // handlers moved verbatim from route-table.ts (PR-D had moved them verbatim
3
+ // from http-server.ts before that) - bodies byte-identical, only the module
4
+ // home changed. route-table.ts keeps the table entries that bind these
5
+ // handlers. Like security.ts, this module imports route-table.js as TYPE
6
+ // ONLY (RouteContext), so the module graph stays acyclic.
7
+ import { sendJson, sendError } from "../protocol.js";
8
+ import { getTeamClawModelReadiness } from "../openclaw-workspace.js";
9
+ import { generateDeliveryReport, renderReportHtml } from "./delivery-report.js";
10
+ import { normalizeControllerIntakeSessionKey } from "./task-execution.js";
11
+ import { getEffectiveStartupReadiness } from "./worker-routes.js";
12
+ import type { RouteContext } from "./route-table.js";
13
+
14
+ // GET /api/v1/reports — list all delivery reports
15
+ function reportsListRoute(ctx: RouteContext): void {
16
+ const { res, deps } = ctx;
17
+ const state = deps.getTeamState();
18
+ const reports = Object.values(state?.reports ?? {}).sort((a, b) => b.generatedAt - a.generatedAt);
19
+ sendJson(res, 200, { reports });
20
+ }
21
+
22
+ // GET /api/v1/reports/:sessionKey — serve delivery report page
23
+ async function reportsSessionRoute(ctx: RouteContext): Promise<void> {
24
+ const { req, res, pathname, deps } = ctx;
25
+ const sessionKey = decodeURIComponent(pathname.slice("/api/v1/reports/".length));
26
+ const state = deps.getTeamState();
27
+ if (!state) {
28
+ sendError(res, 503, "Team state not loaded");
29
+ return;
30
+ }
31
+ const report = generateDeliveryReport(sessionKey, state, normalizeControllerIntakeSessionKey);
32
+ if (!report) {
33
+ sendError(res, 404, "No report found for this session");
34
+ return;
35
+ }
36
+ const accept = (req.headers["accept"] ?? "").toLowerCase();
37
+ if (accept.includes("application/json")) {
38
+ sendJson(res, 200, { report });
39
+ } else {
40
+ const html = renderReportHtml(report);
41
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Content-Length": Buffer.byteLength(html, "utf-8") });
42
+ res.end(html);
43
+ }
44
+ }
45
+
46
+ function healthRoute(ctx: RouteContext): void {
47
+ const { res, deps, currentState } = ctx;
48
+ const readiness = getEffectiveStartupReadiness(deps, currentState);
49
+ const modelReadiness = getTeamClawModelReadiness();
50
+ const statusCode = readiness && readiness.status !== "ready" ? 503 : 200;
51
+ sendJson(res, statusCode, {
52
+ status: readiness?.status === "degraded" ? "degraded" : readiness?.status === "checking" ? "starting" : "ok",
53
+ mode: "controller",
54
+ timestamp: Date.now(),
55
+ provisioningReadiness: readiness,
56
+ modelReadiness,
57
+ });
58
+ }
59
+
60
+ export {
61
+ reportsListRoute,
62
+ reportsSessionRoute,
63
+ healthRoute,
64
+ };
@@ -1,41 +1,279 @@
1
- import { ROLES } from "../roles.js";
1
+ // Phase 1.3: inference candidates come from the active TeamProfile.
2
+ import { getActiveRoles } from "../profile-loader.js";
3
+ import type { ProfileRoleDefinition } from "../profile-loader.js";
2
4
  import type { RoleId, TaskInfo } from "../types.js";
3
5
 
4
6
  /**
5
- * Infer the most appropriate role for a task based on text analysis.
7
+ * Minimum length for ASCII (latin letter / digit) tokens. Two-character
8
+ * tokens such as "qa", "pm", "ci", "ui" are meaningful role identifiers and
9
+ * must participate in scoring. The previous `length > 2` filter dropped them.
10
+ */
11
+ const ASCII_TOKEN_MIN_LENGTH = 2;
12
+
13
+ /**
14
+ * Minimum length for CJK run tokens, in characters. Single CJK characters
15
+ * are too ambiguous to score on; runs of two or more characters are kept.
16
+ */
17
+ const CJK_TOKEN_MIN_LENGTH = 2;
18
+
19
+ const ASCII_TOKEN_PATTERN = /[a-z0-9]+/g;
20
+ // A token made purely of ASCII letters/digits (all tokens the pattern above
21
+ // extracts). Such tokens match as STANDALONE WORDS, never as substrings of a
22
+ // longer ASCII word: "data" must not hit "database", "test" must not hit
23
+ // "testing", "pm" must not hit "npm". Multi-word phrases ("software
24
+ // architect") and CJK runs keep whole-phrase containment semantics.
25
+ const ASCII_WORD_TOKEN_PATTERN = /^[a-z0-9]+$/;
26
+ // CJK Unified Ideographs, Extension A, and CJK Compatibility Ideographs.
27
+ const CJK_RUN_PATTERN = /[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]+/g;
28
+
29
+ // ---------------------------------------------------------------------------
30
+ // Phase 2.5 tiered scoring (vertical-team-profiles-design.md section 2.3).
31
+ //
32
+ // Token hits are weighted by their SOURCE tier:
33
+ // labelZh full phrase > label full phrase > id/label word > capability word
34
+ // ("labelZh 完整词 > 高区分度业务词 > 泛化词"). Weights are integers so the
35
+ // fallback margin below is measured in whole tiers or whole token hits.
36
+ // ---------------------------------------------------------------------------
37
+ const WEIGHT_LABELZH_PHRASE = 8;
38
+ const WEIGHT_LABEL_PHRASE = 6;
39
+ const WEIGHT_ID_LABEL_WORD = 3;
40
+ const WEIGHT_CAPABILITY_WORD = 1;
41
+
42
+ /**
43
+ * Rarity stopword threshold (design 2.3): a token that appears in MORE THAN
44
+ * one third of the active profile's roles discriminates nothing
45
+ * ("分析/管理/合规 全员命中等于没命中") and is dropped from scoring entirely.
46
+ * Computed per inference call over the active role set, so a token that is
47
+ * generic in one profile (合规 in banking) can stay distinctive in another.
48
+ */
49
+ const RARITY_STOPWORD_FRACTION = 1 / 3;
50
+
51
+ /**
52
+ * LLM-fallback margin (design 2.3): the token fast path is confident only
53
+ * when the runner-up scores strictly below the winner by at least this much.
54
+ * Any tie (margin < 1) escalates to the LLM fallback instead of the old
55
+ * "并列取数组靠前" registry-order determinism. The value is 1 - not higher -
56
+ * because the design's own high-distinctiveness examples (反洗钱→aml-analyst,
57
+ * 贷审→approver) are single capability-tier hits with margin exactly 1 and
58
+ * must stay on the fast path.
59
+ */
60
+ const LLM_FALLBACK_SCORE_MARGIN = 1;
61
+
62
+ function isAsciiAlphanumeric(char: string | undefined): boolean {
63
+ if (!char) {
64
+ return false;
65
+ }
66
+ return (char >= "0" && char <= "9") || (char >= "a" && char <= "z");
67
+ }
68
+
69
+ /**
70
+ * Check whether a pure-ASCII word token occurs in `text` as a standalone
71
+ * word rather than inside a longer ASCII word. Plain substring containment
72
+ * would misroute texts like "npm install fails" to the "pm" role, "build a
73
+ * guide page" to the "ui" role, or (Phase 2.5 regression found in testing)
74
+ * "Design the database schema" to the data-engineer role via "data" inside
75
+ * "database". Non-ASCII neighbours (CJK characters, punctuation, string
76
+ * boundaries, hyphens in kebab ids) still count as boundaries, so "qa"
77
+ * matches inside "处理QA登录问题" after lowercasing.
78
+ */
79
+ function asciiWordTokenInText(token: string, text: string): boolean {
80
+ let index = text.indexOf(token);
81
+ while (index !== -1) {
82
+ const boundedBefore = !isAsciiAlphanumeric(text[index - 1]);
83
+ const boundedAfter = !isAsciiAlphanumeric(text[index + token.length]);
84
+ if (boundedBefore && boundedAfter) {
85
+ return true;
86
+ }
87
+ index = text.indexOf(token, index + 1);
88
+ }
89
+ return false;
90
+ }
91
+
92
+ function tokenInText(token: string, text: string): boolean {
93
+ if (ASCII_WORD_TOKEN_PATTERN.test(token)) {
94
+ return asciiWordTokenInText(token, text);
95
+ }
96
+ return text.includes(token);
97
+ }
98
+
99
+ /**
100
+ * Extract scoring tokens from one role-facing string (id, label, capability).
6
101
  *
7
- * If `task.assignedRole` is already set, returns it directly.
8
- * Otherwise, tokenizes the task title + description and scores each known
9
- * role by overlap with its id, label, and capabilities.
102
+ * Two kinds of tokens are produced:
103
+ * - ASCII alphanumeric runs of at least 2 characters ("qa", "deployment").
104
+ * - Contiguous CJK runs of at least 2 characters ("核保", "架构设计"), kept
105
+ * whole: `text.includes(token)` then has exact-phrase semantics and cannot
106
+ * produce crossing-window false positives.
10
107
  */
11
- export function inferTaskRole(task: Pick<TaskInfo, "assignedRole" | "title" | "description">): RoleId | null {
108
+ export function extractRoleTokens(entry: string): string[] {
109
+ const lowered = entry.toLowerCase();
110
+ const tokens: string[] = [];
111
+ for (const match of lowered.matchAll(ASCII_TOKEN_PATTERN)) {
112
+ if (match[0].length >= ASCII_TOKEN_MIN_LENGTH) {
113
+ tokens.push(match[0]);
114
+ }
115
+ }
116
+ for (const match of lowered.matchAll(CJK_RUN_PATTERN)) {
117
+ if (match[0].length >= CJK_TOKEN_MIN_LENGTH) {
118
+ tokens.push(match[0]);
119
+ }
120
+ }
121
+ return tokens;
122
+ }
123
+
124
+ /** Scoring units of one role: token/phrase -> its highest source-tier weight. */
125
+ function buildRoleScoringUnits(role: ProfileRoleDefinition): Map<string, number> {
126
+ const units = new Map<string, number>();
127
+ const put = (token: string, weight: number): void => {
128
+ const current = units.get(token);
129
+ if (current === undefined || weight > current) {
130
+ units.set(token, weight);
131
+ }
132
+ };
133
+
134
+ const labelZh = typeof role.labelZh === "string" ? role.labelZh.trim().toLowerCase() : "";
135
+ if (labelZh) {
136
+ put(labelZh, WEIGHT_LABELZH_PHRASE);
137
+ for (const token of extractRoleTokens(labelZh)) {
138
+ put(token, WEIGHT_ID_LABEL_WORD);
139
+ }
140
+ }
141
+ const label = role.label.trim().toLowerCase();
142
+ if (label) {
143
+ put(label, WEIGHT_LABEL_PHRASE);
144
+ }
145
+ for (const entry of [role.id, role.label]) {
146
+ for (const token of extractRoleTokens(entry)) {
147
+ put(token, WEIGHT_ID_LABEL_WORD);
148
+ }
149
+ }
150
+ for (const capability of role.capabilities) {
151
+ for (const token of extractRoleTokens(capability)) {
152
+ put(token, WEIGHT_CAPABILITY_WORD);
153
+ }
154
+ }
155
+ return units;
156
+ }
157
+
158
+ export type RoleInferenceVerdict = {
159
+ /** Fast-path winner; null when nothing scored or the verdict escalated. */
160
+ role: RoleId | null;
161
+ runnerUp: RoleId | null;
162
+ topScore: number;
163
+ runnerUpScore: number;
164
+ topScoreMinusRunnerUp: number;
165
+ /** True when the token fast path refuses to decide (design 2.3 LLM fallback). */
166
+ needsLlmFallback: boolean;
167
+ reason: "assigned" | "confident" | "all-zero" | "tie";
168
+ };
169
+
170
+ /**
171
+ * Rank the active profile's roles against the task text with tiered,
172
+ * rarity-adjusted token scoring and report the confidence verdict.
173
+ *
174
+ * Pure function: no LLM calls. Callers that need a decision when
175
+ * `needsLlmFallback` is true own the fallback (see
176
+ * resolveTaskRoleWithLlmFallback in kickoff-orchestrator.ts).
177
+ */
178
+ export function inferTaskRoleWithConfidence(
179
+ task: Pick<TaskInfo, "assignedRole" | "title" | "description">,
180
+ ): RoleInferenceVerdict {
12
181
  if (task.assignedRole) {
13
- return task.assignedRole;
182
+ return {
183
+ role: task.assignedRole,
184
+ runnerUp: null,
185
+ topScore: 0,
186
+ runnerUpScore: 0,
187
+ topScoreMinusRunnerUp: 0,
188
+ needsLlmFallback: false,
189
+ reason: "assigned",
190
+ };
14
191
  }
15
192
 
193
+ const roles = getActiveRoles();
16
194
  const text = `${task.title} ${task.description}`.toLowerCase();
195
+ const unitMaps = roles.map((role) => buildRoleScoringUnits(role));
196
+
197
+ // Rarity stopwords over the active profile's role set: token -> number of
198
+ // roles carrying it at any tier.
199
+ const documentFrequency = new Map<string, number>();
200
+ for (const units of unitMaps) {
201
+ for (const token of units.keys()) {
202
+ documentFrequency.set(token, (documentFrequency.get(token) ?? 0) + 1);
203
+ }
204
+ }
205
+ const stopwordCount = roles.length * RARITY_STOPWORD_FRACTION;
206
+ const isStopword = (token: string): boolean => (documentFrequency.get(token) ?? 0) > stopwordCount;
207
+
17
208
  let bestRole: RoleId | null = null;
18
209
  let bestScore = 0;
19
-
20
- for (const role of ROLES) {
21
- const roleTokens = [
22
- role.id,
23
- role.label,
24
- ...role.capabilities,
25
- ].flatMap((entry) => entry.toLowerCase().split(/[^a-z0-9]+/).filter((token) => token.length > 2));
26
- const uniqueTokens = [...new Set(roleTokens)];
27
- const score = uniqueTokens.reduce((count, token) => count + (text.includes(token) ? 1 : 0), 0);
210
+ let runnerUpRole: RoleId | null = null;
211
+ let runnerUpScore = 0;
212
+ roles.forEach((role, index) => {
213
+ let score = 0;
214
+ for (const [token, weight] of unitMaps[index]!) {
215
+ if (isStopword(token)) {
216
+ continue;
217
+ }
218
+ if (tokenInText(token, text)) {
219
+ score += weight;
220
+ }
221
+ }
28
222
  if (score > bestScore) {
29
- bestScore = score;
223
+ runnerUpRole = bestRole;
224
+ runnerUpScore = bestScore;
30
225
  bestRole = role.id;
226
+ bestScore = score;
227
+ } else if (score > runnerUpScore) {
228
+ runnerUpRole = role.id;
229
+ runnerUpScore = score;
31
230
  }
32
- }
231
+ });
33
232
 
34
- return bestScore > 0 ? bestRole : null;
233
+ if (bestScore <= 0) {
234
+ return {
235
+ role: null,
236
+ runnerUp: null,
237
+ topScore: 0,
238
+ runnerUpScore: 0,
239
+ topScoreMinusRunnerUp: 0,
240
+ needsLlmFallback: true,
241
+ reason: "all-zero",
242
+ };
243
+ }
244
+ const margin = bestScore - runnerUpScore;
245
+ if (margin < LLM_FALLBACK_SCORE_MARGIN) {
246
+ return {
247
+ role: bestRole,
248
+ runnerUp: runnerUpRole,
249
+ topScore: bestScore,
250
+ runnerUpScore,
251
+ topScoreMinusRunnerUp: margin,
252
+ needsLlmFallback: true,
253
+ reason: "tie",
254
+ };
255
+ }
256
+ return {
257
+ role: bestRole,
258
+ runnerUp: runnerUpRole,
259
+ topScore: bestScore,
260
+ runnerUpScore,
261
+ topScoreMinusRunnerUp: margin,
262
+ needsLlmFallback: false,
263
+ reason: "confident",
264
+ };
35
265
  }
36
266
 
37
267
  /**
38
- * Fallback role when inference produces no match.
39
- * The developer role is the most versatile generalist.
268
+ * Infer the most appropriate role for a task based on text analysis.
269
+ *
270
+ * If `task.assignedRole` is already set, returns it directly. Otherwise the
271
+ * tiered token fast path decides only when it is confident (design 2.3): a
272
+ * tie between the top two roles - the old "并列取数组靠前" registry-order
273
+ * determinism - or an all-zero scoreboard returns `null` so the caller can
274
+ * escalate to the controller LLM fallback (or its own default role).
40
275
  */
41
- export const FALLBACK_ROLE: RoleId = "developer";
276
+ export function inferTaskRole(task: Pick<TaskInfo, "assignedRole" | "title" | "description">): RoleId | null {
277
+ const verdict = inferTaskRoleWithConfidence(task);
278
+ return verdict.needsLlmFallback ? null : verdict.role;
279
+ }