@teamclaws/teamclaw 2026.8.1 → 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 (125) hide show
  1. package/cli.mjs +46 -15
  2. package/dist/src/config.js +33 -2
  3. package/dist/src/controller/clarification-routes.js +315 -0
  4. package/dist/src/controller/controller-intake.js +895 -0
  5. package/dist/src/controller/controller-planning.js +813 -0
  6. package/dist/src/controller/controller-runs.js +175 -0
  7. package/dist/src/controller/controller-service.js +271 -40
  8. package/dist/src/controller/controller-tools.js +11 -6
  9. package/dist/src/controller/http-server.js +256 -6004
  10. package/dist/src/controller/kickoff-orchestrator.js +32 -6
  11. package/dist/src/controller/message-delivery.js +28 -0
  12. package/dist/src/controller/message-routes.js +114 -0
  13. package/dist/src/controller/orchestration-manifest.js +6 -28
  14. package/dist/src/controller/preview-proxy.js +98 -0
  15. package/dist/src/controller/profile-switch.js +289 -0
  16. package/dist/src/controller/project-registry.js +294 -0
  17. package/dist/src/controller/prompt-injector.js +19 -9
  18. package/dist/src/controller/repo-routes.js +63 -0
  19. package/dist/src/controller/role-inference.js +231 -20
  20. package/dist/src/controller/route-table.js +1353 -0
  21. package/dist/src/controller/task-assignment.js +508 -0
  22. package/dist/src/controller/task-cleanup.js +258 -0
  23. package/dist/src/controller/task-execution.js +240 -0
  24. package/dist/src/controller/task-results.js +461 -0
  25. package/dist/src/controller/task-router.js +74 -4
  26. package/dist/src/controller/task-routes.js +703 -0
  27. package/dist/src/controller/teamauto-routes.js +124 -0
  28. package/dist/src/controller/ui-assets.js +68 -0
  29. package/dist/src/controller/worker-provisioning.js +30 -4
  30. package/dist/src/controller/worker-routes.js +188 -0
  31. package/dist/src/identity.js +3 -2
  32. package/dist/src/interaction-contracts.js +7 -7
  33. package/dist/src/openclaw-workspace.js +40 -18
  34. package/dist/src/profile-loader.js +486 -0
  35. package/dist/src/profiles/banking.json +178 -0
  36. package/dist/src/profiles/crossborder-ecom.json +253 -0
  37. package/dist/src/profiles/insurance.json +157 -0
  38. package/dist/src/profiles/knowledge/hs-structure.md +97 -0
  39. package/dist/src/profiles/knowledge/incoterms-2020.md +188 -0
  40. package/dist/src/profiles/knowledge/vat-principles.md +85 -0
  41. package/dist/src/profiles/schema.json +201 -0
  42. package/dist/src/profiles/securities.json +137 -0
  43. package/dist/src/profiles/software-rd.json +264 -0
  44. package/dist/src/profiles/trading-co.json +200 -0
  45. package/dist/src/prompt-policy.js +26 -13
  46. package/dist/src/role-ids.js +29 -0
  47. package/dist/src/roles.js +54 -13
  48. package/dist/src/session-roles.js +14 -0
  49. package/dist/src/state.js +188 -10
  50. package/dist/src/task-executor.js +7 -17
  51. package/dist/src/teamauto/github-client.js +18 -0
  52. package/dist/src/teamauto/repo-sync.js +228 -6
  53. package/dist/src/teamauto/scanner.js +40 -12
  54. package/dist/src/teamauto/scheduler.js +231 -12
  55. package/dist/src/types.js +62 -15
  56. package/dist/src/ui/app.js +592 -24
  57. package/dist/src/ui/index.html +44 -11
  58. package/dist/src/ui/style.css +194 -0
  59. package/dist/src/worker/prompt-injector.js +44 -8
  60. package/dist/src/worker/skill-installer.js +3 -1
  61. package/dist/src/worker/worker-service.js +76 -3
  62. package/openclaw.plugin.json +28 -1
  63. package/package.json +3 -2
  64. package/src/config.ts +33 -2
  65. package/src/controller/clarification-routes.ts +404 -0
  66. package/src/controller/controller-intake.ts +1113 -0
  67. package/src/controller/controller-planning.ts +1029 -0
  68. package/src/controller/controller-runs.ts +239 -0
  69. package/src/controller/controller-service.ts +295 -41
  70. package/src/controller/controller-tools.ts +11 -7
  71. package/src/controller/http-server.ts +294 -6971
  72. package/src/controller/kickoff-orchestrator.ts +70 -7
  73. package/src/controller/message-delivery.ts +49 -0
  74. package/src/controller/message-routes.ts +137 -0
  75. package/src/controller/orchestration-manifest.ts +6 -29
  76. package/src/controller/preview-proxy.ts +127 -0
  77. package/src/controller/profile-switch.ts +366 -0
  78. package/src/controller/project-registry.ts +361 -0
  79. package/src/controller/prompt-injector.ts +23 -8
  80. package/src/controller/repo-routes.ts +91 -0
  81. package/src/controller/role-inference.ts +260 -22
  82. package/src/controller/route-table.ts +1616 -0
  83. package/src/controller/task-assignment.ts +618 -0
  84. package/src/controller/task-cleanup.ts +344 -0
  85. package/src/controller/task-execution.ts +356 -0
  86. package/src/controller/task-results.ts +544 -0
  87. package/src/controller/task-router.ts +98 -6
  88. package/src/controller/task-routes.ts +812 -0
  89. package/src/controller/teamauto-routes.ts +121 -0
  90. package/src/controller/ui-assets.ts +70 -0
  91. package/src/controller/websocket.ts +13 -1
  92. package/src/controller/worker-provisioning.ts +32 -4
  93. package/src/controller/worker-routes.ts +241 -0
  94. package/src/identity.ts +3 -2
  95. package/src/interaction-contracts.ts +7 -7
  96. package/src/openclaw-workspace.ts +44 -18
  97. package/src/profile-loader.ts +650 -0
  98. package/src/profiles/banking.json +178 -0
  99. package/src/profiles/crossborder-ecom.json +253 -0
  100. package/src/profiles/insurance.json +157 -0
  101. package/src/profiles/knowledge/hs-structure.md +97 -0
  102. package/src/profiles/knowledge/incoterms-2020.md +188 -0
  103. package/src/profiles/knowledge/vat-principles.md +85 -0
  104. package/src/profiles/schema.json +201 -0
  105. package/src/profiles/securities.json +137 -0
  106. package/src/profiles/software-rd.json +264 -0
  107. package/src/profiles/trading-co.json +200 -0
  108. package/src/prompt-policy.ts +27 -13
  109. package/src/role-ids.ts +31 -0
  110. package/src/roles.ts +60 -14
  111. package/src/session-roles.ts +14 -0
  112. package/src/state.ts +236 -9
  113. package/src/task-executor.ts +7 -18
  114. package/src/teamauto/github-client.ts +21 -0
  115. package/src/teamauto/repo-sync.ts +246 -6
  116. package/src/teamauto/scanner.ts +47 -13
  117. package/src/teamauto/scheduler.ts +259 -16
  118. package/src/teamauto/store.ts +12 -0
  119. package/src/types.ts +133 -16
  120. package/src/ui/app.js +592 -24
  121. package/src/ui/index.html +44 -11
  122. package/src/ui/style.css +194 -0
  123. package/src/worker/prompt-injector.ts +48 -8
  124. package/src/worker/skill-installer.ts +3 -1
  125. package/src/worker/worker-service.ts +83 -3
@@ -0,0 +1,294 @@
1
+ import { deriveStableProjectKey } from "../openclaw-workspace.js";
2
+ import { normalizeControllerIntakeSessionKey } from "./task-execution.js";
3
+ const EXISTING_PROJECT_REUSE_HINT_RE = /\b(existing|optimi(?:s|z)e|optimi(?:s|z)ation|improvement|enhanc(?:e|ement)|follow[- ]?up|extend|update|bugfix|bug fix)\b/iu;
4
+ const GENERIC_PROJECT_FOLLOW_UP_RE = /\b(continue|continuing|next step|what else|what's next|follow[- ]?up|more|remaining)\b|继续|接下来|下一步|还有哪些|还可以做什么/u;
5
+ const PROJECT_MATCH_STOPWORDS = new Set([
6
+ "a",
7
+ "an",
8
+ "and",
9
+ "app",
10
+ "application",
11
+ "build",
12
+ "complete",
13
+ "existing",
14
+ "follow",
15
+ "for",
16
+ "hub",
17
+ "improvement",
18
+ "improvements",
19
+ "internal",
20
+ "optimization",
21
+ "product",
22
+ "project",
23
+ "requirement",
24
+ "request",
25
+ "studio",
26
+ "system",
27
+ "the",
28
+ "this",
29
+ "up",
30
+ "update",
31
+ "web",
32
+ ]);
33
+ export function resolveExistingProjectIdentityFromMessage(message, state) {
34
+ const normalizedMessage = normalizeProjectMatchingText(message);
35
+ if (!normalizedMessage) {
36
+ return undefined;
37
+ }
38
+ const explicitAlias = normalizeProjectMatchingText(extractExplicitProjectNameHint(message) ?? "");
39
+ let best = null;
40
+ const candidates = collectExistingProjectCandidates(state);
41
+ for (const candidate of candidates) {
42
+ const normalizedAliases = Array.from(candidate.aliases)
43
+ .map((alias) => normalizeProjectMatchingText(alias))
44
+ .filter(Boolean)
45
+ .reduce((acc, alias) => {
46
+ acc.push(alias);
47
+ return acc;
48
+ }, []);
49
+ const hasExplicitAliasMatch = explicitAlias
50
+ ? normalizedAliases.some((alias) => alias.includes(explicitAlias) || explicitAlias.includes(alias))
51
+ : false;
52
+ if (explicitAlias && !hasExplicitAliasMatch) {
53
+ continue;
54
+ }
55
+ const aliasScore = normalizedAliases
56
+ .reduce((score, alias) => {
57
+ if (!alias) {
58
+ return score;
59
+ }
60
+ return normalizedMessage.includes(alias)
61
+ ? Math.max(score, alias.split(" ").length + 10)
62
+ : score;
63
+ }, 0);
64
+ const tokenScore = scoreProjectTokenOverlap(normalizedMessage, candidate.searchText);
65
+ const totalScore = Math.max(aliasScore, tokenScore);
66
+ if (totalScore < 2) {
67
+ continue;
68
+ }
69
+ if (!best || totalScore > best.score || (totalScore === best.score && candidate.updatedAt > best.updatedAt)) {
70
+ best = {
71
+ projectId: candidate.projectId,
72
+ projectDir: candidate.projectDir,
73
+ score: totalScore,
74
+ updatedAt: candidate.updatedAt,
75
+ };
76
+ }
77
+ }
78
+ if (best) {
79
+ return { projectId: best.projectId, projectDir: best.projectDir };
80
+ }
81
+ if ((EXISTING_PROJECT_REUSE_HINT_RE.test(message) || GENERIC_PROJECT_FOLLOW_UP_RE.test(message)) && candidates.length === 1) {
82
+ return {
83
+ projectId: candidates[0]?.projectId,
84
+ projectDir: candidates[0]?.projectDir,
85
+ };
86
+ }
87
+ return undefined;
88
+ }
89
+ export function collectExistingProjectCandidates(state) {
90
+ const byProjectDir = new Map();
91
+ const addCandidate = (projectDir, text, updatedAt, alias, projectId) => {
92
+ if (!projectDir) {
93
+ return;
94
+ }
95
+ const entry = byProjectDir.get(projectDir) ?? { projectId, aliases: new Set(), texts: [], updatedAt: 0 };
96
+ if (!entry.projectId && projectId) {
97
+ entry.projectId = projectId;
98
+ }
99
+ if (text && text.trim()) {
100
+ entry.texts.push(text);
101
+ }
102
+ if (alias && alias.trim()) {
103
+ entry.aliases.add(alias.trim());
104
+ }
105
+ entry.updatedAt = Math.max(entry.updatedAt, updatedAt);
106
+ byProjectDir.set(projectDir, entry);
107
+ };
108
+ for (const project of Object.values(state?.projects ?? {})) {
109
+ addCandidate(project.projectDir, project.summary, project.updatedAt, project.id, project.id);
110
+ for (const alias of project.aliases ?? []) {
111
+ addCandidate(project.projectDir, alias, project.updatedAt, alias, project.id);
112
+ }
113
+ }
114
+ for (const run of Object.values(state?.controllerRuns ?? {})) {
115
+ addCandidate(run.projectDir, run.request, run.updatedAt, extractProjectAliasFromText(run.request), run.projectId);
116
+ addCandidate(run.projectDir, run.title, run.updatedAt, extractProjectAliasFromText(run.title), run.projectId);
117
+ addCandidate(run.projectDir, run.manifest?.projectName, run.updatedAt, run.manifest?.projectName, run.projectId);
118
+ }
119
+ for (const task of Object.values(state?.tasks ?? {})) {
120
+ addCandidate(task.projectDir, task.title, task.updatedAt, extractProjectAliasFromText(task.title), task.projectId);
121
+ addCandidate(task.projectDir, task.description, task.updatedAt, extractProjectAliasFromText(task.description), task.projectId);
122
+ addCandidate(task.projectDir, task.resultContract?.summary, task.updatedAt, null, task.projectId);
123
+ }
124
+ return Array.from(byProjectDir.entries()).map(([projectDir, entry]) => ({
125
+ projectId: entry.projectId,
126
+ projectDir,
127
+ aliases: entry.aliases,
128
+ searchText: entry.texts.join("\n"),
129
+ updatedAt: entry.updatedAt,
130
+ }));
131
+ }
132
+ export function extractExplicitProjectNameHint(text) {
133
+ const value = String(text ?? "");
134
+ const namedMatch = value.match(/(?:品牌|brand|project\s*name|产品名|名字)\s*[::]?\s*[`"'“”]?([a-z][a-z0-9_-]{1,39})[`"'“”]?/iu);
135
+ if (namedMatch?.[1]) {
136
+ return deriveStableProjectKey(namedMatch[1]);
137
+ }
138
+ const inlineNames = Array.from(value.matchAll(/`([a-z][a-z0-9_-]{1,39})`/giu))
139
+ .map((match) => deriveStableProjectKey(match[1]))
140
+ .filter(Boolean);
141
+ return inlineNames.length === 1 ? inlineNames[0] : undefined;
142
+ }
143
+ export function findProjectRecordByDir(state, projectDir) {
144
+ if (!state || !projectDir) {
145
+ return undefined;
146
+ }
147
+ return Object.values(state.projects ?? {}).find((project) => project.projectDir === projectDir);
148
+ }
149
+ export function syncProjectRegistryEntry(state, input) {
150
+ state.projects = state.projects && typeof state.projects === "object" ? state.projects : {};
151
+ let normalizedProjectId = deriveStableProjectKey(input.projectId ?? "");
152
+ let existing = normalizedProjectId ? state.projects[normalizedProjectId] : undefined;
153
+ const byDir = findProjectRecordByDir(state, input.projectDir);
154
+ if (!existing && byDir) {
155
+ existing = byDir;
156
+ }
157
+ if (!existing && input.projectDir) {
158
+ normalizedProjectId = normalizedProjectId || deriveStableProjectKey(input.projectDir);
159
+ if (normalizedProjectId) {
160
+ existing = {
161
+ id: normalizedProjectId,
162
+ projectDir: input.projectDir,
163
+ aliases: [],
164
+ createdAt: input.updatedAt,
165
+ updatedAt: input.updatedAt,
166
+ lastUsedAt: input.updatedAt,
167
+ };
168
+ state.projects[normalizedProjectId] = existing;
169
+ }
170
+ }
171
+ if (!existing) {
172
+ return { projectId: normalizedProjectId || undefined, projectDir: input.projectDir };
173
+ }
174
+ if (normalizedProjectId && existing.id !== normalizedProjectId && !state.projects[normalizedProjectId]) {
175
+ delete state.projects[existing.id];
176
+ existing.id = normalizedProjectId;
177
+ state.projects[normalizedProjectId] = existing;
178
+ }
179
+ if (!existing.projectDir && input.projectDir) {
180
+ existing.projectDir = input.projectDir;
181
+ }
182
+ const aliasSet = new Set(existing.aliases ?? []);
183
+ aliasSet.add(existing.id);
184
+ if (existing.projectDir) {
185
+ aliasSet.add(existing.projectDir);
186
+ }
187
+ for (const alias of input.aliases ?? []) {
188
+ const normalizedAlias = deriveStableProjectKey(String(alias ?? ""));
189
+ if (normalizedAlias) {
190
+ aliasSet.add(normalizedAlias);
191
+ }
192
+ }
193
+ existing.aliases = Array.from(aliasSet);
194
+ existing.summary = input.summary || existing.summary;
195
+ existing.updatedAt = Math.max(existing.updatedAt || 0, input.updatedAt);
196
+ existing.lastUsedAt = Math.max(existing.lastUsedAt || 0, input.updatedAt);
197
+ return { projectId: existing.id, projectDir: existing.projectDir };
198
+ }
199
+ export function resolveProjectIdentityForSession(sessionKey, state) {
200
+ const runId = findLatestControllerRunIdForSession(sessionKey, state, { preferActive: true });
201
+ if (!runId) {
202
+ return undefined;
203
+ }
204
+ const run = state?.controllerRuns[runId];
205
+ if (!run) {
206
+ return undefined;
207
+ }
208
+ const project = findProjectRecordByDir(state, run.projectDir);
209
+ return {
210
+ projectId: run.projectId ?? project?.id,
211
+ projectDir: run.projectDir ?? project?.projectDir,
212
+ };
213
+ }
214
+ export function resolveProjectIdentityForTaskId(taskId, state) {
215
+ const task = state?.tasks?.[taskId];
216
+ if (!task) {
217
+ return undefined;
218
+ }
219
+ const project = findProjectRecordByDir(state, task.projectDir);
220
+ return {
221
+ projectId: task.projectId ?? project?.id,
222
+ projectDir: task.projectDir ?? project?.projectDir,
223
+ };
224
+ }
225
+ export function extractProjectAliasFromText(text) {
226
+ const firstMeaningfulLine = String(text ?? "")
227
+ .split(/\n+/u)
228
+ .map((line) => line.replace(/^#+\s*/u, "").trim())
229
+ .find(Boolean);
230
+ if (!firstMeaningfulLine) {
231
+ return null;
232
+ }
233
+ const normalized = firstMeaningfulLine
234
+ .replace(/^(product|optimization)\s+requirement[::]\s*/iu, "")
235
+ .replace(/^implement\s+/iu, "")
236
+ .replace(/^design\s+/iu, "")
237
+ .replace(/^enhance\s+/iu, "")
238
+ .replace(/^qa[:\s-]+/iu, "")
239
+ .replace(/\s+(architecture|application|web app|workflows?|improvements?)$/iu, "")
240
+ .trim();
241
+ if (normalized.length < 4 || normalized.length > 80) {
242
+ return null;
243
+ }
244
+ return normalized;
245
+ }
246
+ export function normalizeProjectMatchingText(text) {
247
+ return text
248
+ .toLowerCase()
249
+ .replace(/[`*_#:[\]()/\\-]+/gu, " ")
250
+ .replace(/\s+/gu, " ")
251
+ .trim();
252
+ }
253
+ export function scoreProjectTokenOverlap(message, candidateText) {
254
+ const messageTokens = tokenizeProjectMatchingText(message);
255
+ if (messageTokens.size === 0) {
256
+ return 0;
257
+ }
258
+ const candidateTokens = tokenizeProjectMatchingText(candidateText);
259
+ let overlap = 0;
260
+ for (const token of candidateTokens) {
261
+ if (messageTokens.has(token)) {
262
+ overlap += 1;
263
+ }
264
+ }
265
+ return overlap;
266
+ }
267
+ export function tokenizeProjectMatchingText(text) {
268
+ return new Set(normalizeProjectMatchingText(text)
269
+ .split(" ")
270
+ .map((token) => token.trim())
271
+ .filter((token) => token.length >= 4 && !PROJECT_MATCH_STOPWORDS.has(token)));
272
+ }
273
+ export function isActiveControllerRun(run) {
274
+ return run.status === "pending" || run.status === "running";
275
+ }
276
+ export function findLatestControllerRunIdForSession(sessionKey, state, options) {
277
+ const normalizedSessionKey = normalizeControllerIntakeSessionKey(sessionKey);
278
+ const matchingRuns = Object.values(state?.controllerRuns ?? {})
279
+ .filter((run) => normalizeControllerIntakeSessionKey(run.sessionKey) === normalizedSessionKey)
280
+ .sort((left, right) => {
281
+ if (options?.preferActive) {
282
+ const leftScore = isActiveControllerRun(left) ? 1 : 0;
283
+ const rightScore = isActiveControllerRun(right) ? 1 : 0;
284
+ if (leftScore !== rightScore) {
285
+ return rightScore - leftScore;
286
+ }
287
+ }
288
+ return right.updatedAt - left.updatedAt;
289
+ });
290
+ return matchingRuns[0]?.id ?? null;
291
+ }
292
+ export function resolveProjectDirForSession(sessionKey, state) {
293
+ return resolveProjectIdentityForSession(sessionKey, state)?.projectDir;
294
+ }
@@ -1,14 +1,10 @@
1
- import { ROLES } from "../roles.js";
2
- import { buildControllerCompletionRules, buildControllerDisciplineRules, buildControllerEvidenceMemoryRules, buildControllerIntakeRules, buildControllerStructuredContractRules, buildControllerToolRules, buildControllerWorkflowRules, composePrompt, } from "../prompt-policy.js";
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";
3
4
  import { hasOnDemandWorkerProvisioning, shouldBlockControllerWithoutWorkers } from "./controller-capacity.js";
4
5
  import { resolveTeamClawWorkspaceDir } from "../openclaw-workspace.js";
5
6
  import fs from "node:fs";
6
7
  import path from "node:path";
7
- const TEAMCLAW_ROLE_IDS_TEXT = [
8
- "pm", "architect", "developer", "qa",
9
- "release-engineer", "infra-engineer", "devops", "security-engineer",
10
- "designer", "marketing", "data-engineer",
11
- ];
12
8
  export function createControllerPromptInjector(deps) {
13
9
  return () => {
14
10
  const state = deps.getTeamState();
@@ -44,7 +40,7 @@ export function createControllerPromptInjector(deps) {
44
40
  }
45
41
  else {
46
42
  for (const w of workers) {
47
- const roleDef = ROLES.find((r) => r.id === w.role);
43
+ const roleDef = getActiveRoles().find((r) => r.id === w.role);
48
44
  const statusIcon = w.status === "idle" ? "[idle]" : w.status === "busy" ? "[busy]" : "[offline]";
49
45
  const currentTask = w.currentTaskId ? ` (task: ${w.currentTaskId})` : "";
50
46
  parts.push(`- ${roleDef?.icon ?? ""} ${w.label} (${w.id}) ${statusIcon}${currentTask}`);
@@ -69,12 +65,26 @@ export function createControllerPromptInjector(deps) {
69
65
  }
70
66
  parts.push("");
71
67
  parts.push("### Available Roles");
72
- for (const role of ROLES) {
68
+ for (const role of getActiveRoles()) {
73
69
  const skillLine = role.recommendedSkills.length > 0
74
70
  ? ` Recommended skills: ${role.recommendedSkills.join(", ")}.`
75
71
  : "";
76
72
  parts.push(`- ${role.icon} ${role.label}: ${role.description}.${skillLine}`);
77
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
+ }
78
88
  // List existing projects so the controller can distinguish new vs. existing
79
89
  parts.push("");
80
90
  parts.push("### Existing Projects in Workspace");
@@ -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
+ }
@@ -1,35 +1,246 @@
1
- import { ROLES } from "../roles.js";
1
+ // Phase 1.3: inference candidates come from the active TeamProfile.
2
+ import { getActiveRoles } from "../profile-loader.js";
2
3
  /**
3
- * Infer the most appropriate role for a task based on text analysis.
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).
4
89
  *
5
- * If `task.assignedRole` is already set, returns it directly.
6
- * Otherwise, tokenizes the task title + description and scores each known
7
- * role by overlap with its id, label, and capabilities.
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.
8
95
  */
9
- export function inferTaskRole(task) {
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) {
10
152
  if (task.assignedRole) {
11
- return 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
+ };
12
162
  }
163
+ const roles = getActiveRoles();
13
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;
14
176
  let bestRole = null;
15
177
  let bestScore = 0;
16
- for (const role of ROLES) {
17
- const roleTokens = [
18
- role.id,
19
- role.label,
20
- ...role.capabilities,
21
- ].flatMap((entry) => entry.toLowerCase().split(/[^a-z0-9]+/).filter((token) => token.length > 2));
22
- const uniqueTokens = [...new Set(roleTokens)];
23
- const score = uniqueTokens.reduce((count, token) => count + (text.includes(token) ? 1 : 0), 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
+ }
24
190
  if (score > bestScore) {
25
- bestScore = score;
191
+ runnerUpRole = bestRole;
192
+ runnerUpScore = bestScore;
26
193
  bestRole = role.id;
194
+ bestScore = score;
195
+ }
196
+ else if (score > runnerUpScore) {
197
+ runnerUpRole = role.id;
198
+ runnerUpScore = score;
27
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
+ };
28
211
  }
29
- return bestScore > 0 ? bestRole : null;
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
+ };
30
233
  }
31
234
  /**
32
- * Fallback role when inference produces no match.
33
- * The developer role is the most versatile generalist.
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).
34
242
  */
35
- export const FALLBACK_ROLE = "developer";
243
+ export function inferTaskRole(task) {
244
+ const verdict = inferTaskRoleWithConfidence(task);
245
+ return verdict.needsLlmFallback ? null : verdict.role;
246
+ }