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