@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
@@ -5,18 +5,31 @@ import type { KickoffAssessment, PluginConfig, RoleId, TeamState } from "../type
5
5
  import { loadTeamState, saveTeamState } from "../state.js";
6
6
  import { MDnsAdvertiser } from "../discovery.js";
7
7
  import { WORKER_TIMEOUT_MS } from "../protocol.js";
8
- import { createControllerHttpServer, autoAssignPendingTasks } from "./http-server.js";
8
+ import { createControllerHttpServer, type ControllerHttpDeps } from "./http-server.js";
9
+ // PR-C of issue #204: the assignment pipeline incl. the gated auto-assign
10
+ // loop lives in ./task-assignment.js, not http-server.ts.
11
+ import { autoAssignPendingTasks } from "./task-assignment.js";
12
+ // Issue #222: worker dispatch-token header helper for controller -> worker calls.
13
+ import { withWorkerDispatchToken } from "./task-execution.js";
14
+ // PR-A of issue #204: the profile switch state machine (incl. crash resume)
15
+ // lives in ./profile-switch.ts, not http-server.ts.
16
+ import { resumeTeamProfileSwitch } from "./profile-switch.js";
9
17
  import { TaskRouter } from "./task-router.js";
10
18
  import { MessageRouter } from "./message-router.js";
11
- import { TeamWebSocketServer } from "./websocket.js";
12
- import { ensureOpenClawWorkspaceMemoryDir } from "../openclaw-workspace.js";
19
+ import { TeamWebSocketServer, type WsEvent } from "./websocket.js";
20
+ import { ensureOpenClawWorkspaceMemoryDir, buildTeamClawAgentSessionKey } from "../openclaw-workspace.js";
13
21
  import { ensureControllerGitRepo } from "../git-collaboration.js";
14
22
  import { WorkerProvisioningManager } from "./worker-provisioning.js";
15
23
  import { PreviewManager } from "./preview-manager.js";
16
- import { runKickoffMeeting, buildKickoffAssessmentPrompt, ASSESSMENT_TIMEOUT_MS } from "./kickoff-orchestrator.js";
24
+ import { runKickoffMeeting, ASSESSMENT_TIMEOUT_MS, type TaskRoleResolutionDeps } from "./kickoff-orchestrator.js";
25
+ // Issue #226 W3: the kickoff prompt contract lives in the shared layer now.
26
+ import { buildKickoffAssessmentPrompt } from "../shared/kickoff-prompt.js";
17
27
  import { resolvePreferredLanAddress } from "../networking.js";
18
28
  import { createTeamAutoScheduler, type TeamAutoScheduler } from "../teamauto/scheduler.js";
19
29
  import { getGithubAuthManager } from "./github-auth.js";
30
+ // Phase 1.6 (design 2.3): TeamState.profileId is the single runtime truth for
31
+ // the active TeamProfile; config teamProfile only seeds first initialization.
32
+ import { getActiveProfile, getActiveRoleIds, hasProfile, setActiveProfileId, validateActiveRoleId, SOFTWARE_RD_PROFILE_ID } from "../profile-loader.js";
20
33
 
21
34
  export type KickoffHandler = (
22
35
  candidateRoles: RoleId[],
@@ -24,6 +37,66 @@ export type KickoffHandler = (
24
37
  requirement: string,
25
38
  ) => Promise<{ assessments: KickoffAssessment[]; summary: string }>;
26
39
 
40
+ // ===========================================================================
41
+ // Issue #226 W4: the single TeamState write-entry contract.
42
+ //
43
+ // `updateState` below is the ONLY sanctioned way to mutate the shared
44
+ // TeamState and persist it: the updater closure runs synchronously on the
45
+ // shared object, then the entry owns persistence (and, when asked, the WS
46
+ // broadcast). Before W4 there were three parallel write tracks - this
47
+ // controlled channel, direct mutation + saveTeamState in route-table's
48
+ // inline handlers, and profile-switch's independent saves - with
49
+ // lost-update / missed-broadcast risk across await interleavings. The
50
+ // route-handler and profile-switch tracks were migrated onto this entry;
51
+ // the remaining direct saveTeamState call sites are startup-early writes
52
+ // registered as explicit exemptions (search "W4 write-face exemption") and
53
+ // machine-pinned by tests/test-teamstate-writes.mjs, so a new unregistered
54
+ // direct save turns the suite red.
55
+ // ===========================================================================
56
+
57
+ /** A WS event the entry broadcasts on the caller's behalf (see below). */
58
+ export type TeamStateUpdateEvent = WsEvent;
59
+
60
+ export type TeamStateUpdateOptions = {
61
+ /**
62
+ * WS events to broadcast after the updater returned. With the default
63
+ * background persistence they fire synchronously right after the save was
64
+ * enqueued (the historical shape of callers broadcasting manually right
65
+ * after updateTeamState); with `persist: "awaited"` they fire only once
66
+ * the state-file write has fulfilled - the durability-before-broadcast
67
+ * contract the profile switch steps 1/6 rely on - and never fire when the
68
+ * write fails.
69
+ */
70
+ broadcast?: ReadonlyArray<TeamStateUpdateEvent>;
71
+ /**
72
+ * "background" (default): fire-and-forget save, the exact semantics every
73
+ * pre-W4 caller of updateTeamState relies on (an un-caught promise, same
74
+ * as the historical `void saveTeamState(...)`).
75
+ * "awaited": durability barrier - the update returns a handle carrying
76
+ * the save promise so the caller can enforce persisted-before-broadcast
77
+ * (profile switch transition step 1) and roll the in-memory mutation back
78
+ * when the write fails.
79
+ */
80
+ persist?: "background" | "awaited";
81
+ };
82
+
83
+ /** Return shape of the `persist: "awaited"` variant (see UpdateTeamStateFn). */
84
+ export type TeamStateUpdateHandle = {
85
+ state: TeamState;
86
+ /** Resolves when the state-file write settled; rejects on write failure. */
87
+ persisted: Promise<void>;
88
+ };
89
+
90
+ /**
91
+ * The deps-facing signature of the single write entry. Callers that pass no
92
+ * options keep the historical `(updater) => TeamState` behavior; the second
93
+ * overload is the awaited-durability variant used by the profile switch.
94
+ */
95
+ export type UpdateTeamStateFn = {
96
+ (updater: (state: TeamState) => void, options?: TeamStateUpdateOptions & { persist?: "background" }): TeamState;
97
+ (updater: (state: TeamState) => void, options: TeamStateUpdateOptions & { persist: "awaited" }): TeamStateUpdateHandle;
98
+ };
99
+
27
100
  export type ControllerServiceDeps = {
28
101
  config: PluginConfig;
29
102
  logger: PluginLogger;
@@ -62,16 +135,57 @@ export function createControllerService(deps: ControllerServiceDeps): OpenClawPl
62
135
  async start(_ctx: OpenClawPluginServiceContext) {
63
136
  const serviceStartedAt = Date.now();
64
137
  await ensureOpenClawWorkspaceMemoryDir(logger);
65
- const repoState = await ensureControllerGitRepo(config, logger).catch((err) => {
66
- logger.warn(`Controller: failed to prepare git collaboration repo: ${err instanceof Error ? err.message : String(err)}`);
67
- return null;
68
- });
69
138
 
70
- // Load or create team state
139
+ // Load or create team state. The active profile is resolved FIRST (from
140
+ // the restored TeamState.profileId, or the config bootstrap value on
141
+ // first initialization) so that capability-dependent startup wiring
142
+ // below knows which profile it is initializing (Phase 2.3 preview).
71
143
  teamState = await loadTeamState(config.teamName);
144
+ let seededProfileId: string;
145
+ if (!teamState) {
146
+ // Phase 1.6: first initialization seeds the active profile from the
147
+ // config bootstrap value. An unknown id is the one sanctioned
148
+ // fallback (design 2.2): warn and run the software-rd baseline.
149
+ const requestedProfileId = config.teamProfile;
150
+ seededProfileId = requestedProfileId;
151
+ if (!hasProfile(requestedProfileId)) {
152
+ seededProfileId = SOFTWARE_RD_PROFILE_ID;
153
+ logger.warn(`Controller: configured teamProfile "${requestedProfileId}" is not a built-in profile; falling back to "${SOFTWARE_RD_PROFILE_ID}"`);
154
+ }
155
+ } else {
156
+ // Restored state: TeamState.profileId is the runtime truth (config
157
+ // changes do not re-seed it). A dangling reference means the profile
158
+ // package this team ran on is not available in this installation.
159
+ // Design 2.2 red line: FATAL, never silently run another profile -
160
+ // that is exactly how a banking team would degrade into the software
161
+ // baseline unnoticed. (The config-miss fallback above stays a warn:
162
+ // it only seeds first initialization, where no team exists yet.)
163
+ if (!hasProfile(teamState.profileId)) {
164
+ throw new Error(
165
+ `Controller: team state references team profile "${teamState.profileId}", which is not available in this installation. `
166
+ + "Check the teamProfile config value and the persisted state profileId, or reinstall a TeamClaw version that ships this profile.",
167
+ );
168
+ }
169
+ seededProfileId = teamState.profileId;
170
+ }
171
+ setActiveProfileId(seededProfileId);
172
+ const activeCapabilities = getActiveProfile().capabilities;
173
+
174
+ // Phase 2.3 preview (minimal capability wiring, design 2.1): the git
175
+ // collaboration repo is only prepared for profiles with git enabled -
176
+ // a document-delivery team has no repo concept. On the software-rd
177
+ // baseline (git: true) behavior is unchanged.
178
+ const repoState = activeCapabilities.git
179
+ ? await ensureControllerGitRepo(config, logger).catch((err) => {
180
+ logger.warn(`Controller: failed to prepare git collaboration repo: ${err instanceof Error ? err.message : String(err)}`);
181
+ return null;
182
+ })
183
+ : null;
184
+
72
185
  let repoStateChanged = false;
73
186
  if (!teamState) {
74
187
  teamState = {
188
+ profileId: seededProfileId,
75
189
  teamName: config.teamName,
76
190
  workers: {},
77
191
  tasks: {},
@@ -83,21 +197,52 @@ export function createControllerService(deps: ControllerServiceDeps): OpenClawPl
83
197
  createdAt: Date.now(),
84
198
  updatedAt: Date.now(),
85
199
  };
200
+ // W4 write-face exemption (#226): first-boot TeamState creation.
201
+ // This is initialization, not an update - the updateState entry is
202
+ // only defined below and presupposes an existing shared object. No
203
+ // WS server exists yet, so there is nothing to broadcast to.
86
204
  await saveTeamState(teamState);
87
- logger.info(`Controller: created new team "${config.teamName}"`);
205
+ logger.info(`Controller: created new team "${config.teamName}" (profile: ${seededProfileId})`);
88
206
  } else {
89
207
  const previousRepoState = JSON.stringify(teamState.repo ?? null);
90
- teamState.repo = repoState ?? teamState.repo;
208
+ teamState.repo = repoState ?? (activeCapabilities.git ? teamState.repo : undefined);
91
209
  repoStateChanged = JSON.stringify(teamState.repo ?? null) !== previousRepoState;
92
210
  logger.info(`Controller: restored team "${config.teamName}" with ${Object.keys(teamState.workers).length} workers`);
93
211
  }
94
212
  deps.onTeamStateAvailable?.(() => teamState);
95
213
 
96
- const updateState = (updater: (state: TeamState) => void): TeamState => {
97
- updater(teamState!);
98
- void saveTeamState(teamState!);
99
- return teamState!;
100
- };
214
+ // Issue #226 W4: the single TeamState write entry (see the contract
215
+ // block above). The updater stays a synchronous closure over the
216
+ // shared object; persistence - and, when requested, the WS broadcast -
217
+ // happen strictly after the updater returned. Existing one-argument
218
+ // callers keep the exact pre-W4 fire-and-forget semantics.
219
+ const updateState = ((updater: (state: TeamState) => void, options: TeamStateUpdateOptions = {}) => {
220
+ const state = teamState!;
221
+ updater(state);
222
+ if (options.persist === "awaited") {
223
+ // Durability variant (profile switch): the caller owns the save
224
+ // promise - broadcast events ride its fulfillment and never fire
225
+ // on failure; rejections surface to the caller's rollback. A
226
+ // dropped handle rejects unhandled, exactly like the historical
227
+ // floating void save.
228
+ let persisted = saveTeamState(state);
229
+ if (options.broadcast?.length) {
230
+ persisted = persisted.then(() => {
231
+ for (const event of options.broadcast!) {
232
+ wsServer.broadcastUpdate(event);
233
+ }
234
+ });
235
+ }
236
+ return { state, persisted };
237
+ }
238
+ void saveTeamState(state);
239
+ if (options.broadcast?.length) {
240
+ for (const event of options.broadcast) {
241
+ wsServer.broadcastUpdate(event);
242
+ }
243
+ }
244
+ return state;
245
+ }) as UpdateTeamStateFn;
101
246
 
102
247
  // Provisioned workers die with the previous gateway process. Their
103
248
  // persisted entries flip to offline once heartbeats stop but were
@@ -139,6 +284,11 @@ export function createControllerService(deps: ControllerServiceDeps): OpenClawPl
139
284
  // Run ALL syncState calls (avoid || short-circuit skipping some).
140
285
  const syncC = workerProvisioningManager.syncState(teamState);
141
286
  if (repoStateChanged || syncC) {
287
+ // W4 write-face exemption (#226): startup durability barrier for the
288
+ // startup state assembly above (repo stamp + provisioning syncState's
289
+ // in-place mutations, which belong to the provisioning module). Runs
290
+ // before the WS server exists; there is no updater closure to run
291
+ // here - the mutations already happened on the shared object.
142
292
  await saveTeamState(teamState);
143
293
  }
144
294
 
@@ -178,12 +328,29 @@ export function createControllerService(deps: ControllerServiceDeps): OpenClawPl
178
328
  }
179
329
  }
180
330
  if (orphanCleaned) {
331
+ // W4 write-face exemption (#226): startup orphan-task sweep. The
332
+ // loop above mutates in place interleaved with per-task startup
333
+ // logging; this awaited save is the pre-HTTP durability barrier -
334
+ // folding the sweep into an updater closure would reshuffle the
335
+ // startup crash-window ordering for zero convergence gain (the WS
336
+ // server does not exist yet, nothing to broadcast).
181
337
  await saveTeamState(teamState);
182
338
  }
183
339
  }
184
340
 
185
341
  mdnsAdvertiser = new MDnsAdvertiser(logger);
186
- taskRouter = new TaskRouter(logger);
342
+ // Phase 2.5 wiring (design 2.3 "LLM 兜底", P2.5 follow-up): the
343
+ // controller LLM session is the production role judge for tasks the
344
+ // bilingual token fast path refuses to decide (tie / all-zero). The
345
+ // judge runs on a dedicated one-shot subagent session - NOT the intake
346
+ // conversation - so verdicts never pollute intake semantics. Missing
347
+ // runtime subagent => no judge, and the TaskRouter keeps its exact
348
+ // pre-wiring behavior.
349
+ const llmRoleJudge = createControllerLlmRoleJudge(deps);
350
+ if (llmRoleJudge) {
351
+ logger.info("Controller: LLM role judge wired into task dispatch (unconfident role inference escalates to the controller LLM)");
352
+ }
353
+ taskRouter = new TaskRouter(logger, llmRoleJudge ? { llmRoleJudge } : undefined);
187
354
  messageRouter = new MessageRouter(logger);
188
355
  wsServer = new TeamWebSocketServer(logger);
189
356
 
@@ -198,7 +365,7 @@ export function createControllerService(deps: ControllerServiceDeps): OpenClawPl
198
365
 
199
366
  let serviceKickoffHandler: KickoffHandler | undefined;
200
367
 
201
- const server = createControllerHttpServer({
368
+ const httpDeps: ControllerHttpDeps = {
202
369
  config,
203
370
  logger,
204
371
  runtime: deps.runtime,
@@ -211,7 +378,9 @@ export function createControllerService(deps: ControllerServiceDeps): OpenClawPl
211
378
  previewManager,
212
379
  getKickoffHandler: () => serviceKickoffHandler,
213
380
  getTeamAutoScheduler: () => teamAutoSchedulerRef,
214
- });
381
+ };
382
+
383
+ const server = createControllerHttpServer(httpDeps);
215
384
 
216
385
  const PORT_RETRY_STEP = 10;
217
386
  const PORT_MAX_RETRIES = 10;
@@ -256,29 +425,54 @@ export function createControllerService(deps: ControllerServiceDeps): OpenClawPl
256
425
  workerProvisioningManager.setActualPort(actualPort);
257
426
  }
258
427
 
428
+ // Phase 2.1 (design 2.3 crash semantics): resume an interrupted team
429
+ // profile switch before TeamAuto/preview restoration/provisioning kick
430
+ // in, so no subsystem fights the resume. Runs after the port is known
431
+ // (switch warmup launches need the actual controller URL). Requests
432
+ // arriving mid-resume hit the transition concurrency matrix (409/503),
433
+ // which is exactly what it exists for. An unavailable target profile is
434
+ // fatal here - same red line as restoring an unknown profileId.
435
+ await resumeTeamProfileSwitch(httpDeps);
436
+
259
437
  // TeamAuto: autonomous repo collaboration (bind repos via /api/v1/teamauto/*).
260
- try {
261
- const auth = getGithubAuthManager(config, logger);
262
- const httpDepsForAutoAssign = { config, logger, getTeamState: () => teamState, updateTeamState: updateState, taskRouter, messageRouter, wsServer } as Parameters<typeof autoAssignPendingTasks>[0];
263
- teamAutoSchedulerRef = createTeamAutoScheduler({
264
- logger,
265
- auth,
266
- getTeamState: () => teamState,
267
- updateTeamState: updateState,
268
- onTasksCreated: async () => {
269
- await autoAssignPendingTasks(httpDepsForAutoAssign);
270
- },
271
- onActivity: (entry) => {
272
- wsServer.broadcastUpdate({
273
- type: "teamauto:activity",
274
- data: { at: entry.at, repoId: entry.repoId, kind: entry.kind, text: entry.text },
275
- });
276
- },
277
- });
278
- await teamAutoSchedulerRef.start();
279
- deps.onTeamAutoSchedulerAvailable?.(() => teamAutoSchedulerRef);
280
- } catch (err) {
281
- logger.warn(`Controller: TeamAuto scheduler failed to start: ${err instanceof Error ? err.message : String(err)}`);
438
+ // Phase 2.3 preview (minimal capability wiring): a profile with
439
+ // teamauto disabled never starts the scheduler at all.
440
+ if (getActiveProfile().capabilities.teamauto) {
441
+ try {
442
+ const auth = getGithubAuthManager(config, logger);
443
+ teamAutoSchedulerRef = createTeamAutoScheduler({
444
+ logger,
445
+ auth,
446
+ getTeamState: () => teamState,
447
+ updateTeamState: updateState,
448
+ onTasksCreated: async () => {
449
+ // Same deps object as every HTTP call site (issue #191 gate
450
+ // review): the autoAssign re-entrancy gate is keyed per deps
451
+ // object, so an ad-hoc object here would open a SECOND gate -
452
+ // a TeamAuto round and an HTTP round could then run concurrently
453
+ // with separate attemptedPairs sets (double dispatch attempts,
454
+ // same-task double LLM-judge window). The ad-hoc object also
455
+ // silently dropped workerProvisioningManager/getTeamAutoScheduler
456
+ // for these rounds (no reconcile nudge; teamauto write tasks
457
+ // dispatched from this path fell back to the shared checkout
458
+ // instead of a task-scoped worktree). It was a leftover from
459
+ // before the shared httpDeps existed, not a deliberate split.
460
+ await autoAssignPendingTasks(httpDeps);
461
+ },
462
+ onActivity: (entry) => {
463
+ wsServer.broadcastUpdate({
464
+ type: "teamauto:activity",
465
+ data: { at: entry.at, repoId: entry.repoId, kind: entry.kind, text: entry.text },
466
+ });
467
+ },
468
+ });
469
+ await teamAutoSchedulerRef.start();
470
+ deps.onTeamAutoSchedulerAvailable?.(() => teamAutoSchedulerRef);
471
+ } catch (err) {
472
+ logger.warn(`Controller: TeamAuto scheduler failed to start: ${err instanceof Error ? err.message : String(err)}`);
473
+ }
474
+ } else {
475
+ logger.info("Controller: TeamAuto scheduler skipped (capability disabled by the active team profile)");
282
476
  }
283
477
 
284
478
  // Start mDNS advertising with the actual port
@@ -301,7 +495,8 @@ export function createControllerService(deps: ControllerServiceDeps): OpenClawPl
301
495
  }
302
496
  },
303
497
  requestWorkerAssessment: async (worker, req) => {
304
- return await requestKickoffAssessment(worker, req);
498
+ // Issue #222: carry the worker's dispatch token on the assess call.
499
+ return await requestKickoffAssessment(worker, req, withWorkerDispatchToken({}, worker.id, config, teamState));
305
500
  },
306
501
  },
307
502
  );
@@ -310,12 +505,16 @@ export function createControllerService(deps: ControllerServiceDeps): OpenClawPl
310
505
  serviceKickoffHandler = kickoffHandler;
311
506
  deps.onKickoffHandlerAvailable?.(kickoffHandler);
312
507
 
313
- logger.info(`Controller: starting preview restoration...`);
314
- void previewManager.restorePreviewsOnStartup().then(() => {
315
- logger.info(`Controller: preview restoration completed`);
316
- }).catch((err) => {
317
- logger.warn(`Controller: failed to restore previews on startup: ${String(err)}`);
318
- });
508
+ // Phase 2.3 preview (minimal capability wiring): only profiles with
509
+ // runnablePreview enabled restore dynamic previews on startup.
510
+ if (getActiveProfile().capabilities.runnablePreview) {
511
+ logger.info(`Controller: starting preview restoration...`);
512
+ void previewManager.restorePreviewsOnStartup().then(() => {
513
+ logger.info(`Controller: preview restoration completed`);
514
+ }).catch((err) => {
515
+ logger.warn(`Controller: failed to restore previews on startup: ${String(err)}`);
516
+ });
517
+ }
319
518
 
320
519
  // Start timeout monitoring
321
520
  timeoutTimer = setInterval(() => {
@@ -370,9 +569,60 @@ export function createControllerService(deps: ControllerServiceDeps): OpenClawPl
370
569
  }
371
570
 
372
571
  if (changed) {
572
+ // W4 write-face exemption (#226): heartbeat-timeout sweep. The
573
+ // mutations interleave with per-worker WS broadcasts inside the
574
+ // synchronous loop above; this floating save is byte-for-byte the
575
+ // entry's own background semantics (void saveTeamState), so
576
+ // routing it through updateState with a no-op updater would add
577
+ // ceremony without moving any save or broadcast.
373
578
  saveTeamState(teamState);
374
579
  }
375
580
 
581
+ // Runtime orphan-task reconciliation (user-found: one live worker but
582
+ // two active tasks - the second task was pinned to a worker whose
583
+ // registry entry was already gone). The startup sweep handles this
584
+ // once at boot; tasks whose worker disappears AFTER claiming sat in
585
+ // in_progress forever. Mirror the startup semantics: reset to pending
586
+ // (bounded resume attempts), re-dispatch happens via the reconcile
587
+ // call below. Skip workers the sweep above just released - their
588
+ // tasks were already handled with a broadcast.
589
+ {
590
+ let orphaned = false;
591
+ for (const task of Object.values(teamState.tasks)) {
592
+ if (
593
+ task.assignedWorkerId &&
594
+ (task.status === "assigned" || task.status === "in_progress") &&
595
+ !teamState.workers[task.assignedWorkerId]
596
+ ) {
597
+ const attempt = (task.resumeAttempt ?? 0) + 1;
598
+ const MAX_RESUME_ATTEMPTS = 3;
599
+ if (attempt > MAX_RESUME_ATTEMPTS) {
600
+ logger.warn(`Controller: task ${task.id} exceeded ${MAX_RESUME_ATTEMPTS} resume attempts (worker gone) - failing`);
601
+ task.status = "failed";
602
+ task.error = `worker disappeared without completing (resumed ${MAX_RESUME_ATTEMPTS} times)`;
603
+ } else {
604
+ logger.info(`Controller: resetting orphaned task ${task.id} for resume attempt ${attempt} (worker ${task.assignedWorkerId} missing)`);
605
+ task.status = "pending";
606
+ task.resumeAttempt = attempt;
607
+ if (task.checkpoint) {
608
+ task.checkpoint.attempt = attempt;
609
+ }
610
+ }
611
+ task.assignedWorkerId = undefined;
612
+ task.updatedAt = now;
613
+ wsServer.broadcastUpdate({ type: "task:updated", data: { ...task } });
614
+ orphaned = true;
615
+ }
616
+ }
617
+ if (orphaned) {
618
+ // W4 write-face exemption (#226): runtime orphan-task
619
+ // reconciliation, same sweep-interleaved-broadcast shape as the
620
+ // worker loop above (see that exemption note).
621
+ saveTeamState(teamState);
622
+ changed = true;
623
+ }
624
+ }
625
+
376
626
  if (workerProvisioningManager?.isEnabled()) {
377
627
  void workerProvisioningManager.requestReconcile("periodic controller sync");
378
628
  }
@@ -420,11 +670,13 @@ function openBrowser(url: string, logger: PluginLogger): void {
420
670
  /**
421
671
  * Request a kickoff assessment from a worker.
422
672
  *
423
- * Request kickoff assessment from a worker over HTTP.
673
+ * Request kickoff assessment from a worker over HTTP. `authHeaders` carries
674
+ * the worker's dispatch token (issue #222) when the controller knows one.
424
675
  */
425
676
  async function requestKickoffAssessment(
426
677
  worker: import("../types.js").WorkerInfo,
427
678
  requirement: string,
679
+ authHeaders: Record<string, string> = {},
428
680
  ): Promise<import("../types.js").KickoffAssessment> {
429
681
  const role = worker.role;
430
682
  const prompt = buildKickoffAssessmentPrompt(role, requirement);
@@ -440,7 +692,7 @@ async function requestKickoffAssessment(
440
692
  try {
441
693
  const res = await fetch(`${worker.url}/api/v1/kickoff/assess`, {
442
694
  method: "POST",
443
- headers: { "Content-Type": "application/json" },
695
+ headers: { "Content-Type": "application/json", ...authHeaders },
444
696
  body: JSON.stringify({ requirement, role }),
445
697
  signal: controller.signal,
446
698
  });
@@ -455,3 +707,123 @@ async function requestKickoffAssessment(
455
707
  clearTimeout(timeout);
456
708
  }
457
709
  }
710
+
711
+ // ── Phase 2.5 wiring: controller LLM as the role judge ───────────────────────
712
+ //
713
+ // resolveTaskRoleWithLlmFallback (kickoff-orchestrator) defined the seam in
714
+ // P2.5 with fake-driven tests but no production caller. This factory builds
715
+ // the production llmRoleJudge: a ONE-SHOT subagent session on the controller
716
+ // runtime (never the long-lived intake conversation, so verdicts cannot
717
+ // pollute intake semantics) that answers with a single role id of the ACTIVE
718
+ // profile. The resolver validates the answer (validateActiveRoleId) and
719
+ // degrades to the profile defaultRole when the judge is unavailable, times
720
+ // out, errors, or names a role outside the active profile - the TaskRouter
721
+ // then treats the outcome as a routing hint, so dispatch never blocks on a
722
+ // strand.
723
+
724
+ /** Budget for a one-id LLM verdict; past it the resolver degrades to defaultRole. */
725
+ const ROLE_JUDGE_TIMEOUT_MS = 30_000;
726
+ const ROLE_JUDGE_SESSION_PREFIX = "teamclaw-role-judge:";
727
+ const ROLE_JUDGE_SYSTEM_PROMPT = [
728
+ "You are the role router of a TeamClaw controller.",
729
+ "Given one task, pick the single team role that should own it.",
730
+ "Reply with EXACTLY one role id from the provided list - no prose, no markdown, no explanation.",
731
+ ].join(" ");
732
+
733
+ function createControllerLlmRoleJudge(
734
+ deps: Pick<ControllerServiceDeps, "runtime" | "logger">,
735
+ ): TaskRoleResolutionDeps["llmRoleJudge"] | undefined {
736
+ const subagent = deps.runtime?.subagent;
737
+ if (
738
+ !subagent
739
+ || typeof subagent.run !== "function"
740
+ || typeof subagent.waitForRun !== "function"
741
+ || typeof subagent.getSessionMessages !== "function"
742
+ ) {
743
+ // Runtime without an LLM subagent (e.g. minimal test doubles): leave the
744
+ // seam unwired; the TaskRouter keeps its pre-wiring behavior.
745
+ return undefined;
746
+ }
747
+ const logger = deps.logger;
748
+
749
+ return async ({ task, verdict }) => {
750
+ const roleIds = getActiveRoleIds();
751
+ const message = [
752
+ `Task title: ${task.title}`,
753
+ `Task description: ${task.description?.trim() || "(none)"}`,
754
+ "",
755
+ `Token-based role scoring refused to decide (${verdict.reason}).`,
756
+ `Pick the single role that should own this task. Answer with EXACTLY one role id from: ${roleIds.join(", ")}`,
757
+ ].join("\n");
758
+
759
+ // Fresh one-shot session per verdict: the judge must stay stateless and
760
+ // separate from any intake/worker conversation.
761
+ const sessionKey = buildTeamClawAgentSessionKey(
762
+ `${ROLE_JUDGE_SESSION_PREFIX}${task.id}-${Date.now()}`,
763
+ );
764
+ const run = await subagent.run({
765
+ sessionKey,
766
+ message,
767
+ extraSystemPrompt: ROLE_JUDGE_SYSTEM_PROMPT,
768
+ idempotencyKey: `role-judge-${task.id}-${Date.now()}`,
769
+ });
770
+ const waited = await subagent.waitForRun({
771
+ runId: run.runId,
772
+ timeoutMs: ROLE_JUDGE_TIMEOUT_MS,
773
+ });
774
+ if (waited.status !== "ok") {
775
+ logger.warn(
776
+ `Controller: LLM role judge did not complete for task ${task.id} (${waited.status}${"error" in waited && waited.error ? `: ${waited.error}` : ""}); using the profile defaultRole`,
777
+ );
778
+ return null;
779
+ }
780
+
781
+ const session = await subagent.getSessionMessages({ sessionKey, limit: 5 });
782
+ const reply = extractLastAssistantText(session.messages);
783
+ const direct = validateActiveRoleId(reply.trim());
784
+ if (direct) {
785
+ return direct;
786
+ }
787
+ // Tolerate light prose wrapping ("The role is: qa."): first ACTIVE role
788
+ // id that appears as a whole word in the reply.
789
+ for (const roleId of roleIds) {
790
+ const pattern = new RegExp(`(^|[^a-z0-9-])${roleId.replace(/[-]/g, "\\-")}([^a-z0-9-]|$)`);
791
+ if (pattern.test(reply)) {
792
+ return roleId;
793
+ }
794
+ }
795
+ logger.warn(
796
+ `Controller: LLM role judge reply for task ${task.id} named no active role (${reply.slice(0, 120) || "empty reply"}); using the profile defaultRole`,
797
+ );
798
+ return null;
799
+ };
800
+ }
801
+
802
+ /** Last assistant message text (string or text blocks), mirroring the http-server intake helper semantics. */
803
+ function extractLastAssistantText(messages: unknown[]): string {
804
+ const assistantMessages = messages.filter((message): message is { role?: unknown; content?: unknown } => {
805
+ if (!message || typeof message !== "object") {
806
+ return false;
807
+ }
808
+ return (message as { role?: unknown }).role === "assistant";
809
+ });
810
+ const lastAssistant = assistantMessages[assistantMessages.length - 1];
811
+ if (!lastAssistant) {
812
+ return "";
813
+ }
814
+ if (typeof lastAssistant.content === "string") {
815
+ return lastAssistant.content;
816
+ }
817
+ if (Array.isArray(lastAssistant.content)) {
818
+ const textBlocks = lastAssistant.content
819
+ .filter((block): block is { type?: unknown; text?: unknown } => {
820
+ return !!block && typeof block === "object" && (block as { type?: unknown }).type === "text";
821
+ })
822
+ .map((block) => (typeof block.text === "string" ? block.text : ""))
823
+ .filter(Boolean);
824
+ if (textBlocks.length > 0) {
825
+ return textBlocks.join("\n");
826
+ }
827
+ }
828
+ return "";
829
+ }
@@ -9,19 +9,28 @@ import type {
9
9
  } from "../types.js";
10
10
  import { buildControllerNoWorkersMessage, hasOnDemandWorkerProvisioning, shouldBlockControllerWithoutWorkers } from "./controller-capacity.js";
11
11
  import {
12
- normalizeClarificationQuestionSchemas,
13
12
  normalizeManifestCompletionOpportunities,
14
13
  normalizeManifestCreatedTasks,
15
14
  normalizeManifestDeferredTasks,
16
15
  normalizeManifestRoleList,
17
16
  normalizeManifestStringList,
18
- normalizeOptionalManifestText,
19
17
  } from "./orchestration-manifest.js";
18
+ // Issue #226 W3: the clarification-schema family lives in the shared layer now.
19
+ import {
20
+ normalizeClarificationQuestionSchemas,
21
+ normalizeOptionalManifestText,
22
+ } from "../shared/clarification-schema.js";
20
23
  import {
21
24
  ensureTeamMessageContract,
22
25
  normalizeContractRole,
23
26
  normalizeContractStringList,
24
27
  } from "../interaction-contracts.js";
28
+ // Phase 2.1 debt item 1 (P1 closeout handover): tool input validation checks
29
+ // the ACTIVE TeamProfile's role set via the profile loader. The previous
30
+ // registry-set check would silently kill every non-software role once a team
31
+ // switches profiles; behavior on the software-rd baseline is unchanged
32
+ // (active set == registry set).
33
+ import { validateActiveRoleId } from "../profile-loader.js";
25
34
 
26
35
  export type ControllerToolsDeps = {
27
36
  config: PluginConfig;
@@ -45,11 +54,6 @@ const EXECUTION_READY_BLOCKERS: Array<{ pattern: RegExp; reason: string }> = [
45
54
  { pattern: /需要.*先完成/u, reason: "it states another piece of work must complete first" },
46
55
  ];
47
56
 
48
- const VALID_ROLE_IDS = new Set([
49
- "pm", "architect", "developer", "qa", "release-engineer",
50
- "infra-engineer", "devops", "security-engineer", "designer", "marketing",
51
- ]);
52
-
53
57
  const ENGLISH_LATER_PHASE_CLAUSE_RE = /\b(?:after|once)\b(.+?)\b(complete|completed|ready|available|exists?)\b/i;
54
58
  const ENGLISH_LATER_PHASE_DEPENDENCY_RE = /\b(?:task|tasks|service|services|module|modules|phase|phases|api|apis|interface|interfaces|review|qa|design|developer|architect|skeleton|backend|frontend|deliverable|artifact|handoff)\b/i;
55
59
  const CHINESE_LATER_PHASE_CLAUSE_RE = /(.+?)(完成后|就绪后)/u;
@@ -98,9 +102,12 @@ export function createControllerTools(deps: ControllerToolsDeps) {
98
102
  }
99
103
 
100
104
  const rawRoles = Array.isArray(params.candidateRoles) ? params.candidateRoles : [];
105
+ // Phase 2.1 debt item 1: validate against the ACTIVE profile's role
106
+ // set (validateActiveRoleId) so kickoff candidate roles of a switched
107
+ // team (e.g. banking) pass instead of being silently filtered out.
101
108
  const candidateRoles = rawRoles
102
- .map((r) => String(r ?? "").trim().toLowerCase())
103
- .filter((r): r is RoleId => VALID_ROLE_IDS.has(r));
109
+ .map((r) => validateActiveRoleId(String(r ?? "").trim().toLowerCase()))
110
+ .filter((r): r is RoleId => r !== undefined);
104
111
 
105
112
  if (candidateRoles.length === 0) {
106
113
  return { details: {}, content: [{ type: "text" as const, text: "At least one valid candidate role is required." }] };