@teamclaws/teamclaw 2026.8.0 → 2026.11.0

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 (149) hide show
  1. package/cli.mjs +46 -15
  2. package/dist/api.js +1 -0
  3. package/dist/index.js +325 -0
  4. package/dist/src/config.js +412 -0
  5. package/dist/src/controller/clarification-routes.js +315 -0
  6. package/dist/src/controller/controller-capacity.js +14 -0
  7. package/dist/src/controller/controller-intake.js +895 -0
  8. package/dist/src/controller/controller-planning.js +813 -0
  9. package/dist/src/controller/controller-runs.js +175 -0
  10. package/dist/src/controller/controller-service.js +624 -0
  11. package/dist/src/controller/controller-tools.js +587 -0
  12. package/dist/src/controller/delivery-report.js +458 -0
  13. package/dist/src/controller/github-auth.js +564 -0
  14. package/dist/src/controller/http-server.js +284 -0
  15. package/dist/src/controller/kickoff-orchestrator.js +246 -0
  16. package/dist/src/controller/managed-gateway-process.js +286 -0
  17. package/dist/src/controller/message-delivery.js +28 -0
  18. package/dist/src/controller/message-router.js +38 -0
  19. package/dist/src/controller/message-routes.js +114 -0
  20. package/dist/src/controller/orchestration-manifest.js +151 -0
  21. package/dist/src/controller/preview-manager.js +586 -0
  22. package/dist/src/controller/preview-proxy.js +98 -0
  23. package/dist/src/controller/profile-switch.js +289 -0
  24. package/dist/src/controller/project-registry.js +294 -0
  25. package/dist/src/controller/prompt-injector.js +197 -0
  26. package/dist/src/controller/repo-routes.js +63 -0
  27. package/dist/src/controller/role-inference.js +246 -0
  28. package/dist/src/controller/route-table.js +1353 -0
  29. package/dist/src/controller/task-assignment.js +508 -0
  30. package/dist/src/controller/task-cleanup.js +258 -0
  31. package/dist/src/controller/task-execution.js +240 -0
  32. package/dist/src/controller/task-results.js +461 -0
  33. package/dist/src/controller/task-router.js +137 -0
  34. package/dist/src/controller/task-routes.js +703 -0
  35. package/dist/src/controller/teamauto-routes.js +124 -0
  36. package/dist/src/controller/tunnel-manager.js +548 -0
  37. package/dist/src/controller/ui-assets.js +68 -0
  38. package/dist/src/controller/websocket.js +42 -0
  39. package/dist/src/controller/worker-provisioning.js +1674 -0
  40. package/dist/src/controller/worker-routes.js +188 -0
  41. package/dist/src/discovery.js +86 -0
  42. package/dist/src/git-collaboration.js +694 -0
  43. package/dist/src/identity.js +132 -0
  44. package/dist/src/install-defaults.js +1 -0
  45. package/dist/src/interaction-contracts.js +531 -0
  46. package/dist/src/networking.js +91 -0
  47. package/dist/src/openclaw-workspace.js +925 -0
  48. package/dist/src/profile-loader.js +486 -0
  49. package/dist/src/profiles/banking.json +178 -0
  50. package/dist/src/profiles/crossborder-ecom.json +253 -0
  51. package/dist/src/profiles/insurance.json +157 -0
  52. package/dist/src/profiles/knowledge/hs-structure.md +97 -0
  53. package/dist/src/profiles/knowledge/incoterms-2020.md +188 -0
  54. package/dist/src/profiles/knowledge/vat-principles.md +85 -0
  55. package/dist/src/profiles/schema.json +201 -0
  56. package/dist/src/profiles/securities.json +137 -0
  57. package/dist/src/profiles/software-rd.json +264 -0
  58. package/dist/src/profiles/trading-co.json +200 -0
  59. package/dist/src/prompt-policy.js +386 -0
  60. package/dist/src/protocol.js +58 -0
  61. package/dist/src/role-ids.js +29 -0
  62. package/dist/src/roles.js +390 -0
  63. package/dist/src/session-roles.js +14 -0
  64. package/dist/src/state.js +361 -0
  65. package/dist/src/task-executor.js +1023 -0
  66. package/dist/src/teamauto/github-client.js +210 -0
  67. package/dist/src/teamauto/norms.js +85 -0
  68. package/dist/src/teamauto/repo-sync.js +423 -0
  69. package/dist/src/teamauto/scanner.js +207 -0
  70. package/dist/src/teamauto/schedule.js +123 -0
  71. package/dist/src/teamauto/scheduler.js +907 -0
  72. package/dist/src/teamauto/store.js +133 -0
  73. package/dist/src/types.js +290 -0
  74. package/dist/src/ui/app.js +4860 -0
  75. package/dist/src/ui/assets/teamclaw-app-icon.png +0 -0
  76. package/dist/src/ui/github-login.html +296 -0
  77. package/dist/src/ui/index.html +447 -0
  78. package/dist/src/ui/style.css +2805 -0
  79. package/dist/src/worker/http-handler.js +146 -0
  80. package/dist/src/worker/message-queue.js +24 -0
  81. package/dist/src/worker/prompt-injector.js +78 -0
  82. package/dist/src/worker/skill-installer.js +255 -0
  83. package/dist/src/worker/tools.js +541 -0
  84. package/dist/src/worker/worker-service.js +307 -0
  85. package/dist/src/workspace-browser.js +269 -0
  86. package/openclaw.plugin.json +28 -1
  87. package/package.json +3 -2
  88. package/src/config.ts +33 -2
  89. package/src/controller/clarification-routes.ts +404 -0
  90. package/src/controller/controller-intake.ts +1113 -0
  91. package/src/controller/controller-planning.ts +1029 -0
  92. package/src/controller/controller-runs.ts +239 -0
  93. package/src/controller/controller-service.ts +295 -41
  94. package/src/controller/controller-tools.ts +11 -7
  95. package/src/controller/http-server.ts +294 -6971
  96. package/src/controller/kickoff-orchestrator.ts +70 -7
  97. package/src/controller/message-delivery.ts +49 -0
  98. package/src/controller/message-routes.ts +137 -0
  99. package/src/controller/orchestration-manifest.ts +6 -29
  100. package/src/controller/preview-proxy.ts +127 -0
  101. package/src/controller/profile-switch.ts +366 -0
  102. package/src/controller/project-registry.ts +361 -0
  103. package/src/controller/prompt-injector.ts +23 -8
  104. package/src/controller/repo-routes.ts +91 -0
  105. package/src/controller/role-inference.ts +260 -22
  106. package/src/controller/route-table.ts +1616 -0
  107. package/src/controller/task-assignment.ts +618 -0
  108. package/src/controller/task-cleanup.ts +344 -0
  109. package/src/controller/task-execution.ts +356 -0
  110. package/src/controller/task-results.ts +544 -0
  111. package/src/controller/task-router.ts +98 -6
  112. package/src/controller/task-routes.ts +812 -0
  113. package/src/controller/teamauto-routes.ts +121 -0
  114. package/src/controller/ui-assets.ts +70 -0
  115. package/src/controller/websocket.ts +13 -1
  116. package/src/controller/worker-provisioning.ts +32 -4
  117. package/src/controller/worker-routes.ts +241 -0
  118. package/src/identity.ts +3 -2
  119. package/src/interaction-contracts.ts +7 -7
  120. package/src/openclaw-workspace.ts +44 -18
  121. package/src/profile-loader.ts +650 -0
  122. package/src/profiles/banking.json +178 -0
  123. package/src/profiles/crossborder-ecom.json +253 -0
  124. package/src/profiles/insurance.json +157 -0
  125. package/src/profiles/knowledge/hs-structure.md +97 -0
  126. package/src/profiles/knowledge/incoterms-2020.md +188 -0
  127. package/src/profiles/knowledge/vat-principles.md +85 -0
  128. package/src/profiles/schema.json +201 -0
  129. package/src/profiles/securities.json +137 -0
  130. package/src/profiles/software-rd.json +264 -0
  131. package/src/profiles/trading-co.json +200 -0
  132. package/src/prompt-policy.ts +27 -13
  133. package/src/role-ids.ts +31 -0
  134. package/src/roles.ts +60 -14
  135. package/src/session-roles.ts +14 -0
  136. package/src/state.ts +236 -9
  137. package/src/task-executor.ts +7 -18
  138. package/src/teamauto/github-client.ts +21 -0
  139. package/src/teamauto/repo-sync.ts +246 -6
  140. package/src/teamauto/scanner.ts +47 -13
  141. package/src/teamauto/scheduler.ts +259 -16
  142. package/src/teamauto/store.ts +12 -0
  143. package/src/types.ts +133 -16
  144. package/src/ui/app.js +592 -24
  145. package/src/ui/index.html +44 -11
  146. package/src/ui/style.css +194 -0
  147. package/src/worker/prompt-injector.ts +48 -8
  148. package/src/worker/skill-installer.ts +3 -1
  149. package/src/worker/worker-service.ts +83 -3
@@ -0,0 +1,486 @@
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
+ /** Structural checks that sit outside what the JSON Schema subset can express. */
283
+ function crossValidateProfile(profile, profileFile) {
284
+ const roleIds = profile.roles.map((role) => role.id);
285
+ const roleIdSet = new Set(roleIds);
286
+ if (roleIdSet.size !== roleIds.length) {
287
+ throw new Error(`TeamClaw profile ${profileFile} ("${profile.id}") has duplicate role ids`);
288
+ }
289
+ const referenceErrors = [];
290
+ if (!roleIdSet.has(profile.defaultRole)) {
291
+ referenceErrors.push(`defaultRole "${profile.defaultRole}" is not a role of this profile`);
292
+ }
293
+ // Phase 2.4 red line (design 2.1/2.4): domainInstructions REPLACE the
294
+ // software operating rules, and the software-rd baseline deliberately does
295
+ // not carry them (its rules stay pre-composed in the role systemPrompts,
296
+ // locked byte-for-byte by the Phase 1.7 golden). Setting them on software-rd
297
+ // would double-inject an operating contract, so it is a fatal load error.
298
+ if (profile.id === SOFTWARE_RD_PROFILE_ID && profile.domainInstructions && profile.domainInstructions.length > 0) {
299
+ referenceErrors.push(`the "${SOFTWARE_RD_PROFILE_ID}" baseline profile must not set domainInstructions `
300
+ + "(its operating rules stay pre-composed in the role systemPrompts; design 2.1/2.4)");
301
+ }
302
+ for (const roleId of profile.warmupRoles) {
303
+ if (!roleIdSet.has(roleId)) {
304
+ referenceErrors.push(`warmupRoles entry "${roleId}" is not a role of this profile`);
305
+ }
306
+ }
307
+ for (const role of profile.roles) {
308
+ for (const nextRoleId of role.suggestedNextRoles) {
309
+ if (!roleIdSet.has(nextRoleId)) {
310
+ referenceErrors.push(`role "${role.id}" suggestedNextRoles entry "${nextRoleId}" is not a role of this profile`);
311
+ }
312
+ }
313
+ }
314
+ if (referenceErrors.length > 0) {
315
+ throw new Error(`TeamClaw profile ${profileFile} ("${profile.id}") has dangling role references (design 2.2 - refusing to start):\n`
316
+ + referenceErrors.map((line) => ` - ${line}`).join("\n"));
317
+ }
318
+ }
319
+ const BUILTIN_PROFILES = loadBuiltinProfiles();
320
+ // ---------------------------------------------------------------------------
321
+ // Phase 2.1 test-hook: optional extra profile packages (additive merge).
322
+ //
323
+ // TEAMCLAW_EXTRA_PROFILES_DIR points at a directory (e.g. the repository's
324
+ // tests/fixtures/profiles/) whose *.json packages are validated with the same
325
+ // schema + cross-field pipeline and MERGED into the built-in registry. This
326
+ // lets integration tests exercise the switch/archive/capability paths against
327
+ // a minimal non-software profile WITHOUT shipping test fixtures inside
328
+ // src/profiles/ (design 2.2: that directory is the distributed package set).
329
+ // The env var is unset in production, so runtime behavior is bit-identical;
330
+ // a broken extra package stays FATAL (same loader red line).
331
+ // ---------------------------------------------------------------------------
332
+ const EXTRA_PROFILES_DIR = process.env.TEAMCLAW_EXTRA_PROFILES_DIR?.trim() ?? "";
333
+ function mergeExtraProfiles() {
334
+ let files;
335
+ try {
336
+ files = fs.readdirSync(EXTRA_PROFILES_DIR)
337
+ .filter((name) => name.endsWith(".json") && name !== "schema.json")
338
+ .sort();
339
+ }
340
+ catch {
341
+ throw new Error(`TeamClaw cannot read TEAMCLAW_EXTRA_PROFILES_DIR "${EXTRA_PROFILES_DIR}" `
342
+ + "(set it to a directory of TeamProfile JSON packages, or unset it).");
343
+ }
344
+ const schemaFilePath = path.join(PROFILES_DIR, "schema.json");
345
+ const schema = readJsonFile(schemaFilePath);
346
+ for (const file of files) {
347
+ const record = validateProfilePackage(readJsonFile(path.join(EXTRA_PROFILES_DIR, file)), schema, file);
348
+ if (BUILTIN_PROFILES.has(record.id)) {
349
+ throw new Error(`TeamClaw extra profile ${file} shadows the built-in profile id "${record.id}"`);
350
+ }
351
+ BUILTIN_PROFILES.set(record.id, record);
352
+ }
353
+ }
354
+ if (EXTRA_PROFILES_DIR) {
355
+ mergeExtraProfiles();
356
+ }
357
+ // The active profile defaults to the software-rd baseline. In controller
358
+ // mode, controller-service re-points it from TeamState.profileId (the single
359
+ // runtime truth, design 2.3) after loading state; config teamProfile only
360
+ // seeds FIRST initialization. Worker mode follows the controller (v1).
361
+ let activeProfileId = SOFTWARE_RD_PROFILE_ID;
362
+ /** True when `id` names a built-in profile package. */
363
+ function hasProfile(id) {
364
+ return BUILTIN_PROFILES.has(id);
365
+ }
366
+ /** Switch the active profile. Unknown ids are a programming error (throw). */
367
+ function setActiveProfileId(id) {
368
+ if (!BUILTIN_PROFILES.has(id)) {
369
+ throw new Error(`TeamClaw profile "${id}" is not a built-in profile (available: ${[...BUILTIN_PROFILES.keys()].sort().join(", ")})`);
370
+ }
371
+ activeProfileId = id;
372
+ }
373
+ function getActiveProfileId() {
374
+ return activeProfileId;
375
+ }
376
+ function getActiveProfile() {
377
+ const profile = BUILTIN_PROFILES.get(activeProfileId);
378
+ if (!profile) {
379
+ throw new Error(`TeamClaw active profile "${activeProfileId}" disappeared from the built-in registry`);
380
+ }
381
+ return profile;
382
+ }
383
+ function getActiveRoles() {
384
+ return getActiveProfile().roles;
385
+ }
386
+ function getActiveRoleIds() {
387
+ return getActiveRoles().map((role) => role.id);
388
+ }
389
+ function getActiveDefaultRole() {
390
+ return getActiveProfile().defaultRole;
391
+ }
392
+ /**
393
+ * Phase 2.4 (design 2.1/2.4): the active profile's industry guardrails, or
394
+ * undefined when the profile does not carry them (software-rd baseline).
395
+ * The prompt pipelines REPLACE buildRoleOperatingRules with these lines;
396
+ * a profile without them keeps the software operating rules unchanged.
397
+ */
398
+ function getActiveDomainInstructions() {
399
+ const instructions = getActiveProfile().domainInstructions;
400
+ return instructions && instructions.length > 0 ? instructions : undefined;
401
+ }
402
+ /**
403
+ * Phase 4 (design 2.1 knowledgePacks + 3 Phase 4 exception): the active
404
+ * profile's static reference packs, in declaration order, or an empty array
405
+ * when the profile declares none (software-rd baseline) - the worker prompt
406
+ * injector appends a Reference Packs section only for non-empty results, so
407
+ * profiles without packs keep their prompt bytes unchanged (Phase 1.7
408
+ * golden). Contents were validated + cached at load time; a hit that misses
409
+ * the cache is impossible by construction and stays a hard throw.
410
+ */
411
+ function getActiveKnowledgePacks() {
412
+ const names = getActiveProfile().knowledgePacks ?? [];
413
+ return names.map((name) => {
414
+ const content = KNOWLEDGE_PACK_CONTENTS.get(name);
415
+ if (content === undefined) {
416
+ throw new Error(`TeamClaw knowledge pack "${name}" (active profile "${getActiveProfileId()}") passed load validation `
417
+ + "but its cached content is missing - this is a loader invariant violation");
418
+ }
419
+ return { name, content };
420
+ });
421
+ }
422
+ /** Active-profile counterpart of roles.ts getRole. */
423
+ function getActiveRole(id) {
424
+ return getActiveRoles().find((role) => role.id === id);
425
+ }
426
+ /**
427
+ * Phase 2.6 labelZh fallback rule (vertical-team-profiles-design.md 2.1/2.6):
428
+ * the zh display name is labelZh when the role carries one, otherwise the
429
+ * English label. Encoded here - the loading-validation layer - so UI
430
+ * consumers (Phase 5) have a single backend source for the rule instead of
431
+ * re-implementing `labelZh ?? label` per surface; the schema guarantees a
432
+ * present labelZh is never an EMPTY string (minLength 1), and a
433
+ * whitespace-only labelZh (which minLength cannot reject) also falls back
434
+ * here via trim - a blank chip must never win over the fallback. v1 is
435
+ * bilingual only (design 5.3: no additional locales); "en" is accepted
436
+ * explicitly for symmetric rendering.
437
+ */
438
+ function resolveRoleDisplayName(role, locale = "zh") {
439
+ if (locale === "en") {
440
+ return role.label;
441
+ }
442
+ const labelZh = typeof role.labelZh === "string" ? role.labelZh.trim() : "";
443
+ return labelZh.length > 0 ? labelZh : role.label;
444
+ }
445
+ /**
446
+ * Active-profile counterpart of roles.ts validateRoleId: returns the trimmed
447
+ * role id when `raw` is a string naming a role of the active profile,
448
+ * otherwise undefined. Never throws.
449
+ */
450
+ function validateActiveRoleId(raw) {
451
+ if (typeof raw !== "string") {
452
+ return undefined;
453
+ }
454
+ return getActiveRole(raw.trim())?.id;
455
+ }
456
+ /**
457
+ * Same normalization semantics as the roles.ts registry helper (trim, drop
458
+ * blanks, dedupe case-insensitively keeping first occurrence and original
459
+ * casing). Lives here because the runtime consumers (http-server endpoints,
460
+ * worker skill-installer) moved to the profile face in Phase 1.3; roles.ts
461
+ * keeps its own copy for the registry layer. Behavior is locked byte-for-byte
462
+ * by tests/test-software-rd-golden.mjs.
463
+ */
464
+ function normalizeRecommendedSkills(skills = []) {
465
+ const seen = new Set();
466
+ const normalized = [];
467
+ for (const entry of skills) {
468
+ const value = String(entry || "").trim();
469
+ if (!value) {
470
+ continue;
471
+ }
472
+ const key = value.toLowerCase();
473
+ if (seen.has(key)) {
474
+ continue;
475
+ }
476
+ seen.add(key);
477
+ normalized.push(value);
478
+ }
479
+ return normalized;
480
+ }
481
+ /** Active-profile counterpart of roles.ts resolveRecommendedSkillsForRole. */
482
+ function resolveActiveRoleSkills(roleId, taskSkills = []) {
483
+ const roleSkills = roleId ? (getActiveRole(roleId)?.recommendedSkills ?? []) : [];
484
+ return normalizeRecommendedSkills([...roleSkills, ...taskSkills]);
485
+ }
486
+ export { BUILTIN_PROFILES, SOFTWARE_RD_PROFILE_ID, validateProfilePackage, hasProfile, setActiveProfileId, getActiveProfileId, getActiveProfile, getActiveRoles, getActiveRoleIds, getActiveDefaultRole, getActiveDomainInstructions, getActiveKnowledgePacks, getActiveRole, validateActiveRoleId, normalizeRecommendedSkills, resolveActiveRoleSkills, resolveRoleDisplayName, };