@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
@@ -3,18 +3,31 @@ import { exec } from "node:child_process";
3
3
  import { loadTeamState, saveTeamState } from "../state.js";
4
4
  import { MDnsAdvertiser } from "../discovery.js";
5
5
  import { WORKER_TIMEOUT_MS } from "../protocol.js";
6
- import { createControllerHttpServer, autoAssignPendingTasks } from "./http-server.js";
6
+ import { createControllerHttpServer } from "./http-server.js";
7
+ // PR-C of issue #204: the assignment pipeline incl. the gated auto-assign
8
+ // loop lives in ./task-assignment.js, not http-server.ts.
9
+ import { autoAssignPendingTasks } from "./task-assignment.js";
10
+ // Issue #222: worker dispatch-token header helper for controller -> worker calls.
11
+ import { withWorkerDispatchToken } from "./task-execution.js";
12
+ // PR-A of issue #204: the profile switch state machine (incl. crash resume)
13
+ // lives in ./profile-switch.ts, not http-server.ts.
14
+ import { resumeTeamProfileSwitch } from "./profile-switch.js";
7
15
  import { TaskRouter } from "./task-router.js";
8
16
  import { MessageRouter } from "./message-router.js";
9
17
  import { TeamWebSocketServer } from "./websocket.js";
10
- import { ensureOpenClawWorkspaceMemoryDir } from "../openclaw-workspace.js";
18
+ import { ensureOpenClawWorkspaceMemoryDir, buildTeamClawAgentSessionKey } from "../openclaw-workspace.js";
11
19
  import { ensureControllerGitRepo } from "../git-collaboration.js";
12
20
  import { WorkerProvisioningManager } from "./worker-provisioning.js";
13
21
  import { PreviewManager } from "./preview-manager.js";
14
- import { runKickoffMeeting, buildKickoffAssessmentPrompt, ASSESSMENT_TIMEOUT_MS } from "./kickoff-orchestrator.js";
22
+ import { runKickoffMeeting, ASSESSMENT_TIMEOUT_MS } from "./kickoff-orchestrator.js";
23
+ // Issue #226 W3: the kickoff prompt contract lives in the shared layer now.
24
+ import { buildKickoffAssessmentPrompt } from "../shared/kickoff-prompt.js";
15
25
  import { resolvePreferredLanAddress } from "../networking.js";
16
26
  import { createTeamAutoScheduler } from "../teamauto/scheduler.js";
17
27
  import { getGithubAuthManager } from "./github-auth.js";
28
+ // Phase 1.6 (design 2.3): TeamState.profileId is the single runtime truth for
29
+ // the active TeamProfile; config teamProfile only seeds first initialization.
30
+ import { getActiveProfile, getActiveRoleIds, hasProfile, setActiveProfileId, validateActiveRoleId, SOFTWARE_RD_PROFILE_ID } from "../profile-loader.js";
18
31
  function getPreferredLanUiUrl(port) {
19
32
  const preferredLanAddress = resolvePreferredLanAddress();
20
33
  if (!preferredLanAddress) {
@@ -38,15 +51,53 @@ export function createControllerService(deps) {
38
51
  async start(_ctx) {
39
52
  const serviceStartedAt = Date.now();
40
53
  await ensureOpenClawWorkspaceMemoryDir(logger);
41
- const repoState = await ensureControllerGitRepo(config, logger).catch((err) => {
42
- logger.warn(`Controller: failed to prepare git collaboration repo: ${err instanceof Error ? err.message : String(err)}`);
43
- return null;
44
- });
45
- // Load or create team state
54
+ // Load or create team state. The active profile is resolved FIRST (from
55
+ // the restored TeamState.profileId, or the config bootstrap value on
56
+ // first initialization) so that capability-dependent startup wiring
57
+ // below knows which profile it is initializing (Phase 2.3 preview).
46
58
  teamState = await loadTeamState(config.teamName);
59
+ let seededProfileId;
60
+ if (!teamState) {
61
+ // Phase 1.6: first initialization seeds the active profile from the
62
+ // config bootstrap value. An unknown id is the one sanctioned
63
+ // fallback (design 2.2): warn and run the software-rd baseline.
64
+ const requestedProfileId = config.teamProfile;
65
+ seededProfileId = requestedProfileId;
66
+ if (!hasProfile(requestedProfileId)) {
67
+ seededProfileId = SOFTWARE_RD_PROFILE_ID;
68
+ logger.warn(`Controller: configured teamProfile "${requestedProfileId}" is not a built-in profile; falling back to "${SOFTWARE_RD_PROFILE_ID}"`);
69
+ }
70
+ }
71
+ else {
72
+ // Restored state: TeamState.profileId is the runtime truth (config
73
+ // changes do not re-seed it). A dangling reference means the profile
74
+ // package this team ran on is not available in this installation.
75
+ // Design 2.2 red line: FATAL, never silently run another profile -
76
+ // that is exactly how a banking team would degrade into the software
77
+ // baseline unnoticed. (The config-miss fallback above stays a warn:
78
+ // it only seeds first initialization, where no team exists yet.)
79
+ if (!hasProfile(teamState.profileId)) {
80
+ throw new Error(`Controller: team state references team profile "${teamState.profileId}", which is not available in this installation. `
81
+ + "Check the teamProfile config value and the persisted state profileId, or reinstall a TeamClaw version that ships this profile.");
82
+ }
83
+ seededProfileId = teamState.profileId;
84
+ }
85
+ setActiveProfileId(seededProfileId);
86
+ const activeCapabilities = getActiveProfile().capabilities;
87
+ // Phase 2.3 preview (minimal capability wiring, design 2.1): the git
88
+ // collaboration repo is only prepared for profiles with git enabled -
89
+ // a document-delivery team has no repo concept. On the software-rd
90
+ // baseline (git: true) behavior is unchanged.
91
+ const repoState = activeCapabilities.git
92
+ ? await ensureControllerGitRepo(config, logger).catch((err) => {
93
+ logger.warn(`Controller: failed to prepare git collaboration repo: ${err instanceof Error ? err.message : String(err)}`);
94
+ return null;
95
+ })
96
+ : null;
47
97
  let repoStateChanged = false;
48
98
  if (!teamState) {
49
99
  teamState = {
100
+ profileId: seededProfileId,
50
101
  teamName: config.teamName,
51
102
  workers: {},
52
103
  tasks: {},
@@ -58,21 +109,52 @@ export function createControllerService(deps) {
58
109
  createdAt: Date.now(),
59
110
  updatedAt: Date.now(),
60
111
  };
112
+ // W4 write-face exemption (#226): first-boot TeamState creation.
113
+ // This is initialization, not an update - the updateState entry is
114
+ // only defined below and presupposes an existing shared object. No
115
+ // WS server exists yet, so there is nothing to broadcast to.
61
116
  await saveTeamState(teamState);
62
- logger.info(`Controller: created new team "${config.teamName}"`);
117
+ logger.info(`Controller: created new team "${config.teamName}" (profile: ${seededProfileId})`);
63
118
  }
64
119
  else {
65
120
  const previousRepoState = JSON.stringify(teamState.repo ?? null);
66
- teamState.repo = repoState ?? teamState.repo;
121
+ teamState.repo = repoState ?? (activeCapabilities.git ? teamState.repo : undefined);
67
122
  repoStateChanged = JSON.stringify(teamState.repo ?? null) !== previousRepoState;
68
123
  logger.info(`Controller: restored team "${config.teamName}" with ${Object.keys(teamState.workers).length} workers`);
69
124
  }
70
125
  deps.onTeamStateAvailable?.(() => teamState);
71
- const updateState = (updater) => {
72
- updater(teamState);
73
- void saveTeamState(teamState);
74
- return teamState;
75
- };
126
+ // Issue #226 W4: the single TeamState write entry (see the contract
127
+ // block above). The updater stays a synchronous closure over the
128
+ // shared object; persistence - and, when requested, the WS broadcast -
129
+ // happen strictly after the updater returned. Existing one-argument
130
+ // callers keep the exact pre-W4 fire-and-forget semantics.
131
+ const updateState = ((updater, options = {}) => {
132
+ const state = teamState;
133
+ updater(state);
134
+ if (options.persist === "awaited") {
135
+ // Durability variant (profile switch): the caller owns the save
136
+ // promise - broadcast events ride its fulfillment and never fire
137
+ // on failure; rejections surface to the caller's rollback. A
138
+ // dropped handle rejects unhandled, exactly like the historical
139
+ // floating void save.
140
+ let persisted = saveTeamState(state);
141
+ if (options.broadcast?.length) {
142
+ persisted = persisted.then(() => {
143
+ for (const event of options.broadcast) {
144
+ wsServer.broadcastUpdate(event);
145
+ }
146
+ });
147
+ }
148
+ return { state, persisted };
149
+ }
150
+ void saveTeamState(state);
151
+ if (options.broadcast?.length) {
152
+ for (const event of options.broadcast) {
153
+ wsServer.broadcastUpdate(event);
154
+ }
155
+ }
156
+ return state;
157
+ });
76
158
  // Provisioned workers die with the previous gateway process. Their
77
159
  // persisted entries flip to offline once heartbeats stop but were
78
160
  // never removed, so every gateway restart accumulated ghost rows in
@@ -108,6 +190,11 @@ export function createControllerService(deps) {
108
190
  // Run ALL syncState calls (avoid || short-circuit skipping some).
109
191
  const syncC = workerProvisioningManager.syncState(teamState);
110
192
  if (repoStateChanged || syncC) {
193
+ // W4 write-face exemption (#226): startup durability barrier for the
194
+ // startup state assembly above (repo stamp + provisioning syncState's
195
+ // in-place mutations, which belong to the provisioning module). Runs
196
+ // before the WS server exists; there is no updater closure to run
197
+ // here - the mutations already happened on the shared object.
111
198
  await saveTeamState(teamState);
112
199
  }
113
200
  // Clean up orphaned tasks — tasks assigned to workers that no longer
@@ -144,11 +231,28 @@ export function createControllerService(deps) {
144
231
  }
145
232
  }
146
233
  if (orphanCleaned) {
234
+ // W4 write-face exemption (#226): startup orphan-task sweep. The
235
+ // loop above mutates in place interleaved with per-task startup
236
+ // logging; this awaited save is the pre-HTTP durability barrier -
237
+ // folding the sweep into an updater closure would reshuffle the
238
+ // startup crash-window ordering for zero convergence gain (the WS
239
+ // server does not exist yet, nothing to broadcast).
147
240
  await saveTeamState(teamState);
148
241
  }
149
242
  }
150
243
  mdnsAdvertiser = new MDnsAdvertiser(logger);
151
- taskRouter = new TaskRouter(logger);
244
+ // Phase 2.5 wiring (design 2.3 "LLM 兜底", P2.5 follow-up): the
245
+ // controller LLM session is the production role judge for tasks the
246
+ // bilingual token fast path refuses to decide (tie / all-zero). The
247
+ // judge runs on a dedicated one-shot subagent session - NOT the intake
248
+ // conversation - so verdicts never pollute intake semantics. Missing
249
+ // runtime subagent => no judge, and the TaskRouter keeps its exact
250
+ // pre-wiring behavior.
251
+ const llmRoleJudge = createControllerLlmRoleJudge(deps);
252
+ if (llmRoleJudge) {
253
+ logger.info("Controller: LLM role judge wired into task dispatch (unconfident role inference escalates to the controller LLM)");
254
+ }
255
+ taskRouter = new TaskRouter(logger, llmRoleJudge ? { llmRoleJudge } : undefined);
152
256
  messageRouter = new MessageRouter(logger);
153
257
  wsServer = new TeamWebSocketServer(logger);
154
258
  // When running inside a container (Docker or K8s), bind to 0.0.0.0
@@ -160,7 +264,7 @@ export function createControllerService(deps) {
160
264
  const listenPort = config.port;
161
265
  const listenHost = isContainer ? "0.0.0.0" : "127.0.0.1";
162
266
  let serviceKickoffHandler;
163
- const server = createControllerHttpServer({
267
+ const httpDeps = {
164
268
  config,
165
269
  logger,
166
270
  runtime: deps.runtime,
@@ -173,7 +277,8 @@ export function createControllerService(deps) {
173
277
  previewManager,
174
278
  getKickoffHandler: () => serviceKickoffHandler,
175
279
  getTeamAutoScheduler: () => teamAutoSchedulerRef,
176
- });
280
+ };
281
+ const server = createControllerHttpServer(httpDeps);
177
282
  const PORT_RETRY_STEP = 10;
178
283
  const PORT_MAX_RETRIES = 10;
179
284
  let actualPort = 0;
@@ -215,30 +320,55 @@ export function createControllerService(deps) {
215
320
  if (workerProvisioningManager.isEnabled()) {
216
321
  workerProvisioningManager.setActualPort(actualPort);
217
322
  }
323
+ // Phase 2.1 (design 2.3 crash semantics): resume an interrupted team
324
+ // profile switch before TeamAuto/preview restoration/provisioning kick
325
+ // in, so no subsystem fights the resume. Runs after the port is known
326
+ // (switch warmup launches need the actual controller URL). Requests
327
+ // arriving mid-resume hit the transition concurrency matrix (409/503),
328
+ // which is exactly what it exists for. An unavailable target profile is
329
+ // fatal here - same red line as restoring an unknown profileId.
330
+ await resumeTeamProfileSwitch(httpDeps);
218
331
  // TeamAuto: autonomous repo collaboration (bind repos via /api/v1/teamauto/*).
219
- try {
220
- const auth = getGithubAuthManager(config, logger);
221
- const httpDepsForAutoAssign = { config, logger, getTeamState: () => teamState, updateTeamState: updateState, taskRouter, messageRouter, wsServer };
222
- teamAutoSchedulerRef = createTeamAutoScheduler({
223
- logger,
224
- auth,
225
- getTeamState: () => teamState,
226
- updateTeamState: updateState,
227
- onTasksCreated: async () => {
228
- await autoAssignPendingTasks(httpDepsForAutoAssign);
229
- },
230
- onActivity: (entry) => {
231
- wsServer.broadcastUpdate({
232
- type: "teamauto:activity",
233
- data: { at: entry.at, repoId: entry.repoId, kind: entry.kind, text: entry.text },
234
- });
235
- },
236
- });
237
- await teamAutoSchedulerRef.start();
238
- deps.onTeamAutoSchedulerAvailable?.(() => teamAutoSchedulerRef);
332
+ // Phase 2.3 preview (minimal capability wiring): a profile with
333
+ // teamauto disabled never starts the scheduler at all.
334
+ if (getActiveProfile().capabilities.teamauto) {
335
+ try {
336
+ const auth = getGithubAuthManager(config, logger);
337
+ teamAutoSchedulerRef = createTeamAutoScheduler({
338
+ logger,
339
+ auth,
340
+ getTeamState: () => teamState,
341
+ updateTeamState: updateState,
342
+ onTasksCreated: async () => {
343
+ // Same deps object as every HTTP call site (issue #191 gate
344
+ // review): the autoAssign re-entrancy gate is keyed per deps
345
+ // object, so an ad-hoc object here would open a SECOND gate -
346
+ // a TeamAuto round and an HTTP round could then run concurrently
347
+ // with separate attemptedPairs sets (double dispatch attempts,
348
+ // same-task double LLM-judge window). The ad-hoc object also
349
+ // silently dropped workerProvisioningManager/getTeamAutoScheduler
350
+ // for these rounds (no reconcile nudge; teamauto write tasks
351
+ // dispatched from this path fell back to the shared checkout
352
+ // instead of a task-scoped worktree). It was a leftover from
353
+ // before the shared httpDeps existed, not a deliberate split.
354
+ await autoAssignPendingTasks(httpDeps);
355
+ },
356
+ onActivity: (entry) => {
357
+ wsServer.broadcastUpdate({
358
+ type: "teamauto:activity",
359
+ data: { at: entry.at, repoId: entry.repoId, kind: entry.kind, text: entry.text },
360
+ });
361
+ },
362
+ });
363
+ await teamAutoSchedulerRef.start();
364
+ deps.onTeamAutoSchedulerAvailable?.(() => teamAutoSchedulerRef);
365
+ }
366
+ catch (err) {
367
+ logger.warn(`Controller: TeamAuto scheduler failed to start: ${err instanceof Error ? err.message : String(err)}`);
368
+ }
239
369
  }
240
- catch (err) {
241
- logger.warn(`Controller: TeamAuto scheduler failed to start: ${err instanceof Error ? err.message : String(err)}`);
370
+ else {
371
+ logger.info("Controller: TeamAuto scheduler skipped (capability disabled by the active team profile)");
242
372
  }
243
373
  // Start mDNS advertising with the actual port
244
374
  await mdnsAdvertiser.start(actualPort, config.teamName);
@@ -256,19 +386,24 @@ export function createControllerService(deps) {
256
386
  }
257
387
  },
258
388
  requestWorkerAssessment: async (worker, req) => {
259
- return await requestKickoffAssessment(worker, req);
389
+ // Issue #222: carry the worker's dispatch token on the assess call.
390
+ return await requestKickoffAssessment(worker, req, withWorkerDispatchToken({}, worker.id, config, teamState));
260
391
  },
261
392
  });
262
393
  return { assessments: result.plan.assessments, summary: result.summary };
263
394
  };
264
395
  serviceKickoffHandler = kickoffHandler;
265
396
  deps.onKickoffHandlerAvailable?.(kickoffHandler);
266
- logger.info(`Controller: starting preview restoration...`);
267
- void previewManager.restorePreviewsOnStartup().then(() => {
268
- logger.info(`Controller: preview restoration completed`);
269
- }).catch((err) => {
270
- logger.warn(`Controller: failed to restore previews on startup: ${String(err)}`);
271
- });
397
+ // Phase 2.3 preview (minimal capability wiring): only profiles with
398
+ // runnablePreview enabled restore dynamic previews on startup.
399
+ if (getActiveProfile().capabilities.runnablePreview) {
400
+ logger.info(`Controller: starting preview restoration...`);
401
+ void previewManager.restorePreviewsOnStartup().then(() => {
402
+ logger.info(`Controller: preview restoration completed`);
403
+ }).catch((err) => {
404
+ logger.warn(`Controller: failed to restore previews on startup: ${String(err)}`);
405
+ });
406
+ }
272
407
  // Start timeout monitoring
273
408
  timeoutTimer = setInterval(() => {
274
409
  if (!teamState)
@@ -316,8 +451,57 @@ export function createControllerService(deps) {
316
451
  }
317
452
  }
318
453
  if (changed) {
454
+ // W4 write-face exemption (#226): heartbeat-timeout sweep. The
455
+ // mutations interleave with per-worker WS broadcasts inside the
456
+ // synchronous loop above; this floating save is byte-for-byte the
457
+ // entry's own background semantics (void saveTeamState), so
458
+ // routing it through updateState with a no-op updater would add
459
+ // ceremony without moving any save or broadcast.
319
460
  saveTeamState(teamState);
320
461
  }
462
+ // Runtime orphan-task reconciliation (user-found: one live worker but
463
+ // two active tasks - the second task was pinned to a worker whose
464
+ // registry entry was already gone). The startup sweep handles this
465
+ // once at boot; tasks whose worker disappears AFTER claiming sat in
466
+ // in_progress forever. Mirror the startup semantics: reset to pending
467
+ // (bounded resume attempts), re-dispatch happens via the reconcile
468
+ // call below. Skip workers the sweep above just released - their
469
+ // tasks were already handled with a broadcast.
470
+ {
471
+ let orphaned = false;
472
+ for (const task of Object.values(teamState.tasks)) {
473
+ if (task.assignedWorkerId &&
474
+ (task.status === "assigned" || task.status === "in_progress") &&
475
+ !teamState.workers[task.assignedWorkerId]) {
476
+ const attempt = (task.resumeAttempt ?? 0) + 1;
477
+ const MAX_RESUME_ATTEMPTS = 3;
478
+ if (attempt > MAX_RESUME_ATTEMPTS) {
479
+ logger.warn(`Controller: task ${task.id} exceeded ${MAX_RESUME_ATTEMPTS} resume attempts (worker gone) - failing`);
480
+ task.status = "failed";
481
+ task.error = `worker disappeared without completing (resumed ${MAX_RESUME_ATTEMPTS} times)`;
482
+ }
483
+ else {
484
+ logger.info(`Controller: resetting orphaned task ${task.id} for resume attempt ${attempt} (worker ${task.assignedWorkerId} missing)`);
485
+ task.status = "pending";
486
+ task.resumeAttempt = attempt;
487
+ if (task.checkpoint) {
488
+ task.checkpoint.attempt = attempt;
489
+ }
490
+ }
491
+ task.assignedWorkerId = undefined;
492
+ task.updatedAt = now;
493
+ wsServer.broadcastUpdate({ type: "task:updated", data: { ...task } });
494
+ orphaned = true;
495
+ }
496
+ }
497
+ if (orphaned) {
498
+ // W4 write-face exemption (#226): runtime orphan-task
499
+ // reconciliation, same sweep-interleaved-broadcast shape as the
500
+ // worker loop above (see that exemption note).
501
+ saveTeamState(teamState);
502
+ changed = true;
503
+ }
504
+ }
321
505
  if (workerProvisioningManager?.isEnabled()) {
322
506
  void workerProvisioningManager.requestReconcile("periodic controller sync");
323
507
  }
@@ -363,9 +547,10 @@ function openBrowser(url, logger) {
363
547
  /**
364
548
  * Request a kickoff assessment from a worker.
365
549
  *
366
- * Request kickoff assessment from a worker over HTTP.
550
+ * Request kickoff assessment from a worker over HTTP. `authHeaders` carries
551
+ * the worker's dispatch token (issue #222) when the controller knows one.
367
552
  */
368
- async function requestKickoffAssessment(worker, requirement) {
553
+ async function requestKickoffAssessment(worker, requirement, authHeaders = {}) {
369
554
  const role = worker.role;
370
555
  const prompt = buildKickoffAssessmentPrompt(role, requirement);
371
556
  // External worker — POST to kickoff assess endpoint
@@ -377,7 +562,7 @@ async function requestKickoffAssessment(worker, requirement) {
377
562
  try {
378
563
  const res = await fetch(`${worker.url}/api/v1/kickoff/assess`, {
379
564
  method: "POST",
380
- headers: { "Content-Type": "application/json" },
565
+ headers: { "Content-Type": "application/json", ...authHeaders },
381
566
  body: JSON.stringify({ requirement, role }),
382
567
  signal: controller.signal,
383
568
  });
@@ -391,3 +576,106 @@ async function requestKickoffAssessment(worker, requirement) {
391
576
  clearTimeout(timeout);
392
577
  }
393
578
  }
579
+ // ── Phase 2.5 wiring: controller LLM as the role judge ───────────────────────
580
+ //
581
+ // resolveTaskRoleWithLlmFallback (kickoff-orchestrator) defined the seam in
582
+ // P2.5 with fake-driven tests but no production caller. This factory builds
583
+ // the production llmRoleJudge: a ONE-SHOT subagent session on the controller
584
+ // runtime (never the long-lived intake conversation, so verdicts cannot
585
+ // pollute intake semantics) that answers with a single role id of the ACTIVE
586
+ // profile. The resolver validates the answer (validateActiveRoleId) and
587
+ // degrades to the profile defaultRole when the judge is unavailable, times
588
+ // out, errors, or names a role outside the active profile - the TaskRouter
589
+ // then treats the outcome as a routing hint, so dispatch never blocks on a
590
+ // strand.
591
+ /** Budget for a one-id LLM verdict; past it the resolver degrades to defaultRole. */
592
+ const ROLE_JUDGE_TIMEOUT_MS = 30_000;
593
+ const ROLE_JUDGE_SESSION_PREFIX = "teamclaw-role-judge:";
594
+ const ROLE_JUDGE_SYSTEM_PROMPT = [
595
+ "You are the role router of a TeamClaw controller.",
596
+ "Given one task, pick the single team role that should own it.",
597
+ "Reply with EXACTLY one role id from the provided list - no prose, no markdown, no explanation.",
598
+ ].join(" ");
599
+ function createControllerLlmRoleJudge(deps) {
600
+ const subagent = deps.runtime?.subagent;
601
+ if (!subagent
602
+ || typeof subagent.run !== "function"
603
+ || typeof subagent.waitForRun !== "function"
604
+ || typeof subagent.getSessionMessages !== "function") {
605
+ // Runtime without an LLM subagent (e.g. minimal test doubles): leave the
606
+ // seam unwired; the TaskRouter keeps its pre-wiring behavior.
607
+ return undefined;
608
+ }
609
+ const logger = deps.logger;
610
+ return async ({ task, verdict }) => {
611
+ const roleIds = getActiveRoleIds();
612
+ const message = [
613
+ `Task title: ${task.title}`,
614
+ `Task description: ${task.description?.trim() || "(none)"}`,
615
+ "",
616
+ `Token-based role scoring refused to decide (${verdict.reason}).`,
617
+ `Pick the single role that should own this task. Answer with EXACTLY one role id from: ${roleIds.join(", ")}`,
618
+ ].join("\n");
619
+ // Fresh one-shot session per verdict: the judge must stay stateless and
620
+ // separate from any intake/worker conversation.
621
+ const sessionKey = buildTeamClawAgentSessionKey(`${ROLE_JUDGE_SESSION_PREFIX}${task.id}-${Date.now()}`);
622
+ const run = await subagent.run({
623
+ sessionKey,
624
+ message,
625
+ extraSystemPrompt: ROLE_JUDGE_SYSTEM_PROMPT,
626
+ idempotencyKey: `role-judge-${task.id}-${Date.now()}`,
627
+ });
628
+ const waited = await subagent.waitForRun({
629
+ runId: run.runId,
630
+ timeoutMs: ROLE_JUDGE_TIMEOUT_MS,
631
+ });
632
+ if (waited.status !== "ok") {
633
+ logger.warn(`Controller: LLM role judge did not complete for task ${task.id} (${waited.status}${"error" in waited && waited.error ? `: ${waited.error}` : ""}); using the profile defaultRole`);
634
+ return null;
635
+ }
636
+ const session = await subagent.getSessionMessages({ sessionKey, limit: 5 });
637
+ const reply = extractLastAssistantText(session.messages);
638
+ const direct = validateActiveRoleId(reply.trim());
639
+ if (direct) {
640
+ return direct;
641
+ }
642
+ // Tolerate light prose wrapping ("The role is: qa."): first ACTIVE role
643
+ // id that appears as a whole word in the reply.
644
+ for (const roleId of roleIds) {
645
+ const pattern = new RegExp(`(^|[^a-z0-9-])${roleId.replace(/[-]/g, "\\-")}([^a-z0-9-]|$)`);
646
+ if (pattern.test(reply)) {
647
+ return roleId;
648
+ }
649
+ }
650
+ logger.warn(`Controller: LLM role judge reply for task ${task.id} named no active role (${reply.slice(0, 120) || "empty reply"}); using the profile defaultRole`);
651
+ return null;
652
+ };
653
+ }
654
+ /** Last assistant message text (string or text blocks), mirroring the http-server intake helper semantics. */
655
+ function extractLastAssistantText(messages) {
656
+ const assistantMessages = messages.filter((message) => {
657
+ if (!message || typeof message !== "object") {
658
+ return false;
659
+ }
660
+ return message.role === "assistant";
661
+ });
662
+ const lastAssistant = assistantMessages[assistantMessages.length - 1];
663
+ if (!lastAssistant) {
664
+ return "";
665
+ }
666
+ if (typeof lastAssistant.content === "string") {
667
+ return lastAssistant.content;
668
+ }
669
+ if (Array.isArray(lastAssistant.content)) {
670
+ const textBlocks = lastAssistant.content
671
+ .filter((block) => {
672
+ return !!block && typeof block === "object" && block.type === "text";
673
+ })
674
+ .map((block) => (typeof block.text === "string" ? block.text : ""))
675
+ .filter(Boolean);
676
+ if (textBlocks.length > 0) {
677
+ return textBlocks.join("\n");
678
+ }
679
+ }
680
+ return "";
681
+ }
@@ -1,7 +1,15 @@
1
1
  import { Type } from "@sinclair/typebox";
2
2
  import { buildControllerNoWorkersMessage, hasOnDemandWorkerProvisioning, shouldBlockControllerWithoutWorkers } from "./controller-capacity.js";
3
- import { normalizeClarificationQuestionSchemas, normalizeManifestCompletionOpportunities, normalizeManifestCreatedTasks, normalizeManifestDeferredTasks, normalizeManifestRoleList, normalizeManifestStringList, normalizeOptionalManifestText, } from "./orchestration-manifest.js";
3
+ import { normalizeManifestCompletionOpportunities, normalizeManifestCreatedTasks, normalizeManifestDeferredTasks, normalizeManifestRoleList, normalizeManifestStringList, } from "./orchestration-manifest.js";
4
+ // Issue #226 W3: the clarification-schema family lives in the shared layer now.
5
+ import { normalizeClarificationQuestionSchemas, normalizeOptionalManifestText, } from "../shared/clarification-schema.js";
4
6
  import { ensureTeamMessageContract, normalizeContractRole, normalizeContractStringList, } from "../interaction-contracts.js";
7
+ // Phase 2.1 debt item 1 (P1 closeout handover): tool input validation checks
8
+ // the ACTIVE TeamProfile's role set via the profile loader. The previous
9
+ // registry-set check would silently kill every non-software role once a team
10
+ // switches profiles; behavior on the software-rd baseline is unchanged
11
+ // (active set == registry set).
12
+ import { validateActiveRoleId } from "../profile-loader.js";
5
13
  const EXECUTION_READY_BLOCKERS = [
6
14
  { pattern: /\bdepends?\s+on\b/i, reason: "it explicitly depends on other unfinished work" },
7
15
  { pattern: /\bprerequisite\b/i, reason: "it references a prerequisite that may not be satisfied yet" },
@@ -12,10 +20,6 @@ const EXECUTION_READY_BLOCKERS = [
12
20
  { pattern: /blocked\s*-\s*by/i, reason: "it explicitly says the task is blocked by another item" },
13
21
  { pattern: /需要.*先完成/u, reason: "it states another piece of work must complete first" },
14
22
  ];
15
- const VALID_ROLE_IDS = new Set([
16
- "pm", "architect", "developer", "qa", "release-engineer",
17
- "infra-engineer", "devops", "security-engineer", "designer", "marketing",
18
- ]);
19
23
  const ENGLISH_LATER_PHASE_CLAUSE_RE = /\b(?:after|once)\b(.+?)\b(complete|completed|ready|available|exists?)\b/i;
20
24
  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;
21
25
  const CHINESE_LATER_PHASE_CLAUSE_RE = /(.+?)(完成后|就绪后)/u;
@@ -58,9 +62,12 @@ export function createControllerTools(deps) {
58
62
  return { details: {}, content: [{ type: "text", text: "requirement is required." }] };
59
63
  }
60
64
  const rawRoles = Array.isArray(params.candidateRoles) ? params.candidateRoles : [];
65
+ // Phase 2.1 debt item 1: validate against the ACTIVE profile's role
66
+ // set (validateActiveRoleId) so kickoff candidate roles of a switched
67
+ // team (e.g. banking) pass instead of being silently filtered out.
61
68
  const candidateRoles = rawRoles
62
- .map((r) => String(r ?? "").trim().toLowerCase())
63
- .filter((r) => VALID_ROLE_IDS.has(r));
69
+ .map((r) => validateActiveRoleId(String(r ?? "").trim().toLowerCase()))
70
+ .filter((r) => r !== undefined);
64
71
  if (candidateRoles.length === 0) {
65
72
  return { details: {}, content: [{ type: "text", text: "At least one valid candidate role is required." }] };
66
73
  }
@@ -12,7 +12,8 @@ import path from "node:path";
12
12
  * Persistence: a single JSON file under the plugin state directory
13
13
  * (`auth/github.json`, mode 0600, atomic tmp+rename writes).
14
14
  */
15
- export const DEFAULT_GITHUB_CLIENT_ID = "Iv23liqWmzrS3swGiIvK";
15
+ import { DEFAULT_GITHUB_CLIENT_ID } from "../shared/github-auth.js";
16
+ export { DEFAULT_GITHUB_CLIENT_ID };
16
17
  export const GITHUB_AUTH_CALLBACK_PATH = "/api/v1/auth/github/callback";
17
18
  export const GITHUB_CLIENT_SECRET_ENV = "TEAMCLAW_GITHUB_CLIENT_SECRET";
18
19
  const GITHUB_AUTHORIZE_URL = "https://github.com/login/oauth/authorize";