@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,309 @@
1
+ import { archiveTeamState, findTeamSwitchArchive } from "../state.js";
2
+ import { BUILTIN_PROFILES, getActiveProfile, hasProfile, setActiveProfileId, } from "../profile-loader.js";
3
+ import { ensureControllerGitRepo } from "../git-collaboration.js";
4
+ // ===========================================================================
5
+ // Team profile switch (Phase 2.1, vertical-team-profiles-design.md 2.3).
6
+ //
7
+ // Six-step semantics of POST /api/v1/team/profile:
8
+ // 0. validate profileId + reject concurrent switches (409) [endpoint]
9
+ // 1. transition = { draining, target, startedAt }; persisted + WS event
10
+ // 2. graceful drain of in-flight tasks (timeout -> force-collect),
11
+ // terminate workers [drainTeam...]
12
+ // 3. archive the WHOLE TeamState + roles snapshot [state.ts]
13
+ // 4. fresh capability-conditioned TeamState for the target
14
+ // 5. warm the target profile's warmupRoles [provisioner]
15
+ // 6. clear transition, persist, broadcast team.switch_completed
16
+ // ===========================================================================
17
+ const SWITCH_DRAIN_POLL_INTERVAL_MS = 500;
18
+ function sleepForSwitchDrain(ms) {
19
+ return new Promise((resolve) => setTimeout(resolve, ms));
20
+ }
21
+ function taskInFlightForDrain(task) {
22
+ return Boolean(task.assignedWorkerId) && (task.status === "assigned" || task.status === "in_progress");
23
+ }
24
+ /**
25
+ * Design 2.3 step 2: graceful drain. Waits until no task is assigned /
26
+ * in-progress any more (in-flight workers report results through their
27
+ * normal endpoints, which stay open during the transition), then returns.
28
+ * On timeout the remaining in-flight tasks are force-collected (failed with
29
+ * an explicit error so the archive records the forced end) and all workers
30
+ * are marked offline. Managed workers are terminated by the caller through
31
+ * the provisioning manager's onWorkerRemoved (the terminateManagedWorker
32
+ * single point); external workers observe 409 heartbeats and back off.
33
+ */
34
+ async function drainTeamForProfileSwitch(deps) {
35
+ const { config, logger, getTeamState, updateTeamState } = deps;
36
+ const deadline = Date.now() + config.teamSwitchDrainTimeoutMs;
37
+ while (Date.now() < deadline) {
38
+ const state = getTeamState();
39
+ if (!state || !Object.values(state.tasks).some(taskInFlightForDrain)) {
40
+ return { timedOut: false, forceCollected: [] };
41
+ }
42
+ await sleepForSwitchDrain(SWITCH_DRAIN_POLL_INTERVAL_MS);
43
+ }
44
+ const forceCollected = [];
45
+ updateTeamState((state) => {
46
+ for (const task of Object.values(state.tasks)) {
47
+ if (taskInFlightForDrain(task)) {
48
+ task.status = "failed";
49
+ task.error = `team profile switch drain timeout (${config.teamSwitchDrainTimeoutMs}ms) - in-flight task force-collected into the team archive`;
50
+ task.updatedAt = Date.now();
51
+ forceCollected.push(task.id);
52
+ }
53
+ }
54
+ for (const worker of Object.values(state.workers)) {
55
+ worker.status = "offline";
56
+ worker.currentTaskId = undefined;
57
+ }
58
+ });
59
+ logger.warn(`Controller: profile switch drain timed out after ${config.teamSwitchDrainTimeoutMs}ms - force-collected ${forceCollected.length} in-flight task(s)`);
60
+ return { timedOut: true, forceCollected };
61
+ }
62
+ /**
63
+ * Run switch steps 2-6 (step 1 - setting and persisting the transition -
64
+ * belongs to the POST endpoint / crash resume). Exported so the controller
65
+ * startup chain can resume an interrupted switch with the same semantics.
66
+ */
67
+ export async function executeTeamProfileSwitch(deps, targetProfileId, options = {}) {
68
+ const { config, logger, getTeamState, updateTeamState, workerProvisioningManager } = deps;
69
+ const target = BUILTIN_PROFILES.get(targetProfileId);
70
+ if (!target) {
71
+ throw new Error(`TeamClaw team profile "${targetProfileId}" is not available in this installation`);
72
+ }
73
+ // W4 (#226): phase flips persist through the single write entry. The
74
+ // awaited-durability variant is used everywhere so callers that need the
75
+ // crash-window barrier (step 3's archiving flip, step 5's warming flip)
76
+ // can await it; callers that historically fire-and-forget the save simply
77
+ // drop the handle (an un-awaited rejection behaves exactly like the old
78
+ // floating void save).
79
+ const setPhase = (phase, options = {}) => {
80
+ return updateTeamState((state) => {
81
+ if (state.transition?.targetProfileId === targetProfileId) {
82
+ state.transition.phase = phase;
83
+ }
84
+ }, { ...options, persist: "awaited" });
85
+ };
86
+ if (!options.skipArchive) {
87
+ // Step 2: drain in-flight work, then stop every worker.
88
+ void setPhase("draining").persisted.catch(() => undefined);
89
+ workerProvisioningManager?.setReconcileSuspended(true);
90
+ const drain = await drainTeamForProfileSwitch(deps);
91
+ for (const workerId of Object.keys(getTeamState()?.provisioning?.workers ?? {})) {
92
+ if (workerProvisioningManager?.hasManagedWorker(workerId)) {
93
+ await workerProvisioningManager
94
+ .onWorkerRemoved(workerId, `team profile switch to "${targetProfileId}"`)
95
+ .catch((err) => logger.warn(`Controller: failed to terminate managed worker ${workerId} during profile switch: ${String(err)}`));
96
+ }
97
+ }
98
+ // Capability teardown for subsystems the target profile switches off
99
+ // (minimal Phase 2.3 preview; the full 404 short-circuit lands in 2.3).
100
+ // NOTE: teardown is one-directional at runtime. Switching a capability
101
+ // back ON does not (re)start its subsystem here - TeamAuto scheduling
102
+ // and preview restoration are wired at controller startup only, so an
103
+ // off -> on switch (e.g. minimal-bank -> software-rd) takes effect for
104
+ // those subsystems after the next gateway restart.
105
+ if (!target.capabilities.teamauto) {
106
+ const scheduler = deps.getTeamAutoScheduler?.() ?? null;
107
+ if (scheduler) {
108
+ try {
109
+ await scheduler.stop();
110
+ }
111
+ catch { /* scheduler already stopped */ }
112
+ }
113
+ }
114
+ if (!target.capabilities.runnablePreview && deps.previewManager) {
115
+ try {
116
+ await deps.previewManager.stopAll();
117
+ }
118
+ catch { /* previews already stopped */ }
119
+ }
120
+ // Step 3: archive the whole previous TeamState with a roles snapshot.
121
+ // The phase flip is persisted BEFORE the archive write so a crash between
122
+ // the two leaves an unambiguous "archive may exist" state for the resume
123
+ // path (file existence check). W4 (#226): the awaited durability barrier
124
+ // is the single entry's persisted handle (one save enqueued at the same
125
+ // point the old fire-and-forget + awaited second save pair wrote).
126
+ const archiving = setPhase("archiving");
127
+ // #251 note (no behavior change): `sourceState` below is whatever
128
+ // getTeamState() returns AFTER the awaited "archiving" persist barrier
129
+ // - it is NOT a phase-accurate snapshot frozen at the moment the drain
130
+ // finished. In-flight mutations racing the switch can be captured in
131
+ // the archive; the resume path tolerates this because the transition
132
+ // marker, not the snapshot contents, drives recovery.
133
+ const sourceState = getTeamState();
134
+ if (sourceState) {
135
+ await archiving.persisted;
136
+ const sourceProfile = getActiveProfile();
137
+ await archiveTeamState(sourceState, {
138
+ id: sourceProfile.id,
139
+ name: sourceProfile.name,
140
+ nameZh: sourceProfile.nameZh,
141
+ version: sourceProfile.version,
142
+ roles: sourceProfile.roles,
143
+ });
144
+ logger.info(`Controller: archived team "${sourceState.teamName}" (profile ${sourceProfile.id}, `
145
+ + `${Object.keys(sourceState.tasks).length} task(s))${drain.timedOut ? " after drain timeout" : ""}`);
146
+ }
147
+ }
148
+ // Step 4: fresh TeamState for the target profile, conditioned on its
149
+ // capability switches (design 2.3: banking omits repo/previews/reports).
150
+ // setActiveProfileId and the state mutation below are both synchronous, so
151
+ // no request can observe the new state against the old profile.
152
+ const repoState = target.capabilities.git
153
+ ? await ensureControllerGitRepo(config, logger).catch((err) => {
154
+ logger.warn(`Controller: failed to prepare git collaboration repo for profile "${target.id}": ${err instanceof Error ? err.message : String(err)}`);
155
+ return null;
156
+ })
157
+ : null;
158
+ setActiveProfileId(target.id);
159
+ const newCreatedAt = Date.now();
160
+ const step4 = updateTeamState((state) => {
161
+ state.profileId = target.id;
162
+ state.teamName = target.name;
163
+ state.workers = {};
164
+ state.tasks = {};
165
+ state.controllerRuns = {};
166
+ state.projects = {};
167
+ state.messages = [];
168
+ state.clarifications = {};
169
+ state.provisioning = { workers: {} };
170
+ if (target.capabilities.git && repoState) {
171
+ state.repo = repoState;
172
+ }
173
+ else {
174
+ delete state.repo;
175
+ }
176
+ if (target.capabilities.runnablePreview) {
177
+ state.previews = {};
178
+ }
179
+ else {
180
+ delete state.previews;
181
+ }
182
+ if (target.capabilities.deliveryReview) {
183
+ state.reports = {};
184
+ }
185
+ else {
186
+ delete state.reports;
187
+ }
188
+ state.createdAt = newCreatedAt;
189
+ }, { persist: "awaited" });
190
+ await step4.persisted;
191
+ // Step 5: warm the new profile's warmupRoles through the provisioning
192
+ // pipeline (launch dispatch; registration/readiness tracking continues in
193
+ // the background exactly like a cold start).
194
+ await setPhase("warming").persisted;
195
+ workerProvisioningManager?.setReconcileSuspended(false);
196
+ if (workerProvisioningManager?.isEnabled() && target.warmupRoles.length > 0) {
197
+ await workerProvisioningManager
198
+ .warmRolesForTeamSwitch(target.warmupRoles, `profile switch warmup (${target.id})`)
199
+ .catch((err) => logger.warn(`Controller: profile switch warmup failed: ${err instanceof Error ? err.message : String(err)}`));
200
+ }
201
+ // Step 6: settle - clear the transition, persist, announce. W4 (#226):
202
+ // the switch_completed broadcast rides the single entry's awaited
203
+ // persistence, preserving the event order (persisted, then announced).
204
+ const settled = updateTeamState((state) => {
205
+ delete state.transition;
206
+ }, {
207
+ persist: "awaited",
208
+ broadcast: [{ type: "team.switch_completed", data: { profileId: target.id } }],
209
+ });
210
+ await settled.persisted;
211
+ logger.info(`Controller: team profile switch to "${target.id}" completed`);
212
+ }
213
+ /**
214
+ * Design 2.3 crash semantics: on controller startup, an unfinished persisted
215
+ * transition is resumed idempotently. If the archive file for this switch
216
+ * already exists AND the phase is at/after "archiving", jump straight to
217
+ * building the new team (skipArchive); otherwise re-run the drain from
218
+ * scratch (drain is idempotent - a completed drain simply finds no in-flight
219
+ * tasks). Returns true when a transition was resumed.
220
+ */
221
+ // No team.switch_failed broadcast on this path: startup resume runs before
222
+ // the HTTP/WS listeners exist, so there are no clients to receive it - a
223
+ // failed resume surfaces through the fatal startup path instead (#201 review
224
+ // note, recorded for external reviewers).
225
+ export async function resumeTeamProfileSwitch(deps) {
226
+ const state = deps.getTeamState();
227
+ const transition = state?.transition;
228
+ if (!state || !transition) {
229
+ return false;
230
+ }
231
+ if (!hasProfile(transition.targetProfileId)) {
232
+ // Same red line as restoring an unknown profileId (design 2.2): a team
233
+ // mid-switch to an unavailable profile must never silently land on a
234
+ // different profile.
235
+ throw new Error(`Controller: interrupted team profile switch references profile "${transition.targetProfileId}", which is not available in this installation. `);
236
+ }
237
+ deps.logger.info(`Controller: resuming interrupted team profile switch to "${transition.targetProfileId}" (phase: ${transition.phase}, started at ${new Date(transition.startedAt).toISOString()})`);
238
+ // A persisted state whose profileId already equals the target means step 4
239
+ // flipped the team identity onto the NEW team. Step 4 strictly follows the
240
+ // completed archive write in the same execution (the archive file lands
241
+ // atomically before step 4 runs), so that flip PROVES the archive exists.
242
+ // This covers both phase "warming" and the ghost-archive window between
243
+ // the step-4 flip reaching disk and the warming phase persisting - on disk
244
+ // that window reads as (phase "archiving", profileId = target), where
245
+ // looking up the SOURCE-named archive file with state.profileId would miss
246
+ // it and a re-drain would seal the already-emptied NEW team as a ghost
247
+ // archive entry. (Alternative considered: persisting a sourceProfileId on
248
+ // the transition - rejected; this flip predicate is the identical proof
249
+ // without transition-shape or migration churn, and it also degrades the
250
+ // manually-corrupted (draining, target) combination the same safe way.)
251
+ const step4Flipped = state.profileId === transition.targetProfileId;
252
+ const archiveExists = step4Flipped
253
+ || transition.phase === "warming"
254
+ || Boolean(await findTeamSwitchArchive(state.profileId, transition.startedAt));
255
+ const phaseAtOrAfterArchive = transition.phase === "archiving" || transition.phase === "warming";
256
+ await executeTeamProfileSwitch(deps, transition.targetProfileId, {
257
+ skipArchive: archiveExists && (phaseAtOrAfterArchive || step4Flipped),
258
+ });
259
+ return true;
260
+ }
261
+ /**
262
+ * Fire-and-forget switch execution launched by POST /api/v1/team/profile
263
+ * after step 1 (transition persisted + switch_started broadcast). Owns the
264
+ * failure path: worst-case archive-preservation detection, the
265
+ * team.switch_failed broadcast, and unwedging the transition.
266
+ */
267
+ export function startTeamProfileSwitch(deps, state, profileId, previousProfileId) {
268
+ const { logger, wsServer, updateTeamState } = deps;
269
+ void executeTeamProfileSwitch(deps, profileId).catch(async (err) => {
270
+ const detail = err instanceof Error ? err.message : String(err);
271
+ logger.error(`Controller: team profile switch to "${profileId}" failed: ${detail}`);
272
+ // Never leave the team wedged in a transition: clear it so whichever
273
+ // team the state now holds keeps serving and the switch can be
274
+ // re-issued. The archive (if step 3 ran) keeps the previous team. Also
275
+ // lift the provisioning reconcile suspension so the manager keeps
276
+ // operating for whichever team survived.
277
+ deps.workerProvisioningManager?.setReconcileSuspended(false);
278
+ // Honest worst case for the failure payload: once the step-3 archive
279
+ // write has landed (or step 4 already flipped the team identity - which
280
+ // strictly proves the archive landed), the state on disk may be
281
+ // partially switched and a restart is the reliable recovery. Detect
282
+ // with the same resume-path predicate: a source-named archive file at
283
+ // or after the transition's startedAt.
284
+ const transition = state.transition;
285
+ let archivePreserved = state.profileId === profileId;
286
+ if (!archivePreserved && transition) {
287
+ archivePreserved = Boolean(await findTeamSwitchArchive(previousProfileId, transition.startedAt).catch(() => null));
288
+ }
289
+ const reason = archivePreserved
290
+ ? `${detail} (archive preserved, team state may be partially switched, restart recommended)`
291
+ : detail;
292
+ // Broadcast BEFORE clearing the transition: the web switcher releases
293
+ // its loading/confirm state on this event instead of silently timing
294
+ // out on the reconcile fallback.
295
+ wsServer.broadcastUpdate({
296
+ type: "team.switch_failed",
297
+ data: { previousProfileId, targetProfileId: profileId, reason },
298
+ });
299
+ // W4 (#226): best-effort persist of the unwedging through the single
300
+ // entry - one enqueued save with the failure path's swallow (the old
301
+ // shape fired an un-caught floating save plus this caught one).
302
+ const cleared = updateTeamState((s) => {
303
+ if (s.transition?.targetProfileId === profileId) {
304
+ delete s.transition;
305
+ }
306
+ }, { persist: "awaited" });
307
+ void cleared.persisted.catch(() => undefined);
308
+ });
309
+ }
@@ -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,9 @@
1
+ export function requiresDedicatedHostPortsForProvisioner(provider, config) {
2
+ if (provider === "process") {
3
+ return true;
4
+ }
5
+ return provider === "docker" && isDockerHostNetwork(config.workerProvisioningDockerNetwork);
6
+ }
7
+ export function isDockerHostNetwork(networkMode) {
8
+ return networkMode.trim().toLowerCase() === "host";
9
+ }