@teamclaws/teamclaw 2026.11.0 → 2026.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/cli.mjs +272 -2
  2. package/dist/index.js +54 -32
  3. package/dist/src/config.js +24 -0
  4. package/dist/src/controller/auth-routes.js +129 -0
  5. package/dist/src/controller/clarification-routes.js +1 -1
  6. package/dist/src/controller/controller-planning.js +1 -0
  7. package/dist/src/controller/controller-routes.js +195 -0
  8. package/dist/src/controller/controller-service.js +67 -10
  9. package/dist/src/controller/controller-tools.js +3 -1
  10. package/dist/src/controller/github-auth.js +2 -1
  11. package/dist/src/controller/http-server.js +51 -16
  12. package/dist/src/controller/kickoff-orchestrator.js +3 -39
  13. package/dist/src/controller/message-delivery.js +4 -1
  14. package/dist/src/controller/orchestration-manifest.js +5 -65
  15. package/dist/src/controller/preview-manager.js +51 -3
  16. package/dist/src/controller/profile-switch.js +42 -22
  17. package/dist/src/controller/provisioning/backend-contract.js +9 -0
  18. package/dist/src/controller/provisioning/container-shared.js +64 -0
  19. package/dist/src/controller/provisioning/docker.js +214 -0
  20. package/dist/src/controller/provisioning/kubernetes.js +244 -0
  21. package/dist/src/controller/provisioning/plugin-root.js +41 -0
  22. package/dist/src/controller/provisioning/process-supervisor.js +190 -0
  23. package/dist/src/controller/provisioning-config.js +239 -0
  24. package/dist/src/controller/repo-routes.js +70 -4
  25. package/dist/src/controller/report-routes.js +56 -0
  26. package/dist/src/controller/route-table.js +67 -1045
  27. package/dist/src/controller/security.js +775 -0
  28. package/dist/src/controller/status-routes.js +287 -0
  29. package/dist/src/controller/task-assignment.js +5 -2
  30. package/dist/src/controller/task-execution.js +31 -0
  31. package/dist/src/controller/task-results.js +10 -0
  32. package/dist/src/controller/tunnel-manager.js +41 -8
  33. package/dist/src/controller/tunnel-routes.js +225 -0
  34. package/dist/src/controller/websocket.js +6 -2
  35. package/dist/src/controller/webui-routes.js +49 -0
  36. package/dist/src/controller/worker-provisioning.js +39 -949
  37. package/dist/src/controller/workflow-routes.js +407 -0
  38. package/dist/src/controller/workspace-routes.js +200 -0
  39. package/dist/src/git-collaboration.js +4 -9
  40. package/dist/src/identity.js +12 -1
  41. package/dist/src/profile-loader.js +119 -1
  42. package/dist/src/profiles/banking.json +26 -2
  43. package/dist/src/profiles/schema.json +82 -2
  44. package/dist/src/prompt-policy.js +18 -6
  45. package/dist/src/protocol.js +66 -3
  46. package/dist/src/shared/clarification-schema.js +65 -0
  47. package/dist/src/shared/github-auth.js +15 -0
  48. package/dist/src/shared/kickoff-prompt.js +37 -0
  49. package/dist/src/shared/utils.js +47 -0
  50. package/dist/src/state.js +89 -3
  51. package/dist/src/types.js +15 -1
  52. package/dist/src/ui/app.js +846 -62
  53. package/dist/src/ui/github-login.html +1 -0
  54. package/dist/src/ui/index.html +102 -36
  55. package/dist/src/worker/http-handler.js +59 -0
  56. package/dist/src/worker/skill-installer.js +3 -9
  57. package/dist/src/worker/tools.js +20 -10
  58. package/dist/src/worker/worker-service.js +17 -4
  59. package/index.ts +61 -32
  60. package/openclaw.plugin.json +23 -2
  61. package/package.json +1 -1
  62. package/src/config.ts +24 -0
  63. package/src/controller/auth-routes.ts +157 -0
  64. package/src/controller/clarification-routes.ts +1 -1
  65. package/src/controller/controller-planning.ts +8 -0
  66. package/src/controller/controller-routes.ts +237 -0
  67. package/src/controller/controller-service.ts +128 -10
  68. package/src/controller/controller-tools.ts +5 -2
  69. package/src/controller/github-auth.ts +28 -63
  70. package/src/controller/http-server.ts +66 -17
  71. package/src/controller/kickoff-orchestrator.ts +3 -42
  72. package/src/controller/message-delivery.ts +4 -1
  73. package/src/controller/orchestration-manifest.ts +8 -71
  74. package/src/controller/preview-manager.ts +53 -3
  75. package/src/controller/profile-switch.ts +53 -23
  76. package/src/controller/provisioning/backend-contract.ts +51 -0
  77. package/src/controller/provisioning/container-shared.ts +84 -0
  78. package/src/controller/provisioning/docker.ts +260 -0
  79. package/src/controller/provisioning/kubernetes.ts +263 -0
  80. package/src/controller/provisioning/plugin-root.ts +42 -0
  81. package/src/controller/provisioning/process-supervisor.ts +214 -0
  82. package/src/controller/provisioning-config.ts +289 -0
  83. package/src/controller/repo-routes.ts +84 -12
  84. package/src/controller/report-routes.ts +64 -0
  85. package/src/controller/route-table.ts +133 -1152
  86. package/src/controller/security.ts +899 -0
  87. package/src/controller/status-routes.ts +354 -0
  88. package/src/controller/task-assignment.ts +5 -1
  89. package/src/controller/task-execution.ts +43 -0
  90. package/src/controller/task-results.ts +12 -0
  91. package/src/controller/tunnel-manager.ts +45 -8
  92. package/src/controller/tunnel-routes.ts +231 -0
  93. package/src/controller/websocket.ts +19 -3
  94. package/src/controller/webui-routes.ts +55 -0
  95. package/src/controller/worker-provisioning.ts +51 -1117
  96. package/src/controller/workflow-routes.ts +498 -0
  97. package/src/controller/workspace-routes.ts +222 -0
  98. package/src/git-collaboration.ts +4 -9
  99. package/src/identity.ts +13 -1
  100. package/src/profile-loader.ts +167 -1
  101. package/src/profiles/banking.json +26 -2
  102. package/src/profiles/schema.json +82 -2
  103. package/src/prompt-policy.ts +19 -6
  104. package/src/protocol.ts +72 -2
  105. package/src/shared/clarification-schema.ts +81 -0
  106. package/src/shared/github-auth.ts +92 -0
  107. package/src/shared/kickoff-prompt.ts +47 -0
  108. package/src/shared/utils.ts +51 -0
  109. package/src/state.ts +92 -3
  110. package/src/teamauto/github-client.ts +2 -1
  111. package/src/teamauto/repo-sync.ts +2 -1
  112. package/src/teamauto/scheduler.ts +2 -1
  113. package/src/types.ts +130 -1
  114. package/src/ui/app.js +846 -62
  115. package/src/ui/github-login.html +1 -0
  116. package/src/ui/index.html +102 -36
  117. package/src/worker/http-handler.ts +64 -1
  118. package/src/worker/skill-installer.ts +3 -9
  119. package/src/worker/tools.ts +21 -10
  120. package/src/worker/worker-service.ts +18 -4
@@ -0,0 +1,222 @@
1
+ // Issue #226 W2 (route-table carve-up): the workspace browser + model-config
2
+ // route handlers (plus their private error-mapping helpers) moved verbatim
3
+ // from route-table.ts (PR-D had moved them verbatim from http-server.ts
4
+ // before that) - bodies byte-identical, only the module home changed.
5
+ // route-table.ts keeps the table entries that bind these handlers. Like
6
+ // security.ts, this module imports route-table.js as TYPE ONLY
7
+ // (RouteContext), so the module graph stays acyclic.
8
+ import fs from "node:fs";
9
+ import { parseJsonBody, sendJson, sendError, pinnedCorsAllowOrigin } from "../protocol.js";
10
+ import { listWorkspaceTree, listWorkspaceSubtree, readWorkspaceFile, readWorkspaceRawFile } from "../workspace-browser.js";
11
+ import {
12
+ teamClawWorkspaceIsDefault,
13
+ updateTeamClawWorkspaceDir,
14
+ getTeamClawModelCatalog,
15
+ updateTeamClawModelConfig,
16
+ resolveTeamClawWorkspaceDir,
17
+ } from "../openclaw-workspace.js";
18
+ import { resolveSafeProjectDirectory } from "./task-cleanup.js";
19
+ import type { RouteContext } from "./route-table.js";
20
+
21
+ function workspaceRequestErrorStatus(err: unknown): number {
22
+ if (err && typeof err === "object" && "code" in err && (err as { code?: unknown }).code === "ENOENT") {
23
+ return 404;
24
+ }
25
+ return 400;
26
+ }
27
+
28
+ function workspaceRequestErrorMessage(err: unknown): string {
29
+ return err instanceof Error ? err.message : "Workspace request failed";
30
+ }
31
+
32
+ function workspaceStatusRoute(ctx: RouteContext): void {
33
+ const { res } = ctx;
34
+ sendJson(res, 200, {
35
+ workspaceDir: resolveTeamClawWorkspaceDir(),
36
+ isDefault: teamClawWorkspaceIsDefault(),
37
+ });
38
+ }
39
+
40
+ async function workspaceChangeDirRoute(ctx: RouteContext): Promise<void> {
41
+ const { req, res, deps } = ctx;
42
+ let body: unknown;
43
+ try {
44
+ body = await parseJsonBody(req);
45
+ } catch {
46
+ sendError(res, 400, "invalid JSON body");
47
+ return;
48
+ }
49
+ const workspaceDir = typeof (body as { workspaceDir?: unknown })?.workspaceDir === "string"
50
+ ? (body as { workspaceDir: string }).workspaceDir
51
+ : "";
52
+ if (!workspaceDir.trim()) {
53
+ sendError(res, 400, "workspaceDir is required");
54
+ return;
55
+ }
56
+ try {
57
+ const result = await updateTeamClawWorkspaceDir(workspaceDir, {
58
+ warn: (message: string) => deps.logger.info(message),
59
+ });
60
+ sendJson(res, 200, {
61
+ ok: true,
62
+ workspaceDir: result.agentEntryPath,
63
+ configPath: result.configPath,
64
+ restartRequired: true,
65
+ });
66
+ } catch (err) {
67
+ sendError(res, 400, err instanceof Error ? err.message : "failed to update workspace directory");
68
+ }
69
+ }
70
+
71
+ // GET /api/v1/models/config - model catalog + current selection for the UI settings dialog
72
+ async function modelsConfigGetRoute(ctx: RouteContext): Promise<void> {
73
+ const { res } = ctx;
74
+ try {
75
+ sendJson(res, 200, await getTeamClawModelCatalog());
76
+ } catch (err) {
77
+ sendError(res, 500, err instanceof Error ? err.message : "failed to read model configuration");
78
+ }
79
+ }
80
+
81
+ // PUT /api/v1/models/config - persist default and per-role model selection
82
+ async function modelsConfigPutRoute(ctx: RouteContext): Promise<void> {
83
+ const { req, res, deps } = ctx;
84
+ let body: { defaultModel?: unknown; roleModelOverrides?: unknown } | null = null;
85
+ try {
86
+ body = await parseJsonBody(req) as { defaultModel?: unknown; roleModelOverrides?: unknown };
87
+ } catch {
88
+ sendError(res, 400, "invalid JSON body");
89
+ return;
90
+ }
91
+ const update: { defaultModel?: string; roleModelOverrides?: Record<string, string> } = {};
92
+ if (typeof body?.defaultModel === "string") {
93
+ update.defaultModel = body.defaultModel.trim();
94
+ }
95
+ if (body?.roleModelOverrides && typeof body.roleModelOverrides === "object" && !Array.isArray(body.roleModelOverrides)) {
96
+ const overrides: Record<string, string> = {};
97
+ for (const [role, value] of Object.entries(body.roleModelOverrides as Record<string, unknown>)) {
98
+ if (typeof value === "string" && value.trim()) {
99
+ overrides[role] = value.trim();
100
+ }
101
+ }
102
+ update.roleModelOverrides = overrides;
103
+ }
104
+ if (update.defaultModel === undefined && update.roleModelOverrides === undefined) {
105
+ sendError(res, 400, "defaultModel or roleModelOverrides is required");
106
+ return;
107
+ }
108
+ try {
109
+ await updateTeamClawModelConfig(update, {
110
+ warn: (message: string) => deps.logger.info(message),
111
+ });
112
+ sendJson(res, 200, {
113
+ ok: true,
114
+ restartNote: "Config changes hot-reload; restart the gateway (openclaw gateway restart) if a change does not take effect.",
115
+ catalog: await getTeamClawModelCatalog(),
116
+ });
117
+ } catch (err) {
118
+ sendError(res, 400, err instanceof Error ? err.message : "failed to update model configuration");
119
+ }
120
+ }
121
+
122
+ async function workspaceTreeRoute(ctx: RouteContext): Promise<void> {
123
+ const { res, requestUrl } = ctx;
124
+ try {
125
+ // depth=N limits tree expansion (default 1 for lazy loading)
126
+ const depthParam = requestUrl.searchParams.get("depth");
127
+ const maxDepth = depthParam !== null ? Math.max(0, Math.min(parseInt(depthParam, 10) || 1, 8)) : 1;
128
+ sendJson(res, 200, await listWorkspaceTree(maxDepth));
129
+ } catch (err) {
130
+ sendError(res, workspaceRequestErrorStatus(err), workspaceRequestErrorMessage(err));
131
+ }
132
+ }
133
+
134
+ async function workspaceSubtreeRoute(ctx: RouteContext): Promise<void> {
135
+ const { res, requestUrl } = ctx;
136
+ const dirPath = requestUrl.searchParams.get("path") ?? "";
137
+ if (!dirPath) {
138
+ sendError(res, 400, "path is required");
139
+ return;
140
+ }
141
+ try {
142
+ sendJson(res, 200, { entries: await listWorkspaceSubtree(dirPath) });
143
+ } catch (err) {
144
+ sendError(res, workspaceRequestErrorStatus(err), workspaceRequestErrorMessage(err));
145
+ }
146
+ }
147
+
148
+ async function workspaceFileRoute(ctx: RouteContext): Promise<void> {
149
+ const { res, requestUrl } = ctx;
150
+ const relativePath = requestUrl.searchParams.get("path") ?? "";
151
+ if (!relativePath) {
152
+ sendError(res, 400, "path is required");
153
+ return;
154
+ }
155
+
156
+ try {
157
+ sendJson(res, 200, { file: await readWorkspaceFile(relativePath) });
158
+ } catch (err) {
159
+ sendError(res, workspaceRequestErrorStatus(err), workspaceRequestErrorMessage(err));
160
+ }
161
+ }
162
+
163
+ async function workspaceProjectPathRoute(ctx: RouteContext): Promise<void> {
164
+ const { res, requestUrl } = ctx;
165
+ const projectDir = requestUrl.searchParams.get("projectDir") ?? "";
166
+ if (!projectDir) {
167
+ sendError(res, 400, "projectDir is required");
168
+ return;
169
+ }
170
+ const absolutePath = resolveSafeProjectDirectory(projectDir);
171
+ if (!absolutePath) {
172
+ sendError(res, 400, "Invalid projectDir");
173
+ return;
174
+ }
175
+ if (!fs.existsSync(absolutePath)) {
176
+ sendError(res, 404, "Project directory not found");
177
+ return;
178
+ }
179
+ sendJson(res, 200, {
180
+ projectDir,
181
+ absolutePath,
182
+ });
183
+ }
184
+
185
+ async function workspaceRawFileRoute(ctx: RouteContext): Promise<void> {
186
+ const { res, pathname } = ctx;
187
+ const rawPathname = pathname.slice("/api/v1/workspace/raw/".length);
188
+ if (!rawPathname) {
189
+ sendError(res, 400, "path is required");
190
+ return;
191
+ }
192
+
193
+ try {
194
+ const relativePath = decodeURIComponent(rawPathname);
195
+ const file = await readWorkspaceRawFile(relativePath);
196
+ res.writeHead(200, {
197
+ "Content-Type": file.contentType,
198
+ "Cache-Control": "no-store",
199
+ // Issue #23 security review follow-up: honor a CORS origin the
200
+ // security gate pinned (device protection on) instead of hardcoding
201
+ // the wildcard, which silently widened it; unpinned keeps the
202
+ // historical "*" byte for byte (shared helper, see protocol.ts).
203
+ "Access-Control-Allow-Origin": pinnedCorsAllowOrigin(res),
204
+ "X-Content-Type-Options": "nosniff",
205
+ });
206
+ res.end(file.content);
207
+ } catch (err) {
208
+ sendError(res, workspaceRequestErrorStatus(err), workspaceRequestErrorMessage(err));
209
+ }
210
+ }
211
+
212
+ export {
213
+ workspaceStatusRoute,
214
+ workspaceChangeDirRoute,
215
+ modelsConfigGetRoute,
216
+ modelsConfigPutRoute,
217
+ workspaceTreeRoute,
218
+ workspaceSubtreeRoute,
219
+ workspaceFileRoute,
220
+ workspaceProjectPathRoute,
221
+ workspaceRawFileRoute,
222
+ };
@@ -5,6 +5,10 @@ import { spawn } from "node:child_process";
5
5
  import type { PluginLogger } from "../api.js";
6
6
  import type { GitRepoState, PluginConfig, RepoSyncInfo } from "./types.js";
7
7
  import { resolveTeamClawWorkspaceDir } from "./openclaw-workspace.js";
8
+ // W6 of issue #226: the local swallowing pathExists copy was removed; the
9
+ // alias keeps every call site byte-identical while the shared copy pins the
10
+ // exact original semantics (any fs.access error resolves false).
11
+ import { pathExistsTolerant as pathExists } from "./shared/utils.js";
8
12
 
9
13
  const TEAMCLAW_IMPORT_REF_PREFIX = "refs/teamclaw/imports";
10
14
  const BUNDLE_IMPORT_MAX_RETRIES = 3;
@@ -783,15 +787,6 @@ async function tryRebaseWorkerOntoController(
783
787
  }
784
788
  }
785
789
 
786
- async function pathExists(filePath: string): Promise<boolean> {
787
- try {
788
- await fs.access(filePath);
789
- return true;
790
- } catch {
791
- return false;
792
- }
793
- }
794
-
795
790
  async function runGit(args: string[], options: { cwd: string }): Promise<CommandResult> {
796
791
  const result = await runCommand("git", args, options);
797
792
  if (result.exitCode !== 0) {
package/src/identity.ts CHANGED
@@ -7,6 +7,17 @@ import { getActiveRole } from "./profile-loader.js";
7
7
  import { loadWorkerIdentity, saveWorkerIdentity, clearWorkerIdentity } from "./state.js";
8
8
  import { MDnsBrowser } from "./discovery.js";
9
9
 
10
+ /**
11
+ * Issue #23 (client wave): headers for worker -> controller calls. While a
12
+ * paired device token is configured it rides the X-TeamClaw-Token header the
13
+ * controller's device gate accepts; without one the headers pass through
14
+ * unchanged (L0). The token value itself is never logged.
15
+ */
16
+ function withDeviceToken(config: PluginConfig, headers: Record<string, string>): Record<string, string> {
17
+ const token = config.securityToken?.trim();
18
+ return token ? { ...headers, "X-TeamClaw-Token": token } : headers;
19
+ }
20
+
10
21
  function getLocalIp(targetHost?: string): string {
11
22
  if (!targetHost || targetHost === "localhost" || targetHost === "127.0.0.1") {
12
23
  return "localhost";
@@ -115,7 +126,7 @@ export class IdentityManager {
115
126
  try {
116
127
  const res = await fetch(`${controllerUrl}/api/v1/workers/register`, {
117
128
  method: "POST",
118
- headers: { "Content-Type": "application/json" },
129
+ headers: withDeviceToken(this.config, { "Content-Type": "application/json" }),
119
130
  body: JSON.stringify(registration),
120
131
  });
121
132
 
@@ -147,6 +158,7 @@ export class IdentityManager {
147
158
  try {
148
159
  await fetch(`${this.identity.controllerUrl}/api/v1/workers/${this.identity.workerId}`, {
149
160
  method: "DELETE",
161
+ headers: withDeviceToken(this.config, {}),
150
162
  });
151
163
  } catch {
152
164
  // ignore
@@ -38,6 +38,33 @@ export type TeamProfileOutputConstraints = {
38
38
  citationPolicy?: Record<string, unknown>;
39
39
  };
40
40
 
41
+ /**
42
+ * Design 2.4 declarative workflow template: a conclusion-branched step chain.
43
+ * Integer step ids form the linear spine (default "next" routing advances to
44
+ * the smallest numeric id greater than the current one); string ids (e.g.
45
+ * "committee") are branch-only targets reachable exclusively through an
46
+ * explicit `on` jump. Structural + reference red lines are enforced by
47
+ * crossValidateProfile at load time (fatal), mirroring the role-reference
48
+ * red line.
49
+ */
50
+ export type TeamProfileWorkflowStep = {
51
+ id: number | string;
52
+ role: RoleId;
53
+ title: string;
54
+ description?: string;
55
+ inputs?: string[];
56
+ conclusion?: string[];
57
+ on?: Record<string, number | string>;
58
+ outputs?: Array<{ key: string; name: string }>;
59
+ };
60
+
61
+ export type TeamProfileWorkflow = {
62
+ id: string;
63
+ name: string;
64
+ description?: string;
65
+ steps: TeamProfileWorkflowStep[];
66
+ };
67
+
41
68
  /**
42
69
  * Profile role face (Phase 2.5, design 2.3): RoleDefinition plus the optional
43
70
  * Chinese display label the schema already allows. role-inference reads
@@ -64,7 +91,7 @@ export type TeamProfile = {
64
91
  domainInstructions?: string[];
65
92
  outputConstraints?: TeamProfileOutputConstraints;
66
93
  glossary?: string[];
67
- workflows?: Array<Record<string, unknown>>;
94
+ workflows?: TeamProfileWorkflow[];
68
95
  capabilities: TeamProfileCapabilities;
69
96
  warmupRoles: RoleId[];
70
97
  knowledgePacks?: string[];
@@ -397,6 +424,133 @@ function loadBuiltinProfiles(): Map<string, TeamProfile> {
397
424
  return profiles;
398
425
  }
399
426
 
427
+ /**
428
+ * Design 2.4 workflow red lines that the JSON Schema subset cannot express:
429
+ * step-id uniqueness, step.role must be a role of this profile, `on` keys must
430
+ * come from the step's conclusion enum, `on` targets must resolve to an
431
+ * existing step id (or "next"), and every inputs[] key must be an outputs[]
432
+ * key declared by some step of the same workflow. All failures are FATAL load
433
+ * errors (design 2.2), same as the role-reference red line.
434
+ */
435
+ function crossValidateWorkflows(
436
+ profile: TeamProfile,
437
+ roleIdSet: Set<string>,
438
+ referenceErrors: string[],
439
+ ): void {
440
+ const workflows = profile.workflows ?? [];
441
+ const workflowIds = new Set<string>();
442
+ for (const workflow of workflows) {
443
+ const workflowLabel = `workflow "${workflow.id}"`;
444
+ if (workflowIds.has(workflow.id)) {
445
+ referenceErrors.push(`${workflowLabel} id is declared more than once`);
446
+ }
447
+ workflowIds.add(workflow.id);
448
+
449
+ const stepKey = (stepId: number | string) => String(stepId);
450
+ const stepIds = new Set<string>(workflow.steps.map((step) => stepKey(step.id)));
451
+ if (stepIds.size !== workflow.steps.length) {
452
+ referenceErrors.push(`${workflowLabel} has duplicate step ids`);
453
+ }
454
+ // #251 L7: runs start at steps[0] (workflow-routes "按 steps 建任务链"),
455
+ // so the first step must sit on the numeric spine - a branch-only string
456
+ // id first step would route nowhere on completion and the run dies
457
+ // instantly. Load validation refuses such templates.
458
+ const firstStepId = workflow.steps[0]?.id;
459
+ if (firstStepId !== undefined && typeof firstStepId !== "number") {
460
+ referenceErrors.push(
461
+ `${workflowLabel} first step must be a numeric spine step (design 2.4): runs start at steps[0], and the branch-only string id ${JSON.stringify(firstStepId)} would end the run immediately`,
462
+ );
463
+ }
464
+ const outputKeys = new Set<string>();
465
+ for (const step of workflow.steps) {
466
+ for (const output of step.outputs ?? []) {
467
+ if (outputKeys.has(output.key)) {
468
+ referenceErrors.push(`${workflowLabel} declares output key "${output.key}" more than once`);
469
+ }
470
+ outputKeys.add(output.key);
471
+ }
472
+ }
473
+ for (const step of workflow.steps) {
474
+ const stepLabel = `${workflowLabel} step ${JSON.stringify(step.id)}`;
475
+ const stepIdTypeOk = (typeof step.id === "number" && Number.isSafeInteger(step.id))
476
+ || (typeof step.id === "string" && step.id.trim().length > 0);
477
+ if (!stepIdTypeOk) {
478
+ referenceErrors.push(
479
+ `${stepLabel}: step id must be a safe integer (linear spine) or a non-empty string (branch-only target), got ${typeof step.id}`,
480
+ );
481
+ }
482
+ if (!roleIdSet.has(step.role)) {
483
+ referenceErrors.push(`${stepLabel} role "${step.role}" is not a role of this profile`);
484
+ }
485
+ const conclusion = step.conclusion ?? [];
486
+ for (const [jumpConclusion, target] of Object.entries(step.on ?? {})) {
487
+ if (!conclusion.includes(jumpConclusion)) {
488
+ referenceErrors.push(
489
+ `${stepLabel} on-jump key "${jumpConclusion}" is not in the step's conclusion enum (dead routing, design 2.4)`,
490
+ );
491
+ }
492
+ if (target !== "next" && !stepIds.has(stepKey(target))) {
493
+ referenceErrors.push(
494
+ `${stepLabel} on-jump "${jumpConclusion}" targets ${JSON.stringify(target)}, which is not a step id of this workflow`,
495
+ );
496
+ }
497
+ }
498
+ for (const inputKey of step.inputs ?? []) {
499
+ if (!outputKeys.has(inputKey)) {
500
+ referenceErrors.push(
501
+ `${stepLabel} inputs key "${inputKey}" is not declared as an output of any step of this workflow (dangling input, design 2.4)`,
502
+ );
503
+ }
504
+ }
505
+ }
506
+
507
+ // #251 M2 static cycle red line: explicit on-jumps between DISTINCT steps
508
+ // must not form a cycle. Without this check a mutual-jump template loads
509
+ // fine and the cycle is only cut off at runtime by the visit cap, after
510
+ // burning real LLM calls. A step jumping back to ITSELF stays legal - it
511
+ // is the bounded self-retry pattern the banking pack ships
512
+ // (需补充材料 -> re-run intake), still guarded by MAX_WORKFLOW_STEP_VISITS.
513
+ const jumpTargets = new Map<string, string[]>();
514
+ for (const step of workflow.steps) {
515
+ const targets: string[] = [];
516
+ for (const target of Object.values(step.on ?? {})) {
517
+ if (target !== "next" && stepKey(target) !== stepKey(step.id)) {
518
+ targets.push(stepKey(target));
519
+ }
520
+ }
521
+ if (targets.length > 0) {
522
+ jumpTargets.set(stepKey(step.id), targets);
523
+ }
524
+ }
525
+ for (const startId of jumpTargets.keys()) {
526
+ const path: string[] = [];
527
+ const onPath = new Set<string>();
528
+ const visit = (nodeId: string): boolean => {
529
+ path.push(nodeId);
530
+ onPath.add(nodeId);
531
+ for (const nextId of jumpTargets.get(nodeId) ?? []) {
532
+ if (onPath.has(nextId)) {
533
+ referenceErrors.push(
534
+ `${workflowLabel} explicit on-jump cycle ${[...path.slice(path.indexOf(nextId)), nextId].join(" -> ")} `
535
+ + "(design 2.4: the runtime visit cap would only stop it after burning real LLM calls)",
536
+ );
537
+ return true;
538
+ }
539
+ if (visit(nextId)) {
540
+ return true;
541
+ }
542
+ }
543
+ path.pop();
544
+ onPath.delete(nodeId);
545
+ return false;
546
+ };
547
+ if (visit(startId)) {
548
+ break;
549
+ }
550
+ }
551
+ }
552
+ }
553
+
400
554
  /** Structural checks that sit outside what the JSON Schema subset can express. */
401
555
  function crossValidateProfile(profile: TeamProfile, profileFile: string): void {
402
556
  const roleIds = profile.roles.map((role) => role.id);
@@ -431,6 +585,7 @@ function crossValidateProfile(profile: TeamProfile, profileFile: string): void {
431
585
  }
432
586
  }
433
587
  }
588
+ crossValidateWorkflows(profile, roleIdSet, referenceErrors);
434
589
  if (referenceErrors.length > 0) {
435
590
  throw new Error(
436
591
  `TeamClaw profile ${profileFile} ("${profile.id}") has dangling role references (design 2.2 - refusing to start):\n`
@@ -565,6 +720,16 @@ function getActiveRole(id: RoleId): ProfileRoleDefinition | undefined {
565
720
  return getActiveRoles().find((role) => role.id === id);
566
721
  }
567
722
 
723
+ /**
724
+ * Design 2.4: the active profile's validated workflow templates, or an empty
725
+ * array when the profile ships none (software-rd baseline). Consumers: the
726
+ * POST /api/v1/workflows/{id}/start route and the task-completion routing
727
+ * hook (controller/workflow-routes.ts).
728
+ */
729
+ function getActiveWorkflows(): TeamProfileWorkflow[] {
730
+ return getActiveProfile().workflows ?? [];
731
+ }
732
+
568
733
  /**
569
734
  * Phase 2.6 labelZh fallback rule (vertical-team-profiles-design.md 2.1/2.6):
570
735
  * the zh display name is labelZh when the role carries one, otherwise the
@@ -642,6 +807,7 @@ export {
642
807
  getActiveDefaultRole,
643
808
  getActiveDomainInstructions,
644
809
  getActiveKnowledgePacks,
810
+ getActiveWorkflows,
645
811
  getActiveRole,
646
812
  validateActiveRoleId,
647
813
  normalizeRecommendedSkills,
@@ -5,11 +5,12 @@
5
5
  "nameZh": "银行对公信贷团队",
6
6
  "industry": "banking",
7
7
  "icon": "🏦",
8
- "version": "0.1.1",
8
+ "version": "0.1.2",
9
9
  "reviewedBy": [
10
10
  "drafted-by: Agent N (implementation team)",
11
11
  "AI domain review 2026-11-08: approved conditional on removing bare 「押品」 token from banking risk-reviewer capabilities (applied); securities/insurance approved as-is; glossary version-cutoff implemented as no-citation-number policy (accepted deviation). Human sign-off recorded 2026-11-08.",
12
- "Human sign-off: zhanju (repo owner), 2026-11-08 - approved via the TeamProfile implementation session after AI domain review conditions were applied."
12
+ "Human sign-off: zhanju (repo owner), 2026-11-08 - approved via the TeamProfile implementation session after AI domain review conditions were applied.",
13
+ "0.1.2 workflows wave (2026-11-10): added the credit-approval declarative workflow template (design section 2.4, copied field-for-field; step 1 additionally declares its reviewOpinion output so every downstream inputs[] key resolves). Roles, prompts, guardrails and glossary are unchanged from the signed 0.1.1."
13
14
  ],
14
15
  "description": "Corporate credit line team (v1 scope: 对公信贷) covering intake, risk review, approval, AML analysis, credit compliance and post-loan management; every output is an internal working draft pending a human decision.",
15
16
  "roles": [
@@ -167,6 +168,29 @@
167
168
  "风险分类: 按行内金融资产风险分类框架输出「分类提示」(事实+考量+缺口清单),分类结果由人工认定。",
168
169
  "法规版本截止声明: 法规修订频繁,助手记忆中的生效日期与修订状态不可作为依据;一律要求用户提供现行有效的权威文本,本词条表不携带文号。"
169
170
  ],
171
+ "workflows": [
172
+ {
173
+ "id": "credit-approval",
174
+ "name": "信贷审批流(对公)",
175
+ "steps": [
176
+ { "id": 0, "role": "credit-officer", "title": "受理与尽调",
177
+ "conclusion": ["材料齐全", "需补充材料"],
178
+ "on": { "需补充材料": 0 },
179
+ "outputs": [{ "key": "dueDiligenceReport", "name": "尽调报告" }] },
180
+ { "id": 1, "role": "risk-reviewer", "title": "风险审查",
181
+ "inputs": ["dueDiligenceReport"],
182
+ "conclusion": ["通过", "退回补充材料", "超权限上会"],
183
+ "on": { "退回补充材料": 0, "超权限上会": "committee", "通过": 2 },
184
+ "outputs": [{ "key": "reviewOpinion", "name": "风险审查意见" }] },
185
+ { "id": 2, "role": "approver", "title": "审批决策",
186
+ "inputs": ["dueDiligenceReport", "reviewOpinion"],
187
+ "outputs": [{ "key": "approvalDecision", "name": "审批结论" }] },
188
+ { "id": "committee", "role": "approver", "title": "贷审会(超权限)",
189
+ "inputs": ["dueDiligenceReport", "reviewOpinion"],
190
+ "outputs": [{ "key": "committeeMinutes", "name": "贷审会纪要式结论" }] }
191
+ ]
192
+ }
193
+ ],
170
194
  "capabilities": {
171
195
  "git": false,
172
196
  "teamauto": false,
@@ -159,8 +159,88 @@
159
159
  },
160
160
  "workflows": {
161
161
  "type": "array",
162
- "items": { "type": "object" },
163
- "description": "Reserved (Phase 3): declarative workflow templates with conclusion branches (design section 2.4)."
162
+ "items": {
163
+ "type": "object",
164
+ "required": ["id", "name", "steps"],
165
+ "properties": {
166
+ "id": {
167
+ "type": "string",
168
+ "pattern": "^[a-z][a-z0-9-]*$",
169
+ "minLength": 1,
170
+ "description": "Workflow template slug (the start endpoint key), unique within the profile."
171
+ },
172
+ "name": {
173
+ "type": "string",
174
+ "minLength": 1,
175
+ "description": "Display name of the workflow (button label for the UI quick-actions group)."
176
+ },
177
+ "description": {
178
+ "type": "string",
179
+ "description": "Optional one-line summary of what the workflow covers."
180
+ },
181
+ "steps": {
182
+ "type": "array",
183
+ "minItems": 1,
184
+ "items": {
185
+ "type": "object",
186
+ "required": ["id", "role", "title"],
187
+ "properties": {
188
+ "id": {
189
+ "description": "Step identifier: an integer on the linear spine (0, 1, 2, ...) or a non-numeric string for branch-only steps (e.g. \"committee\"). Uniqueness and on-target resolution are enforced by loader cross-validation; the schema subset cannot express unions."
190
+ },
191
+ "role": {
192
+ "type": "string",
193
+ "minLength": 1,
194
+ "description": "RoleId of the step's executing role; must be a role of this profile (loader cross-validation red line)."
195
+ },
196
+ "title": {
197
+ "type": "string",
198
+ "minLength": 1,
199
+ "description": "Step title; becomes the created task's title."
200
+ },
201
+ "description": {
202
+ "type": "string",
203
+ "description": "Optional extra instructions folded into the step's task description."
204
+ },
205
+ "inputs": {
206
+ "type": "array",
207
+ "items": { "type": "string", "minLength": 1 },
208
+ "uniqueItems": true,
209
+ "description": "Output keys from upstream steps whose results are embedded into this step's task description (design 2.4 outputKey passing). Each key must be declared by some step's outputs (loader cross-validation)."
210
+ },
211
+ "conclusion": {
212
+ "type": "array",
213
+ "items": { "type": "string", "minLength": 1 },
214
+ "uniqueItems": true,
215
+ "description": "Conclusion phrases; the step's deliverable must end with exactly one of them, and the task-completion hook matches them against the result to route (design 2.4)."
216
+ },
217
+ "on": {
218
+ "type": "object",
219
+ "description": "Conclusion -> step id jumps. Every key must be in this step's conclusion enum; every value must be \"next\" or an existing step id (loader cross-validation). Conclusions without an explicit mapping default to the next numeric-spine step."
220
+ },
221
+ "outputs": {
222
+ "type": "array",
223
+ "items": {
224
+ "type": "object",
225
+ "required": ["key", "name"],
226
+ "properties": {
227
+ "key": { "type": "string", "pattern": "^[a-z][a-zA-Z0-9-]*$", "minLength": 1, "description": "Output key downstream steps reference via inputs." },
228
+ "name": { "type": "string", "minLength": 1, "description": "Display name of the output artifact." }
229
+ },
230
+ "additionalProperties": false
231
+ },
232
+ "uniqueItems": true,
233
+ "description": "Named outputs this step produces; keys must be unique across the whole workflow (loader cross-validation)."
234
+ }
235
+ },
236
+ "additionalProperties": false
237
+ },
238
+ "description": "Ordered steps; numeric ids form the linear spine, string ids are branch-only targets."
239
+ }
240
+ },
241
+ "additionalProperties": false
242
+ },
243
+ "description": "Industry workflow templates with conclusion branches (design section 2.4; consumed by POST /api/v1/workflows/{id}/start and the task-completion routing hook). Optional; software-rd ships none."
164
244
  },
165
245
  "capabilities": {
166
246
  "type": "object",