@teamclaws/teamclaw 2026.8.1 → 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 (184) hide show
  1. package/cli.mjs +318 -17
  2. package/dist/index.js +54 -32
  3. package/dist/src/config.js +57 -2
  4. package/dist/src/controller/auth-routes.js +129 -0
  5. package/dist/src/controller/clarification-routes.js +315 -0
  6. package/dist/src/controller/controller-intake.js +895 -0
  7. package/dist/src/controller/controller-planning.js +814 -0
  8. package/dist/src/controller/controller-routes.js +195 -0
  9. package/dist/src/controller/controller-runs.js +175 -0
  10. package/dist/src/controller/controller-service.js +338 -50
  11. package/dist/src/controller/controller-tools.js +14 -7
  12. package/dist/src/controller/github-auth.js +2 -1
  13. package/dist/src/controller/http-server.js +290 -6003
  14. package/dist/src/controller/kickoff-orchestrator.js +33 -43
  15. package/dist/src/controller/message-delivery.js +31 -0
  16. package/dist/src/controller/message-routes.js +114 -0
  17. package/dist/src/controller/orchestration-manifest.js +11 -93
  18. package/dist/src/controller/preview-manager.js +51 -3
  19. package/dist/src/controller/preview-proxy.js +98 -0
  20. package/dist/src/controller/profile-switch.js +309 -0
  21. package/dist/src/controller/project-registry.js +294 -0
  22. package/dist/src/controller/prompt-injector.js +19 -9
  23. package/dist/src/controller/provisioning/backend-contract.js +9 -0
  24. package/dist/src/controller/provisioning/container-shared.js +64 -0
  25. package/dist/src/controller/provisioning/docker.js +214 -0
  26. package/dist/src/controller/provisioning/kubernetes.js +244 -0
  27. package/dist/src/controller/provisioning/plugin-root.js +41 -0
  28. package/dist/src/controller/provisioning/process-supervisor.js +190 -0
  29. package/dist/src/controller/provisioning-config.js +239 -0
  30. package/dist/src/controller/repo-routes.js +129 -0
  31. package/dist/src/controller/report-routes.js +56 -0
  32. package/dist/src/controller/role-inference.js +231 -20
  33. package/dist/src/controller/route-table.js +375 -0
  34. package/dist/src/controller/security.js +775 -0
  35. package/dist/src/controller/status-routes.js +287 -0
  36. package/dist/src/controller/task-assignment.js +511 -0
  37. package/dist/src/controller/task-cleanup.js +258 -0
  38. package/dist/src/controller/task-execution.js +271 -0
  39. package/dist/src/controller/task-results.js +471 -0
  40. package/dist/src/controller/task-router.js +74 -4
  41. package/dist/src/controller/task-routes.js +703 -0
  42. package/dist/src/controller/teamauto-routes.js +124 -0
  43. package/dist/src/controller/tunnel-manager.js +41 -8
  44. package/dist/src/controller/tunnel-routes.js +225 -0
  45. package/dist/src/controller/ui-assets.js +68 -0
  46. package/dist/src/controller/websocket.js +6 -2
  47. package/dist/src/controller/webui-routes.js +49 -0
  48. package/dist/src/controller/worker-provisioning.js +69 -953
  49. package/dist/src/controller/worker-routes.js +188 -0
  50. package/dist/src/controller/workflow-routes.js +407 -0
  51. package/dist/src/controller/workspace-routes.js +200 -0
  52. package/dist/src/git-collaboration.js +4 -9
  53. package/dist/src/identity.js +15 -3
  54. package/dist/src/interaction-contracts.js +7 -7
  55. package/dist/src/openclaw-workspace.js +40 -18
  56. package/dist/src/profile-loader.js +604 -0
  57. package/dist/src/profiles/banking.json +202 -0
  58. package/dist/src/profiles/crossborder-ecom.json +253 -0
  59. package/dist/src/profiles/insurance.json +157 -0
  60. package/dist/src/profiles/knowledge/hs-structure.md +97 -0
  61. package/dist/src/profiles/knowledge/incoterms-2020.md +188 -0
  62. package/dist/src/profiles/knowledge/vat-principles.md +85 -0
  63. package/dist/src/profiles/schema.json +281 -0
  64. package/dist/src/profiles/securities.json +137 -0
  65. package/dist/src/profiles/software-rd.json +264 -0
  66. package/dist/src/profiles/trading-co.json +200 -0
  67. package/dist/src/prompt-policy.js +42 -17
  68. package/dist/src/protocol.js +66 -3
  69. package/dist/src/role-ids.js +29 -0
  70. package/dist/src/roles.js +54 -13
  71. package/dist/src/session-roles.js +14 -0
  72. package/dist/src/shared/clarification-schema.js +65 -0
  73. package/dist/src/shared/github-auth.js +15 -0
  74. package/dist/src/shared/kickoff-prompt.js +37 -0
  75. package/dist/src/shared/utils.js +47 -0
  76. package/dist/src/state.js +275 -11
  77. package/dist/src/task-executor.js +7 -17
  78. package/dist/src/teamauto/github-client.js +18 -0
  79. package/dist/src/teamauto/repo-sync.js +228 -6
  80. package/dist/src/teamauto/scanner.js +40 -12
  81. package/dist/src/teamauto/scheduler.js +231 -12
  82. package/dist/src/types.js +77 -16
  83. package/dist/src/ui/app.js +1434 -82
  84. package/dist/src/ui/github-login.html +1 -0
  85. package/dist/src/ui/index.html +144 -45
  86. package/dist/src/ui/style.css +194 -0
  87. package/dist/src/worker/http-handler.js +59 -0
  88. package/dist/src/worker/prompt-injector.js +44 -8
  89. package/dist/src/worker/skill-installer.js +6 -10
  90. package/dist/src/worker/tools.js +20 -10
  91. package/dist/src/worker/worker-service.js +93 -7
  92. package/index.ts +61 -32
  93. package/openclaw.plugin.json +50 -2
  94. package/package.json +3 -2
  95. package/src/config.ts +57 -2
  96. package/src/controller/auth-routes.ts +157 -0
  97. package/src/controller/clarification-routes.ts +404 -0
  98. package/src/controller/controller-intake.ts +1113 -0
  99. package/src/controller/controller-planning.ts +1037 -0
  100. package/src/controller/controller-routes.ts +237 -0
  101. package/src/controller/controller-runs.ts +239 -0
  102. package/src/controller/controller-service.ts +422 -50
  103. package/src/controller/controller-tools.ts +16 -9
  104. package/src/controller/github-auth.ts +28 -63
  105. package/src/controller/http-server.ts +336 -6964
  106. package/src/controller/kickoff-orchestrator.ts +69 -45
  107. package/src/controller/message-delivery.ts +52 -0
  108. package/src/controller/message-routes.ts +137 -0
  109. package/src/controller/orchestration-manifest.ts +14 -100
  110. package/src/controller/preview-manager.ts +53 -3
  111. package/src/controller/preview-proxy.ts +127 -0
  112. package/src/controller/profile-switch.ts +396 -0
  113. package/src/controller/project-registry.ts +361 -0
  114. package/src/controller/prompt-injector.ts +23 -8
  115. package/src/controller/provisioning/backend-contract.ts +51 -0
  116. package/src/controller/provisioning/container-shared.ts +84 -0
  117. package/src/controller/provisioning/docker.ts +260 -0
  118. package/src/controller/provisioning/kubernetes.ts +263 -0
  119. package/src/controller/provisioning/plugin-root.ts +42 -0
  120. package/src/controller/provisioning/process-supervisor.ts +214 -0
  121. package/src/controller/provisioning-config.ts +289 -0
  122. package/src/controller/repo-routes.ts +163 -0
  123. package/src/controller/report-routes.ts +64 -0
  124. package/src/controller/role-inference.ts +260 -22
  125. package/src/controller/route-table.ts +597 -0
  126. package/src/controller/security.ts +899 -0
  127. package/src/controller/status-routes.ts +354 -0
  128. package/src/controller/task-assignment.ts +622 -0
  129. package/src/controller/task-cleanup.ts +344 -0
  130. package/src/controller/task-execution.ts +399 -0
  131. package/src/controller/task-results.ts +556 -0
  132. package/src/controller/task-router.ts +98 -6
  133. package/src/controller/task-routes.ts +812 -0
  134. package/src/controller/teamauto-routes.ts +121 -0
  135. package/src/controller/tunnel-manager.ts +45 -8
  136. package/src/controller/tunnel-routes.ts +231 -0
  137. package/src/controller/ui-assets.ts +70 -0
  138. package/src/controller/websocket.ts +32 -4
  139. package/src/controller/webui-routes.ts +55 -0
  140. package/src/controller/worker-provisioning.ts +83 -1121
  141. package/src/controller/worker-routes.ts +241 -0
  142. package/src/controller/workflow-routes.ts +498 -0
  143. package/src/controller/workspace-routes.ts +222 -0
  144. package/src/git-collaboration.ts +4 -9
  145. package/src/identity.ts +16 -3
  146. package/src/interaction-contracts.ts +7 -7
  147. package/src/openclaw-workspace.ts +44 -18
  148. package/src/profile-loader.ts +816 -0
  149. package/src/profiles/banking.json +202 -0
  150. package/src/profiles/crossborder-ecom.json +253 -0
  151. package/src/profiles/insurance.json +157 -0
  152. package/src/profiles/knowledge/hs-structure.md +97 -0
  153. package/src/profiles/knowledge/incoterms-2020.md +188 -0
  154. package/src/profiles/knowledge/vat-principles.md +85 -0
  155. package/src/profiles/schema.json +281 -0
  156. package/src/profiles/securities.json +137 -0
  157. package/src/profiles/software-rd.json +264 -0
  158. package/src/profiles/trading-co.json +200 -0
  159. package/src/prompt-policy.ts +44 -17
  160. package/src/protocol.ts +72 -2
  161. package/src/role-ids.ts +31 -0
  162. package/src/roles.ts +60 -14
  163. package/src/session-roles.ts +14 -0
  164. package/src/shared/clarification-schema.ts +81 -0
  165. package/src/shared/github-auth.ts +92 -0
  166. package/src/shared/kickoff-prompt.ts +47 -0
  167. package/src/shared/utils.ts +51 -0
  168. package/src/state.ts +326 -10
  169. package/src/task-executor.ts +7 -18
  170. package/src/teamauto/github-client.ts +23 -1
  171. package/src/teamauto/repo-sync.ts +248 -7
  172. package/src/teamauto/scanner.ts +47 -13
  173. package/src/teamauto/scheduler.ts +261 -17
  174. package/src/teamauto/store.ts +12 -0
  175. package/src/types.ts +263 -17
  176. package/src/ui/app.js +1434 -82
  177. package/src/ui/github-login.html +1 -0
  178. package/src/ui/index.html +144 -45
  179. package/src/ui/style.css +194 -0
  180. package/src/worker/http-handler.ts +64 -1
  181. package/src/worker/prompt-injector.ts +48 -8
  182. package/src/worker/skill-installer.ts +6 -10
  183. package/src/worker/tools.ts +21 -10
  184. package/src/worker/worker-service.ts +101 -7
@@ -0,0 +1,604 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ // ---------------------------------------------------------------------------
5
+ // JSON Schema (subset) validation.
6
+ //
7
+ // schema.json is a plain JSON file, so it cannot carry TypeBox Kind symbols
8
+ // and @sinclair/typebox/value rejects serialized schemas (verified: throws
9
+ // ValueCheckUnknownTypeError). Instead of adding a JSON Schema dependency to
10
+ // the runtime, this interpreter supports exactly the keyword subset
11
+ // schema.json uses. assertSchemaUsesSupportedKeywords() runs at init against
12
+ // the loaded schema itself, so schema.json can never silently use a keyword
13
+ // the interpreter would ignore.
14
+ // ---------------------------------------------------------------------------
15
+ const SUPPORTED_SCHEMA_KEYWORDS = new Set([
16
+ "$schema",
17
+ "$id",
18
+ "title",
19
+ "description",
20
+ "type",
21
+ "enum",
22
+ "required",
23
+ "properties",
24
+ "additionalProperties",
25
+ "items",
26
+ "minItems",
27
+ "uniqueItems",
28
+ "minLength",
29
+ "pattern",
30
+ ]);
31
+ const SUPPORTED_SCHEMA_TYPES = new Set(["object", "array", "string", "integer", "number", "boolean", "null"]);
32
+ function isSchemaObject(value) {
33
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
34
+ }
35
+ function assertSchemaUsesSupportedKeywords(schema, at) {
36
+ if (!isSchemaObject(schema)) {
37
+ throw new Error(`profiles schema ${at}: every subschema must be an object`);
38
+ }
39
+ for (const keyword of Object.keys(schema)) {
40
+ if (!SUPPORTED_SCHEMA_KEYWORDS.has(keyword)) {
41
+ throw new Error(`profiles schema ${at}: keyword "${keyword}" is not supported by the profile-loader validator `
42
+ + `(supported: ${[...SUPPORTED_SCHEMA_KEYWORDS].sort().join(", ")}); extend both together`);
43
+ }
44
+ }
45
+ if (schema.type !== undefined) {
46
+ const type = schema.type;
47
+ if (typeof type !== "string" || !SUPPORTED_SCHEMA_TYPES.has(type)) {
48
+ throw new Error(`profiles schema ${at}: unsupported "type" value ${JSON.stringify(type)}`);
49
+ }
50
+ }
51
+ // Keyword FORM guards (review fix): the checker below only interprets a
52
+ // narrow form of each keyword; any other form (e.g. additionalProperties
53
+ // as a permissive subschema, non-string pattern, non-string required
54
+ // entries, non-number length/item bounds) would otherwise be SILENTLY
55
+ // ignored and the schema would validate less than it appears to.
56
+ if (schema.additionalProperties !== undefined && schema.additionalProperties !== false) {
57
+ throw new Error(`profiles schema ${at}: "additionalProperties" is only supported as the literal false `
58
+ + `(permissive-subschema form is not implemented); found ${JSON.stringify(schema.additionalProperties)}`);
59
+ }
60
+ if (schema.pattern !== undefined && typeof schema.pattern !== "string") {
61
+ throw new Error(`profiles schema ${at}: "pattern" must be a string`);
62
+ }
63
+ if (schema.required !== undefined
64
+ && (!Array.isArray(schema.required) || schema.required.some((entry) => typeof entry !== "string"))) {
65
+ throw new Error(`profiles schema ${at}: "required" must be an array of strings`);
66
+ }
67
+ if (schema.minLength !== undefined && typeof schema.minLength !== "number") {
68
+ throw new Error(`profiles schema ${at}: "minLength" must be a number`);
69
+ }
70
+ if (schema.minItems !== undefined && typeof schema.minItems !== "number") {
71
+ throw new Error(`profiles schema ${at}: "minItems" must be a number`);
72
+ }
73
+ if (schema.uniqueItems !== undefined && typeof schema.uniqueItems !== "boolean") {
74
+ throw new Error(`profiles schema ${at}: "uniqueItems" must be a boolean`);
75
+ }
76
+ if (schema.enum !== undefined && !Array.isArray(schema.enum)) {
77
+ throw new Error(`profiles schema ${at}: "enum" must be an array`);
78
+ }
79
+ if (schema.properties !== undefined) {
80
+ if (!isSchemaObject(schema.properties)) {
81
+ throw new Error(`profiles schema ${at}: "properties" must be an object`);
82
+ }
83
+ for (const [key, subschema] of Object.entries(schema.properties)) {
84
+ assertSchemaUsesSupportedKeywords(subschema, `${at}.properties.${key}`);
85
+ }
86
+ }
87
+ if (schema.items !== undefined) {
88
+ assertSchemaUsesSupportedKeywords(schema.items, `${at}.items`);
89
+ }
90
+ }
91
+ function checkTypeMatches(type, value) {
92
+ switch (type) {
93
+ case "object":
94
+ return isSchemaObject(value);
95
+ case "array":
96
+ return Array.isArray(value);
97
+ case "string":
98
+ return typeof value === "string";
99
+ case "integer":
100
+ return typeof value === "number" && Number.isInteger(value);
101
+ case "number":
102
+ return typeof value === "number";
103
+ case "boolean":
104
+ return typeof value === "boolean";
105
+ case "null":
106
+ return value === null;
107
+ default:
108
+ return false;
109
+ }
110
+ }
111
+ function collectSchemaErrors(value, schema, at, errors) {
112
+ if (schema.type !== undefined && !checkTypeMatches(schema.type, value)) {
113
+ errors.push(`${at}: expected ${JSON.stringify(schema.type)}, got ${Array.isArray(value) ? "array" : typeof value}`);
114
+ return;
115
+ }
116
+ if (schema.enum !== undefined) {
117
+ const allowed = schema.enum;
118
+ if (!allowed.some((entry) => JSON.stringify(entry) === JSON.stringify(value))) {
119
+ errors.push(`${at}: value ${JSON.stringify(value)} is not one of ${JSON.stringify(allowed)}`);
120
+ return;
121
+ }
122
+ }
123
+ if (typeof value === "string") {
124
+ if (typeof schema.minLength === "number" && value.length < schema.minLength) {
125
+ errors.push(`${at}: string is shorter than minLength ${schema.minLength}`);
126
+ }
127
+ if (typeof schema.pattern === "string" && !new RegExp(schema.pattern).test(value)) {
128
+ errors.push(`${at}: string does not match pattern ${schema.pattern}`);
129
+ }
130
+ }
131
+ if (Array.isArray(value)) {
132
+ if (typeof schema.minItems === "number" && value.length < schema.minItems) {
133
+ errors.push(`${at}: array has fewer than minItems ${schema.minItems} (${value.length})`);
134
+ }
135
+ if (schema.uniqueItems === true) {
136
+ const seen = new Set(value.map((entry) => JSON.stringify(entry)));
137
+ if (seen.size !== value.length) {
138
+ errors.push(`${at}: array items are not unique`);
139
+ }
140
+ }
141
+ if (isSchemaObject(schema.items)) {
142
+ value.forEach((entry, index) => collectSchemaErrors(entry, schema.items, `${at}[${index}]`, errors));
143
+ }
144
+ }
145
+ if (isSchemaObject(value)) {
146
+ if (Array.isArray(schema.required)) {
147
+ for (const key of schema.required) {
148
+ if (!(key in value)) {
149
+ errors.push(`${at}: missing required property "${key}"`);
150
+ }
151
+ }
152
+ }
153
+ const properties = isSchemaObject(schema.properties) ? schema.properties : {};
154
+ for (const [key, subschema] of Object.entries(properties)) {
155
+ if (key in value) {
156
+ collectSchemaErrors(value[key], subschema, `${at}.${key}`, errors);
157
+ }
158
+ }
159
+ if (schema.additionalProperties === false) {
160
+ for (const key of Object.keys(value)) {
161
+ if (!(key in properties)) {
162
+ errors.push(`${at}: unexpected property "${key}" (additionalProperties is false)`);
163
+ }
164
+ }
165
+ }
166
+ }
167
+ }
168
+ function validateProfileAgainstSchema(profile, schema, profileFile) {
169
+ const errors = [];
170
+ collectSchemaErrors(profile, schema, "$", errors);
171
+ if (errors.length > 0) {
172
+ throw new Error(`TeamClaw profile "${profileFile}" failed schema validation (design 2.2 - refusing to start):\n`
173
+ + errors.map((line) => ` - ${line}`).join("\n"));
174
+ }
175
+ }
176
+ /**
177
+ * Validate one profile package against one schema document with the full
178
+ * loader pipeline (JSON Schema subset + supported schemaVersion + cross-field
179
+ * role-reference checks). Exported for the Phase 1.7 loader unit tests and
180
+ * for future profile-authoring tooling; the built-in load path calls it for
181
+ * every packaged profile at module init.
182
+ */
183
+ function validateProfilePackage(profile, schema, profileFile) {
184
+ assertSchemaUsesSupportedKeywords(schema, "schema.json");
185
+ validateProfileAgainstSchema(profile, schema, profileFile);
186
+ const record = profile;
187
+ if (record.schemaVersion !== SUPPORTED_PROFILE_SCHEMA_VERSION) {
188
+ // Reserved evolution hook (design 2.2, additive-only): a future format
189
+ // version is a hard stop for this build, never a silent skip.
190
+ throw new Error(`TeamClaw profile ${profileFile} declares schemaVersion ${JSON.stringify(record.schemaVersion)}, `
191
+ + `but this build supports only ${SUPPORTED_PROFILE_SCHEMA_VERSION}. Update TeamClaw.`);
192
+ }
193
+ crossValidateProfile(record, profileFile);
194
+ loadKnowledgePackReferences(record, profileFile);
195
+ return record;
196
+ }
197
+ // ---------------------------------------------------------------------------
198
+ // Load + validate the built-in profiles once, at module init.
199
+ // ---------------------------------------------------------------------------
200
+ const SUPPORTED_PROFILE_SCHEMA_VERSION = 1;
201
+ const SOFTWARE_RD_PROFILE_ID = "software-rd";
202
+ const PROFILES_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "profiles");
203
+ // ---------------------------------------------------------------------------
204
+ // Phase 4 static knowledge packs (zero-cost exception, design 2.1/2.2 + 3
205
+ // Phase 4): stable reference files under profiles/knowledge/ that ship with
206
+ // the package and are injected into worker prompts to ground common domain
207
+ // concepts. References resolve ONLY against this built-in knowledge
208
+ // directory (extra-profile fixtures included - they reuse the shipped pack
209
+ // set), the schema pattern already forbids path separators, and a missing or
210
+ // empty referenced file is a FATAL load error, mirroring the role-reference
211
+ // red line. Contents are read once here and cached, so the prompt injector
212
+ // never does IO at render time.
213
+ // ---------------------------------------------------------------------------
214
+ const KNOWLEDGE_PACK_DIR = path.join(PROFILES_DIR, "knowledge");
215
+ const KNOWLEDGE_PACK_CONTENTS = new Map();
216
+ function loadKnowledgePackReferences(profile, profileFile) {
217
+ for (const packName of profile.knowledgePacks ?? []) {
218
+ if (KNOWLEDGE_PACK_CONTENTS.has(packName)) {
219
+ continue;
220
+ }
221
+ let content;
222
+ try {
223
+ content = fs.readFileSync(path.join(KNOWLEDGE_PACK_DIR, packName), "utf8");
224
+ }
225
+ catch {
226
+ throw new Error(`TeamClaw profile ${profileFile} ("${profile.id}") references knowledge pack "${packName}" `
227
+ + `that does not exist in the built-in knowledge directory (design 2.2 - refusing to start; `
228
+ + `run \`npm --prefix src run build\` in a dev checkout, or fix the knowledgePacks reference)`);
229
+ }
230
+ if (content.trim().length === 0) {
231
+ throw new Error(`TeamClaw profile ${profileFile} ("${profile.id}") references knowledge pack "${packName}" `
232
+ + "that is empty (design 2.2 - refusing to start)");
233
+ }
234
+ KNOWLEDGE_PACK_CONTENTS.set(packName, content);
235
+ }
236
+ }
237
+ function readJsonFile(filePath) {
238
+ let raw;
239
+ try {
240
+ raw = fs.readFileSync(filePath, "utf8");
241
+ }
242
+ catch (error) {
243
+ throw new Error(`TeamClaw cannot read required file ${filePath} (${error instanceof Error ? error.message : String(error)}). `
244
+ + "Built-in profiles ship with the package; in a dev checkout run `npm --prefix src run build` first.");
245
+ }
246
+ try {
247
+ return JSON.parse(raw);
248
+ }
249
+ catch (error) {
250
+ throw new Error(`TeamClaw profile file ${filePath} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
251
+ }
252
+ }
253
+ function loadBuiltinProfiles() {
254
+ const schemaFilePath = path.join(PROFILES_DIR, "schema.json");
255
+ const schema = readJsonFile(schemaFilePath);
256
+ assertSchemaUsesSupportedKeywords(schema, "schema.json");
257
+ let profileFiles;
258
+ try {
259
+ profileFiles = fs.readdirSync(PROFILES_DIR)
260
+ .filter((name) => name.endsWith(".json") && name !== "schema.json")
261
+ .sort();
262
+ }
263
+ catch (error) {
264
+ throw new Error(`TeamClaw cannot read the built-in profiles directory ${PROFILES_DIR} `
265
+ + `(${error instanceof Error ? error.message : String(error)}); run \`npm --prefix src run build\` in a dev checkout.`);
266
+ }
267
+ if (profileFiles.length === 0) {
268
+ throw new Error(`TeamClaw built-in profiles directory ${PROFILES_DIR} contains no profile packages`);
269
+ }
270
+ const profiles = new Map();
271
+ for (const file of profileFiles) {
272
+ const profile = readJsonFile(path.join(PROFILES_DIR, file));
273
+ const record = validateProfilePackage(profile, schema, file);
274
+ profiles.set(record.id, record);
275
+ }
276
+ if (!profiles.has(SOFTWARE_RD_PROFILE_ID)) {
277
+ throw new Error(`TeamClaw built-in profiles are missing the "${SOFTWARE_RD_PROFILE_ID}" baseline package `
278
+ + `(it is the fallback profile for unconfigured first initialization)`);
279
+ }
280
+ return profiles;
281
+ }
282
+ /**
283
+ * Design 2.4 workflow red lines that the JSON Schema subset cannot express:
284
+ * step-id uniqueness, step.role must be a role of this profile, `on` keys must
285
+ * come from the step's conclusion enum, `on` targets must resolve to an
286
+ * existing step id (or "next"), and every inputs[] key must be an outputs[]
287
+ * key declared by some step of the same workflow. All failures are FATAL load
288
+ * errors (design 2.2), same as the role-reference red line.
289
+ */
290
+ function crossValidateWorkflows(profile, roleIdSet, referenceErrors) {
291
+ const workflows = profile.workflows ?? [];
292
+ const workflowIds = new Set();
293
+ for (const workflow of workflows) {
294
+ const workflowLabel = `workflow "${workflow.id}"`;
295
+ if (workflowIds.has(workflow.id)) {
296
+ referenceErrors.push(`${workflowLabel} id is declared more than once`);
297
+ }
298
+ workflowIds.add(workflow.id);
299
+ const stepKey = (stepId) => String(stepId);
300
+ const stepIds = new Set(workflow.steps.map((step) => stepKey(step.id)));
301
+ if (stepIds.size !== workflow.steps.length) {
302
+ referenceErrors.push(`${workflowLabel} has duplicate step ids`);
303
+ }
304
+ // #251 L7: runs start at steps[0] (workflow-routes "按 steps 建任务链"),
305
+ // so the first step must sit on the numeric spine - a branch-only string
306
+ // id first step would route nowhere on completion and the run dies
307
+ // instantly. Load validation refuses such templates.
308
+ const firstStepId = workflow.steps[0]?.id;
309
+ if (firstStepId !== undefined && typeof firstStepId !== "number") {
310
+ referenceErrors.push(`${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`);
311
+ }
312
+ const outputKeys = new Set();
313
+ for (const step of workflow.steps) {
314
+ for (const output of step.outputs ?? []) {
315
+ if (outputKeys.has(output.key)) {
316
+ referenceErrors.push(`${workflowLabel} declares output key "${output.key}" more than once`);
317
+ }
318
+ outputKeys.add(output.key);
319
+ }
320
+ }
321
+ for (const step of workflow.steps) {
322
+ const stepLabel = `${workflowLabel} step ${JSON.stringify(step.id)}`;
323
+ const stepIdTypeOk = (typeof step.id === "number" && Number.isSafeInteger(step.id))
324
+ || (typeof step.id === "string" && step.id.trim().length > 0);
325
+ if (!stepIdTypeOk) {
326
+ referenceErrors.push(`${stepLabel}: step id must be a safe integer (linear spine) or a non-empty string (branch-only target), got ${typeof step.id}`);
327
+ }
328
+ if (!roleIdSet.has(step.role)) {
329
+ referenceErrors.push(`${stepLabel} role "${step.role}" is not a role of this profile`);
330
+ }
331
+ const conclusion = step.conclusion ?? [];
332
+ for (const [jumpConclusion, target] of Object.entries(step.on ?? {})) {
333
+ if (!conclusion.includes(jumpConclusion)) {
334
+ referenceErrors.push(`${stepLabel} on-jump key "${jumpConclusion}" is not in the step's conclusion enum (dead routing, design 2.4)`);
335
+ }
336
+ if (target !== "next" && !stepIds.has(stepKey(target))) {
337
+ referenceErrors.push(`${stepLabel} on-jump "${jumpConclusion}" targets ${JSON.stringify(target)}, which is not a step id of this workflow`);
338
+ }
339
+ }
340
+ for (const inputKey of step.inputs ?? []) {
341
+ if (!outputKeys.has(inputKey)) {
342
+ referenceErrors.push(`${stepLabel} inputs key "${inputKey}" is not declared as an output of any step of this workflow (dangling input, design 2.4)`);
343
+ }
344
+ }
345
+ }
346
+ // #251 M2 static cycle red line: explicit on-jumps between DISTINCT steps
347
+ // must not form a cycle. Without this check a mutual-jump template loads
348
+ // fine and the cycle is only cut off at runtime by the visit cap, after
349
+ // burning real LLM calls. A step jumping back to ITSELF stays legal - it
350
+ // is the bounded self-retry pattern the banking pack ships
351
+ // (需补充材料 -> re-run intake), still guarded by MAX_WORKFLOW_STEP_VISITS.
352
+ const jumpTargets = new Map();
353
+ for (const step of workflow.steps) {
354
+ const targets = [];
355
+ for (const target of Object.values(step.on ?? {})) {
356
+ if (target !== "next" && stepKey(target) !== stepKey(step.id)) {
357
+ targets.push(stepKey(target));
358
+ }
359
+ }
360
+ if (targets.length > 0) {
361
+ jumpTargets.set(stepKey(step.id), targets);
362
+ }
363
+ }
364
+ for (const startId of jumpTargets.keys()) {
365
+ const path = [];
366
+ const onPath = new Set();
367
+ const visit = (nodeId) => {
368
+ path.push(nodeId);
369
+ onPath.add(nodeId);
370
+ for (const nextId of jumpTargets.get(nodeId) ?? []) {
371
+ if (onPath.has(nextId)) {
372
+ referenceErrors.push(`${workflowLabel} explicit on-jump cycle ${[...path.slice(path.indexOf(nextId)), nextId].join(" -> ")} `
373
+ + "(design 2.4: the runtime visit cap would only stop it after burning real LLM calls)");
374
+ return true;
375
+ }
376
+ if (visit(nextId)) {
377
+ return true;
378
+ }
379
+ }
380
+ path.pop();
381
+ onPath.delete(nodeId);
382
+ return false;
383
+ };
384
+ if (visit(startId)) {
385
+ break;
386
+ }
387
+ }
388
+ }
389
+ }
390
+ /** Structural checks that sit outside what the JSON Schema subset can express. */
391
+ function crossValidateProfile(profile, profileFile) {
392
+ const roleIds = profile.roles.map((role) => role.id);
393
+ const roleIdSet = new Set(roleIds);
394
+ if (roleIdSet.size !== roleIds.length) {
395
+ throw new Error(`TeamClaw profile ${profileFile} ("${profile.id}") has duplicate role ids`);
396
+ }
397
+ const referenceErrors = [];
398
+ if (!roleIdSet.has(profile.defaultRole)) {
399
+ referenceErrors.push(`defaultRole "${profile.defaultRole}" is not a role of this profile`);
400
+ }
401
+ // Phase 2.4 red line (design 2.1/2.4): domainInstructions REPLACE the
402
+ // software operating rules, and the software-rd baseline deliberately does
403
+ // not carry them (its rules stay pre-composed in the role systemPrompts,
404
+ // locked byte-for-byte by the Phase 1.7 golden). Setting them on software-rd
405
+ // would double-inject an operating contract, so it is a fatal load error.
406
+ if (profile.id === SOFTWARE_RD_PROFILE_ID && profile.domainInstructions && profile.domainInstructions.length > 0) {
407
+ referenceErrors.push(`the "${SOFTWARE_RD_PROFILE_ID}" baseline profile must not set domainInstructions `
408
+ + "(its operating rules stay pre-composed in the role systemPrompts; design 2.1/2.4)");
409
+ }
410
+ for (const roleId of profile.warmupRoles) {
411
+ if (!roleIdSet.has(roleId)) {
412
+ referenceErrors.push(`warmupRoles entry "${roleId}" is not a role of this profile`);
413
+ }
414
+ }
415
+ for (const role of profile.roles) {
416
+ for (const nextRoleId of role.suggestedNextRoles) {
417
+ if (!roleIdSet.has(nextRoleId)) {
418
+ referenceErrors.push(`role "${role.id}" suggestedNextRoles entry "${nextRoleId}" is not a role of this profile`);
419
+ }
420
+ }
421
+ }
422
+ crossValidateWorkflows(profile, roleIdSet, referenceErrors);
423
+ if (referenceErrors.length > 0) {
424
+ throw new Error(`TeamClaw profile ${profileFile} ("${profile.id}") has dangling role references (design 2.2 - refusing to start):\n`
425
+ + referenceErrors.map((line) => ` - ${line}`).join("\n"));
426
+ }
427
+ }
428
+ const BUILTIN_PROFILES = loadBuiltinProfiles();
429
+ // ---------------------------------------------------------------------------
430
+ // Phase 2.1 test-hook: optional extra profile packages (additive merge).
431
+ //
432
+ // TEAMCLAW_EXTRA_PROFILES_DIR points at a directory (e.g. the repository's
433
+ // tests/fixtures/profiles/) whose *.json packages are validated with the same
434
+ // schema + cross-field pipeline and MERGED into the built-in registry. This
435
+ // lets integration tests exercise the switch/archive/capability paths against
436
+ // a minimal non-software profile WITHOUT shipping test fixtures inside
437
+ // src/profiles/ (design 2.2: that directory is the distributed package set).
438
+ // The env var is unset in production, so runtime behavior is bit-identical;
439
+ // a broken extra package stays FATAL (same loader red line).
440
+ // ---------------------------------------------------------------------------
441
+ const EXTRA_PROFILES_DIR = process.env.TEAMCLAW_EXTRA_PROFILES_DIR?.trim() ?? "";
442
+ function mergeExtraProfiles() {
443
+ let files;
444
+ try {
445
+ files = fs.readdirSync(EXTRA_PROFILES_DIR)
446
+ .filter((name) => name.endsWith(".json") && name !== "schema.json")
447
+ .sort();
448
+ }
449
+ catch {
450
+ throw new Error(`TeamClaw cannot read TEAMCLAW_EXTRA_PROFILES_DIR "${EXTRA_PROFILES_DIR}" `
451
+ + "(set it to a directory of TeamProfile JSON packages, or unset it).");
452
+ }
453
+ const schemaFilePath = path.join(PROFILES_DIR, "schema.json");
454
+ const schema = readJsonFile(schemaFilePath);
455
+ for (const file of files) {
456
+ const record = validateProfilePackage(readJsonFile(path.join(EXTRA_PROFILES_DIR, file)), schema, file);
457
+ if (BUILTIN_PROFILES.has(record.id)) {
458
+ throw new Error(`TeamClaw extra profile ${file} shadows the built-in profile id "${record.id}"`);
459
+ }
460
+ BUILTIN_PROFILES.set(record.id, record);
461
+ }
462
+ }
463
+ if (EXTRA_PROFILES_DIR) {
464
+ mergeExtraProfiles();
465
+ }
466
+ // The active profile defaults to the software-rd baseline. In controller
467
+ // mode, controller-service re-points it from TeamState.profileId (the single
468
+ // runtime truth, design 2.3) after loading state; config teamProfile only
469
+ // seeds FIRST initialization. Worker mode follows the controller (v1).
470
+ let activeProfileId = SOFTWARE_RD_PROFILE_ID;
471
+ /** True when `id` names a built-in profile package. */
472
+ function hasProfile(id) {
473
+ return BUILTIN_PROFILES.has(id);
474
+ }
475
+ /** Switch the active profile. Unknown ids are a programming error (throw). */
476
+ function setActiveProfileId(id) {
477
+ if (!BUILTIN_PROFILES.has(id)) {
478
+ throw new Error(`TeamClaw profile "${id}" is not a built-in profile (available: ${[...BUILTIN_PROFILES.keys()].sort().join(", ")})`);
479
+ }
480
+ activeProfileId = id;
481
+ }
482
+ function getActiveProfileId() {
483
+ return activeProfileId;
484
+ }
485
+ function getActiveProfile() {
486
+ const profile = BUILTIN_PROFILES.get(activeProfileId);
487
+ if (!profile) {
488
+ throw new Error(`TeamClaw active profile "${activeProfileId}" disappeared from the built-in registry`);
489
+ }
490
+ return profile;
491
+ }
492
+ function getActiveRoles() {
493
+ return getActiveProfile().roles;
494
+ }
495
+ function getActiveRoleIds() {
496
+ return getActiveRoles().map((role) => role.id);
497
+ }
498
+ function getActiveDefaultRole() {
499
+ return getActiveProfile().defaultRole;
500
+ }
501
+ /**
502
+ * Phase 2.4 (design 2.1/2.4): the active profile's industry guardrails, or
503
+ * undefined when the profile does not carry them (software-rd baseline).
504
+ * The prompt pipelines REPLACE buildRoleOperatingRules with these lines;
505
+ * a profile without them keeps the software operating rules unchanged.
506
+ */
507
+ function getActiveDomainInstructions() {
508
+ const instructions = getActiveProfile().domainInstructions;
509
+ return instructions && instructions.length > 0 ? instructions : undefined;
510
+ }
511
+ /**
512
+ * Phase 4 (design 2.1 knowledgePacks + 3 Phase 4 exception): the active
513
+ * profile's static reference packs, in declaration order, or an empty array
514
+ * when the profile declares none (software-rd baseline) - the worker prompt
515
+ * injector appends a Reference Packs section only for non-empty results, so
516
+ * profiles without packs keep their prompt bytes unchanged (Phase 1.7
517
+ * golden). Contents were validated + cached at load time; a hit that misses
518
+ * the cache is impossible by construction and stays a hard throw.
519
+ */
520
+ function getActiveKnowledgePacks() {
521
+ const names = getActiveProfile().knowledgePacks ?? [];
522
+ return names.map((name) => {
523
+ const content = KNOWLEDGE_PACK_CONTENTS.get(name);
524
+ if (content === undefined) {
525
+ throw new Error(`TeamClaw knowledge pack "${name}" (active profile "${getActiveProfileId()}") passed load validation `
526
+ + "but its cached content is missing - this is a loader invariant violation");
527
+ }
528
+ return { name, content };
529
+ });
530
+ }
531
+ /** Active-profile counterpart of roles.ts getRole. */
532
+ function getActiveRole(id) {
533
+ return getActiveRoles().find((role) => role.id === id);
534
+ }
535
+ /**
536
+ * Design 2.4: the active profile's validated workflow templates, or an empty
537
+ * array when the profile ships none (software-rd baseline). Consumers: the
538
+ * POST /api/v1/workflows/{id}/start route and the task-completion routing
539
+ * hook (controller/workflow-routes.ts).
540
+ */
541
+ function getActiveWorkflows() {
542
+ return getActiveProfile().workflows ?? [];
543
+ }
544
+ /**
545
+ * Phase 2.6 labelZh fallback rule (vertical-team-profiles-design.md 2.1/2.6):
546
+ * the zh display name is labelZh when the role carries one, otherwise the
547
+ * English label. Encoded here - the loading-validation layer - so UI
548
+ * consumers (Phase 5) have a single backend source for the rule instead of
549
+ * re-implementing `labelZh ?? label` per surface; the schema guarantees a
550
+ * present labelZh is never an EMPTY string (minLength 1), and a
551
+ * whitespace-only labelZh (which minLength cannot reject) also falls back
552
+ * here via trim - a blank chip must never win over the fallback. v1 is
553
+ * bilingual only (design 5.3: no additional locales); "en" is accepted
554
+ * explicitly for symmetric rendering.
555
+ */
556
+ function resolveRoleDisplayName(role, locale = "zh") {
557
+ if (locale === "en") {
558
+ return role.label;
559
+ }
560
+ const labelZh = typeof role.labelZh === "string" ? role.labelZh.trim() : "";
561
+ return labelZh.length > 0 ? labelZh : role.label;
562
+ }
563
+ /**
564
+ * Active-profile counterpart of roles.ts validateRoleId: returns the trimmed
565
+ * role id when `raw` is a string naming a role of the active profile,
566
+ * otherwise undefined. Never throws.
567
+ */
568
+ function validateActiveRoleId(raw) {
569
+ if (typeof raw !== "string") {
570
+ return undefined;
571
+ }
572
+ return getActiveRole(raw.trim())?.id;
573
+ }
574
+ /**
575
+ * Same normalization semantics as the roles.ts registry helper (trim, drop
576
+ * blanks, dedupe case-insensitively keeping first occurrence and original
577
+ * casing). Lives here because the runtime consumers (http-server endpoints,
578
+ * worker skill-installer) moved to the profile face in Phase 1.3; roles.ts
579
+ * keeps its own copy for the registry layer. Behavior is locked byte-for-byte
580
+ * by tests/test-software-rd-golden.mjs.
581
+ */
582
+ function normalizeRecommendedSkills(skills = []) {
583
+ const seen = new Set();
584
+ const normalized = [];
585
+ for (const entry of skills) {
586
+ const value = String(entry || "").trim();
587
+ if (!value) {
588
+ continue;
589
+ }
590
+ const key = value.toLowerCase();
591
+ if (seen.has(key)) {
592
+ continue;
593
+ }
594
+ seen.add(key);
595
+ normalized.push(value);
596
+ }
597
+ return normalized;
598
+ }
599
+ /** Active-profile counterpart of roles.ts resolveRecommendedSkillsForRole. */
600
+ function resolveActiveRoleSkills(roleId, taskSkills = []) {
601
+ const roleSkills = roleId ? (getActiveRole(roleId)?.recommendedSkills ?? []) : [];
602
+ return normalizeRecommendedSkills([...roleSkills, ...taskSkills]);
603
+ }
604
+ export { BUILTIN_PROFILES, SOFTWARE_RD_PROFILE_ID, validateProfilePackage, hasProfile, setActiveProfileId, getActiveProfileId, getActiveProfile, getActiveRoles, getActiveRoleIds, getActiveDefaultRole, getActiveDomainInstructions, getActiveKnowledgePacks, getActiveWorkflows, getActiveRole, validateActiveRoleId, normalizeRecommendedSkills, resolveActiveRoleSkills, resolveRoleDisplayName, };