@teamclaws/teamclaw 2026.11.0 → 2026.11.2

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 (128) hide show
  1. package/cli.mjs +368 -13
  2. package/dist/index.js +61 -32
  3. package/dist/src/config.js +24 -0
  4. package/dist/src/controller/auth-routes.js +129 -0
  5. package/dist/src/controller/clarification-routes.js +1 -1
  6. package/dist/src/controller/config-routes.js +138 -0
  7. package/dist/src/controller/controller-planning.js +1 -0
  8. package/dist/src/controller/controller-routes.js +195 -0
  9. package/dist/src/controller/controller-service.js +67 -10
  10. package/dist/src/controller/controller-tools.js +3 -1
  11. package/dist/src/controller/github-auth.js +2 -1
  12. package/dist/src/controller/http-server.js +51 -16
  13. package/dist/src/controller/kickoff-orchestrator.js +3 -39
  14. package/dist/src/controller/message-delivery.js +4 -1
  15. package/dist/src/controller/orchestration-manifest.js +5 -65
  16. package/dist/src/controller/preview-manager.js +51 -3
  17. package/dist/src/controller/profile-switch.js +42 -22
  18. package/dist/src/controller/provisioning/backend-contract.js +9 -0
  19. package/dist/src/controller/provisioning/container-shared.js +64 -0
  20. package/dist/src/controller/provisioning/docker.js +214 -0
  21. package/dist/src/controller/provisioning/kubernetes.js +244 -0
  22. package/dist/src/controller/provisioning/plugin-root.js +41 -0
  23. package/dist/src/controller/provisioning/process-supervisor.js +190 -0
  24. package/dist/src/controller/provisioning-config.js +239 -0
  25. package/dist/src/controller/repo-routes.js +70 -4
  26. package/dist/src/controller/report-routes.js +56 -0
  27. package/dist/src/controller/route-table.js +73 -1045
  28. package/dist/src/controller/security.js +775 -0
  29. package/dist/src/controller/status-routes.js +287 -0
  30. package/dist/src/controller/task-assignment.js +5 -2
  31. package/dist/src/controller/task-execution.js +31 -0
  32. package/dist/src/controller/task-results.js +10 -0
  33. package/dist/src/controller/tunnel-manager.js +41 -8
  34. package/dist/src/controller/tunnel-routes.js +225 -0
  35. package/dist/src/controller/websocket.js +6 -2
  36. package/dist/src/controller/webui-routes.js +49 -0
  37. package/dist/src/controller/worker-provisioning.js +39 -949
  38. package/dist/src/controller/workflow-routes.js +407 -0
  39. package/dist/src/controller/workspace-routes.js +200 -0
  40. package/dist/src/git-collaboration.js +4 -9
  41. package/dist/src/identity.js +12 -1
  42. package/dist/src/openclaw-workspace.js +36 -0
  43. package/dist/src/profile-loader.js +119 -1
  44. package/dist/src/profiles/banking.json +26 -2
  45. package/dist/src/profiles/schema.json +82 -2
  46. package/dist/src/prompt-policy.js +18 -6
  47. package/dist/src/protocol.js +66 -3
  48. package/dist/src/shared/clarification-schema.js +65 -0
  49. package/dist/src/shared/github-auth.js +15 -0
  50. package/dist/src/shared/kickoff-prompt.js +37 -0
  51. package/dist/src/shared/utils.js +47 -0
  52. package/dist/src/state.js +89 -3
  53. package/dist/src/teamauto/scanner.js +21 -2
  54. package/dist/src/teamauto/scheduler.js +9 -2
  55. package/dist/src/types.js +15 -1
  56. package/dist/src/ui/app.js +990 -73
  57. package/dist/src/ui/github-login.html +1 -0
  58. package/dist/src/ui/index.html +125 -36
  59. package/dist/src/worker/http-handler.js +59 -0
  60. package/dist/src/worker/skill-installer.js +3 -9
  61. package/dist/src/worker/tools.js +20 -10
  62. package/dist/src/worker/worker-service.js +17 -4
  63. package/index.ts +69 -32
  64. package/openclaw.plugin.json +23 -2
  65. package/package.json +1 -1
  66. package/src/config.ts +24 -0
  67. package/src/controller/auth-routes.ts +157 -0
  68. package/src/controller/clarification-routes.ts +1 -1
  69. package/src/controller/config-routes.ts +152 -0
  70. package/src/controller/controller-planning.ts +8 -0
  71. package/src/controller/controller-routes.ts +237 -0
  72. package/src/controller/controller-service.ts +128 -10
  73. package/src/controller/controller-tools.ts +5 -2
  74. package/src/controller/github-auth.ts +28 -63
  75. package/src/controller/http-server.ts +66 -17
  76. package/src/controller/kickoff-orchestrator.ts +3 -42
  77. package/src/controller/message-delivery.ts +4 -1
  78. package/src/controller/orchestration-manifest.ts +8 -71
  79. package/src/controller/preview-manager.ts +53 -3
  80. package/src/controller/profile-switch.ts +53 -23
  81. package/src/controller/provisioning/backend-contract.ts +51 -0
  82. package/src/controller/provisioning/container-shared.ts +84 -0
  83. package/src/controller/provisioning/docker.ts +260 -0
  84. package/src/controller/provisioning/kubernetes.ts +263 -0
  85. package/src/controller/provisioning/plugin-root.ts +42 -0
  86. package/src/controller/provisioning/process-supervisor.ts +214 -0
  87. package/src/controller/provisioning-config.ts +289 -0
  88. package/src/controller/repo-routes.ts +84 -12
  89. package/src/controller/report-routes.ts +64 -0
  90. package/src/controller/route-table.ts +139 -1152
  91. package/src/controller/security.ts +899 -0
  92. package/src/controller/status-routes.ts +354 -0
  93. package/src/controller/task-assignment.ts +5 -1
  94. package/src/controller/task-execution.ts +43 -0
  95. package/src/controller/task-results.ts +12 -0
  96. package/src/controller/tunnel-manager.ts +45 -8
  97. package/src/controller/tunnel-routes.ts +231 -0
  98. package/src/controller/websocket.ts +20 -3
  99. package/src/controller/webui-routes.ts +55 -0
  100. package/src/controller/worker-provisioning.ts +51 -1117
  101. package/src/controller/workflow-routes.ts +498 -0
  102. package/src/controller/workspace-routes.ts +222 -0
  103. package/src/git-collaboration.ts +4 -9
  104. package/src/identity.ts +13 -1
  105. package/src/openclaw-workspace.ts +47 -0
  106. package/src/profile-loader.ts +167 -1
  107. package/src/profiles/banking.json +26 -2
  108. package/src/profiles/schema.json +82 -2
  109. package/src/prompt-policy.ts +19 -6
  110. package/src/protocol.ts +72 -2
  111. package/src/shared/clarification-schema.ts +81 -0
  112. package/src/shared/github-auth.ts +92 -0
  113. package/src/shared/kickoff-prompt.ts +47 -0
  114. package/src/shared/utils.ts +51 -0
  115. package/src/state.ts +92 -3
  116. package/src/teamauto/github-client.ts +2 -1
  117. package/src/teamauto/repo-sync.ts +2 -1
  118. package/src/teamauto/scanner.ts +22 -3
  119. package/src/teamauto/scheduler.ts +11 -3
  120. package/src/teamauto/store.ts +5 -0
  121. package/src/types.ts +130 -1
  122. package/src/ui/app.js +990 -73
  123. package/src/ui/github-login.html +1 -0
  124. package/src/ui/index.html +125 -36
  125. package/src/worker/http-handler.ts +64 -1
  126. package/src/worker/skill-installer.ts +3 -9
  127. package/src/worker/tools.ts +21 -10
  128. package/src/worker/worker-service.ts +18 -4
@@ -6,17 +6,25 @@
6
6
  // ./route-table.ts, PR-D) and every handler body lives in a domain module.
7
7
  // Request pipeline, in order:
8
8
  //
9
- // 1. CORS preflight (OPTIONS short-circuit)
10
- // 2. Tunnel gate (viaTunnel classification: gate page routes / gate
9
+ // 1. CORS preflight (OPTIONS short-circuit; wildcard while device
10
+ // protection is off - the historical behavior - and narrowed to the
11
+ // UI's own origin once it is on)
12
+ // 2. Device-auth gate (issue #23, ./security.ts createSecurityMiddleware):
13
+ // zero-op while no devices are paired (L0); once devices exist every
14
+ // non-exempt /api request must present a valid device token and the
15
+ // response CORS policy is pinned before dispatch. Runs BEFORE the
16
+ // tunnel gate and the handleRequest gates so transition/capability/
17
+ // tunnel-management responses never leak to unpaired callers.
18
+ // 3. Tunnel gate (viaTunnel classification: gate page routes / gate
11
19
  // cookie 403 / tunnel management API - tables in ./route-table.ts)
12
- // 3. handleRequest gates (verbatim, NOT part of the route table):
20
+ // 4. handleRequest gates (verbatim, NOT part of the route table):
13
21
  // a. profile-switch transition matrix (409 worker re-register,
14
22
  // 503+Retry-After task submission / repo import)
15
23
  // b. capability 404 gates (steady-state existence gate, after (a) on
16
24
  // purpose: transition semantics win over the 404)
17
- // 4. declarative route table match (./route-table.ts, array order =
25
+ // 5. declarative route table match (./route-table.ts, array order =
18
26
  // the historical if/startsWith chain, one-to-one)
19
- // 5. fall-through 404
27
+ // 6. fall-through 404
20
28
  //
21
29
  // Domain module index (the 18 modules this root composes; none of them may
22
30
  // import this file):
@@ -46,7 +54,7 @@ import { MessageRouter } from "./message-router.js";
46
54
  import { TeamWebSocketServer } from "./websocket.js";
47
55
  import type { WorkerProvisioningManager } from "./worker-provisioning.js";
48
56
  import type { PreviewManager } from "./preview-manager.js";
49
- import type { KickoffHandler } from "./controller-service.js";
57
+ import type { KickoffHandler, UpdateTeamStateFn } from "./controller-service.js";
50
58
  import type { TeamAutoScheduler } from "../teamauto/scheduler.js";
51
59
  import { autoAssignPendingTasks } from "./task-assignment.js";
52
60
  import { createTunnelManager, gatePageHtml, type TunnelManager } from "./tunnel-manager.js";
@@ -65,13 +73,29 @@ import {
65
73
  type RouteContext,
66
74
  type RouteDef,
67
75
  } from "./route-table.js";
76
+ // Issue #23 (backend wave): the device-pairing security module owns the
77
+ // auth middleware, the CORS narrowing policy, the WS upgrade guard and the
78
+ // pairing handlers (registered via route-table.ts). This file only wires
79
+ // them into the pipeline below - all pathname/method policy lives in
80
+ // security.ts.
81
+ import {
82
+ classifySecurityPeer,
83
+ corsPreflightDecision,
84
+ createSecurityMiddleware,
85
+ createWebSocketUpgradeGuard,
86
+ isProtectionOn,
87
+ type SecurityPeer,
88
+ } from "./security.js";
68
89
 
69
90
  export type ControllerHttpDeps = {
70
91
  config: PluginConfig;
71
92
  logger: PluginLogger;
72
93
  runtime: OpenClawPluginApi["runtime"];
73
94
  getTeamState: () => TeamState | null;
74
- updateTeamState: (updater: (state: TeamState) => void) => TeamState;
95
+ // Issue #226 W4: widened to the single-write-entry contract (the optional
96
+ // second argument + awaited-durability overload live in controller-service
97
+ // next to the implementation; one-argument callers are unaffected).
98
+ updateTeamState: UpdateTeamStateFn;
75
99
  taskRouter: TaskRouter;
76
100
  messageRouter: MessageRouter;
77
101
  wsServer: TeamWebSocketServer;
@@ -182,14 +206,18 @@ export function createControllerHttpServer(deps: ControllerHttpDeps): http.Serve
182
206
  // tunnel manager singleton they close over) and reused for every request.
183
207
  let tunnelRoutesSingleton: { gate: readonly RouteDef[]; management: readonly RouteDef[] } | null = null;
184
208
 
209
+ // Issue #23: the device gate. Zero-friction ladder - while no device is
210
+ // paired (protection off) this is a no-op passthrough (L0, the exact
211
+ // pre-issue behavior); once devices exist it enforces per-device tokens
212
+ // on every non-exempt /api route (exemptions and 401 shape in security.ts).
213
+ const securityGate = createSecurityMiddleware(deps);
214
+
185
215
  const server = http.createServer(async (req: IncomingMessage, res: ServerResponse) => {
186
- // CORS preflight
216
+ // CORS preflight (issue #23: wildcard while protection is off - the
217
+ // historical bytes - and narrowed to the UI's own origin once on).
187
218
  if (req.method === "OPTIONS") {
188
- res.writeHead(200, {
189
- "Access-Control-Allow-Origin": "*",
190
- "Access-Control-Allow-Methods": "GET, POST, PATCH, DELETE, OPTIONS",
191
- "Access-Control-Allow-Headers": "Content-Type",
192
- });
219
+ const decision = corsPreflightDecision(req, isProtectionOn(deps.getTeamState()));
220
+ res.writeHead(decision.status, decision.headers);
193
221
  res.end();
194
222
  return;
195
223
  }
@@ -215,6 +243,19 @@ export function createControllerHttpServer(deps: ControllerHttpDeps): http.Serve
215
243
  req, res, requestUrl: url, pathname, deps, currentState: null,
216
244
  };
217
245
  const viaTunnel = tunnelManager.isTunnelRequest(typeof req.headers.host === "string" ? req.headers.host : undefined);
246
+
247
+ // ==================== Device auth gate (issue #23) ====================
248
+ // Runs BEFORE the tunnel gate tables, the transition matrix and the
249
+ // capability gates so none of those surfaces answer - or leak response
250
+ // shape information - to unpaired callers while protection is on.
251
+ // Requests arriving through the sharing tunnel are classified from the
252
+ // Host header (cloudflared dials in from loopback, so the socket peer
253
+ // address would lie); see classifySecurityPeer in ./security.ts.
254
+ const peer = classifySecurityPeer(req.socket.remoteAddress, viaTunnel);
255
+ if (!securityGate(req, res, pathname, peer)) {
256
+ return;
257
+ }
258
+
218
259
  if (viaTunnel) {
219
260
  if (await dispatchRoutes(tunnelRoutesSingleton.gate, tunnelCtx)) {
220
261
  return;
@@ -231,15 +272,22 @@ export function createControllerHttpServer(deps: ControllerHttpDeps): http.Serve
231
272
  }
232
273
 
233
274
  try {
234
- await handleRequest(req, res, pathname, deps);
275
+ await handleRequest(req, res, pathname, deps, peer);
235
276
  } catch (err) {
236
277
  logger.error(`Controller HTTP error: ${err instanceof Error ? err.message : String(err)}`);
237
278
  sendError(res, 500, "Internal server error");
238
279
  }
239
280
  });
240
281
 
241
- // Attach WebSocket
242
- wsServer.attach(server);
282
+ // Attach WebSocket (issue #23: while device protection is on, upgrades
283
+ // must carry a valid device token - ?token= query for browsers, cookie /
284
+ // Bearer for native clients; see createWebSocketUpgradeGuard).
285
+ wsServer.attach(server, {
286
+ verifyUpgrade: createWebSocketUpgradeGuard({
287
+ ...deps,
288
+ isTunnelHost: (host) => tunnelManagerSingleton?.isTunnelRequest(host) ?? false,
289
+ }),
290
+ });
243
291
 
244
292
  // Plugin shutdown: kill the local connector and tear down the remote
245
293
  // tunnel so gateway exits never leak orphan cloudflared processes.
@@ -277,6 +325,7 @@ async function handleRequest(
277
325
  res: ServerResponse,
278
326
  pathname: string,
279
327
  deps: ControllerHttpDeps,
328
+ peer?: SecurityPeer,
280
329
  ): Promise<void> {
281
330
  const requestUrl = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
282
331
  const currentState = deps.getTeamState();
@@ -352,7 +401,7 @@ async function handleRequest(
352
401
  // false) to continue matching; an exhausted table falls through to the
353
402
  // final 404 below - both semantics are preserved from the old chain.
354
403
  const handled = await dispatchRoutes(controllerRouteTable, {
355
- req, res, requestUrl, pathname, deps, currentState,
404
+ req, res, requestUrl, pathname, deps, currentState, peer,
356
405
  });
357
406
  if (!handled) {
358
407
  sendError(res, 404, "Not found");
@@ -19,6 +19,9 @@ import type { PluginLogger } from "../../api.js";
19
19
  import type { KickoffAssessment, KickoffPlan, RoleId, TaskInfo, TeamState, WorkerInfo } from "../types.js";
20
20
  // Phase 1.3: role data comes from the active TeamProfile loader.
21
21
  import { getActiveDefaultRole, getActiveRole, getActiveRoleIds, validateActiveRoleId } from "../profile-loader.js";
22
+ // W6 of issue #226: the local sleep copy (byte-identical to the shared one)
23
+ // was removed in favor of shared/utils.js.
24
+ import { sleep } from "../shared/utils.js";
22
25
  import { inferTaskRoleWithConfidence } from "./role-inference.js";
23
26
  import type { RoleInferenceVerdict } from "./role-inference.js";
24
27
 
@@ -251,48 +254,6 @@ function buildKickoffSummary(plan: KickoffPlan, _requirement: string): string {
251
254
  return parts.join("\n");
252
255
  }
253
256
 
254
- /**
255
- * Build the kickoff assessment prompt sent to a worker.
256
- * The worker should respond with structured JSON matching KickoffAssessment.
257
- */
258
- export function buildKickoffAssessmentPrompt(role: RoleId, requirement: string): string {
259
- const roleDef = getActiveRole(role);
260
- const roleLabel = roleDef?.label ?? role;
261
-
262
- return [
263
- `You are the ${roleLabel} in a virtual software team.`,
264
- `Your team is conducting a kickoff meeting for a new requirement.`,
265
- ``,
266
- `## Requirement`,
267
- requirement,
268
- ``,
269
- `## Your Task`,
270
- `Evaluate this requirement from your professional perspective as ${roleLabel}.`,
271
- `Respond with a JSON object (and nothing else) with these fields:`,
272
- ``,
273
- `{`,
274
- ` "needed": boolean, // Is your role needed for this project?`,
275
- ` "scope": string, // What would you contribute? (1-2 sentences)`,
276
- ` "suggestedTasks": string[], // Specific tasks you'd handle (2-5 items)`,
277
- ` "dependencies": string[], // What you need from other roles before or during your work`,
278
- ` "risks": string[], // Concerns or risks from your perspective`,
279
- ` "questions": string[] // Clarifications you'd want before starting`,
280
- `}`,
281
- ``,
282
- `Guidelines:`,
283
- `- Be honest about whether your role is truly needed. Don't inflate your importance.`,
284
- `- For "needed", consider: does the project actually require ${roleLabel}-level expertise?`,
285
- `- A simple single-file script does NOT need an architect. A TODO app does NOT need a security engineer.`,
286
- `- Keep suggestedTasks concrete and actionable, not vague.`,
287
- `- Only list dependencies on roles that are actually relevant.`,
288
- `- Return ONLY the JSON object, no markdown fencing, no explanation.`,
289
- ].join("\n");
290
- }
291
-
292
- function sleep(ms: number): Promise<void> {
293
- return new Promise((resolve) => setTimeout(resolve, ms));
294
- }
295
-
296
257
  // ── Phase 2.5: LLM fallback for unconfident role inference (design 2.3) ─────
297
258
  //
298
259
  // The tiered token scoring in role-inference.ts is the FAST PATH only. When
@@ -6,6 +6,7 @@
6
6
  // message ROUTES because the controller-planning intake glue also delivers
7
7
  // messages and must stay below the route layer.
8
8
  import type { TeamMessage, WorkerInfo } from "../types.js";
9
+ import { withWorkerDispatchToken } from "./task-execution.js";
9
10
  import type { ControllerTaskDomainDeps } from "./task-execution.js";
10
11
 
11
12
  export async function deliverMessageToWorker(
@@ -13,9 +14,11 @@ export async function deliverMessageToWorker(
13
14
  message: TeamMessage,
14
15
  deps: ControllerTaskDomainDeps,
15
16
  ): Promise<void> {
17
+ // Issue #222: carry the worker's dispatch token so a token-paired worker
18
+ // accepts the injection; L0 sends the historical header set unchanged.
16
19
  const res = await fetch(`${worker.url}/api/v1/messages`, {
17
20
  method: "POST",
18
- headers: { "Content-Type": "application/json" },
21
+ headers: withWorkerDispatchToken({ "Content-Type": "application/json" }, worker.id, deps.config, deps.getTeamState()),
19
22
  body: JSON.stringify(message),
20
23
  });
21
24
 
@@ -1,6 +1,4 @@
1
1
  import type {
2
- ClarificationQuestionOption,
3
- ClarificationQuestionSchema,
4
2
  ControllerManifestCompletionOpportunity,
5
3
  ControllerManifestCreatedTask,
6
4
  ControllerManifestDeferredTask,
@@ -9,6 +7,14 @@ import type {
9
7
  } from "../types.js";
10
8
  import { validateRoleIdList } from "../roles.js";
11
9
  import { deriveStableProjectKey } from "../openclaw-workspace.js";
10
+ // Issue #226 W3: the clarification-schema normalization family moved to the
11
+ // shared layer (worker/tools.ts consumes it; the worker must not import the
12
+ // controller tree). This module keeps the manifest-specific normalizers and
13
+ // imports the shared contract — controller -> shared direction only.
14
+ import {
15
+ normalizeClarificationQuestionSchemas,
16
+ normalizeOptionalManifestText,
17
+ } from "../shared/clarification-schema.js";
12
18
 
13
19
  export function normalizeManifestRoleList(raw: unknown): RoleId[] {
14
20
  // Phase 0.3: delegates to the shared validateRoleIdList guard in roles.ts.
@@ -27,75 +33,6 @@ export function normalizeManifestStringList(raw: unknown): string[] {
27
33
  .filter(Boolean);
28
34
  }
29
35
 
30
- export function normalizeOptionalManifestText(raw: unknown): string | undefined {
31
- if (typeof raw !== "string") {
32
- return undefined;
33
- }
34
- const normalized = raw.trim();
35
- return normalized || undefined;
36
- }
37
-
38
- export function normalizeClarificationOptions(raw: unknown): ClarificationQuestionOption[] {
39
- if (!Array.isArray(raw)) {
40
- return [];
41
- }
42
- return raw
43
- .filter((entry): entry is Record<string, unknown> => !!entry && typeof entry === "object")
44
- .map((entry) => ({
45
- value: typeof entry.value === "string" ? entry.value.trim() : "",
46
- label: typeof entry.label === "string" ? entry.label.trim() : "",
47
- hint: typeof entry.hint === "string" && entry.hint.trim() ? entry.hint.trim() : undefined,
48
- }))
49
- .filter((entry) => entry.value && entry.label);
50
- }
51
-
52
- export function normalizeClarificationQuestionSchema(raw: unknown): ClarificationQuestionSchema | undefined {
53
- if (!raw || typeof raw !== "object") {
54
- return undefined;
55
- }
56
- const input = raw as Record<string, unknown>;
57
- const kind = typeof input.kind === "string" ? input.kind.trim() : "";
58
- const title = typeof input.title === "string" ? input.title.trim() : "";
59
- if (!title || !["single-select", "multi-select", "number", "text"].includes(kind)) {
60
- return undefined;
61
- }
62
- const options = normalizeClarificationOptions(input.options);
63
- const schema: ClarificationQuestionSchema = {
64
- kind: kind as ClarificationQuestionSchema["kind"],
65
- title,
66
- description: normalizeOptionalManifestText(input.description),
67
- required: input.required == null ? true : Boolean(input.required),
68
- allowOther: Boolean(input.allowOther),
69
- placeholder: normalizeOptionalManifestText(input.placeholder),
70
- unit: normalizeOptionalManifestText(input.unit),
71
- };
72
- if (options.length > 0) {
73
- schema.options = options;
74
- }
75
- if (typeof input.min === "number" && Number.isFinite(input.min)) {
76
- schema.min = input.min;
77
- }
78
- if (typeof input.max === "number" && Number.isFinite(input.max)) {
79
- schema.max = input.max;
80
- }
81
- if (typeof input.step === "number" && Number.isFinite(input.step)) {
82
- schema.step = input.step;
83
- }
84
- if ((schema.kind === "single-select" || schema.kind === "multi-select") && (!schema.options || schema.options.length === 0)) {
85
- return undefined;
86
- }
87
- return schema;
88
- }
89
-
90
- export function normalizeClarificationQuestionSchemas(raw: unknown): ClarificationQuestionSchema[] {
91
- if (!Array.isArray(raw)) {
92
- return [];
93
- }
94
- return raw
95
- .map((entry) => normalizeClarificationQuestionSchema(entry))
96
- .filter((entry): entry is ClarificationQuestionSchema => Boolean(entry));
97
- }
98
-
99
36
  export function normalizeManifestCreatedTasks(raw: unknown): ControllerManifestCreatedTask[] {
100
37
  if (!Array.isArray(raw)) {
101
38
  return [];
@@ -13,6 +13,48 @@ const PREVIEW_STOP_TIMEOUT_MS = 5_000;
13
13
 
14
14
  const GENERIC_SERVE_COMMAND = "npx -y serve -l {PORT}";
15
15
 
16
+ // Issue #237 W1: preview commands are LLM-authored (result contracts) and
17
+ // run through a shell - they must NOT inherit the controller's environment,
18
+ // or a prompt-injected previewCommand could exfiltrate every controller
19
+ // credential (GH_TOKEN, provider API keys, tunnel tokens). Policy: minimal
20
+ // allowlist of toolchain basics, matched case-insensitively so Windows
21
+ // (Path/SystemRoot/...) survives, plus the explicit preview vars set at the
22
+ // spawn site. Repos that genuinely need more can pass names through
23
+ // TEAMCLAW_PREVIEW_EXTRA_ENV (comma-separated list of env var names whose
24
+ // controller values are forwarded verbatim); anything else is absent.
25
+ const PREVIEW_ENV_ALLOWLIST = new Set([
26
+ "PATH", "HOME", "LANG", "LC_ALL", "LC_CTYPE", "TMPDIR", "TZ", "TERM", "SHELL",
27
+ // Windows toolchain basics (no-ops elsewhere, harmless to match).
28
+ // PROCESSOR_ARCHITECTURE/PROCESSOR_IDENTIFIER are read by node-gyp-style
29
+ // native builds (review follow-up to #237 W1) - plain toolchain
30
+ // descriptors, no credential material.
31
+ "SYSTEMROOT", "SYSTEMDRIVE", "COMSPEC", "PATHEXT", "WINDIR", "USERPROFILE",
32
+ "APPDATA", "LOCALAPPDATA", "PROGRAMFILES", "PROGRAMDATA", "NUMBER_OF_PROCESSORS", "OS",
33
+ "PROCESSOR_ARCHITECTURE", "PROCESSOR_IDENTIFIER",
34
+ ]);
35
+ const PREVIEW_EXTRA_ENV_VAR = "TEAMCLAW_PREVIEW_EXTRA_ENV";
36
+
37
+ /** Builds the restricted environment for preview subprocesses (#237 W1):
38
+ * allowlisted controller vars + extraEnv (venv PATH/VIRTUAL_ENV) + whatever
39
+ * the operator declared via TEAMCLAW_PREVIEW_EXTRA_ENV. Never returns the
40
+ * full process.env. Exported for the #237 regression test. */
41
+ export function buildPreviewEnv(extraEnv: Record<string, string>): NodeJS.ProcessEnv {
42
+ const allow = new Set(PREVIEW_ENV_ALLOWLIST);
43
+ for (const name of (process.env[PREVIEW_EXTRA_ENV_VAR] ?? "").split(",")) {
44
+ const normalized = name.trim().toUpperCase();
45
+ if (normalized) {
46
+ allow.add(normalized);
47
+ }
48
+ }
49
+ const env: Record<string, string> = {};
50
+ for (const [key, value] of Object.entries(process.env)) {
51
+ if (value !== undefined && allow.has(key.toUpperCase())) {
52
+ env[key] = value;
53
+ }
54
+ }
55
+ return { ...env, ...extraEnv };
56
+ }
57
+
16
58
  /**
17
59
  * Detect the tech stack from files in `cwd` and return a suitable preview command.
18
60
  * Only overrides `existingCommand` when it is the generic static file server
@@ -456,7 +498,10 @@ export class PreviewManager {
456
498
  const pipInstall = spawnManagedCommandProcess({
457
499
  command: `${pipBin} install -q -r requirements.txt`,
458
500
  cwd,
459
- env: { ...process.env, ...extraEnv },
501
+ // #237 W1: requirements.txt is worker-influenced and pip executes
502
+ // setup.py at install time, so this subprocess gets the same
503
+ // restricted env as the preview command itself.
504
+ env: buildPreviewEnv(extraEnv),
460
505
  });
461
506
  await new Promise<void>((resolve) => {
462
507
  pipInstall.on("exit", () => resolve());
@@ -470,10 +515,15 @@ export class PreviewManager {
470
515
 
471
516
  const child = spawnManagedCommandProcess({
472
517
  command: resolvedCommand,
518
+ // cwd is already forced inside the workspace (resolveWorkspaceDirectory
519
+ // confinement above), so the shell cannot escape the deliverable dir.
473
520
  cwd,
521
+ // #237 W1: restricted allowlist env - never the controller's full
522
+ // process.env (credential exfiltration via prompt-injected
523
+ // previewCommand). HOST/PORT/TEAMCLAW_PREVIEW_* are the explicit
524
+ // preview contract vars.
474
525
  env: {
475
- ...process.env,
476
- ...extraEnv,
526
+ ...buildPreviewEnv(extraEnv),
477
527
  HOST: "0.0.0.0",
478
528
  PORT: String(record.targetPort),
479
529
  TEAMCLAW_PREVIEW_BASE_PATH: record.liveUrl.replace(/\/$/u, ""),
@@ -5,13 +5,23 @@
5
5
  // the same deps object as before. This module must NEVER import http-server
6
6
  // (the reverse edge exists: http-server -> profile-switch); ws broadcasts,
7
7
  // state persistence and provisioning all arrive through the deps slice below.
8
+ // Issue #226 W4: persistence rides the single write entry (deps.
9
+ // updateTeamState) - including the awaited durability barriers this state
10
+ // machine needs - instead of independent saveTeamState calls; the update
11
+ // contract types are type-only imports from controller-service.js (the
12
+ // runtime edge points the other way, so the module graph stays acyclic).
8
13
  import type { PluginLogger } from "../../api.js";
9
14
  import type {
10
15
  PluginConfig,
11
16
  TaskInfo,
12
17
  TeamState,
13
18
  } from "../types.js";
14
- import { saveTeamState, archiveTeamState, findTeamSwitchArchive } from "../state.js";
19
+ import type {
20
+ TeamStateUpdateHandle,
21
+ TeamStateUpdateOptions,
22
+ UpdateTeamStateFn,
23
+ } from "./controller-service.js";
24
+ import { archiveTeamState, findTeamSwitchArchive } from "../state.js";
15
25
  import {
16
26
  BUILTIN_PROFILES,
17
27
  getActiveProfile,
@@ -34,7 +44,7 @@ export type TeamProfileSwitchDeps = {
34
44
  config: PluginConfig;
35
45
  logger: PluginLogger;
36
46
  getTeamState: () => TeamState | null;
37
- updateTeamState: (updater: (state: TeamState) => void) => TeamState;
47
+ updateTeamState: UpdateTeamStateFn;
38
48
  wsServer: TeamWebSocketServer;
39
49
  workerProvisioningManager?: WorkerProvisioningManager | null;
40
50
  previewManager?: PreviewManager;
@@ -129,22 +139,28 @@ export async function executeTeamProfileSwitch(
129
139
  targetProfileId: string,
130
140
  options: TeamProfileSwitchOptions = {},
131
141
  ): Promise<void> {
132
- const { config, logger, getTeamState, updateTeamState, wsServer, workerProvisioningManager } = deps;
142
+ const { config, logger, getTeamState, updateTeamState, workerProvisioningManager } = deps;
133
143
  const target = BUILTIN_PROFILES.get(targetProfileId);
134
144
  if (!target) {
135
145
  throw new Error(`TeamClaw team profile "${targetProfileId}" is not available in this installation`);
136
146
  }
137
- const setPhase = (phase: "draining" | "archiving" | "warming"): void => {
138
- updateTeamState((state) => {
147
+ // W4 (#226): phase flips persist through the single write entry. The
148
+ // awaited-durability variant is used everywhere so callers that need the
149
+ // crash-window barrier (step 3's archiving flip, step 5's warming flip)
150
+ // can await it; callers that historically fire-and-forget the save simply
151
+ // drop the handle (an un-awaited rejection behaves exactly like the old
152
+ // floating void save).
153
+ const setPhase = (phase: "draining" | "archiving" | "warming", options: TeamStateUpdateOptions = {}): TeamStateUpdateHandle => {
154
+ return updateTeamState((state) => {
139
155
  if (state.transition?.targetProfileId === targetProfileId) {
140
156
  state.transition.phase = phase;
141
157
  }
142
- });
158
+ }, { ...options, persist: "awaited" });
143
159
  };
144
160
 
145
161
  if (!options.skipArchive) {
146
162
  // Step 2: drain in-flight work, then stop every worker.
147
- setPhase("draining");
163
+ void setPhase("draining").persisted.catch(() => undefined);
148
164
  workerProvisioningManager?.setReconcileSuspended(true);
149
165
  const drain = await drainTeamForProfileSwitch(deps);
150
166
  for (const workerId of Object.keys(getTeamState()?.provisioning?.workers ?? {})) {
@@ -178,11 +194,19 @@ export async function executeTeamProfileSwitch(
178
194
  // Step 3: archive the whole previous TeamState with a roles snapshot.
179
195
  // The phase flip is persisted BEFORE the archive write so a crash between
180
196
  // the two leaves an unambiguous "archive may exist" state for the resume
181
- // path (file existence check).
182
- setPhase("archiving");
197
+ // path (file existence check). W4 (#226): the awaited durability barrier
198
+ // is the single entry's persisted handle (one save enqueued at the same
199
+ // point the old fire-and-forget + awaited second save pair wrote).
200
+ const archiving = setPhase("archiving");
201
+ // #251 note (no behavior change): `sourceState` below is whatever
202
+ // getTeamState() returns AFTER the awaited "archiving" persist barrier
203
+ // - it is NOT a phase-accurate snapshot frozen at the moment the drain
204
+ // finished. In-flight mutations racing the switch can be captured in
205
+ // the archive; the resume path tolerates this because the transition
206
+ // marker, not the snapshot contents, drives recovery.
183
207
  const sourceState = getTeamState();
184
208
  if (sourceState) {
185
- await saveTeamState(sourceState);
209
+ await archiving.persisted;
186
210
  const sourceProfile = getActiveProfile();
187
211
  await archiveTeamState(sourceState, {
188
212
  id: sourceProfile.id,
@@ -210,7 +234,7 @@ export async function executeTeamProfileSwitch(
210
234
  : null;
211
235
  setActiveProfileId(target.id);
212
236
  const newCreatedAt = Date.now();
213
- updateTeamState((state) => {
237
+ const step4 = updateTeamState((state) => {
214
238
  state.profileId = target.id;
215
239
  state.teamName = target.name;
216
240
  state.workers = {};
@@ -236,14 +260,13 @@ export async function executeTeamProfileSwitch(
236
260
  delete state.reports;
237
261
  }
238
262
  state.createdAt = newCreatedAt;
239
- });
240
- await saveTeamState(getTeamState()!);
263
+ }, { persist: "awaited" });
264
+ await step4.persisted;
241
265
 
242
266
  // Step 5: warm the new profile's warmupRoles through the provisioning
243
267
  // pipeline (launch dispatch; registration/readiness tracking continues in
244
268
  // the background exactly like a cold start).
245
- setPhase("warming");
246
- await saveTeamState(getTeamState()!);
269
+ await setPhase("warming").persisted;
247
270
  workerProvisioningManager?.setReconcileSuspended(false);
248
271
  if (workerProvisioningManager?.isEnabled() && target.warmupRoles.length > 0) {
249
272
  await workerProvisioningManager
@@ -251,12 +274,16 @@ export async function executeTeamProfileSwitch(
251
274
  .catch((err) => logger.warn(`Controller: profile switch warmup failed: ${err instanceof Error ? err.message : String(err)}`));
252
275
  }
253
276
 
254
- // Step 6: settle - clear the transition, persist, announce.
255
- updateTeamState((state) => {
277
+ // Step 6: settle - clear the transition, persist, announce. W4 (#226):
278
+ // the switch_completed broadcast rides the single entry's awaited
279
+ // persistence, preserving the event order (persisted, then announced).
280
+ const settled = updateTeamState((state) => {
256
281
  delete state.transition;
282
+ }, {
283
+ persist: "awaited",
284
+ broadcast: [{ type: "team.switch_completed", data: { profileId: target.id } }],
257
285
  });
258
- await saveTeamState(getTeamState()!);
259
- wsServer.broadcastUpdate({ type: "team.switch_completed", data: { profileId: target.id } });
286
+ await settled.persisted;
260
287
  logger.info(`Controller: team profile switch to "${target.id}" completed`);
261
288
  }
262
289
 
@@ -325,7 +352,7 @@ export function startTeamProfileSwitch(
325
352
  profileId: string,
326
353
  previousProfileId: string,
327
354
  ): void {
328
- const { logger, wsServer, updateTeamState, getTeamState } = deps;
355
+ const { logger, wsServer, updateTeamState } = deps;
329
356
  void executeTeamProfileSwitch(deps, profileId).catch(async (err) => {
330
357
  const detail = err instanceof Error ? err.message : String(err);
331
358
  logger.error(`Controller: team profile switch to "${profileId}" failed: ${detail}`);
@@ -356,11 +383,14 @@ export function startTeamProfileSwitch(
356
383
  type: "team.switch_failed",
357
384
  data: { previousProfileId, targetProfileId: profileId, reason },
358
385
  });
359
- updateTeamState((s) => {
386
+ // W4 (#226): best-effort persist of the unwedging through the single
387
+ // entry - one enqueued save with the failure path's swallow (the old
388
+ // shape fired an un-caught floating save plus this caught one).
389
+ const cleared = updateTeamState((s) => {
360
390
  if (s.transition?.targetProfileId === profileId) {
361
391
  delete s.transition;
362
392
  }
363
- });
364
- void saveTeamState(getTeamState()!).catch(() => undefined);
393
+ }, { persist: "awaited" });
394
+ void cleared.persisted.catch(() => undefined);
365
395
  });
366
396
  }
@@ -0,0 +1,51 @@
1
+ // W1 of issue #226 (worker-provisioning god-file split): the provisioner
2
+ // backend contract and the host-port policy shared by the facade and the
3
+ // backend modules, extracted VERBATIM from controller/worker-provisioning.ts.
4
+ // Pure types + pure functions: this module must never import a backend
5
+ // implementation or worker-provisioning.ts (dependency direction is one-way).
6
+ import type {
7
+ PluginConfig,
8
+ ProvisionedWorkerRecord,
9
+ RoleId,
10
+ WorkerProvisioningType,
11
+ } from "../../types.js";
12
+
13
+ export type LaunchSpec = {
14
+ workerId: string;
15
+ role: RoleId;
16
+ launchToken: string;
17
+ controllerUrl: string;
18
+ workerPort: number;
19
+ gatewayPort: number;
20
+ publishedHostPort?: number;
21
+ workspaceDir?: string;
22
+ env: Record<string, string>;
23
+ configJson: string;
24
+ };
25
+
26
+ export type LaunchResult = {
27
+ instanceId?: string;
28
+ instanceName?: string;
29
+ runtimeHomeDir?: string;
30
+ };
31
+
32
+ export interface WorkerProvisionerBackend {
33
+ readonly type: WorkerProvisioningType;
34
+ launch(spec: LaunchSpec): Promise<LaunchResult>;
35
+ terminate(record: ProvisionedWorkerRecord): Promise<void>;
36
+ stop?(): Promise<void>;
37
+ }
38
+
39
+ export function requiresDedicatedHostPortsForProvisioner(
40
+ provider: WorkerProvisioningType,
41
+ config: PluginConfig,
42
+ ): boolean {
43
+ if (provider === "process") {
44
+ return true;
45
+ }
46
+ return provider === "docker" && isDockerHostNetwork(config.workerProvisioningDockerNetwork);
47
+ }
48
+
49
+ export function isDockerHostNetwork(networkMode: string): boolean {
50
+ return networkMode.trim().toLowerCase() === "host";
51
+ }