@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,361 @@
1
+ // PR-C of issue #204 (http-server monolith split): the controller project
2
+ // identity/registry family and the controller-run session queries extracted
3
+ // verbatim from controller/http-server.ts. Zero behavior change. This module
4
+ // must NEVER import http-server (the reverse edge exists:
5
+ // http-server -> project-registry); every function here is pure over
6
+ // TeamState/ControllerRunInfo snapshots.
7
+ import type {
8
+ ControllerRunInfo,
9
+ TeamState,
10
+ } from "../types.js";
11
+ import { deriveStableProjectKey } from "../openclaw-workspace.js";
12
+ import { normalizeControllerIntakeSessionKey } from "./task-execution.js";
13
+
14
+ 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;
15
+ const GENERIC_PROJECT_FOLLOW_UP_RE = /\b(continue|continuing|next step|what else|what's next|follow[- ]?up|more|remaining)\b|继续|接下来|下一步|还有哪些|还可以做什么/u;
16
+ const PROJECT_MATCH_STOPWORDS = new Set([
17
+ "a",
18
+ "an",
19
+ "and",
20
+ "app",
21
+ "application",
22
+ "build",
23
+ "complete",
24
+ "existing",
25
+ "follow",
26
+ "for",
27
+ "hub",
28
+ "improvement",
29
+ "improvements",
30
+ "internal",
31
+ "optimization",
32
+ "product",
33
+ "project",
34
+ "requirement",
35
+ "request",
36
+ "studio",
37
+ "system",
38
+ "the",
39
+ "this",
40
+ "up",
41
+ "update",
42
+ "web",
43
+ ]);
44
+
45
+ export function resolveExistingProjectIdentityFromMessage(
46
+ message: string,
47
+ state: TeamState | null,
48
+ ): { projectId?: string; projectDir?: string } | undefined {
49
+ const normalizedMessage = normalizeProjectMatchingText(message);
50
+ if (!normalizedMessage) {
51
+ return undefined;
52
+ }
53
+ const explicitAlias = normalizeProjectMatchingText(extractExplicitProjectNameHint(message) ?? "");
54
+
55
+ let best: { projectId?: string; projectDir: string; score: number; updatedAt: number } | null = null;
56
+ const candidates = collectExistingProjectCandidates(state);
57
+ for (const candidate of candidates) {
58
+ const normalizedAliases = Array.from(candidate.aliases)
59
+ .map((alias) => normalizeProjectMatchingText(alias))
60
+ .filter(Boolean)
61
+ .reduce<string[]>((acc, alias) => {
62
+ acc.push(alias);
63
+ return acc;
64
+ }, []);
65
+ const hasExplicitAliasMatch = explicitAlias
66
+ ? normalizedAliases.some((alias) => alias.includes(explicitAlias) || explicitAlias.includes(alias))
67
+ : false;
68
+ if (explicitAlias && !hasExplicitAliasMatch) {
69
+ continue;
70
+ }
71
+ const aliasScore = normalizedAliases
72
+ .reduce((score, alias) => {
73
+ if (!alias) {
74
+ return score;
75
+ }
76
+ return normalizedMessage.includes(alias)
77
+ ? Math.max(score, alias.split(" ").length + 10)
78
+ : score;
79
+ }, 0);
80
+ const tokenScore = scoreProjectTokenOverlap(normalizedMessage, candidate.searchText);
81
+ const totalScore = Math.max(aliasScore, tokenScore);
82
+ if (totalScore < 2) {
83
+ continue;
84
+ }
85
+ if (!best || totalScore > best.score || (totalScore === best.score && candidate.updatedAt > best.updatedAt)) {
86
+ best = {
87
+ projectId: candidate.projectId,
88
+ projectDir: candidate.projectDir,
89
+ score: totalScore,
90
+ updatedAt: candidate.updatedAt,
91
+ };
92
+ }
93
+ }
94
+ if (best) {
95
+ return { projectId: best.projectId, projectDir: best.projectDir };
96
+ }
97
+ if ((EXISTING_PROJECT_REUSE_HINT_RE.test(message) || GENERIC_PROJECT_FOLLOW_UP_RE.test(message)) && candidates.length === 1) {
98
+ return {
99
+ projectId: candidates[0]?.projectId,
100
+ projectDir: candidates[0]?.projectDir,
101
+ };
102
+ }
103
+ return undefined;
104
+ }
105
+
106
+ export function collectExistingProjectCandidates(state: TeamState | null): Array<{
107
+ projectId?: string;
108
+ projectDir: string;
109
+ aliases: Set<string>;
110
+ searchText: string;
111
+ updatedAt: number;
112
+ }> {
113
+ const byProjectDir = new Map<string, { projectId?: string; aliases: Set<string>; texts: string[]; updatedAt: number }>();
114
+ const addCandidate = (
115
+ projectDir: string | undefined,
116
+ text: string | undefined,
117
+ updatedAt: number,
118
+ alias?: string | null,
119
+ projectId?: string,
120
+ ) => {
121
+ if (!projectDir) {
122
+ return;
123
+ }
124
+ const entry = byProjectDir.get(projectDir) ?? { projectId, aliases: new Set<string>(), texts: [], updatedAt: 0 };
125
+ if (!entry.projectId && projectId) {
126
+ entry.projectId = projectId;
127
+ }
128
+ if (text && text.trim()) {
129
+ entry.texts.push(text);
130
+ }
131
+ if (alias && alias.trim()) {
132
+ entry.aliases.add(alias.trim());
133
+ }
134
+ entry.updatedAt = Math.max(entry.updatedAt, updatedAt);
135
+ byProjectDir.set(projectDir, entry);
136
+ };
137
+
138
+ for (const project of Object.values(state?.projects ?? {})) {
139
+ addCandidate(project.projectDir, project.summary, project.updatedAt, project.id, project.id);
140
+ for (const alias of project.aliases ?? []) {
141
+ addCandidate(project.projectDir, alias, project.updatedAt, alias, project.id);
142
+ }
143
+ }
144
+ for (const run of Object.values(state?.controllerRuns ?? {})) {
145
+ addCandidate(run.projectDir, run.request, run.updatedAt, extractProjectAliasFromText(run.request), run.projectId);
146
+ addCandidate(run.projectDir, run.title, run.updatedAt, extractProjectAliasFromText(run.title), run.projectId);
147
+ addCandidate(run.projectDir, run.manifest?.projectName, run.updatedAt, run.manifest?.projectName, run.projectId);
148
+ }
149
+ for (const task of Object.values(state?.tasks ?? {})) {
150
+ addCandidate(task.projectDir, task.title, task.updatedAt, extractProjectAliasFromText(task.title), task.projectId);
151
+ addCandidate(task.projectDir, task.description, task.updatedAt, extractProjectAliasFromText(task.description), task.projectId);
152
+ addCandidate(task.projectDir, task.resultContract?.summary, task.updatedAt, null, task.projectId);
153
+ }
154
+
155
+ return Array.from(byProjectDir.entries()).map(([projectDir, entry]) => ({
156
+ projectId: entry.projectId,
157
+ projectDir,
158
+ aliases: entry.aliases,
159
+ searchText: entry.texts.join("\n"),
160
+ updatedAt: entry.updatedAt,
161
+ }));
162
+ }
163
+
164
+ export function extractExplicitProjectNameHint(text: string | undefined): string | undefined {
165
+ const value = String(text ?? "");
166
+ const namedMatch = value.match(/(?:品牌|brand|project\s*name|产品名|名字)\s*[::]?\s*[`"'“”]?([a-z][a-z0-9_-]{1,39})[`"'“”]?/iu);
167
+ if (namedMatch?.[1]) {
168
+ return deriveStableProjectKey(namedMatch[1]);
169
+ }
170
+ const inlineNames = Array.from(value.matchAll(/`([a-z][a-z0-9_-]{1,39})`/giu))
171
+ .map((match) => deriveStableProjectKey(match[1]))
172
+ .filter(Boolean);
173
+ return inlineNames.length === 1 ? inlineNames[0] : undefined;
174
+ }
175
+
176
+ export function findProjectRecordByDir(state: TeamState | null, projectDir: string | undefined) {
177
+ if (!state || !projectDir) {
178
+ return undefined;
179
+ }
180
+ return Object.values(state.projects ?? {}).find((project) => project.projectDir === projectDir);
181
+ }
182
+
183
+ export function syncProjectRegistryEntry(
184
+ state: TeamState,
185
+ input: {
186
+ projectId?: string;
187
+ projectDir?: string;
188
+ aliases?: Array<string | undefined | null>;
189
+ summary?: string;
190
+ updatedAt: number;
191
+ },
192
+ ): { projectId?: string; projectDir?: string } {
193
+ state.projects = state.projects && typeof state.projects === "object" ? state.projects : {};
194
+ let normalizedProjectId = deriveStableProjectKey(input.projectId ?? "");
195
+ let existing = normalizedProjectId ? state.projects[normalizedProjectId] : undefined;
196
+ const byDir = findProjectRecordByDir(state, input.projectDir);
197
+ if (!existing && byDir) {
198
+ existing = byDir;
199
+ }
200
+ if (!existing && input.projectDir) {
201
+ normalizedProjectId = normalizedProjectId || deriveStableProjectKey(input.projectDir);
202
+ if (normalizedProjectId) {
203
+ existing = {
204
+ id: normalizedProjectId,
205
+ projectDir: input.projectDir,
206
+ aliases: [],
207
+ createdAt: input.updatedAt,
208
+ updatedAt: input.updatedAt,
209
+ lastUsedAt: input.updatedAt,
210
+ };
211
+ state.projects[normalizedProjectId] = existing;
212
+ }
213
+ }
214
+ if (!existing) {
215
+ return { projectId: normalizedProjectId || undefined, projectDir: input.projectDir };
216
+ }
217
+ if (normalizedProjectId && existing.id !== normalizedProjectId && !state.projects[normalizedProjectId]) {
218
+ delete state.projects[existing.id];
219
+ existing.id = normalizedProjectId;
220
+ state.projects[normalizedProjectId] = existing;
221
+ }
222
+ if (!existing.projectDir && input.projectDir) {
223
+ existing.projectDir = input.projectDir;
224
+ }
225
+ const aliasSet = new Set(existing.aliases ?? []);
226
+ aliasSet.add(existing.id);
227
+ if (existing.projectDir) {
228
+ aliasSet.add(existing.projectDir);
229
+ }
230
+ for (const alias of input.aliases ?? []) {
231
+ const normalizedAlias = deriveStableProjectKey(String(alias ?? ""));
232
+ if (normalizedAlias) {
233
+ aliasSet.add(normalizedAlias);
234
+ }
235
+ }
236
+ existing.aliases = Array.from(aliasSet);
237
+ existing.summary = input.summary || existing.summary;
238
+ existing.updatedAt = Math.max(existing.updatedAt || 0, input.updatedAt);
239
+ existing.lastUsedAt = Math.max(existing.lastUsedAt || 0, input.updatedAt);
240
+ return { projectId: existing.id, projectDir: existing.projectDir };
241
+ }
242
+
243
+ export function resolveProjectIdentityForSession(
244
+ sessionKey: string,
245
+ state: TeamState | null,
246
+ ): { projectId?: string; projectDir?: string } | undefined {
247
+ const runId = findLatestControllerRunIdForSession(sessionKey, state, { preferActive: true });
248
+ if (!runId) {
249
+ return undefined;
250
+ }
251
+ const run = state?.controllerRuns[runId];
252
+ if (!run) {
253
+ return undefined;
254
+ }
255
+ const project = findProjectRecordByDir(state, run.projectDir);
256
+ return {
257
+ projectId: run.projectId ?? project?.id,
258
+ projectDir: run.projectDir ?? project?.projectDir,
259
+ };
260
+ }
261
+
262
+ export function resolveProjectIdentityForTaskId(
263
+ taskId: string,
264
+ state: TeamState | null,
265
+ ): { projectId?: string; projectDir?: string } | undefined {
266
+ const task = state?.tasks?.[taskId];
267
+ if (!task) {
268
+ return undefined;
269
+ }
270
+ const project = findProjectRecordByDir(state, task.projectDir);
271
+ return {
272
+ projectId: task.projectId ?? project?.id,
273
+ projectDir: task.projectDir ?? project?.projectDir,
274
+ };
275
+ }
276
+
277
+ export function extractProjectAliasFromText(text: string | undefined): string | null {
278
+ const firstMeaningfulLine = String(text ?? "")
279
+ .split(/\n+/u)
280
+ .map((line) => line.replace(/^#+\s*/u, "").trim())
281
+ .find(Boolean);
282
+ if (!firstMeaningfulLine) {
283
+ return null;
284
+ }
285
+ const normalized = firstMeaningfulLine
286
+ .replace(/^(product|optimization)\s+requirement[::]\s*/iu, "")
287
+ .replace(/^implement\s+/iu, "")
288
+ .replace(/^design\s+/iu, "")
289
+ .replace(/^enhance\s+/iu, "")
290
+ .replace(/^qa[:\s-]+/iu, "")
291
+ .replace(/\s+(architecture|application|web app|workflows?|improvements?)$/iu, "")
292
+ .trim();
293
+ if (normalized.length < 4 || normalized.length > 80) {
294
+ return null;
295
+ }
296
+ return normalized;
297
+ }
298
+
299
+ export function normalizeProjectMatchingText(text: string): string {
300
+ return text
301
+ .toLowerCase()
302
+ .replace(/[`*_#:[\]()/\\-]+/gu, " ")
303
+ .replace(/\s+/gu, " ")
304
+ .trim();
305
+ }
306
+
307
+ export function scoreProjectTokenOverlap(message: string, candidateText: string): number {
308
+ const messageTokens = tokenizeProjectMatchingText(message);
309
+ if (messageTokens.size === 0) {
310
+ return 0;
311
+ }
312
+ const candidateTokens = tokenizeProjectMatchingText(candidateText);
313
+ let overlap = 0;
314
+ for (const token of candidateTokens) {
315
+ if (messageTokens.has(token)) {
316
+ overlap += 1;
317
+ }
318
+ }
319
+ return overlap;
320
+ }
321
+
322
+ export function tokenizeProjectMatchingText(text: string): Set<string> {
323
+ return new Set(
324
+ normalizeProjectMatchingText(text)
325
+ .split(" ")
326
+ .map((token) => token.trim())
327
+ .filter((token) => token.length >= 4 && !PROJECT_MATCH_STOPWORDS.has(token)),
328
+ );
329
+ }
330
+
331
+ export function isActiveControllerRun(run: ControllerRunInfo): boolean {
332
+ return run.status === "pending" || run.status === "running";
333
+ }
334
+
335
+ export function findLatestControllerRunIdForSession(
336
+ sessionKey: string,
337
+ state: TeamState | null,
338
+ options?: { preferActive?: boolean },
339
+ ): string | null {
340
+ const normalizedSessionKey = normalizeControllerIntakeSessionKey(sessionKey);
341
+ const matchingRuns = Object.values(state?.controllerRuns ?? {})
342
+ .filter((run) => normalizeControllerIntakeSessionKey(run.sessionKey) === normalizedSessionKey)
343
+ .sort((left, right) => {
344
+ if (options?.preferActive) {
345
+ const leftScore = isActiveControllerRun(left) ? 1 : 0;
346
+ const rightScore = isActiveControllerRun(right) ? 1 : 0;
347
+ if (leftScore !== rightScore) {
348
+ return rightScore - leftScore;
349
+ }
350
+ }
351
+ return right.updatedAt - left.updatedAt;
352
+ });
353
+ return matchingRuns[0]?.id ?? null;
354
+ }
355
+
356
+ export function resolveProjectDirForSession(
357
+ sessionKey: string,
358
+ state: TeamState | null,
359
+ ): string | undefined {
360
+ return resolveProjectIdentityForSession(sessionKey, state)?.projectDir;
361
+ }
@@ -1,5 +1,6 @@
1
1
  import type { PluginConfig, TeamState } from "../types.js";
2
- import { ROLES } from "../roles.js";
2
+ // Phase 1.3: the advertised role set comes from the active TeamProfile.
3
+ import { getActiveDomainInstructions, getActiveRoles } from "../profile-loader.js";
3
4
  import {
4
5
  buildControllerCompletionRules,
5
6
  buildControllerDisciplineRules,
@@ -8,6 +9,7 @@ import {
8
9
  buildControllerStructuredContractRules,
9
10
  buildControllerToolRules,
10
11
  buildControllerWorkflowRules,
12
+ buildRoleOperatingRules,
11
13
  composePrompt,
12
14
  } from "../prompt-policy.js";
13
15
  import { hasOnDemandWorkerProvisioning, shouldBlockControllerWithoutWorkers } from "./controller-capacity.js";
@@ -15,11 +17,9 @@ import { resolveTeamClawWorkspaceDir } from "../openclaw-workspace.js";
15
17
  import fs from "node:fs";
16
18
  import path from "node:path";
17
19
 
18
- const TEAMCLAW_ROLE_IDS_TEXT = [
19
- "pm", "architect", "developer", "qa",
20
- "release-engineer", "infra-engineer", "devops", "security-engineer",
21
- "designer", "marketing", "data-engineer",
22
- ];
20
+ // Phase 1.2: the local TEAMCLAW_ROLE_IDS_TEXT copy that used to live here was
21
+ // dead code (no references) and duplicated the canonical role id list; the
22
+ // shared text is exported from prompt-policy.ts (TEAMCLAW_ROLE_IDS_TEXT).
23
23
 
24
24
  export type ControllerPromptDeps = {
25
25
  config: PluginConfig;
@@ -60,7 +60,7 @@ export function createControllerPromptInjector(deps: ControllerPromptDeps) {
60
60
  }
61
61
  } else {
62
62
  for (const w of workers) {
63
- const roleDef = ROLES.find((r) => r.id === w.role);
63
+ const roleDef = getActiveRoles().find((r) => r.id === w.role);
64
64
  const statusIcon = w.status === "idle" ? "[idle]" : w.status === "busy" ? "[busy]" : "[offline]";
65
65
  const currentTask = w.currentTaskId ? ` (task: ${w.currentTaskId})` : "";
66
66
  parts.push(`- ${roleDef?.icon ?? ""} ${w.label} (${w.id}) ${statusIcon}${currentTask}`);
@@ -89,13 +89,28 @@ export function createControllerPromptInjector(deps: ControllerPromptDeps) {
89
89
 
90
90
  parts.push("");
91
91
  parts.push("### Available Roles");
92
- for (const role of ROLES) {
92
+ for (const role of getActiveRoles()) {
93
93
  const skillLine = role.recommendedSkills.length > 0
94
94
  ? ` Recommended skills: ${role.recommendedSkills.join(", ")}.`
95
95
  : "";
96
96
  parts.push(`- ${role.icon} ${role.label}: ${role.description}.${skillLine}`);
97
97
  }
98
98
 
99
+ // Phase 2.4 (design 2.4): when the active profile carries industry
100
+ // guardrails, the controller's operating contract is replaced by them,
101
+ // assembled right after the role catalog (the controller-side analog of
102
+ // "after the role systemPrompt" on the worker pipeline). Profiles without
103
+ // domainInstructions (software-rd) inject nothing, so the controller
104
+ // prompt bytes are unchanged (Phase 1.7 golden).
105
+ const domainInstructions = getActiveDomainInstructions();
106
+ if (domainInstructions) {
107
+ parts.push(...buildRoleOperatingRules({
108
+ suggestedRoles: [],
109
+ recommendedSkills: [],
110
+ domainInstructions,
111
+ }));
112
+ }
113
+
99
114
  // List existing projects so the controller can distinguish new vs. existing
100
115
  parts.push("");
101
116
  parts.push("### Existing Projects in Workspace");
@@ -0,0 +1,51 @@
1
+ // W1 of issue #226 (worker-provisioning god-file split): the provisioner
2
+ // backend contract and the host-port policy shared by the facade and the
3
+ // backend modules, extracted VERBATIM from controller/worker-provisioning.ts.
4
+ // Pure types + pure functions: this module must never import a backend
5
+ // implementation or worker-provisioning.ts (dependency direction is one-way).
6
+ import type {
7
+ PluginConfig,
8
+ ProvisionedWorkerRecord,
9
+ RoleId,
10
+ WorkerProvisioningType,
11
+ } from "../../types.js";
12
+
13
+ export type LaunchSpec = {
14
+ workerId: string;
15
+ role: RoleId;
16
+ launchToken: string;
17
+ controllerUrl: string;
18
+ workerPort: number;
19
+ gatewayPort: number;
20
+ publishedHostPort?: number;
21
+ workspaceDir?: string;
22
+ env: Record<string, string>;
23
+ configJson: string;
24
+ };
25
+
26
+ export type LaunchResult = {
27
+ instanceId?: string;
28
+ instanceName?: string;
29
+ runtimeHomeDir?: string;
30
+ };
31
+
32
+ export interface WorkerProvisionerBackend {
33
+ readonly type: WorkerProvisioningType;
34
+ launch(spec: LaunchSpec): Promise<LaunchResult>;
35
+ terminate(record: ProvisionedWorkerRecord): Promise<void>;
36
+ stop?(): Promise<void>;
37
+ }
38
+
39
+ export function requiresDedicatedHostPortsForProvisioner(
40
+ provider: WorkerProvisioningType,
41
+ config: PluginConfig,
42
+ ): boolean {
43
+ if (provider === "process") {
44
+ return true;
45
+ }
46
+ return provider === "docker" && isDockerHostNetwork(config.workerProvisioningDockerNetwork);
47
+ }
48
+
49
+ export function isDockerHostNetwork(networkMode: string): boolean {
50
+ return networkMode.trim().toLowerCase() === "host";
51
+ }
@@ -0,0 +1,84 @@
1
+ // W1 of issue #226 (worker-provisioning god-file split): managed-name
2
+ // construction and the container bootstrap script shared by the docker and
3
+ // kubernetes backends, extracted VERBATIM from controller/worker-provisioning.ts.
4
+ // The generic string sanitizers now live in shared/utils.ts.
5
+ import { createHash } from "node:crypto";
6
+ import type { RoleId } from "../../types.js";
7
+ import { sanitizePathSegment, sanitizeName } from "../../shared/utils.js";
8
+
9
+ export function buildManagedInstanceName(teamName: string, role: RoleId, workerId: string): string {
10
+ return buildManagedName("teamclaw", teamName, role, workerId, {
11
+ teamBudget: 18,
12
+ roleBudget: 12,
13
+ workerBudget: 12,
14
+ hashLength: 8,
15
+ maxLength: 63,
16
+ });
17
+ }
18
+
19
+ export function buildManagedHostname(teamName: string, role: RoleId, workerId: string): string {
20
+ return buildManagedName("tc", teamName, role, workerId, {
21
+ teamBudget: 10,
22
+ roleBudget: 8,
23
+ workerBudget: 6,
24
+ hashLength: 6,
25
+ maxLength: 40,
26
+ });
27
+ }
28
+
29
+ function buildManagedName(
30
+ prefix: string,
31
+ teamName: string,
32
+ role: RoleId,
33
+ workerId: string,
34
+ options: {
35
+ teamBudget: number;
36
+ roleBudget: number;
37
+ workerBudget: number;
38
+ hashLength: number;
39
+ maxLength: number;
40
+ },
41
+ ): string {
42
+ const teamPart = sanitizeLeadingSegment(teamName, options.teamBudget, "team");
43
+ const rolePart = sanitizeLeadingSegment(role, options.roleBudget, "worker");
44
+ const workerPart = sanitizeTrailingSegment(workerId, options.workerBudget, "worker");
45
+ const hash = shortStableHash(`${teamName}:${role}:${workerId}`).slice(0, options.hashLength);
46
+ return sanitizeName(`${prefix}-${teamPart}-${rolePart}-${workerPart}-${hash}`, options.maxLength);
47
+ }
48
+
49
+ function shortStableHash(value: string): string {
50
+ return createHash("sha1").update(value).digest("hex");
51
+ }
52
+
53
+ function sanitizeLeadingSegment(value: string, maxLength: number, fallback: string): string {
54
+ const normalized = sanitizePathSegment(value).slice(0, maxLength).replace(/^-+|-+$/g, "");
55
+ return normalized || fallback;
56
+ }
57
+
58
+ function sanitizeTrailingSegment(value: string, maxLength: number, fallback: string): string {
59
+ const normalized = sanitizePathSegment(value).slice(-maxLength).replace(/^-+|-+$/g, "");
60
+ return normalized || fallback;
61
+ }
62
+
63
+ export function buildContainerBootstrapScript(): string {
64
+ return [
65
+ "set -eu",
66
+ "mkdir -p \"$OPENCLAW_STATE_DIR\"",
67
+ "if [ -n \"${TEAMCLAW_WORKSPACE_DIR:-}\" ]; then mkdir -p \"$TEAMCLAW_WORKSPACE_DIR\"; fi",
68
+ // Issue #237 W4: the bootstrap config carries provider API keys - write
69
+ // it owner-only inside the container too (the old permissionless call
70
+ // defaulted to 0644). The remaining exposure is the env injection
71
+ // itself (TEAMCLAW_BOOTSTRAP_CONFIG_B64 is visible to `docker inspect`
72
+ // and pod-env readers); migrating the docker/kubernetes backends to
73
+ // mounted Secrets needs a coordinated chart/image change (cf. #230's
74
+ // image-skew caveat) and is tracked by #237 W4.
75
+ // Review follow-up (#237): { mode } is creation-only, so rewriting a
76
+ // pre-existing 0644 config (baked into an older image or surviving on
77
+ // a mounted volume) would keep the loose mode - chmodSync the existing
78
+ // file first, tolerating ENOENT for first writes (then { mode: 0o600 }
79
+ // creates it owner-only). Chosen over unlink-then-write to avoid the
80
+ // no-config window mid-rewrite.
81
+ "node -e 'const fs=require(\"fs\"); const configPath=process.env.OPENCLAW_CONFIG_PATH; const raw=Buffer.from(process.env.TEAMCLAW_BOOTSTRAP_CONFIG_B64||\"\", \"base64\").toString(\"utf8\"); fs.mkdirSync(require(\"path\").dirname(configPath), { recursive: true }); try { fs.chmodSync(configPath, 0o600); } catch (err) { if (err.code !== \"ENOENT\") throw err; } fs.writeFileSync(configPath, raw, { mode: 0o600 });'",
82
+ "exec node dist/index.js gateway --allow-unconfigured",
83
+ ].join("\n");
84
+ }