@teamclaws/teamclaw 2026.8.0 → 2026.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/api.js +1 -0
  2. package/dist/index.js +325 -0
  3. package/dist/src/config.js +381 -0
  4. package/dist/src/controller/controller-capacity.js +14 -0
  5. package/dist/src/controller/controller-service.js +393 -0
  6. package/dist/src/controller/controller-tools.js +582 -0
  7. package/dist/src/controller/delivery-report.js +458 -0
  8. package/dist/src/controller/github-auth.js +564 -0
  9. package/dist/src/controller/http-server.js +6032 -0
  10. package/dist/src/controller/kickoff-orchestrator.js +220 -0
  11. package/dist/src/controller/managed-gateway-process.js +286 -0
  12. package/dist/src/controller/message-router.js +38 -0
  13. package/dist/src/controller/orchestration-manifest.js +173 -0
  14. package/dist/src/controller/preview-manager.js +586 -0
  15. package/dist/src/controller/prompt-injector.js +187 -0
  16. package/dist/src/controller/role-inference.js +35 -0
  17. package/dist/src/controller/task-router.js +67 -0
  18. package/dist/src/controller/tunnel-manager.js +548 -0
  19. package/dist/src/controller/websocket.js +42 -0
  20. package/dist/src/controller/worker-provisioning.js +1648 -0
  21. package/dist/src/discovery.js +86 -0
  22. package/dist/src/git-collaboration.js +694 -0
  23. package/dist/src/identity.js +131 -0
  24. package/dist/src/install-defaults.js +1 -0
  25. package/dist/src/interaction-contracts.js +531 -0
  26. package/dist/src/networking.js +91 -0
  27. package/dist/src/openclaw-workspace.js +903 -0
  28. package/dist/src/prompt-policy.js +373 -0
  29. package/dist/src/protocol.js +58 -0
  30. package/dist/src/roles.js +349 -0
  31. package/dist/src/state.js +183 -0
  32. package/dist/src/task-executor.js +1033 -0
  33. package/dist/src/teamauto/github-client.js +192 -0
  34. package/dist/src/teamauto/norms.js +85 -0
  35. package/dist/src/teamauto/repo-sync.js +201 -0
  36. package/dist/src/teamauto/scanner.js +179 -0
  37. package/dist/src/teamauto/schedule.js +123 -0
  38. package/dist/src/teamauto/scheduler.js +688 -0
  39. package/dist/src/teamauto/store.js +133 -0
  40. package/dist/src/types.js +243 -0
  41. package/dist/src/ui/app.js +4292 -0
  42. package/dist/src/ui/assets/teamclaw-app-icon.png +0 -0
  43. package/dist/src/ui/github-login.html +296 -0
  44. package/dist/src/ui/index.html +414 -0
  45. package/dist/src/ui/style.css +2611 -0
  46. package/dist/src/worker/http-handler.js +146 -0
  47. package/dist/src/worker/message-queue.js +24 -0
  48. package/dist/src/worker/prompt-injector.js +42 -0
  49. package/dist/src/worker/skill-installer.js +253 -0
  50. package/dist/src/worker/tools.js +541 -0
  51. package/dist/src/worker/worker-service.js +234 -0
  52. package/dist/src/workspace-browser.js +269 -0
  53. package/openclaw.plugin.json +1 -1
  54. package/package.json +1 -1
@@ -0,0 +1,582 @@
1
+ import { Type } from "@sinclair/typebox";
2
+ import { buildControllerNoWorkersMessage, hasOnDemandWorkerProvisioning, shouldBlockControllerWithoutWorkers } from "./controller-capacity.js";
3
+ import { normalizeClarificationQuestionSchemas, normalizeManifestCompletionOpportunities, normalizeManifestCreatedTasks, normalizeManifestDeferredTasks, normalizeManifestRoleList, normalizeManifestStringList, normalizeOptionalManifestText, } from "./orchestration-manifest.js";
4
+ import { ensureTeamMessageContract, normalizeContractRole, normalizeContractStringList, } from "../interaction-contracts.js";
5
+ const EXECUTION_READY_BLOCKERS = [
6
+ { pattern: /\bdepends?\s+on\b/i, reason: "it explicitly depends on other unfinished work" },
7
+ { pattern: /\bprerequisite\b/i, reason: "it references a prerequisite that may not be satisfied yet" },
8
+ { pattern: /\bwait(?:ing)?\s+for\b/i, reason: "it says the work should wait for another output first" },
9
+ { pattern: /依赖于|前置条件|前置依赖|前提条件|前序任务|上游任务/u, reason: "it explicitly mentions a predecessor dependency" },
10
+ { pattern: /待.*完成|等待.*完成/u, reason: "it is described as work for a later phase" },
11
+ { pattern: /前提/u, reason: "it mentions a prerequisite condition that may not be satisfied yet" },
12
+ { pattern: /blocked\s*-\s*by/i, reason: "it explicitly says the task is blocked by another item" },
13
+ { pattern: /需要.*先完成/u, reason: "it states another piece of work must complete first" },
14
+ ];
15
+ const VALID_ROLE_IDS = new Set([
16
+ "pm", "architect", "developer", "qa", "release-engineer",
17
+ "infra-engineer", "devops", "security-engineer", "designer", "marketing",
18
+ ]);
19
+ const ENGLISH_LATER_PHASE_CLAUSE_RE = /\b(?:after|once)\b(.+?)\b(complete|completed|ready|available|exists?)\b/i;
20
+ const ENGLISH_LATER_PHASE_DEPENDENCY_RE = /\b(?:task|tasks|service|services|module|modules|phase|phases|api|apis|interface|interfaces|review|qa|design|developer|architect|skeleton|backend|frontend|deliverable|artifact|handoff)\b/i;
21
+ const CHINESE_LATER_PHASE_CLAUSE_RE = /(.+?)(完成后|就绪后)/u;
22
+ const CHINESE_LATER_PHASE_DEPENDENCY_RE = /(?:服务|模块|任务|阶段|接口|骨架|后端|前端|设计|审查|开发|测试|架构|交付物|文档|交接)/u;
23
+ const SERVICE_NAME_RE = /\b[a-z0-9_-]+-service\b/i;
24
+ const SERVICE_NAME_GLOBAL_RE = /\b[a-z0-9_-]+-service\b/gi;
25
+ const ACTIVE_TASK_STATUSES = new Set(["pending", "assigned", "in_progress", "review", "blocked"]);
26
+ const REPO_WIDE_CODE_CHANGE_RE = /(financial-erp-backend\/|all services|all microservices|all backend services|所有服务|所有微服务|全部微服务|统一.*kafka|kafka topic|db\/migration|schema|ddl|api路径|trusted\.packages|pom\.xml|webmvcconfig|安全响应头)/i;
27
+ const DOC_ONLY_SCOPE_RE = /(文档|docs\/|api design|architecture document|设计文档|报告|report)/i;
28
+ export function createControllerTools(deps) {
29
+ const { config, controllerUrl, getTeamState, sessionKey } = deps;
30
+ const baseUrl = controllerUrl;
31
+ return [
32
+ {
33
+ name: "teamclaw_request_kickoff",
34
+ label: "Request Team Kickoff Meeting",
35
+ description: "Provision candidate role workers and collect structured assessments from each before creating execution tasks. Use for medium/complex projects where multiple roles need to collaborate.",
36
+ parameters: Type.Object({
37
+ requirement: Type.String({ description: "The full user requirement to present to the team for assessment" }),
38
+ candidateRoles: Type.Array(Type.String({ description: "Role IDs to invite to the kickoff meeting (e.g. architect, developer, qa)" })),
39
+ complexity: Type.Union([
40
+ Type.Literal("simple"),
41
+ Type.Literal("medium"),
42
+ Type.Literal("complex"),
43
+ ], { description: "Project complexity: simple (skip kickoff, 1-2 roles), medium (partial kickoff, 2-3 roles), complex (full team kickoff, 4+ roles)" }),
44
+ }),
45
+ async execute(_id, params) {
46
+ const kickoffHandler = deps.getKickoffHandler?.();
47
+ if (!kickoffHandler) {
48
+ return {
49
+ details: {},
50
+ content: [{
51
+ type: "text",
52
+ text: "Kickoff meeting is not available in this deployment. Proceed with direct task creation.",
53
+ }],
54
+ };
55
+ }
56
+ const requirement = String(params.requirement ?? "").trim();
57
+ if (!requirement) {
58
+ return { details: {}, content: [{ type: "text", text: "requirement is required." }] };
59
+ }
60
+ const rawRoles = Array.isArray(params.candidateRoles) ? params.candidateRoles : [];
61
+ const candidateRoles = rawRoles
62
+ .map((r) => String(r ?? "").trim().toLowerCase())
63
+ .filter((r) => VALID_ROLE_IDS.has(r));
64
+ if (candidateRoles.length === 0) {
65
+ return { details: {}, content: [{ type: "text", text: "At least one valid candidate role is required." }] };
66
+ }
67
+ const complexity = (params.complexity === "simple" || params.complexity === "medium" || params.complexity === "complex")
68
+ ? params.complexity
69
+ : "medium";
70
+ try {
71
+ const result = await kickoffHandler(candidateRoles, complexity, requirement);
72
+ return {
73
+ details: {},
74
+ content: [{
75
+ type: "text",
76
+ text: result.summary,
77
+ }],
78
+ };
79
+ }
80
+ catch (err) {
81
+ return {
82
+ details: {},
83
+ content: [{
84
+ type: "text",
85
+ text: `Kickoff meeting failed: ${err instanceof Error ? err.message : String(err)}. Proceed with controller-only planning.`,
86
+ }],
87
+ };
88
+ }
89
+ },
90
+ },
91
+ {
92
+ name: "teamclaw_create_task",
93
+ label: "Create Team Task",
94
+ description: "Create an execution-ready team task after the controller has analyzed the raw human requirement, clarified missing decisions, and confirmed the task can start immediately",
95
+ parameters: Type.Object({
96
+ title: Type.String({ description: "Task title" }),
97
+ description: Type.String({ description: "Execution-ready task description with scope, expected deliverable, constraints, resolved clarifications, and no unmet predecessor dependency" }),
98
+ priority: Type.Optional(Type.String({ description: "Priority: low, medium, high, critical" })),
99
+ assignedRole: Type.Optional(Type.String({ description: "Exact target role ID (pm, architect, developer, qa, release-engineer, infra-engineer, devops, security-engineer, designer, marketing, data-engineer)" })),
100
+ projectName: Type.Optional(Type.String({ description: "Stable project key to reuse or create for this task (for example: ggcode, todo-rest-api)." })),
101
+ recommendedSkills: Type.Optional(Type.Array(Type.String({
102
+ description: "Exact OpenClaw/ClawHub skill slug when known; otherwise a short skill-discovery query",
103
+ }))),
104
+ }),
105
+ async execute(_id, params) {
106
+ const title = String(params.title ?? "");
107
+ const description = String(params.description ?? "");
108
+ const normalizedSessionKey = typeof sessionKey === "string" ? sessionKey.trim() : "";
109
+ if (!title) {
110
+ return { details: {}, content: [{ type: "text", text: "title is required." }] };
111
+ }
112
+ const state = getTeamState();
113
+ if (shouldBlockControllerWithoutWorkers(config, state)) {
114
+ return {
115
+ details: {},
116
+ content: [{
117
+ type: "text",
118
+ text: `${buildControllerNoWorkersMessage()} Stop after reporting this block to the human.`,
119
+ }],
120
+ };
121
+ }
122
+ const blocker = detectExecutionReadyBlocker(description);
123
+ if (blocker) {
124
+ return {
125
+ details: {},
126
+ content: [{
127
+ type: "text",
128
+ text: `Refusing to create task "${title}" because it is not execution-ready: ${blocker}. Only create tasks that can start immediately; keep downstream work in the controller plan until prerequisites are already complete.`,
129
+ }],
130
+ };
131
+ }
132
+ const overlapBlocker = detectActiveTaskOverlap(title, description, state);
133
+ if (overlapBlocker) {
134
+ return {
135
+ details: {},
136
+ content: [{
137
+ type: "text",
138
+ text: `Refusing to create task "${title}" because it is not execution-ready: ${overlapBlocker}. Wait for the active task to finish or narrow the new task so it does not edit the same service scope in parallel.`,
139
+ }],
140
+ };
141
+ }
142
+ try {
143
+ const res = await fetch(`${baseUrl}/api/v1/tasks`, {
144
+ method: "POST",
145
+ headers: { "Content-Type": "application/json" },
146
+ body: JSON.stringify({
147
+ title,
148
+ description,
149
+ priority: params.priority ?? "medium",
150
+ assignedRole: params.assignedRole ?? undefined,
151
+ projectName: typeof params.projectName === "string" ? params.projectName : undefined,
152
+ recommendedSkills: Array.isArray(params.recommendedSkills) ? params.recommendedSkills : undefined,
153
+ createdBy: "controller",
154
+ controllerSessionKey: normalizedSessionKey || undefined,
155
+ }),
156
+ });
157
+ if (!res.ok) {
158
+ const err = await res.text();
159
+ return { details: {}, content: [{ type: "text", text: `Failed to create task: ${err}` }] };
160
+ }
161
+ const data = await res.json();
162
+ const task = data.task;
163
+ const assigned = task.assignedWorkerId
164
+ ? ` -> assigned to ${task.assignedWorkerId}`
165
+ : task.status === "pending"
166
+ ? hasOnDemandWorkerProvisioning(config)
167
+ ? " (pending - waiting for worker provisioning or an available worker)"
168
+ : " (pending - no registered/available worker)"
169
+ : "";
170
+ const recommended = Array.isArray(task.recommendedSkills) && task.recommendedSkills.length > 0
171
+ ? ` | skills: ${task.recommendedSkills.join(", ")}`
172
+ : "";
173
+ return {
174
+ details: {},
175
+ content: [{
176
+ type: "text",
177
+ text: `Task created: ${task.title} [${task.id}] [${task.priority}]${assigned}${recommended}`,
178
+ }],
179
+ };
180
+ }
181
+ catch (err) {
182
+ return { details: {}, content: [{ type: "text", text: `Error: ${err instanceof Error ? err.message : String(err)}` }] };
183
+ }
184
+ },
185
+ },
186
+ {
187
+ name: "teamclaw_submit_manifest",
188
+ label: "Submit Controller Manifest",
189
+ description: "Record the structured orchestration manifest for this intake run after role selection and task creation decisions are complete",
190
+ parameters: Type.Object({
191
+ projectName: Type.Optional(Type.String({ description: "Short, lowercase, kebab-case project name for the workspace directory (e.g. 'todo-rest-api', 'stripe-payment-integration'). 2-5 words max, no random suffixes." })),
192
+ requirementSummary: Type.String({ description: "Brief summary of the requirement the controller is orchestrating" }),
193
+ requiredRoles: Type.Array(Type.String({
194
+ description: "Exact TeamClaw role IDs required for this requirement",
195
+ })),
196
+ clarificationsNeeded: Type.Optional(Type.Boolean({ description: "Whether the controller still needs human clarification" })),
197
+ clarificationQuestions: Type.Optional(Type.Array(Type.String({ description: "Concrete clarification questions still waiting on the human" }))),
198
+ clarificationSchemas: Type.Optional(Type.Array(Type.Object({
199
+ kind: Type.String({ description: "Question kind: single-select, multi-select, number, or text" }),
200
+ title: Type.String({ description: "Question title shown to the human" }),
201
+ description: Type.Optional(Type.String({ description: "Optional supporting context for the question" })),
202
+ required: Type.Optional(Type.Boolean({ description: "Whether the human must answer this question before continuing" })),
203
+ options: Type.Optional(Type.Array(Type.Object({
204
+ value: Type.String({ description: "Stable option value" }),
205
+ label: Type.String({ description: "Human-visible option label" }),
206
+ hint: Type.Optional(Type.String({ description: "Optional helper text for this option" })),
207
+ }))),
208
+ allowOther: Type.Optional(Type.Boolean({ description: "Whether freeform 'other' text is allowed alongside options" })),
209
+ placeholder: Type.Optional(Type.String({ description: "Optional placeholder or hint for text/number input" })),
210
+ unit: Type.Optional(Type.String({ description: "Optional unit label for number questions" })),
211
+ min: Type.Optional(Type.Number({ description: "Optional minimum numeric value" })),
212
+ max: Type.Optional(Type.Number({ description: "Optional maximum numeric value" })),
213
+ step: Type.Optional(Type.Number({ description: "Optional numeric step size" })),
214
+ }))),
215
+ createdTasks: Type.Optional(Type.Array(Type.Object({
216
+ title: Type.String({ description: "Title of an execution-ready task this controller run created or deliberately reused instead of duplicating" }),
217
+ assignedRole: Type.Optional(Type.String({ description: "Exact TeamClaw role ID for the created task" })),
218
+ expectedOutcome: Type.String({ description: "Expected deliverable/result for the created task" }),
219
+ }))),
220
+ deferredTasks: Type.Optional(Type.Array(Type.Object({
221
+ title: Type.String({ description: "Title of a task that should wait for later" }),
222
+ assignedRole: Type.Optional(Type.String({ description: "Exact TeamClaw role ID for the deferred task" })),
223
+ blockedBy: Type.String({ description: "Why this deferred task cannot be created yet" }),
224
+ whenReady: Type.String({ description: "Condition that should become true before this deferred task is created" }),
225
+ }))),
226
+ handoffPlan: Type.Optional(Type.String({ description: "Brief note about how workers should report progress/handoffs across this flow" })),
227
+ notes: Type.Optional(Type.String({ description: "Additional orchestration notes for the human/controller log" })),
228
+ completionOpportunities: Type.Optional(Type.Array(Type.Object({
229
+ title: Type.String({ description: "Human-facing label for an adjacent optional next step after delivery" }),
230
+ value: Type.String({ description: "Stable option value for this next step" }),
231
+ summary: Type.String({ description: "What TeamClaw could continue doing if selected" }),
232
+ }))),
233
+ requirementFullyComplete: Type.Optional(Type.Boolean({ description: "Set to true when the entire human requirement is fully satisfied — all tasks completed, no deferred tasks remaining, no follow-ups needed" })),
234
+ }),
235
+ async execute(_id, params) {
236
+ const normalizedSessionKey = typeof sessionKey === "string" ? sessionKey.trim() : "";
237
+ if (!normalizedSessionKey) {
238
+ return {
239
+ details: {},
240
+ content: [{
241
+ type: "text",
242
+ text: "Cannot record controller manifest because the current TeamClaw controller session key is missing.",
243
+ }],
244
+ };
245
+ }
246
+ const requirementSummary = String(params.requirementSummary ?? "").trim();
247
+ if (!requirementSummary) {
248
+ return { details: {}, content: [{ type: "text", text: "requirementSummary is required." }] };
249
+ }
250
+ const clarificationSchemas = normalizeClarificationQuestionSchemas(params.clarificationSchemas);
251
+ const clarificationQuestions = normalizeManifestStringList(params.clarificationQuestions);
252
+ const manifest = {
253
+ version: "1.0",
254
+ projectName: normalizeOptionalManifestText(params.projectName) || undefined,
255
+ requirementSummary,
256
+ requiredRoles: normalizeManifestRoleList(params.requiredRoles),
257
+ clarificationsNeeded: Boolean(params.clarificationsNeeded),
258
+ clarificationQuestions: clarificationQuestions.length > 0 ? clarificationQuestions : clarificationSchemas.map((entry) => entry.title),
259
+ clarificationSchemas,
260
+ createdTasks: normalizeManifestCreatedTasks(params.createdTasks),
261
+ deferredTasks: normalizeManifestDeferredTasks(params.deferredTasks),
262
+ handoffPlan: normalizeOptionalManifestText(params.handoffPlan),
263
+ notes: normalizeOptionalManifestText(params.notes),
264
+ completionOpportunities: normalizeManifestCompletionOpportunities(params.completionOpportunities),
265
+ requirementFullyComplete: Boolean(params.requirementFullyComplete),
266
+ };
267
+ try {
268
+ const res = await fetch(`${baseUrl}/api/v1/controller/manifest`, {
269
+ method: "POST",
270
+ headers: { "Content-Type": "application/json" },
271
+ body: JSON.stringify({
272
+ sessionKey: normalizedSessionKey,
273
+ manifest,
274
+ }),
275
+ });
276
+ if (!res.ok) {
277
+ const err = await res.text();
278
+ return { details: {}, content: [{ type: "text", text: `Failed to record controller manifest: ${err}` }] };
279
+ }
280
+ return {
281
+ details: {},
282
+ content: [{
283
+ type: "text",
284
+ text: `Controller manifest recorded: roles=${manifest.requiredRoles.join(", ") || "none"} created=${manifest.createdTasks.length} deferred=${manifest.deferredTasks.length}${manifest.requirementFullyComplete ? " requirementFullyComplete=true" : ""}`,
285
+ }],
286
+ };
287
+ }
288
+ catch (err) {
289
+ return { details: {}, content: [{ type: "text", text: `Error: ${err instanceof Error ? err.message : String(err)}` }] };
290
+ }
291
+ },
292
+ },
293
+ {
294
+ name: "teamclaw_list_tasks",
295
+ label: "List Team Tasks",
296
+ description: "List all tasks with optional status filter",
297
+ parameters: Type.Object({
298
+ status: Type.Optional(Type.String({ description: "Filter by status: pending, assigned, in_progress, review, blocked, completed, failed" })),
299
+ }),
300
+ async execute(_id, params) {
301
+ const status = typeof params.status === "string" ? params.status : undefined;
302
+ try {
303
+ const url = new URL(`${baseUrl}/api/v1/tasks`);
304
+ if (status)
305
+ url.searchParams.set("status", status);
306
+ const res = await fetch(url.toString());
307
+ if (!res.ok) {
308
+ return { details: {}, content: [{ type: "text", text: `Failed to list tasks: ${res.status}` }] };
309
+ }
310
+ const data = await res.json();
311
+ if (data.tasks.length === 0) {
312
+ return { details: {}, content: [{ type: "text", text: "No tasks found." }] };
313
+ }
314
+ const lines = data.tasks.map((t) => {
315
+ const assignee = t.assignedWorkerId ? ` -> ${t.assignedWorkerId.slice(0, 8)}` : "";
316
+ return `[${t.status}] ${t.priority.toUpperCase()} ${t.title} (${t.id})${assignee}`;
317
+ });
318
+ return { details: {}, content: [{ type: "text", text: lines.join("\n") }] };
319
+ }
320
+ catch (err) {
321
+ return { details: {}, content: [{ type: "text", text: `Error: ${err instanceof Error ? err.message : String(err)}` }] };
322
+ }
323
+ },
324
+ },
325
+ {
326
+ name: "teamclaw_assign_task",
327
+ label: "Assign Team Task",
328
+ description: "Assign a task to a specific worker or let the router decide",
329
+ parameters: Type.Object({
330
+ taskId: Type.String({ description: "Task ID to assign" }),
331
+ workerId: Type.Optional(Type.String({ description: "Specific worker ID (omit for auto-routing)" })),
332
+ }),
333
+ async execute(_id, params) {
334
+ const taskId = String(params.taskId ?? "");
335
+ if (!taskId) {
336
+ return { details: {}, content: [{ type: "text", text: "taskId is required." }] };
337
+ }
338
+ try {
339
+ const body = {};
340
+ if (params.workerId)
341
+ body.workerId = params.workerId;
342
+ const res = await fetch(`${baseUrl}/api/v1/tasks/${taskId}/assign`, {
343
+ method: "POST",
344
+ headers: { "Content-Type": "application/json" },
345
+ body: JSON.stringify(body),
346
+ });
347
+ if (!res.ok) {
348
+ const err = await res.text();
349
+ return { details: {}, content: [{ type: "text", text: `Failed to assign task: ${err}` }] };
350
+ }
351
+ const data = await res.json();
352
+ const worker = data.worker;
353
+ const workerInfo = worker ? ` assigned to ${worker.label} (${worker.id})` : " (no available worker)";
354
+ return { details: {}, content: [{ type: "text", text: `Task assigned: ${data.task.title}${workerInfo}` }] };
355
+ }
356
+ catch (err) {
357
+ return { details: {}, content: [{ type: "text", text: `Error: ${err instanceof Error ? err.message : String(err)}` }] };
358
+ }
359
+ },
360
+ },
361
+ {
362
+ name: "teamclaw_send_message",
363
+ label: "Send Team Message",
364
+ description: "Send a direct message or broadcast to team members after requirement analysis when coordination is actually needed",
365
+ parameters: Type.Object({
366
+ content: Type.String({ description: "Message content" }),
367
+ toRole: Type.Optional(Type.String({ description: "Target role for direct message (omit for broadcast)" })),
368
+ taskId: Type.Optional(Type.String({ description: "Related task ID" })),
369
+ summary: Type.Optional(Type.String({ description: "Short structured summary for this coordination message" })),
370
+ details: Type.Optional(Type.String({ description: "Optional extra context for the receiving worker(s)" })),
371
+ requestedAction: Type.Optional(Type.String({ description: "Concrete action expected after reading the message" })),
372
+ needsResponse: Type.Optional(Type.Boolean({ description: "Whether this message expects a direct response" })),
373
+ references: Type.Optional(Type.Array(Type.String({ description: "Relevant task IDs, files, or artifacts" }))),
374
+ }),
375
+ async execute(_id, params) {
376
+ const content = String(params.content ?? "");
377
+ if (!content) {
378
+ return { details: {}, content: [{ type: "text", text: "content is required." }] };
379
+ }
380
+ try {
381
+ const normalizedTargetRole = normalizeContractRole(params.toRole);
382
+ const endpoint = params.toRole
383
+ ? `${baseUrl}/api/v1/messages/direct`
384
+ : `${baseUrl}/api/v1/messages/broadcast`;
385
+ const contract = ensureTeamMessageContract(null, {
386
+ type: params.toRole ? "direct" : "broadcast",
387
+ content,
388
+ toRole: normalizedTargetRole,
389
+ taskId: typeof params.taskId === "string" ? params.taskId : undefined,
390
+ summary: typeof params.summary === "string" ? params.summary : undefined,
391
+ details: typeof params.details === "string" ? params.details : undefined,
392
+ requestedAction: typeof params.requestedAction === "string" ? params.requestedAction : undefined,
393
+ needsResponse: typeof params.needsResponse === "boolean" ? params.needsResponse : undefined,
394
+ references: normalizeContractStringList(params.references),
395
+ intent: params.toRole ? undefined : "announcement",
396
+ });
397
+ const body = {
398
+ from: "controller",
399
+ content,
400
+ taskId: params.taskId ?? null,
401
+ contract,
402
+ };
403
+ if (params.toRole)
404
+ body.toRole = params.toRole;
405
+ const res = await fetch(endpoint, {
406
+ method: "POST",
407
+ headers: { "Content-Type": "application/json" },
408
+ body: JSON.stringify(body),
409
+ });
410
+ if (!res.ok) {
411
+ return { details: {}, content: [{ type: "text", text: `Failed to send message: ${res.status}` }] };
412
+ }
413
+ const data = await res.json();
414
+ if (params.toRole) {
415
+ return { details: {}, content: [{ type: "text", text: `Message sent to ${params.toRole}: ${data.status}` }] };
416
+ }
417
+ return { details: {}, content: [{ type: "text", text: `Broadcast sent to ${data.recipients ?? 0} recipients` }] };
418
+ }
419
+ catch (err) {
420
+ return { details: {}, content: [{ type: "text", text: `Error: ${err instanceof Error ? err.message : String(err)}` }] };
421
+ }
422
+ },
423
+ },
424
+ {
425
+ name: "teamclaw_teamauto_status",
426
+ label: "TeamAuto Status",
427
+ description: "List TeamAuto-managed repositories with their schedule, full-review cadence, pause state, and recent activity. Use this to discover which repos this controller autonomously maintains before proposing improvements to them.",
428
+ parameters: Type.Object({}),
429
+ async execute(_id, _params) {
430
+ const scheduler = deps.getTeamAutoScheduler?.();
431
+ if (!scheduler) {
432
+ return { details: {}, content: [{ type: "text", text: "TeamAuto is not active on this controller." }] };
433
+ }
434
+ const status = await scheduler.getStatus();
435
+ const activity = (await scheduler.getActivity()).slice(-10).map((e) => `${new Date(e.at).toISOString().slice(11, 19)} ${e.repoId ?? ""} ${e.text}`);
436
+ return { details: {}, content: [{ type: "text", text: `TeamAuto repos:\n${JSON.stringify(status, null, 2)}\nRecent activity:\n${activity.join("\n") || "(none)"}` }] };
437
+ },
438
+ },
439
+ {
440
+ name: "teamclaw_teamauto_sweep",
441
+ label: "TeamAuto Sweep Now",
442
+ description: "Trigger an immediate TeamAuto sweep of a bound repository (scans GitHub issues/PRs and creates review/ownership tasks) instead of waiting for the next cron tick.",
443
+ parameters: Type.Object({
444
+ repoId: Type.String({ description: "Bound repository id in owner/name form, e.g. topcheer/teamclaw" }),
445
+ }),
446
+ async execute(_id, params) {
447
+ const scheduler = deps.getTeamAutoScheduler?.();
448
+ if (!scheduler) {
449
+ return { details: {}, content: [{ type: "text", text: "TeamAuto is not active on this controller." }] };
450
+ }
451
+ try {
452
+ const summary = await scheduler.runSweepNow(String(params.repoId ?? ""), true);
453
+ return { details: {}, content: [{ type: "text", text: `Sweep done: ${summary}` }] };
454
+ }
455
+ catch (err) {
456
+ return { details: {}, content: [{ type: "text", text: `Sweep failed: ${err instanceof Error ? err.message : String(err)}` }] };
457
+ }
458
+ },
459
+ },
460
+ {
461
+ name: "teamclaw_teamauto_propose",
462
+ label: "TeamAuto Propose",
463
+ description: "Inject a manual work proposal into a TeamAuto-managed repository. The proposal flows through the normal TeamAuto task pipeline (dedup, failure caps, norms, worktree checkout, worker assignment) - no GitHub object is required. Prefer this over teamclaw_create_task when the target repo is TeamAuto-managed so the work inherits its governance.",
464
+ parameters: Type.Object({
465
+ repoId: Type.String({ description: "Bound repository id in owner/name form" }),
466
+ kind: Type.String({ description: "Candidate kind: issueReview, prReview, takeOwnership (write path), or fullReview" }),
467
+ title: Type.String({ description: "Short task title" }),
468
+ context: Type.String({ description: "Full task instructions: goal, scope, constraints, expected deliverable" }),
469
+ role: Type.Optional(Type.String({ description: "Target role id; defaults to developer for takeOwnership, architect otherwise" })),
470
+ writeMode: Type.Optional(Type.String({ description: "read-only (default) or write; takeOwnership defaults to write" })),
471
+ }),
472
+ async execute(_id, params) {
473
+ const scheduler = deps.getTeamAutoScheduler?.();
474
+ if (!scheduler) {
475
+ return { details: {}, content: [{ type: "text", text: "TeamAuto is not active on this controller." }] };
476
+ }
477
+ const writeMode = params.writeMode === "write" ? "write" : params.writeMode === "read-only" ? "read-only" : undefined;
478
+ try {
479
+ const result = await scheduler.proposeManual(String(params.repoId ?? ""), {
480
+ kind: String(params.kind ?? "issueReview"),
481
+ title: String(params.title ?? ""),
482
+ context: String(params.context ?? ""),
483
+ role: params.role ? String(params.role) : undefined,
484
+ writeMode,
485
+ });
486
+ if (result === "duplicate-active-skipped") {
487
+ return { details: {}, content: [{ type: "text", text: "Skipped: an active task for this proposal key already exists." }] };
488
+ }
489
+ return { details: {}, content: [{ type: "text", text: `TeamAuto task created: ${result}` }] };
490
+ }
491
+ catch (err) {
492
+ return { details: {}, content: [{ type: "text", text: `Proposal failed: ${err instanceof Error ? err.message : String(err)}` }] };
493
+ }
494
+ },
495
+ },
496
+ ];
497
+ }
498
+ function detectExecutionReadyBlocker(description) {
499
+ const text = description.trim();
500
+ if (!text) {
501
+ return null;
502
+ }
503
+ for (const blocker of EXECUTION_READY_BLOCKERS) {
504
+ if (blocker.pattern.test(text)) {
505
+ return blocker.reason;
506
+ }
507
+ }
508
+ const laterPhaseBlocker = detectLaterPhasePhrase(text);
509
+ if (laterPhaseBlocker) {
510
+ return laterPhaseBlocker;
511
+ }
512
+ return null;
513
+ }
514
+ function detectLaterPhasePhrase(text) {
515
+ const lines = text
516
+ .split(/\r?\n/)
517
+ .map((line) => line.trim())
518
+ .filter(Boolean);
519
+ for (const line of lines) {
520
+ const englishMatch = line.match(ENGLISH_LATER_PHASE_CLAUSE_RE);
521
+ if (englishMatch) {
522
+ const dependencyClause = englishMatch[1] ?? "";
523
+ if (ENGLISH_LATER_PHASE_DEPENDENCY_RE.test(dependencyClause) || SERVICE_NAME_RE.test(dependencyClause)) {
524
+ return "it is described as work for a later phase";
525
+ }
526
+ }
527
+ const chineseMatch = line.match(CHINESE_LATER_PHASE_CLAUSE_RE);
528
+ if (chineseMatch) {
529
+ const dependencyClause = chineseMatch[1] ?? "";
530
+ if (CHINESE_LATER_PHASE_DEPENDENCY_RE.test(dependencyClause) || SERVICE_NAME_RE.test(dependencyClause)) {
531
+ return "it is described as work for a later phase";
532
+ }
533
+ }
534
+ }
535
+ return null;
536
+ }
537
+ function detectActiveTaskOverlap(title, description, state) {
538
+ if (!state) {
539
+ return null;
540
+ }
541
+ const scopeText = `${title}\n${description}`;
542
+ const serviceNames = extractServiceNames(scopeText);
543
+ const repoWideCodeChange = serviceNames.size === 0
544
+ && REPO_WIDE_CODE_CHANGE_RE.test(scopeText)
545
+ && !DOC_ONLY_SCOPE_RE.test(scopeText);
546
+ if (serviceNames.size === 0 && !repoWideCodeChange) {
547
+ return null;
548
+ }
549
+ const overlappingTasks = Object.values(state.tasks).filter((task) => {
550
+ if (!ACTIVE_TASK_STATUSES.has(task.status)) {
551
+ return false;
552
+ }
553
+ const taskScope = `${task.title}\n${task.description}`;
554
+ const taskServiceNames = extractServiceNames(taskScope);
555
+ if (serviceNames.size > 0) {
556
+ return [...serviceNames].some((serviceName) => taskServiceNames.has(serviceName));
557
+ }
558
+ if (taskServiceNames.size > 0) {
559
+ return true;
560
+ }
561
+ return REPO_WIDE_CODE_CHANGE_RE.test(taskScope) && !DOC_ONLY_SCOPE_RE.test(taskScope);
562
+ });
563
+ if (overlappingTasks.length === 0) {
564
+ return null;
565
+ }
566
+ const overlappingServices = new Set();
567
+ for (const task of overlappingTasks) {
568
+ for (const serviceName of extractServiceNames(`${task.title}\n${task.description}`)) {
569
+ overlappingServices.add(serviceName);
570
+ }
571
+ }
572
+ if (overlappingServices.size > 0) {
573
+ return `it overlaps with active TeamClaw work on ${[...overlappingServices].slice(0, 3).join(", ")}`;
574
+ }
575
+ return `it overlaps with active TeamClaw repo-wide code changes (${overlappingTasks[0]?.title ?? "another active task"})`;
576
+ }
577
+ function extractServiceNames(text) {
578
+ const normalized = String(text || "");
579
+ return new Set(Array.from(normalized.matchAll(SERVICE_NAME_GLOBAL_RE))
580
+ .map((match) => String(match[0] || "").trim().toLowerCase())
581
+ .filter(Boolean));
582
+ }