@teamclaws/teamclaw 2026.4.3-1 → 2026.4.4

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.
@@ -38,7 +38,13 @@ import {
38
38
  } from "../protocol.js";
39
39
  import { listWorkspaceTree, listWorkspaceSubtree, readWorkspaceFile, readWorkspaceRawFile } from "../workspace-browser.js";
40
40
  import { ROLES, normalizeRecommendedSkills, resolveRecommendedSkillsForRole } from "../roles.js";
41
- import { buildRepoSyncInfo, ensureControllerGitRepo, exportControllerGitBundle, importControllerGitBundle } from "../git-collaboration.js";
41
+ import {
42
+ buildRepoSyncInfo,
43
+ ensureControllerGitRepo,
44
+ exportControllerGitBundle,
45
+ importControllerGitBundle,
46
+ removeTrackedWorkspaceSubtree,
47
+ } from "../git-collaboration.js";
42
48
  import { TaskRouter } from "./task-router.js";
43
49
  import { MessageRouter } from "./message-router.js";
44
50
  import { TeamWebSocketServer } from "./websocket.js";
@@ -65,6 +71,10 @@ import {
65
71
  resolveTeamClawProjectsDir,
66
72
  deriveStableProjectKey,
67
73
  deriveProjectSlug,
74
+ teamClawWorkspaceIsDefault,
75
+ updateTeamClawWorkspaceDir,
76
+ getTeamClawModelCatalog,
77
+ updateTeamClawModelConfig,
68
78
  } from "../openclaw-workspace.js";
69
79
  import { resolvePreferredLanAddress } from "../networking.js";
70
80
  import { normalizeClarificationQuestionSchema, normalizeControllerManifest } from "./orchestration-manifest.js";
@@ -92,6 +102,10 @@ const MAX_TASK_CONTEXT_SUMMARY_CHARS = 500;
92
102
  const CONTROLLER_INTAKE_SESSION_PREFIX = "teamclaw-controller-web:";
93
103
  const CONTROLLER_INTAKE_AGENT_SESSION_RE = /^agent:[^:]+:(teamclaw-controller-web:[a-zA-Z0-9:_-]{1,120})$/;
94
104
  const CONTROLLER_RUN_WAIT_SLICE_MS = 30_000;
105
+ const CONTROLLER_SESSION_PROGRESS_MESSAGE_LIMIT = 200;
106
+ const MAX_SESSION_PROGRESS_MESSAGE_CHARS = 4000;
107
+ const TOOL_CALL_BLOCK_TYPES = new Set(["tool_use", "toolcall", "tool_call"]);
108
+ const TOOL_RESULT_BLOCK_TYPES = new Set(["tool_result", "tool_result_error"]);
95
109
  const EXISTING_PROJECT_REUSE_HINT_RE = /\b(existing|optimi(?:s|z)e|optimi(?:s|z)ation|improvement|enhanc(?:e|ement)|follow[- ]?up|extend|update|bugfix|bug fix)\b/iu;
96
110
  const GENERIC_PROJECT_FOLLOW_UP_RE = /\b(continue|continuing|next step|what else|what's next|follow[- ]?up|more|remaining)\b|继续|接下来|下一步|还有哪些|还可以做什么/u;
97
111
  const PROJECT_MATCH_STOPWORDS = new Set([
@@ -404,6 +418,328 @@ function trimControllerRuns(state: TeamState): void {
404
418
  }
405
419
  }
406
420
 
421
+ type TaskCleanupSummary = {
422
+ deletedTaskIds: string[];
423
+ deletedClarificationIds: string[];
424
+ deletedMessageIds: string[];
425
+ stoppedPreviewIds: string[];
426
+ deletedReportIds: string[];
427
+ deletedProjectDirs: string[];
428
+ };
429
+
430
+ function buildEmptyTaskCleanupSummary(): TaskCleanupSummary {
431
+ return {
432
+ deletedTaskIds: [],
433
+ deletedClarificationIds: [],
434
+ deletedMessageIds: [],
435
+ stoppedPreviewIds: [],
436
+ deletedReportIds: [],
437
+ deletedProjectDirs: [],
438
+ };
439
+ }
440
+
441
+ function resolveSafeProjectDirectory(projectDir: string | undefined): string | null {
442
+ const normalized = String(projectDir ?? "").trim().replace(/^\/+|\/+$/gu, "");
443
+ if (!normalized || normalized === "." || normalized === "..") {
444
+ return null;
445
+ }
446
+ if (normalized.split("/").some((segment) => !segment || segment === "." || segment === "..")) {
447
+ return null;
448
+ }
449
+ const projectsRoot = path.resolve(resolveTeamClawProjectsDir());
450
+ const projectPath = path.resolve(projectsRoot, normalized);
451
+ const relative = path.relative(projectsRoot, projectPath);
452
+ if (!relative || relative === "" || relative === "." || relative.startsWith("..") || path.isAbsolute(relative)) {
453
+ return null;
454
+ }
455
+ return projectPath;
456
+ }
457
+
458
+ async function deleteProjectDirectoryIfUnused(
459
+ projectDir: string | undefined,
460
+ deps: ControllerHttpDeps,
461
+ summary: TaskCleanupSummary,
462
+ ): Promise<void> {
463
+ if (!projectDir) {
464
+ return;
465
+ }
466
+ const state = deps.getTeamState();
467
+ const stillReferencedByTask = Object.values(state?.tasks ?? {}).some((task) => task.projectDir === projectDir);
468
+ const stillReferencedByRun = Object.values(state?.controllerRuns ?? {}).some((run) => run.projectDir === projectDir);
469
+ if (stillReferencedByTask || stillReferencedByRun) {
470
+ return;
471
+ }
472
+
473
+ const safeProjectPath = resolveSafeProjectDirectory(projectDir);
474
+ if (!safeProjectPath) {
475
+ deps.logger.warn(`Controller: skipped unsafe project directory cleanup for ${String(projectDir)}`);
476
+ return;
477
+ }
478
+ if (!fs.existsSync(safeProjectPath)) {
479
+ return;
480
+ }
481
+ await removeTrackedWorkspaceSubtree(deps.config, deps.logger, safeProjectPath);
482
+ await fs.promises.rm(safeProjectPath, { recursive: true, force: true });
483
+ if (fs.existsSync(safeProjectPath)) {
484
+ throw new Error(`Project directory cleanup could not be confirmed for ${projectDir}`);
485
+ }
486
+
487
+ deps.updateTeamState((stateDraft) => {
488
+ const projectRecord = findProjectRecordByDir(stateDraft, projectDir);
489
+ if (projectRecord) {
490
+ delete stateDraft.projects[projectRecord.id];
491
+ }
492
+ });
493
+ summary.deletedProjectDirs.push(projectDir);
494
+ }
495
+
496
+ function isTaskTerminalForCleanup(task: TaskInfo | undefined): boolean {
497
+ if (!task) {
498
+ return true;
499
+ }
500
+ return task.status === "completed" || task.status === "failed";
501
+ }
502
+
503
+ function canAutoDeleteStaleControllerRun(
504
+ run: ControllerRunInfo,
505
+ state: TeamState | null,
506
+ now: number,
507
+ staleAfterMs: number,
508
+ ): boolean {
509
+ if (run.status !== "pending" && run.status !== "running") {
510
+ return false;
511
+ }
512
+ const lastActivityAt = run.execution?.lastUpdatedAt ?? run.updatedAt ?? run.createdAt ?? 0;
513
+ if (!lastActivityAt || now - lastActivityAt < staleAfterMs) {
514
+ return false;
515
+ }
516
+ const ownedTasks = Object.values(state?.tasks ?? {}).filter((task) => task.controllerRunId === run.id);
517
+ if (ownedTasks.some((task) => !isTaskTerminalForCleanup(task))) {
518
+ return false;
519
+ }
520
+ const hasPendingClarification = Object.values(state?.clarifications ?? {}).some((clarification) =>
521
+ clarification.controllerRunId === run.id && clarification.status === "pending",
522
+ );
523
+ return !hasPendingClarification;
524
+ }
525
+
526
+ async function pruneStaleControllerRuns(
527
+ deps: ControllerHttpDeps,
528
+ options?: { excludeRunId?: string },
529
+ ): Promise<void> {
530
+ const state = deps.getTeamState();
531
+ const now = Date.now();
532
+ const staleAfterMs = deps.config.taskTimeoutMs * 2;
533
+ const staleRunIds = Object.values(state?.controllerRuns ?? {})
534
+ .filter((run) => run.id !== options?.excludeRunId)
535
+ .filter((run) => canAutoDeleteStaleControllerRun(run, state, now, staleAfterMs))
536
+ .sort((left, right) => left.updatedAt - right.updatedAt)
537
+ .map((run) => run.id);
538
+ for (const staleRunId of staleRunIds) {
539
+ await deleteControllerRunCascade(staleRunId, deps, { preserveSessionArtifacts: true });
540
+ }
541
+ }
542
+
543
+ async function deleteProjectCascade(
544
+ projectDir: string,
545
+ deps: ControllerHttpDeps,
546
+ ): Promise<{ deleted: boolean; summary: TaskCleanupSummary & { projectDir?: string } }> {
547
+ const safeProjectPath = resolveSafeProjectDirectory(projectDir);
548
+ if (!safeProjectPath) {
549
+ return { deleted: false, summary: { ...buildEmptyTaskCleanupSummary(), projectDir: undefined } };
550
+ }
551
+
552
+ const summary: TaskCleanupSummary & { projectDir?: string } = {
553
+ ...buildEmptyTaskCleanupSummary(),
554
+ projectDir,
555
+ };
556
+ const state = deps.getTeamState();
557
+ const runIds = Object.values(state?.controllerRuns ?? {})
558
+ .filter((run) => run.projectDir === projectDir)
559
+ .map((run) => run.id);
560
+ const taskIds = Object.values(state?.tasks ?? {})
561
+ .filter((task) => task.projectDir === projectDir)
562
+ .map((task) => task.id);
563
+
564
+ for (const runId of runIds) {
565
+ const result = await deleteControllerRunCascade(runId, deps);
566
+ if (!result.deleted) {
567
+ continue;
568
+ }
569
+ summary.deletedTaskIds.push(...result.summary.deletedTaskIds);
570
+ summary.deletedClarificationIds.push(...result.summary.deletedClarificationIds);
571
+ summary.deletedMessageIds.push(...result.summary.deletedMessageIds);
572
+ summary.stoppedPreviewIds.push(...result.summary.stoppedPreviewIds);
573
+ summary.deletedReportIds.push(...result.summary.deletedReportIds);
574
+ summary.deletedProjectDirs.push(...result.summary.deletedProjectDirs);
575
+ }
576
+
577
+ for (const taskId of taskIds) {
578
+ await deleteTaskCascade(taskId, deps, summary);
579
+ }
580
+
581
+ await deleteProjectDirectoryIfUnused(projectDir, deps, summary);
582
+ if (!summary.deletedProjectDirs.includes(projectDir) && !fs.existsSync(safeProjectPath)) {
583
+ summary.deletedProjectDirs.push(projectDir);
584
+ }
585
+
586
+ if (summary.deletedProjectDirs.includes(projectDir)) {
587
+ deps.wsServer.broadcastUpdate({ type: "project:deleted", data: { projectDir } });
588
+ }
589
+
590
+ return { deleted: summary.deletedProjectDirs.includes(projectDir), summary };
591
+ }
592
+
593
+ async function deleteTaskCascade(
594
+ taskId: string,
595
+ deps: ControllerHttpDeps,
596
+ summary: TaskCleanupSummary,
597
+ ): Promise<boolean> {
598
+ const existingTask = deps.getTeamState()?.tasks[taskId];
599
+ if (!existingTask) {
600
+ return false;
601
+ }
602
+
603
+ await cancelTaskExecution(taskId, existingTask.assignedWorkerId, "cleanup deletion", deps);
604
+ await deps.previewManager?.stopTaskPreviews(taskId, "task deleted during cleanup");
605
+
606
+ const previewIds = Object.values(deps.getTeamState()?.previews ?? {})
607
+ .filter((preview) => preview.taskId === taskId)
608
+ .map((preview) => preview.id);
609
+
610
+ const deletedClarificationIds: string[] = [];
611
+ const deletedMessageIds: string[] = [];
612
+ const deletedReportIds: string[] = [];
613
+ const normalizedSessionKey = existingTask.controllerSessionKey
614
+ ? normalizeControllerIntakeSessionKey(existingTask.controllerSessionKey)
615
+ : undefined;
616
+
617
+ deps.updateTeamState((state) => {
618
+ delete state.tasks[taskId];
619
+
620
+ for (const clarification of Object.values(state.clarifications)) {
621
+ if (clarification.taskId === taskId) {
622
+ deletedClarificationIds.push(clarification.id);
623
+ delete state.clarifications[clarification.id];
624
+ }
625
+ }
626
+
627
+ if (state.messages.length > 0) {
628
+ const keptMessages: TeamMessage[] = [];
629
+ for (const message of state.messages) {
630
+ if (message.taskId === taskId) {
631
+ deletedMessageIds.push(message.id);
632
+ continue;
633
+ }
634
+ keptMessages.push(message);
635
+ }
636
+ state.messages = keptMessages;
637
+ }
638
+
639
+ if (normalizedSessionKey && state.reports) {
640
+ for (const report of Object.values(state.reports)) {
641
+ if (normalizeControllerIntakeSessionKey(report.sessionKey) === normalizedSessionKey) {
642
+ deletedReportIds.push(report.id);
643
+ delete state.reports[report.id];
644
+ }
645
+ }
646
+ }
647
+
648
+ for (const run of Object.values(state.controllerRuns)) {
649
+ if (run.sourceTaskId === taskId) {
650
+ delete run.sourceTaskId;
651
+ }
652
+ if (run.createdTaskIds.includes(taskId)) {
653
+ run.createdTaskIds = run.createdTaskIds.filter((id) => id !== taskId);
654
+ run.updatedAt = Date.now();
655
+ }
656
+ }
657
+ });
658
+
659
+ summary.deletedTaskIds.push(taskId);
660
+ summary.deletedClarificationIds.push(...deletedClarificationIds);
661
+ summary.deletedMessageIds.push(...deletedMessageIds);
662
+ summary.stoppedPreviewIds.push(...previewIds);
663
+ summary.deletedReportIds.push(...deletedReportIds);
664
+ await deleteProjectDirectoryIfUnused(existingTask.projectDir, deps, summary);
665
+
666
+ deps.wsServer.broadcastUpdate({ type: "task:deleted", data: { taskId } });
667
+ for (const clarificationId of deletedClarificationIds) {
668
+ deps.wsServer.broadcastUpdate({ type: "clarification:deleted", data: { clarificationId, taskId } });
669
+ }
670
+ for (const messageId of deletedMessageIds) {
671
+ deps.wsServer.broadcastUpdate({ type: "message:deleted", data: { messageId, taskId } });
672
+ }
673
+
674
+ return true;
675
+ }
676
+
677
+ async function deleteControllerRunCascade(
678
+ runId: string,
679
+ deps: ControllerHttpDeps,
680
+ options?: {
681
+ preserveSessionArtifacts?: boolean;
682
+ },
683
+ ): Promise<{
684
+ deleted: boolean;
685
+ summary: TaskCleanupSummary & { deletedRunId?: string };
686
+ }> {
687
+ const run = deps.getTeamState()?.controllerRuns[runId];
688
+ if (!run) {
689
+ return { deleted: false, summary: { ...buildEmptyTaskCleanupSummary() } };
690
+ }
691
+
692
+ const summary: TaskCleanupSummary & { deletedRunId?: string } = {
693
+ ...buildEmptyTaskCleanupSummary(),
694
+ deletedRunId: undefined,
695
+ };
696
+
697
+ const linkedTaskIds = new Set<string>(run.createdTaskIds);
698
+ for (const task of Object.values(deps.getTeamState()?.tasks ?? {})) {
699
+ if (task.controllerRunId === run.id) {
700
+ linkedTaskIds.add(task.id);
701
+ }
702
+ }
703
+
704
+ for (const taskId of linkedTaskIds) {
705
+ await deleteTaskCascade(taskId, deps, summary);
706
+ }
707
+
708
+ const deletedClarificationIds: string[] = [];
709
+ const deletedReportIds: string[] = [];
710
+ deps.updateTeamState((state) => {
711
+ delete state.controllerRuns[runId];
712
+ summary.deletedRunId = runId;
713
+
714
+ for (const clarification of Object.values(state.clarifications)) {
715
+ if (clarification.controllerRunId === runId) {
716
+ deletedClarificationIds.push(clarification.id);
717
+ delete state.clarifications[clarification.id];
718
+ }
719
+ }
720
+
721
+ if (state.reports) {
722
+ const normalizedSessionKey = normalizeControllerIntakeSessionKey(run.sessionKey);
723
+ for (const report of Object.values(state.reports)) {
724
+ if (!options?.preserveSessionArtifacts && normalizeControllerIntakeSessionKey(report.sessionKey) === normalizedSessionKey) {
725
+ deletedReportIds.push(report.id);
726
+ delete state.reports[report.id];
727
+ }
728
+ }
729
+ }
730
+ });
731
+
732
+ summary.deletedClarificationIds.push(...deletedClarificationIds);
733
+ summary.deletedReportIds.push(...deletedReportIds);
734
+
735
+ deps.wsServer.broadcastUpdate({ type: "controller:run_deleted", data: { runId } });
736
+ for (const clarificationId of deletedClarificationIds) {
737
+ deps.wsServer.broadcastUpdate({ type: "clarification:deleted", data: { clarificationId, controllerRunId: runId } });
738
+ }
739
+
740
+ return { deleted: true, summary };
741
+ }
742
+
407
743
  function serializeControllerRun(run?: ControllerRunInfo, includeExecutionEvents = true): Record<string, unknown> | undefined {
408
744
  if (!run) {
409
745
  return undefined;
@@ -434,9 +770,14 @@ function buildControllerRunTitle(
434
770
  sourceTaskTitle?: string,
435
771
  ): string {
436
772
  if (source === "task_follow_up") {
437
- return sourceTaskTitle
438
- ? `Controller follow-up after ${sourceTaskTitle}`
439
- : "Controller workflow follow-up";
773
+ const normalizedSourceTitle = String(sourceTaskTitle || "").replace(/\s+/g, " ").trim();
774
+ if (normalizedSourceTitle) {
775
+ const compactSourceTitle = normalizedSourceTitle.length <= 72
776
+ ? normalizedSourceTitle
777
+ : `${normalizedSourceTitle.slice(0, 72).trimEnd()}…`;
778
+ return `Controller follow-up after ${compactSourceTitle}`;
779
+ }
780
+ return "Controller workflow follow-up";
440
781
  }
441
782
 
442
783
  const normalized = message.replace(/\s+/g, " ").trim();
@@ -872,6 +1213,205 @@ function extractLastAssistantText(messages: unknown[]): string {
872
1213
  return JSON.stringify(lastAssistant);
873
1214
  }
874
1215
 
1216
+ type SessionProgressEntry = {
1217
+ fingerprint: string;
1218
+ message: string;
1219
+ phase: string;
1220
+ stream: string;
1221
+ isRateLimit: boolean;
1222
+ };
1223
+
1224
+ function normalizeSessionRole(value: unknown): string {
1225
+ if (typeof value !== "string") {
1226
+ return "";
1227
+ }
1228
+ const normalized = value.trim().toLowerCase().replace(/[-\s]+/g, "_");
1229
+ if (normalized === "toolresult") {
1230
+ return "tool_result";
1231
+ }
1232
+ return normalized;
1233
+ }
1234
+
1235
+ function normalizeBlockType(value: unknown): string {
1236
+ if (typeof value !== "string") {
1237
+ return "";
1238
+ }
1239
+ return value.trim().toLowerCase();
1240
+ }
1241
+
1242
+ function truncateProgressMessage(value: string): string {
1243
+ const trimmed = value.trim();
1244
+ if (!trimmed) {
1245
+ return "";
1246
+ }
1247
+ if (trimmed.length <= MAX_SESSION_PROGRESS_MESSAGE_CHARS) {
1248
+ return trimmed;
1249
+ }
1250
+ return `${trimmed.slice(0, MAX_SESSION_PROGRESS_MESSAGE_CHARS)}\n… (truncated)`;
1251
+ }
1252
+
1253
+ function normalizeProgressComparableText(value: string): string {
1254
+ return value.trim().replace(/\r\n/g, "\n");
1255
+ }
1256
+
1257
+ function safeJsonStringify(value: unknown): string {
1258
+ try {
1259
+ return typeof value === "string" ? value : JSON.stringify(value);
1260
+ } catch (_err) {
1261
+ return String(value);
1262
+ }
1263
+ }
1264
+
1265
+ function renderSessionMessage(message: Record<string, unknown>, role: string): { message: string; stream: string } {
1266
+ const content = message.content;
1267
+ if (typeof content === "string") {
1268
+ return {
1269
+ message: truncateProgressMessage(content),
1270
+ stream: role,
1271
+ };
1272
+ }
1273
+
1274
+ if (Array.isArray(content)) {
1275
+ const textParts: string[] = [];
1276
+ const toolCalls: string[] = [];
1277
+ let toolResultCount = 0;
1278
+ let toolResultErrors = 0;
1279
+
1280
+ for (const entry of content) {
1281
+ if (!entry || typeof entry !== "object") {
1282
+ continue;
1283
+ }
1284
+
1285
+ const block = entry as Record<string, unknown>;
1286
+ const type = normalizeBlockType(block.type);
1287
+ if (type === "text") {
1288
+ const text = typeof block.text === "string" ? block.text.trim() : "";
1289
+ if (text) {
1290
+ textParts.push(text);
1291
+ }
1292
+ continue;
1293
+ }
1294
+
1295
+ if (TOOL_CALL_BLOCK_TYPES.has(type)) {
1296
+ const name = typeof block.name === "string" ? block.name.trim() : "";
1297
+ if (name) {
1298
+ toolCalls.push(name);
1299
+ }
1300
+ continue;
1301
+ }
1302
+
1303
+ if (TOOL_RESULT_BLOCK_TYPES.has(type)) {
1304
+ toolResultCount += 1;
1305
+ if (block.is_error === true) {
1306
+ toolResultErrors += 1;
1307
+ }
1308
+ }
1309
+ }
1310
+
1311
+ const parts: string[] = [];
1312
+ if (textParts.length > 0) {
1313
+ parts.push(textParts.join("\n"));
1314
+ }
1315
+ if (toolCalls.length > 0) {
1316
+ parts.push(`[tool call] ${toolCalls.join(", ")}`);
1317
+ }
1318
+ if (toolResultCount > 0) {
1319
+ parts.push(`[tool result] ${toolResultCount}${toolResultErrors > 0 ? ` (${toolResultErrors} error)` : ""}`);
1320
+ }
1321
+
1322
+ if (parts.length > 0) {
1323
+ return {
1324
+ message: truncateProgressMessage(parts.join("\n")),
1325
+ stream: textParts.length > 0 ? role : "tool",
1326
+ };
1327
+ }
1328
+ }
1329
+
1330
+ const fallbackToolName = typeof message.toolName === "string"
1331
+ ? message.toolName.trim()
1332
+ : (typeof message.tool_name === "string" ? message.tool_name.trim() : "");
1333
+ if (fallbackToolName) {
1334
+ return {
1335
+ message: `[tool call] ${fallbackToolName}`,
1336
+ stream: "tool",
1337
+ };
1338
+ }
1339
+
1340
+ return {
1341
+ message: truncateProgressMessage(safeJsonStringify(message)),
1342
+ stream: role || "session",
1343
+ };
1344
+ }
1345
+
1346
+ function buildSessionProgressEntries(messages: unknown[], controllerMessage: string): SessionProgressEntry[] {
1347
+ const entries: SessionProgressEntry[] = [];
1348
+ const normalizedControllerMessage = normalizeProgressComparableText(controllerMessage);
1349
+
1350
+ for (const rawMessage of messages) {
1351
+ if (!rawMessage || typeof rawMessage !== "object") {
1352
+ continue;
1353
+ }
1354
+
1355
+ const message = rawMessage as Record<string, unknown>;
1356
+ const role = normalizeSessionRole(message.role);
1357
+ if (!role) {
1358
+ continue;
1359
+ }
1360
+
1361
+ const rendered = renderSessionMessage(message, role);
1362
+ if (!rendered.message) {
1363
+ continue;
1364
+ }
1365
+
1366
+ const comparableMessage = normalizeProgressComparableText(rendered.message);
1367
+ if (role === "user" && normalizedControllerMessage && comparableMessage.includes(normalizedControllerMessage)) {
1368
+ continue;
1369
+ }
1370
+
1371
+ entries.push({
1372
+ fingerprint: `${rendered.stream}:${comparableMessage}`,
1373
+ message: rendered.message,
1374
+ phase: rendered.stream,
1375
+ stream: rendered.stream,
1376
+ isRateLimit: isRateLimitMessage(rendered.message),
1377
+ });
1378
+ }
1379
+
1380
+ return entries;
1381
+ }
1382
+
1383
+ function getNewSessionProgressEntries(
1384
+ entries: SessionProgressEntry[],
1385
+ previousFingerprints: string[],
1386
+ ): SessionProgressEntry[] {
1387
+ if (entries.length === 0) {
1388
+ return [];
1389
+ }
1390
+ if (previousFingerprints.length === 0) {
1391
+ return entries;
1392
+ }
1393
+
1394
+ const currentFingerprints = entries.map((entry) => entry.fingerprint);
1395
+ const maxOverlap = Math.min(previousFingerprints.length, currentFingerprints.length);
1396
+ let overlap = 0;
1397
+
1398
+ for (let size = maxOverlap; size > 0; size -= 1) {
1399
+ let matches = true;
1400
+ for (let index = 0; index < size; index += 1) {
1401
+ if (previousFingerprints[previousFingerprints.length - size + index] !== currentFingerprints[index]) {
1402
+ matches = false;
1403
+ break;
1404
+ }
1405
+ }
1406
+ if (matches) {
1407
+ overlap = size;
1408
+ break;
1409
+ }
1410
+ }
1411
+
1412
+ return entries.slice(overlap);
1413
+ }
1414
+
875
1415
  function formatDuration(timeoutMs: number): string {
876
1416
  const totalSeconds = Math.ceil(timeoutMs / 1000);
877
1417
  if (totalSeconds % 3600 === 0) {
@@ -992,6 +1532,7 @@ function reconcileControllerManifestTaskBindings(
992
1532
  sessionKey: string,
993
1533
  createdTaskIds: string[],
994
1534
  manifest: ControllerOrchestrationManifest | undefined,
1535
+ controllerRunId: string,
995
1536
  deps: ControllerHttpDeps,
996
1537
  ): { taskIds: string[]; linkedTaskIds: string[] } {
997
1538
  if (!manifest || manifest.createdTasks.length === 0) {
@@ -1028,6 +1569,7 @@ function reconcileControllerManifestTaskBindings(
1028
1569
  if (matchedTask.controllerSessionKey !== normalizedSessionKey) {
1029
1570
  matchedTask.controllerSessionKey = normalizedSessionKey;
1030
1571
  }
1572
+ matchedTask.controllerRunId = controllerRunId;
1031
1573
  if (!usedTaskIds.has(matchedTask.id)) {
1032
1574
  usedTaskIds.add(matchedTask.id);
1033
1575
  linkedTaskIds.push(matchedTask.id);
@@ -1043,6 +1585,7 @@ function reconcileControllerManifestTaskBindings(
1043
1585
 
1044
1586
  function tagControllerCreatedTasks(
1045
1587
  taskIdsBeforeRun: Set<string>,
1588
+ controllerRunId: string,
1046
1589
  sessionKey: string,
1047
1590
  deps: ControllerHttpDeps,
1048
1591
  ): string[] {
@@ -1056,6 +1599,7 @@ function tagControllerCreatedTasks(
1056
1599
  if (task.createdBy !== "controller") {
1057
1600
  continue;
1058
1601
  }
1602
+ task.controllerRunId = controllerRunId;
1059
1603
  if (!task.controllerSessionKey) {
1060
1604
  task.controllerSessionKey = normalizedSessionKey;
1061
1605
  }
@@ -1306,7 +1850,25 @@ function buildBackfilledControllerManifest(
1306
1850
 
1307
1851
  function looksLikeSoftwareRequirement(request: string): boolean {
1308
1852
  const normalized = request.toLowerCase();
1309
- return /(api|backend|frontend|fastapi|react|vue|node|python|typescript|javascript|sql|database|service|app|web|mobile|docker|kubernetes|deploy|测试|系统|平台|接口|服务|数据库|应用|前端|后端)/.test(normalized);
1853
+ return /(api|backend|frontend|fastapi|react|vue|node|python|typescript|javascript|sql|database|service|app|web|mobile|docker|kubernetes|deploy|stderr|stdout|logging|logger|log file|config|yaml|json|cli|command|build|test|compile|bug|fix|output|file|repo|repository|code|测试|系统|平台|接口|服务|数据库|应用|前端|后端|日志|输出|文件|配置|命令|编译|构建|修复|代码|仓库)/.test(normalized);
1854
+ }
1855
+
1856
+ function looksLikeManualExecutionClarification(question: string): boolean {
1857
+ const normalized = question.toLowerCase();
1858
+ return /(请先|请运行|请执行|请重试|请重新编译|请复现|run\b|rerun\b|retry\b|rebuild\b|recompile\b|git pull\b|go build\b|npm test\b|pnpm test\b|yarn test\b|pytest\b|cargo test\b|是否仍然|does it still|still crash|still fail)/i.test(normalized);
1859
+ }
1860
+
1861
+ function extractExecutableFollowUpFromClarification(question: string): string | null {
1862
+ const trimmed = String(question || "").trim();
1863
+ if (!trimmed || !looksLikeManualExecutionClarification(trimmed)) {
1864
+ return null;
1865
+ }
1866
+ const normalized = trimmed.replace(/\s+/g, " ").trim();
1867
+ return [
1868
+ "Continue the same requirement by executing the obvious validation or rebuild step yourself instead of asking the human to run it manually.",
1869
+ `Requested follow-up verification: ${normalized}`,
1870
+ "Run the needed build/test/repro steps inside the project workspace, inspect the real outcome, and then either fix the issue or report the verified blocker with concrete evidence.",
1871
+ ].join("\n\n");
1310
1872
  }
1311
1873
 
1312
1874
  function isArchitectureFirstRequirement(request: string): boolean {
@@ -1316,6 +1878,10 @@ function isArchitectureFirstRequirement(request: string): boolean {
1316
1878
 
1317
1879
  function chooseFallbackAssignedRole(manifest: ControllerOrchestrationManifest, request: string): RoleId {
1318
1880
  const requiredRoles = manifest.requiredRoles;
1881
+ const implementationLikeRequest = looksLikeSoftwareRequirement(request) && !isArchitectureFirstRequirement(request);
1882
+ if (requiredRoles.length === 1 && requiredRoles[0] === "architect" && implementationLikeRequest) {
1883
+ return "developer";
1884
+ }
1319
1885
  if (requiredRoles.length === 0) {
1320
1886
  return isArchitectureFirstRequirement(request) ? "architect" : "developer";
1321
1887
  }
@@ -1355,6 +1921,116 @@ function buildFallbackControllerTaskTitle(request: string, assignedRole?: RoleId
1355
1921
  : `Perform the requested ${assignedRole || "software"} work`;
1356
1922
  }
1357
1923
 
1924
+ function looksLikeSupplementalHumanContextUpdate(request: string): boolean {
1925
+ const normalized = request.toLowerCase();
1926
+ const hasEndpointOrCredentialHint = /(apikey|api key|token|credential|endpoint|base url|provider|model list|models接口|连接信息|兼容接口|供应商|可用模型)/i.test(request);
1927
+ const urlCount = (request.match(/https?:\/\//gi) || []).length;
1928
+ const looksLikeFreshImplementationAsk = /(implement|build|create|write|develop|fix|refactor|design|架构|设计|实现|开发|修复|重构|创建)/i.test(normalized);
1929
+ return !looksLikeFreshImplementationAsk && (hasEndpointOrCredentialHint || urlCount >= 2);
1930
+ }
1931
+
1932
+ function getActiveTasksForSupplementalHumanContext(
1933
+ controllerRunId: string,
1934
+ sessionKey: string,
1935
+ manifest: ControllerOrchestrationManifest,
1936
+ state: TeamState | null,
1937
+ ): TaskInfo[] {
1938
+ const normalizedSessionKey = normalizeControllerIntakeSessionKey(sessionKey);
1939
+ const runProjectDir = state?.controllerRuns?.[controllerRunId]?.projectDir;
1940
+ const requiredRoles = new Set(manifest.requiredRoles);
1941
+ return Object.values(state?.tasks ?? {})
1942
+ .filter((task) => task.status === "assigned" || task.status === "in_progress" || task.status === "review")
1943
+ .filter((task) => normalizeControllerIntakeSessionKey(task.controllerSessionKey) === normalizedSessionKey)
1944
+ .filter((task) => !runProjectDir || task.projectDir === runProjectDir)
1945
+ .filter((task) => requiredRoles.size === 0 || (task.assignedRole ? requiredRoles.has(task.assignedRole) : false))
1946
+ .sort((left, right) => {
1947
+ const leftScore = left.status === "in_progress" ? 2 : left.status === "assigned" ? 1 : 0;
1948
+ const rightScore = right.status === "in_progress" ? 2 : right.status === "assigned" ? 1 : 0;
1949
+ if (leftScore !== rightScore) {
1950
+ return rightScore - leftScore;
1951
+ }
1952
+ return right.updatedAt - left.updatedAt;
1953
+ });
1954
+ }
1955
+
1956
+ async function forwardSupplementalHumanContextToActiveTasks(
1957
+ controllerRunId: string,
1958
+ sessionKey: string,
1959
+ request: string,
1960
+ manifest: ControllerOrchestrationManifest,
1961
+ deps: ControllerHttpDeps,
1962
+ ): Promise<string[]> {
1963
+ if (!looksLikeSupplementalHumanContextUpdate(request)) {
1964
+ return [];
1965
+ }
1966
+ const state = deps.getTeamState();
1967
+ const targetTasks = getActiveTasksForSupplementalHumanContext(controllerRunId, sessionKey, manifest, state);
1968
+ if (targetTasks.length === 0) {
1969
+ return [];
1970
+ }
1971
+
1972
+ const createdAt = Date.now();
1973
+ const messages: TeamMessage[] = targetTasks.map((task) => ({
1974
+ id: generateId(),
1975
+ from: "human-intake",
1976
+ to: task.assignedWorkerId,
1977
+ toRole: task.assignedRole,
1978
+ type: "direct",
1979
+ content: request,
1980
+ contract: ensureTeamMessageContract(null, {
1981
+ type: "direct",
1982
+ content: request,
1983
+ toRole: task.assignedRole,
1984
+ taskId: task.id,
1985
+ intent: "update",
1986
+ needsResponse: false,
1987
+ }),
1988
+ taskId: task.id,
1989
+ createdAt,
1990
+ }));
1991
+
1992
+ deps.updateTeamState((teamState) => {
1993
+ teamState.messages.push(...messages);
1994
+ });
1995
+
1996
+ for (const message of messages) {
1997
+ recordTaskExecutionEvent(message.taskId!, {
1998
+ type: "progress",
1999
+ phase: "human_context_forwarded",
2000
+ source: "controller",
2001
+ status: "running",
2002
+ message: "Human provided supplemental context for this task. Review task messages for the new details.",
2003
+ }, deps);
2004
+ deps.wsServer.broadcastUpdate({ type: "message:new", data: message });
2005
+ if (message.to) {
2006
+ const worker = deps.getTeamState()?.workers?.[message.to];
2007
+ if (worker && worker.status !== "offline") {
2008
+ try {
2009
+ await deliverMessageToWorker(worker, message, deps);
2010
+ } catch (err) {
2011
+ deps.logger.warn(`Controller: failed to forward supplemental context to ${worker.id}: ${String(err)}`);
2012
+ }
2013
+ }
2014
+ }
2015
+ }
2016
+
2017
+ manifest.notes = manifest.notes
2018
+ ? `${manifest.notes} TeamClaw forwarded this human intake as supplemental context to active task(s): ${targetTasks.map((task) => task.id).join(", ")}.`
2019
+ : `TeamClaw forwarded this human intake as supplemental context to active task(s): ${targetTasks.map((task) => task.id).join(", ")}.`;
2020
+ updateControllerRun(controllerRunId, deps, (run) => {
2021
+ run.manifest = manifest;
2022
+ appendControllerRunEvent(run, {
2023
+ type: "warning",
2024
+ phase: "context_forwarded",
2025
+ source: "controller",
2026
+ status: "running",
2027
+ sessionKey,
2028
+ message: `Forwarded supplemental human context to active task(s): ${targetTasks.map((task) => task.id).join(", ")}`,
2029
+ });
2030
+ });
2031
+ return targetTasks.map((task) => task.id);
2032
+ }
2033
+
1358
2034
  async function createControllerManagedTask(
1359
2035
  input: {
1360
2036
  title: string;
@@ -1362,6 +2038,7 @@ async function createControllerManagedTask(
1362
2038
  priority?: TaskPriority;
1363
2039
  assignedRole?: RoleId;
1364
2040
  createdBy: string;
2041
+ controllerRunId?: string;
1365
2042
  controllerSessionKey?: string;
1366
2043
  projectName?: string;
1367
2044
  recommendedSkills?: string[];
@@ -1379,7 +2056,7 @@ async function createControllerManagedTask(
1379
2056
  ? resolveProjectIdentityForSession(normalizedSessionKey, deps.getTeamState())
1380
2057
  : undefined;
1381
2058
  const explicitProjectId = deriveStableProjectKey(input.projectName ?? "");
1382
- const projectId = inheritedProject?.projectId ?? explicitProjectId || undefined;
2059
+ const projectId = inheritedProject?.projectId ?? (explicitProjectId || undefined);
1383
2060
  const projectDir = inheritedProject?.projectDir ?? projectId ?? deriveProjectSlug(input.title);
1384
2061
 
1385
2062
  const normalizedRecommendedSkills = normalizeRecommendedSkills(input.recommendedSkills ?? []);
@@ -1392,6 +2069,7 @@ async function createControllerManagedTask(
1392
2069
  assignedRole: input.assignedRole,
1393
2070
  createdBy: input.createdBy,
1394
2071
  recommendedSkills: normalizedRecommendedSkills.length > 0 ? normalizedRecommendedSkills : undefined,
2072
+ controllerRunId: input.createdBy === "controller" ? input.controllerRunId : undefined,
1395
2073
  controllerSessionKey: normalizedSessionKey,
1396
2074
  projectId,
1397
2075
  projectDir,
@@ -1465,7 +2143,20 @@ async function maybeBackfillExecutionReadyTask(
1465
2143
  if (options?.source === "task_follow_up") {
1466
2144
  return [];
1467
2145
  }
1468
- if (!looksLikeSoftwareRequirement(request)) {
2146
+ const likelyTechnicalRequest = looksLikeSoftwareRequirement(request)
2147
+ || manifest.requiredRoles.length > 0
2148
+ || /code|repo|repository|日志|输出|文件|配置|命令|修复|实现|修改/.test(request.toLowerCase());
2149
+ if (!likelyTechnicalRequest) {
2150
+ return [];
2151
+ }
2152
+ const forwardedTaskIds = await forwardSupplementalHumanContextToActiveTasks(
2153
+ controllerRunId,
2154
+ sessionKey,
2155
+ request,
2156
+ manifest,
2157
+ deps,
2158
+ );
2159
+ if (forwardedTaskIds.length > 0) {
1469
2160
  return [];
1470
2161
  }
1471
2162
 
@@ -1475,6 +2166,7 @@ async function maybeBackfillExecutionReadyTask(
1475
2166
  description: request,
1476
2167
  assignedRole,
1477
2168
  createdBy: "controller",
2169
+ controllerRunId,
1478
2170
  controllerSessionKey: sessionKey,
1479
2171
  recommendedSkills: resolveRecommendedSkillsForRole(assignedRole, []),
1480
2172
  }, deps);
@@ -1751,6 +2443,59 @@ function buildManifestClarificationEntries(
1751
2443
  ];
1752
2444
  }
1753
2445
 
2446
+ async function maybeConvertControllerClarificationToExecutionTask(
2447
+ controllerRunId: string,
2448
+ sessionKey: string,
2449
+ manifest: ControllerOrchestrationManifest,
2450
+ deps: ControllerHttpDeps,
2451
+ ): Promise<string[]> {
2452
+ const candidateQuestion = (manifest.clarificationQuestions || []).find((entry) => looksLikeManualExecutionClarification(entry));
2453
+ const followUpDescription = candidateQuestion ? extractExecutableFollowUpFromClarification(candidateQuestion) : null;
2454
+ if (!candidateQuestion || !followUpDescription) {
2455
+ return [];
2456
+ }
2457
+
2458
+ const assignedRole = chooseFallbackAssignedRole(manifest, followUpDescription);
2459
+ const task = await createControllerManagedTask({
2460
+ title: buildFallbackControllerTaskTitle(candidateQuestion, assignedRole),
2461
+ description: followUpDescription,
2462
+ assignedRole,
2463
+ createdBy: "controller",
2464
+ controllerRunId,
2465
+ controllerSessionKey: sessionKey,
2466
+ recommendedSkills: resolveRecommendedSkillsForRole(assignedRole, []),
2467
+ }, deps);
2468
+ if (!task) {
2469
+ return [];
2470
+ }
2471
+
2472
+ manifest.createdTasks = [{
2473
+ title: task.title,
2474
+ assignedRole: task.assignedRole,
2475
+ expectedOutcome: summarizeManifestExpectedOutcome(task),
2476
+ }];
2477
+ manifest.clarificationsNeeded = false;
2478
+ manifest.clarificationQuestions = manifest.clarificationQuestions.filter((entry) => entry !== candidateQuestion);
2479
+ if (Array.isArray(manifest.clarificationSchemas)) {
2480
+ manifest.clarificationSchemas = manifest.clarificationSchemas.filter((schema) => schema.title !== candidateQuestion);
2481
+ }
2482
+ manifest.notes = manifest.notes
2483
+ ? `${manifest.notes} TeamClaw converted a manual-action clarification into execution task ${task.id} so the team can perform the validation itself.`
2484
+ : `TeamClaw converted a manual-action clarification into execution task ${task.id} so the team can perform the validation itself.`;
2485
+ updateControllerRun(controllerRunId, deps, (run) => {
2486
+ run.manifest = manifest;
2487
+ appendControllerRunEvent(run, {
2488
+ type: "warning",
2489
+ phase: "clarification_converted_to_task",
2490
+ source: "controller",
2491
+ status: "running",
2492
+ sessionKey,
2493
+ message: `Controller converted a manual-action clarification into execution task ${task.id}.`,
2494
+ });
2495
+ });
2496
+ return [task.id];
2497
+ }
2498
+
1754
2499
  function syncControllerRunClarifications(
1755
2500
  controllerRunId: string,
1756
2501
  sessionKey: string,
@@ -2066,6 +2811,15 @@ async function runControllerIntakeUnlocked(
2066
2811
  nextProbeAt: Date.now() + deps.config.taskTimeoutMs,
2067
2812
  probeCount: 0,
2068
2813
  };
2814
+ const progressSnapshot: {
2815
+ fingerprints: string[];
2816
+ latestMessages: unknown[];
2817
+ lastActivityAt: number;
2818
+ } = {
2819
+ fingerprints: [],
2820
+ latestMessages: [],
2821
+ lastActivityAt: Date.now(),
2822
+ };
2069
2823
 
2070
2824
  const markRateLimitWaiting = async (): Promise<void> => {
2071
2825
  if (rateLimitState.active) {
@@ -2093,11 +2847,48 @@ async function runControllerIntakeUnlocked(
2093
2847
  };
2094
2848
 
2095
2849
  const noteObservedControllerActivity = (): void => {
2850
+ progressSnapshot.lastActivityAt = Date.now();
2096
2851
  inactivityState.active = false;
2097
2852
  inactivityState.visibleAt = undefined;
2098
2853
  inactivityState.nextProbeAt = Date.now() + deps.config.taskTimeoutMs;
2099
2854
  };
2100
2855
 
2856
+ const syncControllerSessionProgress = async (): Promise<void> => {
2857
+ const sessionMessages = await deps.runtime.subagent.getSessionMessages({
2858
+ sessionKey,
2859
+ limit: CONTROLLER_SESSION_PROGRESS_MESSAGE_LIMIT,
2860
+ });
2861
+ progressSnapshot.latestMessages = Array.isArray(sessionMessages.messages) ? sessionMessages.messages : [];
2862
+ const entries = buildSessionProgressEntries(progressSnapshot.latestMessages, message);
2863
+ const newEntries = getNewSessionProgressEntries(entries, progressSnapshot.fingerprints);
2864
+ progressSnapshot.fingerprints = entries.map((entry) => entry.fingerprint);
2865
+ if (newEntries.length > 0) {
2866
+ noteObservedControllerActivity();
2867
+ }
2868
+ for (const entry of newEntries) {
2869
+ if (entry.isRateLimit) {
2870
+ await markRateLimitWaiting();
2871
+ continue;
2872
+ }
2873
+ if (rateLimitState.active && isStillWaitingResponse(entry.message)) {
2874
+ continue;
2875
+ }
2876
+ if (rateLimitState.active) {
2877
+ clearRateLimitWaiting();
2878
+ }
2879
+ recordControllerRunEvent(controllerRun.id, {
2880
+ type: "progress",
2881
+ phase: entry.phase,
2882
+ source: "subagent",
2883
+ stream: entry.stream,
2884
+ status: "running",
2885
+ sessionKey,
2886
+ runId: runResult.runId,
2887
+ message: entry.message,
2888
+ }, deps);
2889
+ }
2890
+ };
2891
+
2101
2892
  const extractSessionAssistantReply = async (): Promise<string> => {
2102
2893
  const sessionMessages = await deps.runtime.subagent.getSessionMessages({
2103
2894
  sessionKey,
@@ -2242,6 +3033,12 @@ async function runControllerIntakeUnlocked(
2242
3033
  timeoutMs: CONTROLLER_RUN_WAIT_SLICE_MS,
2243
3034
  });
2244
3035
 
3036
+ try {
3037
+ await syncControllerSessionProgress();
3038
+ } catch (err) {
3039
+ deps.logger.debug?.(`Controller: failed to sync planning session progress for ${controllerRun.id}: ${String(err)}`);
3040
+ }
3041
+
2245
3042
  if (waitResult.status === "ok") {
2246
3043
  clearRateLimitWaiting();
2247
3044
  noteObservedControllerActivity();
@@ -2257,7 +3054,7 @@ async function runControllerIntakeUnlocked(
2257
3054
  }
2258
3055
  if (waitResult.status !== "ok") {
2259
3056
  const errorMessage = waitResult.error || "Controller intake failed";
2260
- const createdTaskIds = tagControllerCreatedTasks(taskIdsBeforeRun, sessionKey, deps);
3057
+ const createdTaskIds = tagControllerCreatedTasks(taskIdsBeforeRun, controllerRun.id, sessionKey, deps);
2261
3058
  updateControllerRun(controllerRun.id, deps, (run) => {
2262
3059
  run.createdTaskIds = createdTaskIds;
2263
3060
  run.error = errorMessage;
@@ -2274,7 +3071,13 @@ async function runControllerIntakeUnlocked(
2274
3071
  throw new Error(errorMessage);
2275
3072
  }
2276
3073
 
2277
- let createdTaskIds = tagControllerCreatedTasks(taskIdsBeforeRun, sessionKey, deps);
3074
+ let createdTaskIds = tagControllerCreatedTasks(taskIdsBeforeRun, controllerRun.id, sessionKey, deps);
3075
+
3076
+ try {
3077
+ await syncControllerSessionProgress();
3078
+ } catch (err) {
3079
+ deps.logger.debug?.(`Controller: failed final planning session sync for ${controllerRun.id}: ${String(err)}`);
3080
+ }
2278
3081
 
2279
3082
  const rawReply = completionOverride || await extractSessionAssistantReply()
2280
3083
  || "Controller completed the intake run but did not return any text.";
@@ -2297,8 +3100,17 @@ async function runControllerIntakeUnlocked(
2297
3100
  if (fallbackTaskIds.length > 0) {
2298
3101
  createdTaskIds = Array.from(new Set([...createdTaskIds, ...fallbackTaskIds]));
2299
3102
  }
3103
+ const convertedClarificationTaskIds = await maybeConvertControllerClarificationToExecutionTask(
3104
+ controllerRun.id,
3105
+ sessionKey,
3106
+ recordedManifest,
3107
+ deps,
3108
+ );
3109
+ if (convertedClarificationTaskIds.length > 0) {
3110
+ createdTaskIds = Array.from(new Set([...createdTaskIds, ...convertedClarificationTaskIds]));
3111
+ }
2300
3112
  syncControllerRunClarifications(controllerRun.id, sessionKey, recordedManifest, deps);
2301
- const reconciledTasks = reconcileControllerManifestTaskBindings(sessionKey, createdTaskIds, recordedManifest, deps);
3113
+ const reconciledTasks = reconcileControllerManifestTaskBindings(sessionKey, createdTaskIds, recordedManifest, controllerRun.id, deps);
2302
3114
 
2303
3115
  // ── Automatic Team Kickoff ────────────────────────────────────────────
2304
3116
  // For complex projects (3+ roles), automatically run a kickoff meeting
@@ -2334,6 +3146,9 @@ async function runControllerIntakeUnlocked(
2334
3146
  );
2335
3147
  // Store kickoff assessments on the manifest for UI/API visibility
2336
3148
  recordedManifest.kickoffPlan = {
3149
+ complexity: recordedManifest.requiredRoles.length >= 5 ? "complex" : "medium",
3150
+ candidateRoles: recordedManifest.requiredRoles as RoleId[],
3151
+ completed: true,
2337
3152
  assessments: kickoffResult.assessments,
2338
3153
  summary: kickoffResult.summary,
2339
3154
  triggeredAt: Date.now(),
@@ -2417,6 +3232,8 @@ async function runControllerIntakeUnlocked(
2417
3232
  });
2418
3233
  });
2419
3234
 
3235
+ await pruneStaleControllerRuns(deps, { excludeRunId: controllerRun.id });
3236
+
2420
3237
  return {
2421
3238
  sessionKey,
2422
3239
  runId: runResult.runId,
@@ -2533,6 +3350,20 @@ function buildTaskContextSnapshot(task: TaskInfo, state: TeamState | null): Task
2533
3350
  question: clarification.question,
2534
3351
  blockingReason: clarification.blockingReason,
2535
3352
  })),
3353
+ answeredClarifications: Object.values(state.clarifications)
3354
+ .filter((clarification) => clarification.status === "answered" && clarification.answer)
3355
+ .filter((clarification) =>
3356
+ clarification.taskId === task.id
3357
+ || normalizeControllerIntakeSessionKey(clarification.controllerSessionKey) === normalizedSessionKey,
3358
+ )
3359
+ .sort((a, b) => (b.answeredAt ?? b.updatedAt ?? 0) - (a.answeredAt ?? a.updatedAt ?? 0))
3360
+ .slice(0, 5)
3361
+ .map((clarification) => ({
3362
+ question: clarification.question,
3363
+ answer: clarification.answer || "",
3364
+ answeredBy: clarification.answeredBy,
3365
+ blockingReason: clarification.blockingReason,
3366
+ })),
2536
3367
  handoffPlan: latestRun?.manifest?.handoffPlan,
2537
3368
  notes: latestRun?.manifest?.notes,
2538
3369
  kickoffSummary: latestRun?.manifest?.kickoffPlan?.summary,
@@ -2776,7 +3607,7 @@ function getEffectiveStartupReadiness(
2776
3607
  startedAt: recorded?.startedAt ?? state?.createdAt ?? Date.now(),
2777
3608
  checkedAt: Date.now(),
2778
3609
  attempts: recorded?.attempts ?? 0,
2779
- requiredRoles,
3610
+ requiredRoles: requiredRoles as RoleId[],
2780
3611
  readyWorkerIds,
2781
3612
  message: recorded?.status === "ready"
2782
3613
  ? recorded.message
@@ -2789,7 +3620,7 @@ function getEffectiveStartupReadiness(
2789
3620
  startedAt: state?.createdAt ?? Date.now(),
2790
3621
  checkedAt: Date.now(),
2791
3622
  attempts: 0,
2792
- requiredRoles,
3623
+ requiredRoles: requiredRoles as RoleId[],
2793
3624
  readyWorkerIds,
2794
3625
  message: `Startup provisioning warm-up is still initializing for ${requiredRoles.join(", ")}.`,
2795
3626
  };
@@ -3691,9 +4522,10 @@ async function autoAssignPendingTasks(
3691
4522
  deps: ControllerHttpDeps,
3692
4523
  preferredWorkerId?: string,
3693
4524
  ): Promise<TaskInfo[]> {
3694
- const { getTeamState, taskRouter, wsServer, logger } = deps;
4525
+ const { getTeamState, taskRouter, wsServer, logger, config } = deps;
3695
4526
  const attemptedPairs = new Set<string>();
3696
4527
  const assignedTasks: TaskInfo[] = [];
4528
+ const maxConcurrent = config.maxConcurrentTasks;
3697
4529
 
3698
4530
  while (true) {
3699
4531
  const state = getTeamState();
@@ -3701,6 +4533,17 @@ async function autoAssignPendingTasks(
3701
4533
  break;
3702
4534
  }
3703
4535
 
4536
+ // Throttle: count currently in-progress tasks and respect maxConcurrentTasks
4537
+ const inProgressCount = Object.values(state.tasks).filter(
4538
+ (t) => t.status === "in_progress",
4539
+ ).length;
4540
+ if (inProgressCount >= maxConcurrent) {
4541
+ logger.debug?.(
4542
+ `Controller: skipping auto-assign — ${inProgressCount} tasks in_progress (max ${maxConcurrent})`,
4543
+ );
4544
+ break;
4545
+ }
4546
+
3704
4547
  const candidateAssignments = taskRouter
3705
4548
  .autoAssignPendingTasks(state.tasks, state.workers)
3706
4549
  .filter(({ task, worker }) => !attemptedPairs.has(`${task.id}:${worker.id}`));
@@ -3832,6 +4675,96 @@ async function handleRequest(
3832
4675
 
3833
4676
  // ==================== Workspace Browser ====================
3834
4677
 
4678
+ if (req.method === "GET" && pathname === "/api/v1/workspace/status") {
4679
+ sendJson(res, 200, {
4680
+ workspaceDir: resolveTeamClawWorkspaceDir(),
4681
+ isDefault: teamClawWorkspaceIsDefault(),
4682
+ });
4683
+ return;
4684
+ }
4685
+
4686
+ if (req.method === "POST" && pathname === "/api/v1/workspace/change-dir") {
4687
+ let body: unknown;
4688
+ try {
4689
+ body = await parseJsonBody(req);
4690
+ } catch {
4691
+ sendError(res, 400, "invalid JSON body");
4692
+ return;
4693
+ }
4694
+ const workspaceDir = typeof (body as { workspaceDir?: unknown })?.workspaceDir === "string"
4695
+ ? (body as { workspaceDir: string }).workspaceDir
4696
+ : "";
4697
+ if (!workspaceDir.trim()) {
4698
+ sendError(res, 400, "workspaceDir is required");
4699
+ return;
4700
+ }
4701
+ try {
4702
+ const result = await updateTeamClawWorkspaceDir(workspaceDir, {
4703
+ warn: (message: string) => deps.logger.info(message),
4704
+ });
4705
+ sendJson(res, 200, {
4706
+ ok: true,
4707
+ workspaceDir: result.agentEntryPath,
4708
+ configPath: result.configPath,
4709
+ restartRequired: true,
4710
+ });
4711
+ } catch (err) {
4712
+ sendError(res, 400, err instanceof Error ? err.message : "failed to update workspace directory");
4713
+ }
4714
+ return;
4715
+ }
4716
+
4717
+ // GET /api/v1/models/config - model catalog + current selection for the UI settings dialog
4718
+ if (req.method === "GET" && pathname === "/api/v1/models/config") {
4719
+ try {
4720
+ sendJson(res, 200, await getTeamClawModelCatalog());
4721
+ } catch (err) {
4722
+ sendError(res, 500, err instanceof Error ? err.message : "failed to read model configuration");
4723
+ }
4724
+ return;
4725
+ }
4726
+
4727
+ // PUT /api/v1/models/config - persist default and per-role model selection
4728
+ if (req.method === "PUT" && pathname === "/api/v1/models/config") {
4729
+ let body: { defaultModel?: unknown; roleModelOverrides?: unknown } | null = null;
4730
+ try {
4731
+ body = await parseJsonBody(req) as { defaultModel?: unknown; roleModelOverrides?: unknown };
4732
+ } catch {
4733
+ sendError(res, 400, "invalid JSON body");
4734
+ return;
4735
+ }
4736
+ const update: { defaultModel?: string; roleModelOverrides?: Record<string, string> } = {};
4737
+ if (typeof body?.defaultModel === "string") {
4738
+ update.defaultModel = body.defaultModel.trim();
4739
+ }
4740
+ if (body?.roleModelOverrides && typeof body.roleModelOverrides === "object" && !Array.isArray(body.roleModelOverrides)) {
4741
+ const overrides: Record<string, string> = {};
4742
+ for (const [role, value] of Object.entries(body.roleModelOverrides as Record<string, unknown>)) {
4743
+ if (typeof value === "string" && value.trim()) {
4744
+ overrides[role] = value.trim();
4745
+ }
4746
+ }
4747
+ update.roleModelOverrides = overrides;
4748
+ }
4749
+ if (update.defaultModel === undefined && update.roleModelOverrides === undefined) {
4750
+ sendError(res, 400, "defaultModel or roleModelOverrides is required");
4751
+ return;
4752
+ }
4753
+ try {
4754
+ await updateTeamClawModelConfig(update, {
4755
+ warn: (message: string) => deps.logger.info(message),
4756
+ });
4757
+ sendJson(res, 200, {
4758
+ ok: true,
4759
+ restartNote: "Config changes hot-reload; restart the gateway (openclaw gateway restart) if a change does not take effect.",
4760
+ catalog: await getTeamClawModelCatalog(),
4761
+ });
4762
+ } catch (err) {
4763
+ sendError(res, 400, err instanceof Error ? err.message : "failed to update model configuration");
4764
+ }
4765
+ return;
4766
+ }
4767
+
3835
4768
  if (req.method === "GET" && pathname === "/api/v1/workspace/tree") {
3836
4769
  try {
3837
4770
  // depth=N limits tree expansion (default 1 for lazy loading)
@@ -3873,6 +4806,28 @@ async function handleRequest(
3873
4806
  return;
3874
4807
  }
3875
4808
 
4809
+ if (req.method === "GET" && pathname === "/api/v1/workspace/project-path") {
4810
+ const projectDir = requestUrl.searchParams.get("projectDir") ?? "";
4811
+ if (!projectDir) {
4812
+ sendError(res, 400, "projectDir is required");
4813
+ return;
4814
+ }
4815
+ const absolutePath = resolveSafeProjectDirectory(projectDir);
4816
+ if (!absolutePath) {
4817
+ sendError(res, 400, "Invalid projectDir");
4818
+ return;
4819
+ }
4820
+ if (!fs.existsSync(absolutePath)) {
4821
+ sendError(res, 404, "Project directory not found");
4822
+ return;
4823
+ }
4824
+ sendJson(res, 200, {
4825
+ projectDir,
4826
+ absolutePath,
4827
+ });
4828
+ return;
4829
+ }
4830
+
3876
4831
  if (req.method === "GET" && pathname.startsWith("/api/v1/workspace/raw/")) {
3877
4832
  const rawPathname = pathname.slice("/api/v1/workspace/raw/".length);
3878
4833
  if (!rawPathname) {
@@ -3991,7 +4946,15 @@ async function handleRequest(
3991
4946
  // GET /api/v1/workers
3992
4947
  if (req.method === "GET" && pathname === "/api/v1/workers") {
3993
4948
  const state = getTeamState();
3994
- const workers = state ? Object.values(state.workers) : [];
4949
+ const workers = state
4950
+ ? Object.values(state.workers).map((worker) => ({
4951
+ ...worker,
4952
+ // Ghost rows from previous gateway processes (provisioned workers
4953
+ // die with the process they ran in). The controller cleans these on
4954
+ // startup; the flag lets the UI mark leftovers as removable.
4955
+ staleRemovable: worker.id.startsWith("provisioned-") && worker.status === "offline",
4956
+ }))
4957
+ : [];
3995
4958
  sendJson(res, 200, { workers });
3996
4959
  return;
3997
4960
  }
@@ -4064,21 +5027,22 @@ async function handleRequest(
4064
5027
  const inheritedProject = controllerSessionKey
4065
5028
  ? resolveProjectIdentityForSession(controllerSessionKey, getTeamState())
4066
5029
  : undefined;
4067
- const projectId = inheritedProject?.projectId ?? explicitProjectName || undefined;
5030
+ const projectId = inheritedProject?.projectId ?? (explicitProjectName || undefined);
4068
5031
  const projectDir = inheritedProject?.projectDir ?? projectId ?? deriveProjectSlug(title);
4069
5032
 
4070
- const task: TaskInfo = {
4071
- id: taskId,
4072
- title,
4073
- description,
5033
+ const task: TaskInfo = {
5034
+ id: taskId,
5035
+ title,
5036
+ description,
4074
5037
  status: "pending",
4075
5038
  priority,
4076
- assignedRole,
4077
- createdBy,
4078
- recommendedSkills: recommendedSkills.length > 0 ? recommendedSkills : undefined,
4079
- controllerSessionKey,
4080
- projectId,
4081
- projectDir,
5039
+ assignedRole,
5040
+ createdBy,
5041
+ recommendedSkills: recommendedSkills.length > 0 ? recommendedSkills : undefined,
5042
+ controllerRunId: undefined,
5043
+ controllerSessionKey,
5044
+ projectId,
5045
+ projectDir,
4082
5046
  createdAt: now,
4083
5047
  updatedAt: now,
4084
5048
  };
@@ -4134,6 +5098,46 @@ async function handleRequest(
4134
5098
  return;
4135
5099
  }
4136
5100
 
5101
+ type TeamStatsResponse = {
5102
+ totalWorkers: number;
5103
+ workersByStatus: { idle: number; busy: number; offline: number };
5104
+ totalTasks: number;
5105
+ tasksByStatus: Record<string, number>;
5106
+ averageTaskDuration: number | null;
5107
+ uptime: number;
5108
+ };
5109
+
5110
+ function computeTeamStats(state: TeamState): TeamStatsResponse {
5111
+ const workers = Object.values(state.workers);
5112
+ const tasks = Object.values(state.tasks);
5113
+
5114
+ const workersByStatus = { idle: 0, busy: 0, offline: 0 };
5115
+ for (const worker of workers) {
5116
+ workersByStatus[worker.status] += 1;
5117
+ }
5118
+
5119
+ const tasksByStatus: Record<string, number> = {};
5120
+ for (const task of tasks) {
5121
+ tasksByStatus[task.status] = (tasksByStatus[task.status] ?? 0) + 1;
5122
+ }
5123
+
5124
+ const completedTasks = tasks.filter(
5125
+ (task) => task.status === "completed" && task.startedAt && task.completedAt,
5126
+ );
5127
+ const averageTaskDuration = completedTasks.length > 0
5128
+ ? completedTasks.reduce((sum, task) => sum + (task.completedAt! - task.startedAt!), 0) / completedTasks.length
5129
+ : null;
5130
+
5131
+ return {
5132
+ totalWorkers: workers.length,
5133
+ workersByStatus,
5134
+ totalTasks: tasks.length,
5135
+ tasksByStatus,
5136
+ averageTaskDuration,
5137
+ uptime: process.uptime() * 1000,
5138
+ };
5139
+ }
5140
+
4137
5141
  // GET /api/v1/tasks
4138
5142
  if (req.method === "GET" && pathname === "/api/v1/tasks") {
4139
5143
  const state = getTeamState();
@@ -4142,6 +5146,22 @@ async function handleRequest(
4142
5146
  return;
4143
5147
  }
4144
5148
 
5149
+ // GET /api/v1/stats
5150
+ if (req.method === "GET" && pathname === "/api/v1/stats") {
5151
+ const state = getTeamState();
5152
+ if (!state) {
5153
+ sendError(res, 503, "Team state not available");
5154
+ return;
5155
+ }
5156
+ try {
5157
+ const stats = computeTeamStats(state);
5158
+ sendJson(res, 200, stats);
5159
+ } catch (err) {
5160
+ sendError(res, 500, `Failed to compute stats: ${err instanceof Error ? err.message : String(err)}`);
5161
+ }
5162
+ return;
5163
+ }
5164
+
4145
5165
  // GET /api/v1/tasks/:id
4146
5166
  if (req.method === "GET" && pathname.match(/^\/api\/v1\/tasks\/[^/]+$/)) {
4147
5167
  const taskId = pathname.split("/").pop()!;
@@ -4155,6 +5175,29 @@ async function handleRequest(
4155
5175
  return;
4156
5176
  }
4157
5177
 
5178
+ // DELETE /api/v1/tasks/:id
5179
+ if (req.method === "DELETE" && pathname.match(/^\/api\/v1\/tasks\/[^/]+$/)) {
5180
+ const taskId = pathname.split("/").pop()!;
5181
+ const summary = buildEmptyTaskCleanupSummary();
5182
+ const deleted = await deleteTaskCascade(taskId, deps, summary);
5183
+ if (!deleted) {
5184
+ sendError(res, 404, "Task not found");
5185
+ return;
5186
+ }
5187
+ const stillExists = !!getTeamState()?.tasks[taskId];
5188
+ if (stillExists) {
5189
+ sendError(res, 409, "Task cleanup could not be confirmed");
5190
+ return;
5191
+ }
5192
+ sendJson(res, 200, {
5193
+ status: "deleted",
5194
+ confirmed: true,
5195
+ taskId,
5196
+ cleanup: summary,
5197
+ });
5198
+ return;
5199
+ }
5200
+
4158
5201
  // GET /api/v1/tasks/:id/execution
4159
5202
  if (req.method === "GET" && pathname.match(/^\/api\/v1\/tasks\/[^/]+\/execution$/)) {
4160
5203
  const taskId = pathname.split("/")[4]!;
@@ -4468,7 +5511,7 @@ async function handleRequest(
4468
5511
  }, deps);
4469
5512
  }
4470
5513
 
4471
- const effectiveContract = buildEffectiveTaskResultContract(currentTask, result, error, submittedContract);
5514
+ const effectiveContract = buildEffectiveTaskResultContract(currentTask, result, error, submittedContract ?? undefined);
4472
5515
 
4473
5516
  if (!error && effectiveContract.outcome === "blocked") {
4474
5517
  updateTeamState((teamState) => {
@@ -4527,7 +5570,7 @@ async function handleRequest(
4527
5570
  && gatedTask
4528
5571
  && taskRequiresMeaningfulProjectChangeGate(gatedTask)
4529
5572
  && !projectHasMeaningfulFileChanges(gatedTask, effectiveContract)
4530
- && !allowsNoChangeCompletion(gatedTask, submittedContract, result)
5573
+ && !allowsNoChangeCompletion(gatedTask, submittedContract ?? undefined, result)
4531
5574
  ) {
4532
5575
  error = "Task reported completion but no meaningful project file changes were detected in the assigned project directory.";
4533
5576
  recordTaskExecutionEvent(taskId, {
@@ -4770,6 +5813,51 @@ async function handleRequest(
4770
5813
  return;
4771
5814
  }
4772
5815
 
5816
+ // DELETE /api/v1/projects/:projectDir
5817
+ if (req.method === "DELETE" && pathname.match(/^\/api\/v1\/projects\/[^/]+$/)) {
5818
+ const projectDir = decodeURIComponent(pathname.split("/").pop()!);
5819
+ const result = await deleteProjectCascade(projectDir, deps);
5820
+ if (!result.deleted) {
5821
+ sendError(res, 404, "Project not found or project cleanup could not be confirmed");
5822
+ return;
5823
+ }
5824
+ const safeProjectPath = resolveSafeProjectDirectory(projectDir);
5825
+ const stillExists = safeProjectPath ? fs.existsSync(safeProjectPath) : true;
5826
+ if (stillExists) {
5827
+ sendError(res, 409, "Project cleanup could not be confirmed");
5828
+ return;
5829
+ }
5830
+ sendJson(res, 200, {
5831
+ status: "deleted",
5832
+ confirmed: true,
5833
+ projectDir,
5834
+ cleanup: result.summary,
5835
+ });
5836
+ return;
5837
+ }
5838
+
5839
+ // DELETE /api/v1/controller/runs/:id
5840
+ if (req.method === "DELETE" && pathname.match(/^\/api\/v1\/controller\/runs\/[^/]+$/)) {
5841
+ const runId = pathname.split("/").pop()!;
5842
+ const result = await deleteControllerRunCascade(runId, deps);
5843
+ if (!result.deleted) {
5844
+ sendError(res, 404, "Controller run not found");
5845
+ return;
5846
+ }
5847
+ const stillExists = !!getTeamState()?.controllerRuns[runId];
5848
+ if (stillExists) {
5849
+ sendError(res, 409, "Planning run cleanup could not be confirmed");
5850
+ return;
5851
+ }
5852
+ sendJson(res, 200, {
5853
+ status: "deleted",
5854
+ confirmed: true,
5855
+ runId,
5856
+ cleanup: result.summary,
5857
+ });
5858
+ return;
5859
+ }
5860
+
4773
5861
  // POST /api/v1/controller/intake
4774
5862
  if (req.method === "POST" && pathname === "/api/v1/controller/intake") {
4775
5863
  const readinessGate = shouldBlockControllerUntilProvisioningReady(deps, currentState);