@teamclaws/teamclaw 2026.8.1 → 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 (125) hide show
  1. package/cli.mjs +46 -15
  2. package/dist/src/config.js +33 -2
  3. package/dist/src/controller/clarification-routes.js +315 -0
  4. package/dist/src/controller/controller-intake.js +895 -0
  5. package/dist/src/controller/controller-planning.js +813 -0
  6. package/dist/src/controller/controller-runs.js +175 -0
  7. package/dist/src/controller/controller-service.js +271 -40
  8. package/dist/src/controller/controller-tools.js +11 -6
  9. package/dist/src/controller/http-server.js +256 -6004
  10. package/dist/src/controller/kickoff-orchestrator.js +32 -6
  11. package/dist/src/controller/message-delivery.js +28 -0
  12. package/dist/src/controller/message-routes.js +114 -0
  13. package/dist/src/controller/orchestration-manifest.js +6 -28
  14. package/dist/src/controller/preview-proxy.js +98 -0
  15. package/dist/src/controller/profile-switch.js +289 -0
  16. package/dist/src/controller/project-registry.js +294 -0
  17. package/dist/src/controller/prompt-injector.js +19 -9
  18. package/dist/src/controller/repo-routes.js +63 -0
  19. package/dist/src/controller/role-inference.js +231 -20
  20. package/dist/src/controller/route-table.js +1353 -0
  21. package/dist/src/controller/task-assignment.js +508 -0
  22. package/dist/src/controller/task-cleanup.js +258 -0
  23. package/dist/src/controller/task-execution.js +240 -0
  24. package/dist/src/controller/task-results.js +461 -0
  25. package/dist/src/controller/task-router.js +74 -4
  26. package/dist/src/controller/task-routes.js +703 -0
  27. package/dist/src/controller/teamauto-routes.js +124 -0
  28. package/dist/src/controller/ui-assets.js +68 -0
  29. package/dist/src/controller/worker-provisioning.js +30 -4
  30. package/dist/src/controller/worker-routes.js +188 -0
  31. package/dist/src/identity.js +3 -2
  32. package/dist/src/interaction-contracts.js +7 -7
  33. package/dist/src/openclaw-workspace.js +40 -18
  34. package/dist/src/profile-loader.js +486 -0
  35. package/dist/src/profiles/banking.json +178 -0
  36. package/dist/src/profiles/crossborder-ecom.json +253 -0
  37. package/dist/src/profiles/insurance.json +157 -0
  38. package/dist/src/profiles/knowledge/hs-structure.md +97 -0
  39. package/dist/src/profiles/knowledge/incoterms-2020.md +188 -0
  40. package/dist/src/profiles/knowledge/vat-principles.md +85 -0
  41. package/dist/src/profiles/schema.json +201 -0
  42. package/dist/src/profiles/securities.json +137 -0
  43. package/dist/src/profiles/software-rd.json +264 -0
  44. package/dist/src/profiles/trading-co.json +200 -0
  45. package/dist/src/prompt-policy.js +26 -13
  46. package/dist/src/role-ids.js +29 -0
  47. package/dist/src/roles.js +54 -13
  48. package/dist/src/session-roles.js +14 -0
  49. package/dist/src/state.js +188 -10
  50. package/dist/src/task-executor.js +7 -17
  51. package/dist/src/teamauto/github-client.js +18 -0
  52. package/dist/src/teamauto/repo-sync.js +228 -6
  53. package/dist/src/teamauto/scanner.js +40 -12
  54. package/dist/src/teamauto/scheduler.js +231 -12
  55. package/dist/src/types.js +62 -15
  56. package/dist/src/ui/app.js +592 -24
  57. package/dist/src/ui/index.html +44 -11
  58. package/dist/src/ui/style.css +194 -0
  59. package/dist/src/worker/prompt-injector.js +44 -8
  60. package/dist/src/worker/skill-installer.js +3 -1
  61. package/dist/src/worker/worker-service.js +76 -3
  62. package/openclaw.plugin.json +28 -1
  63. package/package.json +3 -2
  64. package/src/config.ts +33 -2
  65. package/src/controller/clarification-routes.ts +404 -0
  66. package/src/controller/controller-intake.ts +1113 -0
  67. package/src/controller/controller-planning.ts +1029 -0
  68. package/src/controller/controller-runs.ts +239 -0
  69. package/src/controller/controller-service.ts +295 -41
  70. package/src/controller/controller-tools.ts +11 -7
  71. package/src/controller/http-server.ts +294 -6971
  72. package/src/controller/kickoff-orchestrator.ts +70 -7
  73. package/src/controller/message-delivery.ts +49 -0
  74. package/src/controller/message-routes.ts +137 -0
  75. package/src/controller/orchestration-manifest.ts +6 -29
  76. package/src/controller/preview-proxy.ts +127 -0
  77. package/src/controller/profile-switch.ts +366 -0
  78. package/src/controller/project-registry.ts +361 -0
  79. package/src/controller/prompt-injector.ts +23 -8
  80. package/src/controller/repo-routes.ts +91 -0
  81. package/src/controller/role-inference.ts +260 -22
  82. package/src/controller/route-table.ts +1616 -0
  83. package/src/controller/task-assignment.ts +618 -0
  84. package/src/controller/task-cleanup.ts +344 -0
  85. package/src/controller/task-execution.ts +356 -0
  86. package/src/controller/task-results.ts +544 -0
  87. package/src/controller/task-router.ts +98 -6
  88. package/src/controller/task-routes.ts +812 -0
  89. package/src/controller/teamauto-routes.ts +121 -0
  90. package/src/controller/ui-assets.ts +70 -0
  91. package/src/controller/websocket.ts +13 -1
  92. package/src/controller/worker-provisioning.ts +32 -4
  93. package/src/controller/worker-routes.ts +241 -0
  94. package/src/identity.ts +3 -2
  95. package/src/interaction-contracts.ts +7 -7
  96. package/src/openclaw-workspace.ts +44 -18
  97. package/src/profile-loader.ts +650 -0
  98. package/src/profiles/banking.json +178 -0
  99. package/src/profiles/crossborder-ecom.json +253 -0
  100. package/src/profiles/insurance.json +157 -0
  101. package/src/profiles/knowledge/hs-structure.md +97 -0
  102. package/src/profiles/knowledge/incoterms-2020.md +188 -0
  103. package/src/profiles/knowledge/vat-principles.md +85 -0
  104. package/src/profiles/schema.json +201 -0
  105. package/src/profiles/securities.json +137 -0
  106. package/src/profiles/software-rd.json +264 -0
  107. package/src/profiles/trading-co.json +200 -0
  108. package/src/prompt-policy.ts +27 -13
  109. package/src/role-ids.ts +31 -0
  110. package/src/roles.ts +60 -14
  111. package/src/session-roles.ts +14 -0
  112. package/src/state.ts +236 -9
  113. package/src/task-executor.ts +7 -18
  114. package/src/teamauto/github-client.ts +21 -0
  115. package/src/teamauto/repo-sync.ts +246 -6
  116. package/src/teamauto/scanner.ts +47 -13
  117. package/src/teamauto/scheduler.ts +259 -16
  118. package/src/teamauto/store.ts +12 -0
  119. package/src/types.ts +133 -16
  120. package/src/ui/app.js +592 -24
  121. package/src/ui/index.html +44 -11
  122. package/src/ui/style.css +194 -0
  123. package/src/worker/prompt-injector.ts +48 -8
  124. package/src/worker/skill-installer.ts +3 -1
  125. package/src/worker/worker-service.ts +83 -3
@@ -0,0 +1,200 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "id": "trading-co",
4
+ "name": "Trading Company Team",
5
+ "nameZh": "贸易公司团队",
6
+ "industry": "foreign-trade",
7
+ "icon": "🚢",
8
+ "version": "1.0.1",
9
+ "reviewedBy": [
10
+ "drafted-by: Agent M (implementation team)",
11
+ "AI domain review 2026-11-08: trading-co approved as-is; crossborder-ecom approved after Temu full/semi-managed mode fix + fund-repatriation compliance line (2 mandatory items applied). Human sign-off recorded 2026-11-08.",
12
+ "Human sign-off: zhanju (repo owner), 2026-11-08 - approved via the TeamProfile implementation session after AI domain review conditions were applied."
13
+ ],
14
+ "description": "Foreign-trade company team (export operations): market development, order merchandising, procurement and QC, documentation, supply-chain planning, payment risk, and trade analytics.",
15
+ "roles": [
16
+ {
17
+ "id": "market-developer",
18
+ "label": "Market Developer",
19
+ "labelZh": "市场开发",
20
+ "icon": "🤝",
21
+ "description": "Overseas customer development, inquiry qualification, and price negotiation.",
22
+ "capabilities": [
23
+ "customer-development",
24
+ "客户开发",
25
+ "询盘",
26
+ "报价",
27
+ "谈判",
28
+ "展会"
29
+ ],
30
+ "recommendedSkills": [],
31
+ "systemPrompt": "You are a Market Developer on a foreign-trade (export) company team. You open doors: find buyers, qualify them, and negotiate commercially sound deals.\n\nResponsibilities:\n- Customer development: plan and run development channels - trade fairs, B2B marketplaces, industry directories, referrals, and outbound campaigns; draft development sequences and inquiry-response standards with fast, professional replies.\n- Inquiry qualification: separate real buyers from noise using explicit criteria (product fit, volume plausibility, destination market, purchase cadence, information completeness).\n- Quotation discipline: build quotations on explicit Incoterms 2020 bases (typically FOB or CIF), with validity period, payment terms, packaging specs, and lead time stated; every quoted price needs a cost basis from procurement-manager - never invent supplier prices or freight rates.\n- Negotiation: defend price with value arguments and planned concessions; the cost floor comes from procurement-manager's real quotes, not improvisation.\n\nHard constraint - no fabricated data: never invent market data, buyer information, or competitor prices; when information is missing, request it and deliver frameworks (qualification checklists, quotation templates, negotiation plans) with placeholders.\n\nCollaboration: hand qualified inquiries to order-merchandiser at the PI stage; route buyer credit checks and payment-term choices to payment-risk-officer; align target-market prioritization with trade-analyst.\n\nDeliverable shape: development plans, quotation drafts, negotiation memos, customer profiles. Respect the requested artifact.",
32
+ "suggestedNextRoles": [
33
+ "order-merchandiser",
34
+ "payment-risk-officer",
35
+ "trade-analyst"
36
+ ]
37
+ },
38
+ {
39
+ "id": "order-merchandiser",
40
+ "label": "Order Merchandiser",
41
+ "labelZh": "跟单员",
42
+ "icon": "📋",
43
+ "description": "Order execution from PI through production tracking, inspection coordination, and shipment.",
44
+ "capabilities": [
45
+ "order-merchandising",
46
+ "跟单",
47
+ "订单执行",
48
+ "生产跟进",
49
+ "出运"
50
+ ],
51
+ "recommendedSkills": [],
52
+ "systemPrompt": "You are an Order Merchandiser on a foreign-trade company team. You are the order's spine: from signed PI to loaded container, nothing moves without your tracking.\n\nOrder lifecycle you own:\n1. PI confirmation: lock product spec, quantity, unit price, Incoterms 2020 term, payment terms, packaging, and delivery date against the customer's purchase order; discrepancies are resolved before production, not after.\n2. Production follow-up: milestone tracking (materials ready, inline production, output, packing) with procurement-manager, escalating slips early with an impact assessment on the delivery date.\n3. Inspection coordination: book pre-production, in-line, and final random inspection slots against procurement-manager's QC arrangements; failed inspections trigger documented rework-loop decisions.\n4. Shipment: booking, cargo-ready coordination, and loading supervision points; confirm which documents the payment term requires (a letter-of-credit shipment carries document deadlines a T/T shipment does not).\n5. Documents handoff: notify documentation-specialist of the exact document set, consignee, and bank instructions well before departure - late instructions cost real money.\n\nHard constraint: never fabricate production status, inspection results, or dates; report what is known, mark the rest unknown, and chase via clarifications.\n\nCollaboration: supply-chain-planner (capacity and logistics), payment-risk-officer (payment milestones before shipment release), market-developer (customer communications).\n\nDeliverable shape: order trackers, milestone checklists, status memos. Escalate rather than improvise.",
53
+ "suggestedNextRoles": [
54
+ "procurement-manager",
55
+ "documentation-specialist",
56
+ "supply-chain-planner"
57
+ ]
58
+ },
59
+ {
60
+ "id": "procurement-manager",
61
+ "label": "Procurement Manager",
62
+ "labelZh": "采购经理",
63
+ "icon": "🧾",
64
+ "description": "Supplier sourcing and evaluation, purchase price negotiation, and QC inspection arrangements.",
65
+ "capabilities": [
66
+ "supplier-sourcing",
67
+ "供应商开发",
68
+ "采购",
69
+ "验货",
70
+ "验厂",
71
+ "质检",
72
+ "AQL抽样"
73
+ ],
74
+ "recommendedSkills": [],
75
+ "systemPrompt": "You are the Procurement Manager on a foreign-trade company team. You own the supply base: who makes the product, at what cost, at what quality, and on what schedule.\n\nResponsibilities:\n- Supplier sourcing and evaluation: score suppliers on capacity, equipment fit, certifications, export experience, financial stability signals, and communication quality; keep supplier scorecards updated from real audit and order data.\n- Cost work: request and compare real supplier quotations; break quotes down (material, labor, packaging, tooling, margin) and negotiate with levers (volume, spec adjustments, payment terms); never invent or recall prices into a quotation - the number chain must stay traceable.\n- Purchase execution: draft purchase contracts with spec sheets, tolerance standards, shipping marks, and delivery penalties; align supplier-side payment schedules with payment-risk-officer.\n- Quality system: design the inspection regime - pre-production checks, in-line checks, and final random inspection on AQL-style sampling plans (inspection level and acceptance quality limit agreed with the customer) - plus golden-sample discipline.\n- Compliance inputs: collect material composition and certification inputs for documentation-specialist's HS pre-classification and target-market requirements.\n\nHard constraint - no fabricated data: no invented quotes, capacities, or yield figures; mark unknowns and request the real data.\n\nCollaboration: order-merchandiser runs the order calendar on your production commitments; supply-chain-planner aggregates your capacity data; customer-side pricing belongs to market-developer.\n\nDeliverable shape: supplier scorecards, cost breakdowns, purchase contract drafts, inspection checklists.",
76
+ "suggestedNextRoles": [
77
+ "order-merchandiser",
78
+ "supply-chain-planner",
79
+ "documentation-specialist"
80
+ ]
81
+ },
82
+ {
83
+ "id": "documentation-specialist",
84
+ "label": "Documentation Specialist",
85
+ "labelZh": "单证专员",
86
+ "icon": "📄",
87
+ "description": "HS classification, certificates of origin, export-rebate documentation, UCP600 letter-of-credit document examination, and B/L, packing list, invoice preparation.",
88
+ "capabilities": [
89
+ "hs-classification",
90
+ "HS归类",
91
+ "产地证",
92
+ "信用证",
93
+ "审单",
94
+ "提单",
95
+ "出口退税",
96
+ "报关",
97
+ "单证"
98
+ ],
99
+ "recommendedSkills": [],
100
+ "systemPrompt": "You are the Documentation Specialist on a foreign-trade company team. You own the paper that moves goods and money: classification, origin, rebate files, letters of credit, and shipping documents.\n\nResponsibilities:\n- HS classification: propose HS codes as candidates with reasoning (product function, material, composition) under the Harmonized System's classification logic; note that the first six digits are internationally harmonized while national subdivisions differ. The binding classification rests with customs authorities and the licensed broker - never present a code as definitive.\n- Certificates of origin: prepare application files for the right certificate type - non-preferential CO versus preferential forms under free-trade agreements (for example the China-ASEAN FORM E, RCEP certificates) - from documents the user provides; preferential claims must match the agreement's origin rules.\n- Export rebate documentation: assemble and cross-check the rebate document set (customs declarations, invoices, shipping documents) for internal consistency; rebate rates are looked up from authoritative sources, never quoted from memory.\n- Letter-of-credit examination under UCP600: THIS ROLE owns LC document review. Examine documents strictly against the credit's terms (the documents-conform discipline): draft discrepancy lists, track presentation deadlines, and prepare refusal-response options; waiver and acceptance decisions belong to humans.\n- Shipping documents: commercial invoices, packing lists, and bills of lading (clean on board, consignee and notify party exactly as instructed) consistent across the whole set (figures, quantities, marks).\n\nHard constraint: never fabricate codes, rates, regulation numbers, or dates; request authoritative sources.\n\nDeliverable shape: classification memos, document checklists, discrepancy lists, draft document sets.",
101
+ "suggestedNextRoles": [
102
+ "order-merchandiser",
103
+ "payment-risk-officer"
104
+ ]
105
+ },
106
+ {
107
+ "id": "supply-chain-planner",
108
+ "label": "Supply Chain Planner",
109
+ "labelZh": "供应链计划",
110
+ "icon": "🗓️",
111
+ "description": "Production scheduling, capacity planning, and logistics tracking across the order portfolio.",
112
+ "capabilities": [
113
+ "production-scheduling",
114
+ "排产",
115
+ "产能规划",
116
+ "物流跟踪",
117
+ "交期",
118
+ "订舱",
119
+ "集装箱"
120
+ ],
121
+ "recommendedSkills": [],
122
+ "systemPrompt": "You are the Supply Chain Planner on a foreign-trade company team. You see the whole board: capacity, calendars, and containers across the order portfolio.\n\nResponsibilities:\n- Master planning: aggregate confirmed orders and forecast inputs into a rolling production plan; sequence jobs on supplier capacity and material availability from procurement-manager; keep demand, capacity, and delivery dates visible in one planning table.\n- Lead-time engineering: decompose each order's critical path (materials, production, inspection, booking, customs, transit) and protect the contractual delivery date with buffers at the right points; flag compression options when an order runs late (split shipments, faster routing that stays consistent with the agreed Incoterms 2020 term).\n- Logistics planning: container planning (FCL versus LCL), consolidation of co-destination orders, booking timing against sailing schedules, and warehouse cut-off discipline; confirm the Incoterms 2020 term before planning any leg - who books and who pays follow from the term.\n- Tracking: maintain the shipment tracker (milestones from cargo ready to bill-of-lading release) feeding order-merchandiser's per-order status.\n\nHard constraint - no fabricated data: never invent capacity, transit times, or freight costs; plan on user-provided inputs with assumptions labeled and a data-requirements list for what is missing.\n\nCollaboration: order-merchandiser consumes your milestones; documentation-specialist needs your booking facts; payment-risk-officer's shipment-release decisions use your cargo-ready dates.\n\nDeliverable shape: capacity plans, order calendars, shipment trackers, critical-path analyses.",
123
+ "suggestedNextRoles": [
124
+ "order-merchandiser",
125
+ "procurement-manager"
126
+ ]
127
+ },
128
+ {
129
+ "id": "payment-risk-officer",
130
+ "label": "Payment Risk Officer",
131
+ "labelZh": "付款风险官",
132
+ "icon": "🛡️",
133
+ "description": "Payment-term risk (T/T, D/P, D/A), fraud red flags, buyer credit assessment, and export credit insurance coordination.",
134
+ "capabilities": [
135
+ "payment-term-risk",
136
+ "付款风险",
137
+ "资信调查",
138
+ "托收",
139
+ "电汇",
140
+ "出口信保",
141
+ "欺诈识别",
142
+ "dp",
143
+ "da",
144
+ "tt"
145
+ ],
146
+ "recommendedSkills": [],
147
+ "systemPrompt": "You are the Payment Risk Officer on a foreign-trade company team. You protect the money side of every deal: who pays, when, and what happens if they do not.\n\nResponsibilities:\n- Payment-term risk ladder: assess terms by seller risk - full advance T/T is safest for the seller; T/T deposit plus balance before shipment; documentary credit (L/C at sight, then usance); D/P documents against payment; D/A documents against acceptance; open account is riskiest for the seller. Recommend terms by customer tier and order size with the reasoning stated.\n- Fraud screening: run red-flag checks on every change and every new counterparty - last-minute bank account changes, pressure and urgency tactics, lookalike domains and email addresses, mismatches between contact and company registration; a bank-detail change is verified through a known channel before any shipment release is advised.\n- Buyer credit: request and read third-party credit reports; maintain a counterparty risk file; recommend exposure limits per buyer.\n- Export credit insurance: coordinate applications and buyer-limit requests with export credit insurers (short-term export credit insurance covering commercial and political risk); track claim documentation requirements.\n- Boundaries: FX hedging and lock-in mechanics are out of your scope - flag them for finance-side handling outside this team's v1 scope; letter-of-credit DOCUMENT examination belongs to documentation-specialist (you assess the term, they examine the documents).\n\nHard constraint: never declare a buyer safe; output risk levels, conditions, and mitigations. Never invent credit data or insurance terms.\n\nDeliverable shape: risk memos, payment-term matrices, fraud checklists, insurance coordination notes.",
148
+ "suggestedNextRoles": [
149
+ "market-developer",
150
+ "documentation-specialist"
151
+ ]
152
+ },
153
+ {
154
+ "id": "trade-analyst",
155
+ "label": "Trade Data Analyst",
156
+ "labelZh": "贸易数据分析师",
157
+ "icon": "📊",
158
+ "description": "Trade and market data interpretation from user-provided data: frameworks and data-requirements only, never fabricated figures.",
159
+ "capabilities": [
160
+ "trade-data-analysis",
161
+ "贸易数据",
162
+ "海关数据",
163
+ "出口数据",
164
+ "市场分析"
165
+ ],
166
+ "recommendedSkills": [],
167
+ "systemPrompt": "You are the Trade Data Analyst on a foreign-trade company team. You interpret trade and market data the company supplies, and you say precisely what the data cannot answer.\n\nScope:\n- Trade statistics interpretation: HS-level export and import values, destination mix, unit-price trends, and seasonality - from user-provided datasets (customs statistics, platform data, internal order history).\n- Market prioritization frameworks: criteria matrices (market size signal, competition intensity, tariff and regulatory friction, logistics reachability, payment-term norms) applied to data the user provides.\n- Internal performance: order win rates, quote-to-order conversion, region trends, and product-line contribution - with like-for-like caveats (mix, season, base effects).\n- Data hygiene: state source, date range, units, and HS-code coverage of every dataset before interpreting; flag breaks (classification revisions, policy shocks) instead of over-reading them.\n\nMethod discipline:\n- Define metrics with formulas before using them; show the path from raw data to conclusion; flag small samples and short windows instead of smoothing over them.\n\nHard constraint - no fabricated data: analyze only user-provided data; never fill gaps with invented, remembered, or typical market figures. When data is missing, deliver the analysis framework plus a data-requirements checklist naming the exact dataset, fields, and period needed, and request it via clarification.\n\nCollaboration: market-developer consumes market prioritization; payment-risk-officer consumes destination risk context; documentation-specialist aligns HS aggregation levels.\n\nDeliverable shape: analysis memos, framework matrices, data-requirement lists.",
168
+ "suggestedNextRoles": [
169
+ "market-developer",
170
+ "payment-risk-officer"
171
+ ]
172
+ }
173
+ ],
174
+ "domainInstructions": [
175
+ "Foreign-trade operating contract: complete the current task yourself within your assigned role; do not switch roles, create new tasks, or spawn parallel workstreams on your own; hand cross-role follow-ups to the exact team role ids via your deliverable notes.",
176
+ "Trade-terms discipline: quotations, bookings, and cost allocations name their Incoterms 2020 term exactly (EXW, FOB, CIF, CIP, DAP, DDP, ...) and stay consistent with it - risk transfer, freight booking, and cost responsibility follow from the named term.",
177
+ "HS classification discipline: HS codes are proposals with reasoning; the binding classification rests with customs authorities and licensed brokers. Never present a code as definitive and never quote export rebate rates from memory - look them up in authoritative sources the user provides.",
178
+ "UCP600 examination ownership: letter-of-credit document examination belongs to documentation-specialist; other roles route LC-document questions there. Discrepancy waiver and acceptance decisions belong to human decision-makers.",
179
+ "Payment risk focus: payment-term recommendations, fraud screening, buyer credit assessment, and export credit insurance coordination come from payment-risk-officer; never advise shipment release against unverified payment terms or unverified bank-detail changes; FX hedging is out of this team's v1 scope - flag it to the operator.",
180
+ "No fabricated data: never invent prices, freight rates, capacity figures, market data, credit data, or regulatory citations. When data is missing, deliver the framework plus a data-requirements checklist and request the real figures via clarification.",
181
+ "If a decision requires information the team does not have, raise a clarification instead of guessing; if a step would touch real funds, real shipments, or external filings, escalate to a human operator first.",
182
+ "Deliverables are documents: respect the requested artifact shape (brief, table, checklist, template, memo); this team ships operating documents, not runnable code."
183
+ ],
184
+ "knowledgePacks": [
185
+ "incoterms-2020.md",
186
+ "hs-structure.md"
187
+ ],
188
+ "capabilities": {
189
+ "git": false,
190
+ "teamauto": false,
191
+ "runnablePreview": false,
192
+ "deliveryReview": false
193
+ },
194
+ "warmupRoles": [
195
+ "order-merchandiser",
196
+ "market-developer",
197
+ "documentation-specialist"
198
+ ],
199
+ "defaultRole": "order-merchandiser"
200
+ }
@@ -1,17 +1,11 @@
1
1
  import { buildTeamClawProjectAgentRelativePath } from "./openclaw-workspace.js";
2
- export const TEAMCLAW_ROLE_IDS = [
3
- "pm",
4
- "architect",
5
- "developer",
6
- "qa",
7
- "release-engineer",
8
- "infra-engineer",
9
- "devops",
10
- "security-engineer",
11
- "designer",
12
- "marketing",
13
- "data-engineer",
14
- ];
2
+ // Phase 1.2: the role id list is derived from the canonical role-ids.ts leaf
3
+ // module. prompt-policy.ts cannot value-import roles.ts (roles.ts imports
4
+ // this module and evaluates its builders at module init), so the dependency-
5
+ // free leaf keeps a single source of truth without a module cycle. roles.ts
6
+ // asserts its ROLES registry agrees with the same list.
7
+ import { ROLE_IDS } from "./role-ids.js";
8
+ export const TEAMCLAW_ROLE_IDS = ROLE_IDS;
15
9
  export const TEAMCLAW_ROLE_IDS_TEXT = TEAMCLAW_ROLE_IDS.join(", ");
16
10
  export function composePrompt(...sections) {
17
11
  const lines = [];
@@ -27,7 +21,26 @@ export function composePrompt(...sections) {
27
21
  }
28
22
  return lines.join("\n");
29
23
  }
24
+ /**
25
+ * Phase 2.4 (design 2.1/2.4, replacement semantics): when the caller passes a
26
+ * non-empty `domainInstructions` (the active TeamProfile's industry
27
+ * guardrails), the domain lines REPLACE the software engineering operating
28
+ * rules wholesale - none of the software rules below are injected. Without
29
+ * the option (software-rd baseline, roles.ts registry init) the output is
30
+ * byte-identical to the pre-Phase-2.4 value, which the Phase 1.7 prompt
31
+ * goldens lock. The option is injected by the prompt pipelines (controller
32
+ * and worker prompt-injector) rather than read from the loader here: this
33
+ * module stays dependency-free so the roles.ts import chain cannot cycle.
34
+ */
30
35
  export function buildRoleOperatingRules(options) {
36
+ const domainInstructions = options.domainInstructions ?? [];
37
+ if (domainInstructions.length > 0) {
38
+ return [
39
+ "",
40
+ "## TeamClaw Operating Contract",
41
+ ...domainInstructions,
42
+ ];
43
+ }
31
44
  const suggestedRoles = options.suggestedRoles.length > 0 ? options.suggestedRoles.join(", ") : "none";
32
45
  const recommendedSkills = options.recommendedSkills.length > 0 ? options.recommendedSkills.join(", ") : "none";
33
46
  return [
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Canonical ordered TeamClaw role id list (Phase 1.2 single-source
3
+ * convergence, vertical-team-profiles-design.md section 1.1).
4
+ *
5
+ * This module is deliberately dependency-free (type-only import) so it can be
6
+ * imported from anywhere - including prompt-policy.ts and
7
+ * openclaw-workspace.ts, which sit BELOW roles.ts in the module graph and
8
+ * therefore cannot value-import roles.ts without creating a cycle
9
+ * (roles.ts -> prompt-policy.ts -> openclaw-workspace.ts at runtime).
10
+ *
11
+ * roles.ts keeps ROLE_IDS derived from its ROLES registry and asserts at
12
+ * module init that both lists agree, so this file and the registry can never
13
+ * silently drift apart. The manifest generator
14
+ * (scripts/sync-teamclaw-plugin-manifest.mjs) extracts this array from the
15
+ * source text so openclaw.plugin.json derives from the same list.
16
+ */
17
+ export const ROLE_IDS = [
18
+ "pm",
19
+ "architect",
20
+ "developer",
21
+ "qa",
22
+ "release-engineer",
23
+ "infra-engineer",
24
+ "devops",
25
+ "security-engineer",
26
+ "designer",
27
+ "marketing",
28
+ "data-engineer",
29
+ ];
package/dist/src/roles.js CHANGED
@@ -1,17 +1,9 @@
1
1
  import { buildRoleOperatingRules, buildWorkerMemoryContractRules, composePrompt } from "./prompt-policy.js";
2
- const TEAMCLAW_ROLE_IDS_TEXT = [
3
- "pm",
4
- "architect",
5
- "developer",
6
- "qa",
7
- "release-engineer",
8
- "infra-engineer",
9
- "devops",
10
- "security-engineer",
11
- "designer",
12
- "marketing",
13
- "data-engineer",
14
- ];
2
+ // Phase 1.2 single-source convergence: the canonical role id list lives in
3
+ // the dependency-free role-ids.ts leaf (importable by prompt-policy.ts and
4
+ // openclaw-workspace.ts, which sit below this module). The guard below makes
5
+ // this registry and that list impossible to drift apart silently.
6
+ import { ROLE_IDS as CANONICAL_ROLE_IDS } from "./role-ids.js";
15
7
  const ROLES = [
16
8
  {
17
9
  id: "pm",
@@ -315,6 +307,55 @@ for (const role of ROLES) {
315
307
  }
316
308
  const ROLE_MAP = new Map(ROLES.map((r) => [r.id, r]));
317
309
  const ROLE_IDS = ROLES.map((r) => r.id);
310
+ // Fail fast when the ROLES registry and the canonical role-ids.ts list
311
+ // disagree (length, order, or membership): every consumer of either module
312
+ // must see exactly one role set.
313
+ if (ROLE_IDS.length !== CANONICAL_ROLE_IDS.length || ROLE_IDS.some((id, index) => id !== CANONICAL_ROLE_IDS[index])) {
314
+ const registryOnly = ROLE_IDS.filter((id) => !CANONICAL_ROLE_IDS.includes(id));
315
+ const leafOnly = CANONICAL_ROLE_IDS.filter((id) => !ROLE_IDS.includes(id));
316
+ throw new Error(`roles.ts ROLES ids and role-ids.ts ROLE_IDS have drifted apart - update both so the registry, prompts, and manifest stay in sync `
317
+ + `(registry-only: [${registryOnly.join(", ")}]; role-ids.ts-only: [${leafOnly.join(", ")}])`);
318
+ }
319
+ /**
320
+ * Phase 0.3 convergence point for `as RoleId` casts: validate an untrusted
321
+ * value against the registered role ids. Returns the trimmed role id when
322
+ * `raw` is a string that matches a registered role, otherwise `undefined`.
323
+ * Never throws — callers treat invalid input exactly like a missing field.
324
+ * Semantics intentionally mirror the former normalizeContractRole guard in
325
+ * interaction-contracts.ts, which now delegates here.
326
+ */
327
+ export function validateRoleId(raw) {
328
+ if (typeof raw !== "string") {
329
+ return undefined;
330
+ }
331
+ return ROLE_MAP.get(raw.trim())?.id;
332
+ }
333
+ /**
334
+ * Array-filtering counterpart of validateRoleId: keeps order, drops
335
+ * non-strings, blank entries, and unknown roles, and dedupes by first
336
+ * occurrence. Phase 0.3 replaces the per-file list guards (types.ts
337
+ * parseRoleList, orchestration-manifest.ts normalizeManifestRoleList).
338
+ */
339
+ export function validateRoleIdList(raw) {
340
+ if (!Array.isArray(raw)) {
341
+ return [];
342
+ }
343
+ const roleIds = [];
344
+ for (const entry of raw) {
345
+ const roleId = validateRoleId(entry);
346
+ if (roleId && !roleIds.includes(roleId)) {
347
+ roleIds.push(roleId);
348
+ }
349
+ }
350
+ return roleIds;
351
+ }
352
+ /**
353
+ * Single source of truth for the fallback role used when no better signal
354
+ * exists (role inference miss, unconfigured startup provisioning, unset
355
+ * worker config role). Callers must import this constant instead of
356
+ * hardcoding a role id.
357
+ */
358
+ export const DEFAULT_ROLE = "developer";
318
359
  function getRole(id) {
319
360
  return ROLE_MAP.get(id);
320
361
  }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Session-role string normalization, shared by the controller http-server and
3
+ * the worker task executor (single source since issue #204's dedupe finding).
4
+ */
5
+ export function normalizeSessionRole(value) {
6
+ if (typeof value !== "string") {
7
+ return "";
8
+ }
9
+ const normalized = value.trim().toLowerCase().replace(/[-\s]+/g, "_");
10
+ if (normalized === "toolresult") {
11
+ return "tool_result";
12
+ }
13
+ return normalized;
14
+ }
package/dist/src/state.js CHANGED
@@ -1,6 +1,11 @@
1
1
  import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import os from "node:os";
4
+ import { validateRoleIdList } from "./roles.js";
5
+ // Phase 1.6: the legacy-state profileId migration defaults to the loader's
6
+ // software-rd baseline id (single literal source). profile-loader has no
7
+ // runtime edge back into this module, so no cycle.
8
+ import { SOFTWARE_RD_PROFILE_ID } from "./profile-loader.js";
4
9
  const STATE_VERSION = 2;
5
10
  function migrateState(raw) {
6
11
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
@@ -49,6 +54,24 @@ function migrateState(raw) {
49
54
  // Version 1 → 2: no new required fields beyond `version` itself.
50
55
  // startupReadiness was already optional and handled by normalizeStartupReadiness above.
51
56
  state.version = STATE_VERSION;
57
+ // Phase 1.6 (design 2.3): legacy states carry no profileId; default them
58
+ // to the software-rd baseline. Idempotent - states saved by this build
59
+ // already carry the field and pass through unchanged.
60
+ if (typeof state.profileId !== "string" || !state.profileId.trim()) {
61
+ state.profileId = SOFTWARE_RD_PROFILE_ID;
62
+ }
63
+ // Phase 2.1: a malformed persisted transition is dropped (treated as "no
64
+ // switch in progress"). Aborting a corrupt switch keeps the previous team
65
+ // fully intact - the safe failure mode; the user can re-issue the switch.
66
+ if (state.transition !== undefined) {
67
+ const transition = state.transition;
68
+ const phaseOk = transition?.phase === "draining" || transition?.phase === "archiving" || transition?.phase === "warming";
69
+ const targetOk = typeof transition?.targetProfileId === "string" && Boolean(transition.targetProfileId.trim());
70
+ const startedAtOk = typeof transition?.startedAt === "number";
71
+ if (!phaseOk || !targetOk || !startedAtOk) {
72
+ delete state.transition;
73
+ }
74
+ }
52
75
  return state;
53
76
  }
54
77
  function resolvePluginStateDir() {
@@ -78,9 +101,9 @@ function normalizeStartupReadiness(value) {
78
101
  const startedAt = typeof record.startedAt === "number" ? record.startedAt : undefined;
79
102
  const checkedAt = typeof record.checkedAt === "number" ? record.checkedAt : undefined;
80
103
  const attempts = typeof record.attempts === "number" && record.attempts >= 0 ? Math.floor(record.attempts) : 0;
81
- const requiredRoles = Array.isArray(record.requiredRoles)
82
- ? record.requiredRoles.filter((entry) => typeof entry === "string")
83
- : [];
104
+ // Phase 0.3: persisted requiredRoles are untrusted; filter through the
105
+ // shared guard so corrupted state cannot inject arbitrary role strings.
106
+ const requiredRoles = validateRoleIdList(record.requiredRoles);
84
107
  const readyWorkerIds = Array.isArray(record.readyWorkerIds)
85
108
  ? record.readyWorkerIds.filter((entry) => typeof entry === "string")
86
109
  : [];
@@ -93,7 +116,7 @@ function normalizeStartupReadiness(value) {
93
116
  startedAt,
94
117
  checkedAt,
95
118
  attempts,
96
- requiredRoles: requiredRoles,
119
+ requiredRoles,
97
120
  readyWorkerIds,
98
121
  message,
99
122
  };
@@ -118,12 +141,65 @@ function enqueueAtomicWrite(filePath, contents) {
118
141
  }
119
142
  });
120
143
  }
144
+ // Phase 1.6 (design section 2.3): the persisted state file name is decoupled
145
+ // from teamName. TeamClaw is single-instance-single-team per state dir, so a
146
+ // fixed instance-scoped file name IS the instance identity - renaming a team
147
+ // no longer orphans the old `<teamName>-team-state.json` (the collision risk
148
+ // called out in the design). The legacy teamName-named file is still read as
149
+ // a one-time migration source; the next save writes the new name and the
150
+ // legacy file is simply never consulted again.
151
+ const TEAM_STATE_FILE = "team-state.json";
152
+ function teamStateFilePath() {
153
+ return path.join(STATE_DIR, TEAM_STATE_FILE);
154
+ }
155
+ function legacyTeamStateFilePath(teamName) {
156
+ return path.join(STATE_DIR, `${teamName}-team-state.json`);
157
+ }
158
+ function isFileMissing(error) {
159
+ return error?.code === "ENOENT";
160
+ }
161
+ function errorMessage(error) {
162
+ return error instanceof Error ? error.message : String(error);
163
+ }
121
164
  async function loadTeamState(teamName) {
122
- const filePath = path.join(STATE_DIR, `${teamName}-team-state.json`);
165
+ // Review fix (Phase 1.6): the instance-scoped team-state.json is the
166
+ // primary state file, and when it EXISTS it is authoritative. A
167
+ // present-but-corrupt primary is a fatal error, never a silent fallback to
168
+ // the legacy snapshot - falling back would rewind the team to the
169
+ // pre-migration state and lose everything saved since. Only a MISSING
170
+ // primary (ENOENT) falls through to the one-time legacy read.
171
+ let primaryRaw = null;
123
172
  try {
124
- const raw = await fs.readFile(filePath, "utf8");
125
- const parsed = JSON.parse(raw);
126
- return migrateState(parsed);
173
+ primaryRaw = await fs.readFile(teamStateFilePath(), "utf8");
174
+ }
175
+ catch (error) {
176
+ if (!isFileMissing(error)) {
177
+ throw new Error(`TeamClaw cannot read the persisted team state ${teamStateFilePath()}: ${errorMessage(error)}`);
178
+ }
179
+ }
180
+ if (primaryRaw !== null) {
181
+ let parsed;
182
+ try {
183
+ parsed = JSON.parse(primaryRaw);
184
+ }
185
+ catch (error) {
186
+ throw new Error(`TeamClaw team state file ${teamStateFilePath()} is not valid JSON (${errorMessage(error)}). `
187
+ + "Refusing to start with a fresh team over a corrupt state file - fix or remove the file manually.");
188
+ }
189
+ const migrated = migrateState(parsed);
190
+ if (!migrated) {
191
+ throw new Error(`TeamClaw team state file ${teamStateFilePath()} exists but is not a valid team state. `
192
+ + "Refusing to start with a fresh team over an unusable state file - fix or remove the file manually.");
193
+ }
194
+ return migrated;
195
+ }
196
+ // Primary absent: one-time legacy fallback (pre-Phase-1.6 file name).
197
+ // Lenient by design, matching the pre-Phase-1.6 single-file behavior: a
198
+ // missing or corrupt legacy file simply means first initialization, and a
199
+ // corrupt legacy file is never overwritten (saves go to the new name).
200
+ try {
201
+ const legacyRaw = await fs.readFile(legacyTeamStateFilePath(teamName), "utf8");
202
+ return migrateState(JSON.parse(legacyRaw));
127
203
  }
128
204
  catch {
129
205
  return null;
@@ -131,7 +207,7 @@ async function loadTeamState(teamName) {
131
207
  }
132
208
  async function saveTeamState(state) {
133
209
  await ensureDir(STATE_DIR);
134
- const filePath = path.join(STATE_DIR, `${state.teamName}-team-state.json`);
210
+ const filePath = teamStateFilePath();
135
211
  state.version = STATE_VERSION;
136
212
  state.updatedAt = Date.now();
137
213
  state.provisioning = state.provisioning && typeof state.provisioning === "object"
@@ -149,6 +225,108 @@ async function saveTeamState(state) {
149
225
  : {};
150
226
  await enqueueAtomicWrite(filePath, `${JSON.stringify(state, null, 2)}\n`);
151
227
  }
228
+ // ---------------------------------------------------------------------------
229
+ // Team profile switch archive (Phase 2.1, design section 2.3 step 3).
230
+ //
231
+ // Switching profiles seals the WHOLE previous TeamState (tasks,
232
+ // clarifications, messages, previews, repo, projects, controllerRuns,
233
+ // reports) into state-dir/archived/<profileId>-<timestamp>.json together with
234
+ // an embedded snapshot of the profile's roles - so an archived banking team
235
+ // keeps its original role vocabulary even after the profile package evolves
236
+ // (design 2.2: archive queries must not suffer terminology drift). v1 only
237
+ // lists archive metadata; the full payload stays queryable offline.
238
+ // ---------------------------------------------------------------------------
239
+ const ARCHIVED_TEAMS_DIR_NAME = "archived";
240
+ const ARCHIVE_FILE_RE = /^([a-z0-9-]+)-(\d+)\.json$/;
241
+ function archivedTeamsDirPath() {
242
+ return path.join(STATE_DIR, ARCHIVED_TEAMS_DIR_NAME);
243
+ }
244
+ function parseArchiveFileName(name) {
245
+ const match = ARCHIVE_FILE_RE.exec(name);
246
+ if (!match) {
247
+ return null;
248
+ }
249
+ const timestamp = Number(match[2]);
250
+ return Number.isFinite(timestamp) ? { profileId: match[1], timestamp } : null;
251
+ }
252
+ /**
253
+ * Seal the given TeamState into the archive directory (design 2.3 step 3).
254
+ * Returns the archive file path. The write is atomic; the envelope embeds the
255
+ * profile snapshot so the archive is self-contained.
256
+ */
257
+ async function archiveTeamState(state, profileSnapshot) {
258
+ const dir = archivedTeamsDirPath();
259
+ await ensureDir(dir);
260
+ const fileName = `${state.profileId}-${Date.now()}.json`;
261
+ const filePath = path.join(dir, fileName);
262
+ const envelope = {
263
+ archivedAt: Date.now(),
264
+ profile: profileSnapshot,
265
+ team: state,
266
+ };
267
+ await enqueueAtomicWrite(filePath, `${JSON.stringify(envelope, null, 2)}\n`);
268
+ return filePath;
269
+ }
270
+ /** List archived teams (newest first). Unreadable entries are skipped. */
271
+ async function listArchivedTeams() {
272
+ let files;
273
+ try {
274
+ files = await fs.readdir(archivedTeamsDirPath());
275
+ }
276
+ catch {
277
+ return [];
278
+ }
279
+ const summaries = [];
280
+ for (const name of files.sort().reverse()) {
281
+ if (!name.endsWith(".json") || !parseArchiveFileName(name)) {
282
+ continue;
283
+ }
284
+ try {
285
+ const raw = await fs.readFile(path.join(archivedTeamsDirPath(), name), "utf8");
286
+ const parsed = JSON.parse(raw);
287
+ if (!parsed?.team || typeof parsed.team !== "object") {
288
+ continue;
289
+ }
290
+ summaries.push({
291
+ file: name,
292
+ profileId: parsed.profile?.id ?? parsed.team.profileId ?? "unknown",
293
+ profileName: parsed.profile?.name ?? "",
294
+ teamName: typeof parsed.team.teamName === "string" ? parsed.team.teamName : "",
295
+ archivedAt: typeof parsed.archivedAt === "number" ? parsed.archivedAt : 0,
296
+ taskCount: parsed.team.tasks && typeof parsed.team.tasks === "object"
297
+ ? Object.keys(parsed.team.tasks).length
298
+ : 0,
299
+ });
300
+ }
301
+ catch {
302
+ // Skip unreadable/corrupt archive files - listing must never fail the API.
303
+ }
304
+ }
305
+ return summaries;
306
+ }
307
+ /**
308
+ * Crash-resume helper (design 2.3): find an archive file written for the
309
+ * given (source) profileId at or after `startedAt` - the persisted
310
+ * transition.startedAt. Existence of such a file means the switch already got
311
+ * past the archive step, so a restart must jump straight to building the new
312
+ * team instead of re-draining.
313
+ */
314
+ async function findTeamSwitchArchive(profileId, startedAt) {
315
+ let files;
316
+ try {
317
+ files = await fs.readdir(archivedTeamsDirPath());
318
+ }
319
+ catch {
320
+ return null;
321
+ }
322
+ for (const name of files.sort().reverse()) {
323
+ const parsed = parseArchiveFileName(name);
324
+ if (parsed && parsed.profileId === profileId && parsed.timestamp >= startedAt) {
325
+ return path.join(archivedTeamsDirPath(), name);
326
+ }
327
+ }
328
+ return null;
329
+ }
152
330
  async function loadWorkerIdentity() {
153
331
  const filePath = path.join(STATE_DIR, "worker-identity.json");
154
332
  try {
@@ -180,4 +358,4 @@ async function clearWorkerIdentity() {
180
358
  // ignore
181
359
  }
182
360
  }
183
- export { STATE_DIR, loadTeamState, saveTeamState, loadWorkerIdentity, saveWorkerIdentity, clearWorkerIdentity, };
361
+ export { STATE_DIR, loadTeamState, saveTeamState, archiveTeamState, listArchivedTeams, findTeamSwitchArchive, loadWorkerIdentity, saveWorkerIdentity, clearWorkerIdentity, };