@teamclaws/teamclaw 2026.8.0 → 2026.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/cli.mjs +46 -15
  2. package/dist/api.js +1 -0
  3. package/dist/index.js +325 -0
  4. package/dist/src/config.js +412 -0
  5. package/dist/src/controller/clarification-routes.js +315 -0
  6. package/dist/src/controller/controller-capacity.js +14 -0
  7. package/dist/src/controller/controller-intake.js +895 -0
  8. package/dist/src/controller/controller-planning.js +813 -0
  9. package/dist/src/controller/controller-runs.js +175 -0
  10. package/dist/src/controller/controller-service.js +624 -0
  11. package/dist/src/controller/controller-tools.js +587 -0
  12. package/dist/src/controller/delivery-report.js +458 -0
  13. package/dist/src/controller/github-auth.js +564 -0
  14. package/dist/src/controller/http-server.js +284 -0
  15. package/dist/src/controller/kickoff-orchestrator.js +246 -0
  16. package/dist/src/controller/managed-gateway-process.js +286 -0
  17. package/dist/src/controller/message-delivery.js +28 -0
  18. package/dist/src/controller/message-router.js +38 -0
  19. package/dist/src/controller/message-routes.js +114 -0
  20. package/dist/src/controller/orchestration-manifest.js +151 -0
  21. package/dist/src/controller/preview-manager.js +586 -0
  22. package/dist/src/controller/preview-proxy.js +98 -0
  23. package/dist/src/controller/profile-switch.js +289 -0
  24. package/dist/src/controller/project-registry.js +294 -0
  25. package/dist/src/controller/prompt-injector.js +197 -0
  26. package/dist/src/controller/repo-routes.js +63 -0
  27. package/dist/src/controller/role-inference.js +246 -0
  28. package/dist/src/controller/route-table.js +1353 -0
  29. package/dist/src/controller/task-assignment.js +508 -0
  30. package/dist/src/controller/task-cleanup.js +258 -0
  31. package/dist/src/controller/task-execution.js +240 -0
  32. package/dist/src/controller/task-results.js +461 -0
  33. package/dist/src/controller/task-router.js +137 -0
  34. package/dist/src/controller/task-routes.js +703 -0
  35. package/dist/src/controller/teamauto-routes.js +124 -0
  36. package/dist/src/controller/tunnel-manager.js +548 -0
  37. package/dist/src/controller/ui-assets.js +68 -0
  38. package/dist/src/controller/websocket.js +42 -0
  39. package/dist/src/controller/worker-provisioning.js +1674 -0
  40. package/dist/src/controller/worker-routes.js +188 -0
  41. package/dist/src/discovery.js +86 -0
  42. package/dist/src/git-collaboration.js +694 -0
  43. package/dist/src/identity.js +132 -0
  44. package/dist/src/install-defaults.js +1 -0
  45. package/dist/src/interaction-contracts.js +531 -0
  46. package/dist/src/networking.js +91 -0
  47. package/dist/src/openclaw-workspace.js +925 -0
  48. package/dist/src/profile-loader.js +486 -0
  49. package/dist/src/profiles/banking.json +178 -0
  50. package/dist/src/profiles/crossborder-ecom.json +253 -0
  51. package/dist/src/profiles/insurance.json +157 -0
  52. package/dist/src/profiles/knowledge/hs-structure.md +97 -0
  53. package/dist/src/profiles/knowledge/incoterms-2020.md +188 -0
  54. package/dist/src/profiles/knowledge/vat-principles.md +85 -0
  55. package/dist/src/profiles/schema.json +201 -0
  56. package/dist/src/profiles/securities.json +137 -0
  57. package/dist/src/profiles/software-rd.json +264 -0
  58. package/dist/src/profiles/trading-co.json +200 -0
  59. package/dist/src/prompt-policy.js +386 -0
  60. package/dist/src/protocol.js +58 -0
  61. package/dist/src/role-ids.js +29 -0
  62. package/dist/src/roles.js +390 -0
  63. package/dist/src/session-roles.js +14 -0
  64. package/dist/src/state.js +361 -0
  65. package/dist/src/task-executor.js +1023 -0
  66. package/dist/src/teamauto/github-client.js +210 -0
  67. package/dist/src/teamauto/norms.js +85 -0
  68. package/dist/src/teamauto/repo-sync.js +423 -0
  69. package/dist/src/teamauto/scanner.js +207 -0
  70. package/dist/src/teamauto/schedule.js +123 -0
  71. package/dist/src/teamauto/scheduler.js +907 -0
  72. package/dist/src/teamauto/store.js +133 -0
  73. package/dist/src/types.js +290 -0
  74. package/dist/src/ui/app.js +4860 -0
  75. package/dist/src/ui/assets/teamclaw-app-icon.png +0 -0
  76. package/dist/src/ui/github-login.html +296 -0
  77. package/dist/src/ui/index.html +447 -0
  78. package/dist/src/ui/style.css +2805 -0
  79. package/dist/src/worker/http-handler.js +146 -0
  80. package/dist/src/worker/message-queue.js +24 -0
  81. package/dist/src/worker/prompt-injector.js +78 -0
  82. package/dist/src/worker/skill-installer.js +255 -0
  83. package/dist/src/worker/tools.js +541 -0
  84. package/dist/src/worker/worker-service.js +307 -0
  85. package/dist/src/workspace-browser.js +269 -0
  86. package/openclaw.plugin.json +28 -1
  87. package/package.json +3 -2
  88. package/src/config.ts +33 -2
  89. package/src/controller/clarification-routes.ts +404 -0
  90. package/src/controller/controller-intake.ts +1113 -0
  91. package/src/controller/controller-planning.ts +1029 -0
  92. package/src/controller/controller-runs.ts +239 -0
  93. package/src/controller/controller-service.ts +295 -41
  94. package/src/controller/controller-tools.ts +11 -7
  95. package/src/controller/http-server.ts +294 -6971
  96. package/src/controller/kickoff-orchestrator.ts +70 -7
  97. package/src/controller/message-delivery.ts +49 -0
  98. package/src/controller/message-routes.ts +137 -0
  99. package/src/controller/orchestration-manifest.ts +6 -29
  100. package/src/controller/preview-proxy.ts +127 -0
  101. package/src/controller/profile-switch.ts +366 -0
  102. package/src/controller/project-registry.ts +361 -0
  103. package/src/controller/prompt-injector.ts +23 -8
  104. package/src/controller/repo-routes.ts +91 -0
  105. package/src/controller/role-inference.ts +260 -22
  106. package/src/controller/route-table.ts +1616 -0
  107. package/src/controller/task-assignment.ts +618 -0
  108. package/src/controller/task-cleanup.ts +344 -0
  109. package/src/controller/task-execution.ts +356 -0
  110. package/src/controller/task-results.ts +544 -0
  111. package/src/controller/task-router.ts +98 -6
  112. package/src/controller/task-routes.ts +812 -0
  113. package/src/controller/teamauto-routes.ts +121 -0
  114. package/src/controller/ui-assets.ts +70 -0
  115. package/src/controller/websocket.ts +13 -1
  116. package/src/controller/worker-provisioning.ts +32 -4
  117. package/src/controller/worker-routes.ts +241 -0
  118. package/src/identity.ts +3 -2
  119. package/src/interaction-contracts.ts +7 -7
  120. package/src/openclaw-workspace.ts +44 -18
  121. package/src/profile-loader.ts +650 -0
  122. package/src/profiles/banking.json +178 -0
  123. package/src/profiles/crossborder-ecom.json +253 -0
  124. package/src/profiles/insurance.json +157 -0
  125. package/src/profiles/knowledge/hs-structure.md +97 -0
  126. package/src/profiles/knowledge/incoterms-2020.md +188 -0
  127. package/src/profiles/knowledge/vat-principles.md +85 -0
  128. package/src/profiles/schema.json +201 -0
  129. package/src/profiles/securities.json +137 -0
  130. package/src/profiles/software-rd.json +264 -0
  131. package/src/profiles/trading-co.json +200 -0
  132. package/src/prompt-policy.ts +27 -13
  133. package/src/role-ids.ts +31 -0
  134. package/src/roles.ts +60 -14
  135. package/src/session-roles.ts +14 -0
  136. package/src/state.ts +236 -9
  137. package/src/task-executor.ts +7 -18
  138. package/src/teamauto/github-client.ts +21 -0
  139. package/src/teamauto/repo-sync.ts +246 -6
  140. package/src/teamauto/scanner.ts +47 -13
  141. package/src/teamauto/scheduler.ts +259 -16
  142. package/src/teamauto/store.ts +12 -0
  143. package/src/types.ts +133 -16
  144. package/src/ui/app.js +592 -24
  145. package/src/ui/index.html +44 -11
  146. package/src/ui/style.css +194 -0
  147. package/src/worker/prompt-injector.ts +48 -8
  148. package/src/worker/skill-installer.ts +3 -1
  149. package/src/worker/worker-service.ts +83 -3
@@ -0,0 +1,239 @@
1
+ // PR-C of issue #204 (http-server monolith split): the controller-run
2
+ // lifecycle (execution event ring, create/update/serialize) extracted
3
+ // verbatim from controller/http-server.ts. Zero behavior change - callers
4
+ // pass the same deps object as before. This module must NEVER import
5
+ // http-server (the reverse edge exists: http-server -> controller-runs).
6
+ import type { PluginLogger } from "../../api.js";
7
+ import type {
8
+ ControllerRunInfo,
9
+ ControllerRunSource,
10
+ TaskExecution,
11
+ TaskExecutionEvent,
12
+ TaskExecutionEventInput,
13
+ TeamState,
14
+ } from "../types.js";
15
+ import { generateId } from "../protocol.js";
16
+ import { deriveProjectSlug } from "../openclaw-workspace.js";
17
+ import { buildTaskExecutionSummary, MAX_TASK_EXECUTION_EVENTS } from "./task-execution.js";
18
+ import {
19
+ extractExplicitProjectNameHint,
20
+ resolveExistingProjectIdentityFromMessage,
21
+ resolveProjectIdentityForSession,
22
+ resolveProjectIdentityForTaskId,
23
+ syncProjectRegistryEntry,
24
+ } from "./project-registry.js";
25
+ import type { ControllerTaskDomainDeps } from "./task-execution.js";
26
+
27
+ const MAX_CONTROLLER_RUNS = 40;
28
+
29
+ export function ensureControllerRunExecution(run: ControllerRunInfo): TaskExecution {
30
+ if (!run.execution) {
31
+ run.execution = {
32
+ status: run.status,
33
+ runId: run.runId,
34
+ startedAt: run.startedAt,
35
+ endedAt: run.completedAt,
36
+ lastUpdatedAt: run.updatedAt,
37
+ events: [],
38
+ };
39
+ }
40
+
41
+ if (!Array.isArray(run.execution.events)) {
42
+ run.execution.events = [];
43
+ }
44
+
45
+ run.execution.status = run.status;
46
+ run.execution.runId = run.runId ?? run.execution.runId;
47
+ run.execution.startedAt = run.startedAt ?? run.execution.startedAt;
48
+ run.execution.endedAt = run.completedAt ?? run.execution.endedAt;
49
+ run.execution.lastUpdatedAt = run.updatedAt ?? run.execution.lastUpdatedAt;
50
+ return run.execution;
51
+ }
52
+
53
+ export function appendControllerRunEvent(run: ControllerRunInfo, input: TaskExecutionEventInput): TaskExecutionEvent {
54
+ const now = input.createdAt ?? Date.now();
55
+ const execution = ensureControllerRunExecution(run);
56
+
57
+ if (input.runId) {
58
+ run.runId = input.runId;
59
+ execution.runId = input.runId;
60
+ }
61
+ if (input.sessionKey) {
62
+ execution.sessionKey = input.sessionKey;
63
+ }
64
+ if (input.status) {
65
+ run.status = input.status;
66
+ execution.status = input.status;
67
+ }
68
+
69
+ if ((input.status === "running" || input.phase === "run_started") && !run.startedAt) {
70
+ run.startedAt = now;
71
+ execution.startedAt = now;
72
+ }
73
+ if (run.status === "completed" || run.status === "failed") {
74
+ run.completedAt = run.completedAt ?? now;
75
+ execution.endedAt = execution.endedAt ?? now;
76
+ }
77
+
78
+ run.updatedAt = now;
79
+ execution.lastUpdatedAt = now;
80
+
81
+ const event: TaskExecutionEvent = {
82
+ id: generateId(),
83
+ type: input.type,
84
+ createdAt: now,
85
+ message: input.message,
86
+ phase: input.phase,
87
+ source: input.source,
88
+ stream: input.stream,
89
+ };
90
+
91
+ execution.events.push(event);
92
+ if (execution.events.length > MAX_TASK_EXECUTION_EVENTS) {
93
+ execution.events = execution.events.slice(-MAX_TASK_EXECUTION_EVENTS);
94
+ }
95
+
96
+ return event;
97
+ }
98
+
99
+ export function trimControllerRuns(state: TeamState): void {
100
+ const runs = Object.values(state.controllerRuns)
101
+ .sort((left, right) => left.updatedAt - right.updatedAt);
102
+ if (runs.length <= MAX_CONTROLLER_RUNS) {
103
+ return;
104
+ }
105
+ for (const run of runs.slice(0, runs.length - MAX_CONTROLLER_RUNS)) {
106
+ delete state.controllerRuns[run.id];
107
+ }
108
+ }
109
+
110
+ export function serializeControllerRun(run?: ControllerRunInfo, includeExecutionEvents = true): Record<string, unknown> | undefined {
111
+ if (!run) {
112
+ return undefined;
113
+ }
114
+
115
+ const payload: Record<string, unknown> = { ...run };
116
+ if (!run.execution) {
117
+ return payload;
118
+ }
119
+
120
+ payload.execution = includeExecutionEvents
121
+ ? {
122
+ status: run.execution.status,
123
+ runId: run.execution.runId,
124
+ startedAt: run.execution.startedAt,
125
+ endedAt: run.execution.endedAt,
126
+ lastUpdatedAt: run.execution.lastUpdatedAt,
127
+ events: run.execution.events.map((event) => ({ ...event })),
128
+ }
129
+ : buildTaskExecutionSummary(run.execution);
130
+
131
+ return payload;
132
+ }
133
+
134
+ export function buildControllerRunTitle(
135
+ message: string,
136
+ source: ControllerRunSource,
137
+ sourceTaskTitle?: string,
138
+ ): string {
139
+ if (source === "task_follow_up") {
140
+ const normalizedSourceTitle = String(sourceTaskTitle || "").replace(/\s+/g, " ").trim();
141
+ if (normalizedSourceTitle) {
142
+ const compactSourceTitle = normalizedSourceTitle.length <= 72
143
+ ? normalizedSourceTitle
144
+ : `${normalizedSourceTitle.slice(0, 72).trimEnd()}…`;
145
+ return `Controller follow-up after ${compactSourceTitle}`;
146
+ }
147
+ return "Controller workflow follow-up";
148
+ }
149
+
150
+ const normalized = message.replace(/\s+/g, " ").trim();
151
+ if (!normalized) {
152
+ return "Controller intake";
153
+ }
154
+ if (normalized.length <= 100) {
155
+ return normalized;
156
+ }
157
+ return `${normalized.slice(0, 100).trimEnd()}…`;
158
+ }
159
+
160
+ export function createControllerRun(
161
+ message: string,
162
+ sessionKey: string,
163
+ deps: ControllerTaskDomainDeps,
164
+ options?: {
165
+ source?: ControllerRunSource;
166
+ sourceTaskId?: string;
167
+ sourceTaskTitle?: string;
168
+ },
169
+ ): ControllerRunInfo {
170
+ const now = Date.now();
171
+ const existingState = deps.getTeamState();
172
+ const inheritedProject = options?.sourceTaskId
173
+ ? resolveProjectIdentityForTaskId(options.sourceTaskId, existingState)
174
+ : resolveProjectIdentityForSession(sessionKey, existingState)
175
+ ?? resolveExistingProjectIdentityFromMessage(message, existingState);
176
+ const explicitProjectId = extractExplicitProjectNameHint(message);
177
+ const projectId = inheritedProject?.projectId ?? explicitProjectId;
178
+ const projectDir = inheritedProject?.projectDir ?? projectId ?? deriveProjectSlug(message);
179
+ const run: ControllerRunInfo = {
180
+ id: generateId(),
181
+ title: buildControllerRunTitle(message, options?.source ?? "human", options?.sourceTaskTitle),
182
+ sessionKey,
183
+ projectId: projectId || undefined,
184
+ projectDir,
185
+ source: options?.source ?? "human",
186
+ sourceTaskId: options?.sourceTaskId,
187
+ sourceTaskTitle: options?.sourceTaskTitle,
188
+ request: message,
189
+ createdTaskIds: [],
190
+ status: "pending",
191
+ createdAt: now,
192
+ updatedAt: now,
193
+ };
194
+
195
+ const state = deps.updateTeamState((teamState) => {
196
+ syncProjectRegistryEntry(teamState, {
197
+ projectId: run.projectId,
198
+ projectDir: run.projectDir,
199
+ aliases: [run.projectId, extractExplicitProjectNameHint(message)],
200
+ summary: run.title,
201
+ updatedAt: now,
202
+ });
203
+ teamState.controllerRuns[run.id] = run;
204
+ trimControllerRuns(teamState);
205
+ });
206
+ const createdRun = state.controllerRuns[run.id] ?? run;
207
+ deps.wsServer.broadcastUpdate({ type: "controller:run", data: serializeControllerRun(createdRun) });
208
+ return createdRun;
209
+ }
210
+
211
+ export function updateControllerRun(
212
+ runId: string,
213
+ deps: ControllerTaskDomainDeps,
214
+ updater: (run: ControllerRunInfo) => void,
215
+ ): ControllerRunInfo | undefined {
216
+ const state = deps.updateTeamState((teamState) => {
217
+ const run = teamState.controllerRuns[runId];
218
+ if (!run) {
219
+ return;
220
+ }
221
+ updater(run);
222
+ trimControllerRuns(teamState);
223
+ });
224
+ const updatedRun = state.controllerRuns[runId];
225
+ if (updatedRun) {
226
+ deps.wsServer.broadcastUpdate({ type: "controller:run", data: serializeControllerRun(updatedRun) });
227
+ }
228
+ return updatedRun;
229
+ }
230
+
231
+ export function recordControllerRunEvent(
232
+ runId: string,
233
+ input: TaskExecutionEventInput,
234
+ deps: ControllerTaskDomainDeps,
235
+ ): ControllerRunInfo | undefined {
236
+ return updateControllerRun(runId, deps, (run) => {
237
+ appendControllerRunEvent(run, input);
238
+ });
239
+ }
@@ -5,18 +5,27 @@ 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
+ // 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";
9
15
  import { TaskRouter } from "./task-router.js";
10
16
  import { MessageRouter } from "./message-router.js";
11
17
  import { TeamWebSocketServer } from "./websocket.js";
12
- import { ensureOpenClawWorkspaceMemoryDir } from "../openclaw-workspace.js";
18
+ import { ensureOpenClawWorkspaceMemoryDir, buildTeamClawAgentSessionKey } from "../openclaw-workspace.js";
13
19
  import { ensureControllerGitRepo } from "../git-collaboration.js";
14
20
  import { WorkerProvisioningManager } from "./worker-provisioning.js";
15
21
  import { PreviewManager } from "./preview-manager.js";
16
- import { runKickoffMeeting, buildKickoffAssessmentPrompt, ASSESSMENT_TIMEOUT_MS } from "./kickoff-orchestrator.js";
22
+ import { runKickoffMeeting, buildKickoffAssessmentPrompt, ASSESSMENT_TIMEOUT_MS, type TaskRoleResolutionDeps } from "./kickoff-orchestrator.js";
17
23
  import { resolvePreferredLanAddress } from "../networking.js";
18
24
  import { createTeamAutoScheduler, type TeamAutoScheduler } from "../teamauto/scheduler.js";
19
25
  import { getGithubAuthManager } from "./github-auth.js";
26
+ // Phase 1.6 (design 2.3): TeamState.profileId is the single runtime truth for
27
+ // the active TeamProfile; config teamProfile only seeds first initialization.
28
+ import { getActiveProfile, getActiveRoleIds, hasProfile, setActiveProfileId, validateActiveRoleId, SOFTWARE_RD_PROFILE_ID } from "../profile-loader.js";
20
29
 
21
30
  export type KickoffHandler = (
22
31
  candidateRoles: RoleId[],
@@ -62,16 +71,57 @@ export function createControllerService(deps: ControllerServiceDeps): OpenClawPl
62
71
  async start(_ctx: OpenClawPluginServiceContext) {
63
72
  const serviceStartedAt = Date.now();
64
73
  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
74
 
70
- // Load or create team state
75
+ // Load or create team state. The active profile is resolved FIRST (from
76
+ // the restored TeamState.profileId, or the config bootstrap value on
77
+ // first initialization) so that capability-dependent startup wiring
78
+ // below knows which profile it is initializing (Phase 2.3 preview).
71
79
  teamState = await loadTeamState(config.teamName);
80
+ let seededProfileId: string;
81
+ if (!teamState) {
82
+ // Phase 1.6: first initialization seeds the active profile from the
83
+ // config bootstrap value. An unknown id is the one sanctioned
84
+ // fallback (design 2.2): warn and run the software-rd baseline.
85
+ const requestedProfileId = config.teamProfile;
86
+ seededProfileId = requestedProfileId;
87
+ if (!hasProfile(requestedProfileId)) {
88
+ seededProfileId = SOFTWARE_RD_PROFILE_ID;
89
+ logger.warn(`Controller: configured teamProfile "${requestedProfileId}" is not a built-in profile; falling back to "${SOFTWARE_RD_PROFILE_ID}"`);
90
+ }
91
+ } else {
92
+ // Restored state: TeamState.profileId is the runtime truth (config
93
+ // changes do not re-seed it). A dangling reference means the profile
94
+ // package this team ran on is not available in this installation.
95
+ // Design 2.2 red line: FATAL, never silently run another profile -
96
+ // that is exactly how a banking team would degrade into the software
97
+ // baseline unnoticed. (The config-miss fallback above stays a warn:
98
+ // it only seeds first initialization, where no team exists yet.)
99
+ if (!hasProfile(teamState.profileId)) {
100
+ throw new Error(
101
+ `Controller: team state references team profile "${teamState.profileId}", which is not available in this installation. `
102
+ + "Check the teamProfile config value and the persisted state profileId, or reinstall a TeamClaw version that ships this profile.",
103
+ );
104
+ }
105
+ seededProfileId = teamState.profileId;
106
+ }
107
+ setActiveProfileId(seededProfileId);
108
+ const activeCapabilities = getActiveProfile().capabilities;
109
+
110
+ // Phase 2.3 preview (minimal capability wiring, design 2.1): the git
111
+ // collaboration repo is only prepared for profiles with git enabled -
112
+ // a document-delivery team has no repo concept. On the software-rd
113
+ // baseline (git: true) behavior is unchanged.
114
+ const repoState = activeCapabilities.git
115
+ ? await ensureControllerGitRepo(config, logger).catch((err) => {
116
+ logger.warn(`Controller: failed to prepare git collaboration repo: ${err instanceof Error ? err.message : String(err)}`);
117
+ return null;
118
+ })
119
+ : null;
120
+
72
121
  let repoStateChanged = false;
73
122
  if (!teamState) {
74
123
  teamState = {
124
+ profileId: seededProfileId,
75
125
  teamName: config.teamName,
76
126
  workers: {},
77
127
  tasks: {},
@@ -84,10 +134,10 @@ export function createControllerService(deps: ControllerServiceDeps): OpenClawPl
84
134
  updatedAt: Date.now(),
85
135
  };
86
136
  await saveTeamState(teamState);
87
- logger.info(`Controller: created new team "${config.teamName}"`);
137
+ logger.info(`Controller: created new team "${config.teamName}" (profile: ${seededProfileId})`);
88
138
  } else {
89
139
  const previousRepoState = JSON.stringify(teamState.repo ?? null);
90
- teamState.repo = repoState ?? teamState.repo;
140
+ teamState.repo = repoState ?? (activeCapabilities.git ? teamState.repo : undefined);
91
141
  repoStateChanged = JSON.stringify(teamState.repo ?? null) !== previousRepoState;
92
142
  logger.info(`Controller: restored team "${config.teamName}" with ${Object.keys(teamState.workers).length} workers`);
93
143
  }
@@ -183,7 +233,18 @@ export function createControllerService(deps: ControllerServiceDeps): OpenClawPl
183
233
  }
184
234
 
185
235
  mdnsAdvertiser = new MDnsAdvertiser(logger);
186
- taskRouter = new TaskRouter(logger);
236
+ // Phase 2.5 wiring (design 2.3 "LLM 兜底", P2.5 follow-up): the
237
+ // controller LLM session is the production role judge for tasks the
238
+ // bilingual token fast path refuses to decide (tie / all-zero). The
239
+ // judge runs on a dedicated one-shot subagent session - NOT the intake
240
+ // conversation - so verdicts never pollute intake semantics. Missing
241
+ // runtime subagent => no judge, and the TaskRouter keeps its exact
242
+ // pre-wiring behavior.
243
+ const llmRoleJudge = createControllerLlmRoleJudge(deps);
244
+ if (llmRoleJudge) {
245
+ logger.info("Controller: LLM role judge wired into task dispatch (unconfident role inference escalates to the controller LLM)");
246
+ }
247
+ taskRouter = new TaskRouter(logger, llmRoleJudge ? { llmRoleJudge } : undefined);
187
248
  messageRouter = new MessageRouter(logger);
188
249
  wsServer = new TeamWebSocketServer(logger);
189
250
 
@@ -198,7 +259,7 @@ export function createControllerService(deps: ControllerServiceDeps): OpenClawPl
198
259
 
199
260
  let serviceKickoffHandler: KickoffHandler | undefined;
200
261
 
201
- const server = createControllerHttpServer({
262
+ const httpDeps: ControllerHttpDeps = {
202
263
  config,
203
264
  logger,
204
265
  runtime: deps.runtime,
@@ -211,7 +272,9 @@ export function createControllerService(deps: ControllerServiceDeps): OpenClawPl
211
272
  previewManager,
212
273
  getKickoffHandler: () => serviceKickoffHandler,
213
274
  getTeamAutoScheduler: () => teamAutoSchedulerRef,
214
- });
275
+ };
276
+
277
+ const server = createControllerHttpServer(httpDeps);
215
278
 
216
279
  const PORT_RETRY_STEP = 10;
217
280
  const PORT_MAX_RETRIES = 10;
@@ -256,29 +319,54 @@ export function createControllerService(deps: ControllerServiceDeps): OpenClawPl
256
319
  workerProvisioningManager.setActualPort(actualPort);
257
320
  }
258
321
 
322
+ // Phase 2.1 (design 2.3 crash semantics): resume an interrupted team
323
+ // profile switch before TeamAuto/preview restoration/provisioning kick
324
+ // in, so no subsystem fights the resume. Runs after the port is known
325
+ // (switch warmup launches need the actual controller URL). Requests
326
+ // arriving mid-resume hit the transition concurrency matrix (409/503),
327
+ // which is exactly what it exists for. An unavailable target profile is
328
+ // fatal here - same red line as restoring an unknown profileId.
329
+ await resumeTeamProfileSwitch(httpDeps);
330
+
259
331
  // 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)}`);
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
+ } catch (err) {
366
+ logger.warn(`Controller: TeamAuto scheduler failed to start: ${err instanceof Error ? err.message : String(err)}`);
367
+ }
368
+ } else {
369
+ logger.info("Controller: TeamAuto scheduler skipped (capability disabled by the active team profile)");
282
370
  }
283
371
 
284
372
  // Start mDNS advertising with the actual port
@@ -310,12 +398,16 @@ export function createControllerService(deps: ControllerServiceDeps): OpenClawPl
310
398
  serviceKickoffHandler = kickoffHandler;
311
399
  deps.onKickoffHandlerAvailable?.(kickoffHandler);
312
400
 
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
- });
401
+ // Phase 2.3 preview (minimal capability wiring): only profiles with
402
+ // runnablePreview enabled restore dynamic previews on startup.
403
+ if (getActiveProfile().capabilities.runnablePreview) {
404
+ logger.info(`Controller: starting preview restoration...`);
405
+ void previewManager.restorePreviewsOnStartup().then(() => {
406
+ logger.info(`Controller: preview restoration completed`);
407
+ }).catch((err) => {
408
+ logger.warn(`Controller: failed to restore previews on startup: ${String(err)}`);
409
+ });
410
+ }
319
411
 
320
412
  // Start timeout monitoring
321
413
  timeoutTimer = setInterval(() => {
@@ -373,6 +465,48 @@ export function createControllerService(deps: ControllerServiceDeps): OpenClawPl
373
465
  saveTeamState(teamState);
374
466
  }
375
467
 
468
+ // Runtime orphan-task reconciliation (user-found: one live worker but
469
+ // two active tasks - the second task was pinned to a worker whose
470
+ // registry entry was already gone). The startup sweep handles this
471
+ // once at boot; tasks whose worker disappears AFTER claiming sat in
472
+ // in_progress forever. Mirror the startup semantics: reset to pending
473
+ // (bounded resume attempts), re-dispatch happens via the reconcile
474
+ // call below. Skip workers the sweep above just released - their
475
+ // tasks were already handled with a broadcast.
476
+ {
477
+ let orphaned = false;
478
+ for (const task of Object.values(teamState.tasks)) {
479
+ if (
480
+ task.assignedWorkerId &&
481
+ (task.status === "assigned" || task.status === "in_progress") &&
482
+ !teamState.workers[task.assignedWorkerId]
483
+ ) {
484
+ const attempt = (task.resumeAttempt ?? 0) + 1;
485
+ const MAX_RESUME_ATTEMPTS = 3;
486
+ if (attempt > MAX_RESUME_ATTEMPTS) {
487
+ logger.warn(`Controller: task ${task.id} exceeded ${MAX_RESUME_ATTEMPTS} resume attempts (worker gone) - failing`);
488
+ task.status = "failed";
489
+ task.error = `worker disappeared without completing (resumed ${MAX_RESUME_ATTEMPTS} times)`;
490
+ } else {
491
+ logger.info(`Controller: resetting orphaned task ${task.id} for resume attempt ${attempt} (worker ${task.assignedWorkerId} missing)`);
492
+ task.status = "pending";
493
+ task.resumeAttempt = attempt;
494
+ if (task.checkpoint) {
495
+ task.checkpoint.attempt = attempt;
496
+ }
497
+ }
498
+ task.assignedWorkerId = undefined;
499
+ task.updatedAt = now;
500
+ wsServer.broadcastUpdate({ type: "task:updated", data: { ...task } });
501
+ orphaned = true;
502
+ }
503
+ }
504
+ if (orphaned) {
505
+ saveTeamState(teamState);
506
+ changed = true;
507
+ }
508
+ }
509
+
376
510
  if (workerProvisioningManager?.isEnabled()) {
377
511
  void workerProvisioningManager.requestReconcile("periodic controller sync");
378
512
  }
@@ -455,3 +589,123 @@ async function requestKickoffAssessment(
455
589
  clearTimeout(timeout);
456
590
  }
457
591
  }
592
+
593
+ // ── Phase 2.5 wiring: controller LLM as the role judge ───────────────────────
594
+ //
595
+ // resolveTaskRoleWithLlmFallback (kickoff-orchestrator) defined the seam in
596
+ // P2.5 with fake-driven tests but no production caller. This factory builds
597
+ // the production llmRoleJudge: a ONE-SHOT subagent session on the controller
598
+ // runtime (never the long-lived intake conversation, so verdicts cannot
599
+ // pollute intake semantics) that answers with a single role id of the ACTIVE
600
+ // profile. The resolver validates the answer (validateActiveRoleId) and
601
+ // degrades to the profile defaultRole when the judge is unavailable, times
602
+ // out, errors, or names a role outside the active profile - the TaskRouter
603
+ // then treats the outcome as a routing hint, so dispatch never blocks on a
604
+ // strand.
605
+
606
+ /** Budget for a one-id LLM verdict; past it the resolver degrades to defaultRole. */
607
+ const ROLE_JUDGE_TIMEOUT_MS = 30_000;
608
+ const ROLE_JUDGE_SESSION_PREFIX = "teamclaw-role-judge:";
609
+ const ROLE_JUDGE_SYSTEM_PROMPT = [
610
+ "You are the role router of a TeamClaw controller.",
611
+ "Given one task, pick the single team role that should own it.",
612
+ "Reply with EXACTLY one role id from the provided list - no prose, no markdown, no explanation.",
613
+ ].join(" ");
614
+
615
+ function createControllerLlmRoleJudge(
616
+ deps: Pick<ControllerServiceDeps, "runtime" | "logger">,
617
+ ): TaskRoleResolutionDeps["llmRoleJudge"] | undefined {
618
+ const subagent = deps.runtime?.subagent;
619
+ if (
620
+ !subagent
621
+ || typeof subagent.run !== "function"
622
+ || typeof subagent.waitForRun !== "function"
623
+ || typeof subagent.getSessionMessages !== "function"
624
+ ) {
625
+ // Runtime without an LLM subagent (e.g. minimal test doubles): leave the
626
+ // seam unwired; the TaskRouter keeps its pre-wiring behavior.
627
+ return undefined;
628
+ }
629
+ const logger = deps.logger;
630
+
631
+ return async ({ task, verdict }) => {
632
+ const roleIds = getActiveRoleIds();
633
+ const message = [
634
+ `Task title: ${task.title}`,
635
+ `Task description: ${task.description?.trim() || "(none)"}`,
636
+ "",
637
+ `Token-based role scoring refused to decide (${verdict.reason}).`,
638
+ `Pick the single role that should own this task. Answer with EXACTLY one role id from: ${roleIds.join(", ")}`,
639
+ ].join("\n");
640
+
641
+ // Fresh one-shot session per verdict: the judge must stay stateless and
642
+ // separate from any intake/worker conversation.
643
+ const sessionKey = buildTeamClawAgentSessionKey(
644
+ `${ROLE_JUDGE_SESSION_PREFIX}${task.id}-${Date.now()}`,
645
+ );
646
+ const run = await subagent.run({
647
+ sessionKey,
648
+ message,
649
+ extraSystemPrompt: ROLE_JUDGE_SYSTEM_PROMPT,
650
+ idempotencyKey: `role-judge-${task.id}-${Date.now()}`,
651
+ });
652
+ const waited = await subagent.waitForRun({
653
+ runId: run.runId,
654
+ timeoutMs: ROLE_JUDGE_TIMEOUT_MS,
655
+ });
656
+ if (waited.status !== "ok") {
657
+ logger.warn(
658
+ `Controller: LLM role judge did not complete for task ${task.id} (${waited.status}${"error" in waited && waited.error ? `: ${waited.error}` : ""}); using the profile defaultRole`,
659
+ );
660
+ return null;
661
+ }
662
+
663
+ const session = await subagent.getSessionMessages({ sessionKey, limit: 5 });
664
+ const reply = extractLastAssistantText(session.messages);
665
+ const direct = validateActiveRoleId(reply.trim());
666
+ if (direct) {
667
+ return direct;
668
+ }
669
+ // Tolerate light prose wrapping ("The role is: qa."): first ACTIVE role
670
+ // id that appears as a whole word in the reply.
671
+ for (const roleId of roleIds) {
672
+ const pattern = new RegExp(`(^|[^a-z0-9-])${roleId.replace(/[-]/g, "\\-")}([^a-z0-9-]|$)`);
673
+ if (pattern.test(reply)) {
674
+ return roleId;
675
+ }
676
+ }
677
+ logger.warn(
678
+ `Controller: LLM role judge reply for task ${task.id} named no active role (${reply.slice(0, 120) || "empty reply"}); using the profile defaultRole`,
679
+ );
680
+ return null;
681
+ };
682
+ }
683
+
684
+ /** Last assistant message text (string or text blocks), mirroring the http-server intake helper semantics. */
685
+ function extractLastAssistantText(messages: unknown[]): string {
686
+ const assistantMessages = messages.filter((message): message is { role?: unknown; content?: unknown } => {
687
+ if (!message || typeof message !== "object") {
688
+ return false;
689
+ }
690
+ return (message as { role?: unknown }).role === "assistant";
691
+ });
692
+ const lastAssistant = assistantMessages[assistantMessages.length - 1];
693
+ if (!lastAssistant) {
694
+ return "";
695
+ }
696
+ if (typeof lastAssistant.content === "string") {
697
+ return lastAssistant.content;
698
+ }
699
+ if (Array.isArray(lastAssistant.content)) {
700
+ const textBlocks = lastAssistant.content
701
+ .filter((block): block is { type?: unknown; text?: unknown } => {
702
+ return !!block && typeof block === "object" && (block as { type?: unknown }).type === "text";
703
+ })
704
+ .map((block) => (typeof block.text === "string" ? block.text : ""))
705
+ .filter(Boolean);
706
+ if (textBlocks.length > 0) {
707
+ return textBlocks.join("\n");
708
+ }
709
+ }
710
+ return "";
711
+ }