BossAgents × WeChat Intelligent Agent Ecosystem Optimization Solution v2 — Requirements Specification Document
Version: 1.0 | Date: 2026-06-24 | Based on Optimization Solution v2.0 | Format: EARS
1. Component Positioning
1.1 Core Responsibilities
This component is responsible for deeply integrating the BossAgents industrial intelligent agent ecosystem with the WeChat/Tencent AI Agent ecosystem, enabling security fixes, memory system upgrades, WeChat channel access, multi-agent parallelism, model routing enhancements, and ecosystem expansion.
1.2 Core Inputs
- User Instructions: Business operation requests initiated via WeChat/WeCom/Feishu/Mini Program/Web Dashboard
- Audit Log Data: Two-phase log data generated by the existing audit-log.js
- Knowledge Base Query Requests: Search requests initiated by the frontend KnowledgeService
- LLM Inference Requests: Various AI tasks distributed by the CapabilityDispatcher
- Scheduled Trigger Signals: Heartbeat/analysis tasks triggered by LiteScheduler cron scheduling
- WeChat Ecosystem Events: Messages and callbacks pushed by ClawBot/WeCom/Mini Program AI SDK
1.3 Core Outputs
- Business Execution Results: Structured responses (text/cards/notifications) processed by the digital employee
- Memory Data: Extracted facts, profiles, summaries, mental models, and forward-looking intents
- Knowledge Retrieval Results: Matched knowledge entries returned by the backend search API
- WeChat Message Push: Execution results and progress notifications returned via the WeChat channel
- Audit and Evolution Logs: Operation audit records and rule evolution history
1.4 Responsibility Boundaries
- Not Responsible For: Underlying AML data storage and CRUD operations of the SCSAI Agent platform
- Not responsible for: Rule generation logic of SCIOT rule engine (reuse existing generated/ directory)
- Not responsible for: Underlying compute scheduling of Ascend NPU/MTCLAW (only invoked via SmartLLMRouter)
- Not responsible for: Internal implementation maintenance of WeChat/WeCom official SDKs
- Not responsible for: Deployment and O&M of OpenClaw/iLink platform itself
2. Domain Terminology
SmartLLMRouter
: BossAgents' unified LLM scheduler, implementing a 5-level fallback chain (MTCLAW → AscendNPU → Ollama → DeepSeek → rule engine → simulatedThinking), with circuit breaker and response caching.
LiteScheduler
: BossAgents' digital employee scheduler, implementing collaboration chains (triggered by onComplete), Loop/Goal scheduling, confirmation-suspension mechanism, supporting serial orchestration.
CapabilityDispatcher
: BossAgents' unified capability dispatcher, responsible for parameter normalization, audit logging, permission validation, with existing source routing support (wechat/feishu/web, etc.).
Hy-Memory
: WeChat agent's six-layer memory architecture (Atomic Traces → Atomic Facts → Identity Profile → Session Summaries → Mental Models → Forward-looking Intentions), incorporating System 1/2 dual systems and evolution chain.
OpenClaw
: Tencent's internal intelligent agent platform ecosystem, providing capabilities such as ClawBot WeChat plugin, iLink protocol, and Skills market. The access path for external projects is pending confirmation.
RuleEvolution
: The self-evolution closed-loop framework of BossAgents (414 lines), implementing the complete chain of rule collection → identification → suggestion → approval → monitoring.
Agentic RAG
: An enhanced knowledge retrieval mode where the agent autonomously evaluates retrieval quality and decides whether to re-retrieve or change strategies.
Mutex (_withStaffMutex)
: A memory-level Map lock in LiteScheduler used to prevent concurrent execution by the same staff member, currently lacking timeout release, deadlock detection, and distributed support.
simulatedThinking
: The final fallback mechanism in the SmartLLMRouter's degradation chain, returning a hardcoded thinking process. This is by design, not a defect, but the quality of degradation data needs enhancement.
Evolution Chain
: A memory management mechanism linking old/new memory versions via supersedes pointers, reusing the version management concept from RuleEvolution.
3. Roles and Boundaries
3.1 Core Roles
- Boss (Enterprise Decision-Maker): Issues business instructions to digital employees via WeChat/WeCom/Mini Programs, receives execution results and suggestions.
- System Administrator: Configures WeChat channels, manages digital employee permissions, and approves rule evolution suggestions.
- Developer: Deploys the BossAgents system, integrates new channels and models, and debugs issues.
3.2 External Systems
- WeChat/WeCom Platform: Message channels and AI SDK integration.
- Hunyuan Large Model API: Domestic compliant LLM inference service.
- OpenClaw Platform: Intelligent agent ecosystem (ClawBot plugin, Skills market, iLink protocol).
- SCSAI Agent: PLM foundation, providing industrial object models and business data
- Feishu Platform: Existing IM channel, already supports message sending and receiving
3.3 Interaction Context
@startuml
left to right direction
rectangle "BossAgents 生态优化系统" as core {
}
actor "老板" as boss
actor "系统管理员" as admin
actor "开发者" as dev
system "WeChat/企微平台" as wechat
system "混元大模型API" as hunyuan
system "OpenClaw平台" as openclaw
system "SCSAI Agent" as SCSAI
system "飞书平台" as feishu
boss --> core : WeChat/小程序下达指令\n接收执行结果
admin --> core : 配置通道/审批规则\n管理权限
dev --> core : 部署/集成/调试
core --> wechat : 消息收发/AI SDK
core --> hunyuan : LLM推理请求
core --> openclaw : ClawBot/Skills/iLink
core --> SCSAI : 业务数据读写
core --> feishu : 消息收发(现有)
@enduml
4. DFX约束
4.1 性能
- 微信消息响应时间:When 用户通过微信发送指令,the BossAgents系统 shall 在5秒内返回确认回执
- 知识检索响应时间:When 前端发起知识搜索请求,the 后端搜索API shall 在2秒内返回结果
- 记忆写入延迟:When CapabilityDispatcher完成一次执行,the Memory Service shall 在500ms内完成事实提取与写入
- 并行任务调度:When TaskDecomposer拆解出多个子任务,the LiteScheduler shall 在1秒内完成并行调度启动
4.2 可靠性
- 降级链路可用性:The SmartLLMRouter 5级降级链路 shall 保证99.5%的请求得到有效响应
- 审计日志持久化:The 审计日志系统 shall 确保所有操作日志写入数据库,不丢失任何一条记录
- 互斥锁超时释放:While 员工任务执行超过30秒,the 互斥锁 shall 自动释放,避免死锁
4.3 安全性
- JWT密钥管理:The 系统shall禁止使用硬编码fallback密钥,JWT密钥必须从环境变量读取
- Token持久化:The Token缓存shall使用Redis或文件持久化,禁止仅内存缓存(多实例场景)
- 审计日志完整性:The 审计日志shall记录所有关键操作,不可被篡改或跳过
4.4 可维护性
- 配置驱动:The 系统shall使用YAML/JSON配置驱动架构,新通道/模型接入无需修改核心代码
- 健康检查:The 系统shall提供/api/health端点,返回各组件运行状态
- 日志规范:The 系统shall使用结构化日志,包含traceId、tenantId、staffId等关键上下文
4.5 兼容性
- 现有通道兼容:Where 新增微信通道,the 系统shall保持飞书/Web/小程序现有通道功能不受影响
- 降级链路兼容:Where 新增混元模型provider,the SmartLLMRouter shall保持现有5级降级链路完整
- 数据迁移兼容:Where 新增记忆层存储,the 系统shall支持从空状态冷启动,无需历史数据迁移
5. 核心能力
Phase 0 — 前置修复
#### 5.0.1 JWT密钥硬编码fallbackRepair
##### Business Rules
- Prohibit hardcoded secrets: The miniapp-auth module shall read the secret key from the environment variable JWT_SECRET. If the environment variable is not set, it shall refuse to start and output a clear error message. Using 'change-me-in-production' as a fallback is prohibited.
a. Acceptance Criteria: [Environment variable JWT_SECRET is not set] → [Service fails to start, log outputs 'JWT_SECRET environment variable is required']
b. Acceptance Criteria: [Environment variable JWT_SECRET is set] → [Service starts normally, issued tokens use the environment variable value]
- Token cache persistence: The token cache shall use file persistence (single instance) or Redis (multiple instances). Using only an in-memory Map cache is prohibited.
a. Acceptance Criteria: [After service restart] → [Previously cached tokens remain verifiable, no re-login required]
b. Acceptance Criteria: [During multi-instance deployment] → [Tokens issued by instance A are verifiable on instance B]
##### Exception Scenarios
- JWT_SECRET is not set
a. Trigger Condition: Environment variable JWT_SECRET is empty or undefined at startup
b. System Behavior: Prevents service startup, outputs error log
c. User Perception: Startup script returns a non-zero exit code, console displays clear configuration guidance
#### 5.0.2 Audit Log DB Write Confirmation and Repair
##### Business Rules
- Audit Log Write Confirmation: The audit log system shall ensure that both the start and complete two-phase logs from audit-log.js are written to the database. The issue of the audit-logs/ directory being empty shall be fixed.
a. Acceptance Criteria: [Any staff member with a number executes a task] → [Corresponding start and complete audit records are queryable in the database]
b. Acceptance Criteria: [Query the audit-logs/ directory] → [Directory contains corresponding log files, or it is confirmed that logs are written only to the DB (not to files)]
- Audit Log Query API: The system shall provide a /api/audit-logs query interface supporting filtering by time range, staff ID, and task type.
a. Acceptance Criteria: [Call GET /api/audit-logs?staffId=xxx&from=2026-01-01] → [Return a list of audit records for that staff member within the specified time range]
##### Exception Scenarios
- Database Write Failure
a. Trigger Condition: Error occurs when writing audit logs to SQLite/MySQL
b. System Behavior: Degrade log writing to local file and trigger an alert
c. User Perception: Management interface displays an "Audit Log Storage Exception" alert
#### 5.0.3 Knowledge Base Frontend Integration with Backend Search API
##### Business Rules
- Frontend Search API Integration: The KnowledgeService shall call the backend /api/knowledge/search interface to obtain search results. Hardcoded data is prohibited.
a. Acceptance Criteria: [Enter a search keyword in the frontend knowledge base page] → [Initiate a fetch('/api/knowledge/search?q=...') request and display the results returned by the backend]
b. Acceptance criteria: [New rule added to backend knowledge base] → [New rule is immediately searchable in frontend search without frontend code changes]
- Search fallback strategy: When FTS5 is unavailable, the backend search API shall use LIKE + simple Chinese tokenization as the fallback solution.
a. Acceptance criteria: [SQLite version does not support FTS5] → [Search still works normally, using LIKE fuzzy matching]
b. Acceptance criteria: [Search for Chinese keyword "变更流程"] → [Returns knowledge entries containing "变更流程"]
- Search result format unification: The backend search API shall return a unified JSON format result, containing the fields: id, title, content, category, relevanceScore.
a. Acceptance criteria: [Calling the search API] → [Returns a JSON array, each record containing the above 5 fields]
##### Exception Scenarios
- Backend search service unavailable
a. Trigger condition: Frontend calling the search API returns a 5xx error or times out.
b. System behavior: Frontend displays a "Search service temporarily unavailable" prompt and provides a retry button.
c. User perception: The search page displays a user-friendly error message, not a blank screen or error stack.
- Jieba tokenization compilation failure
a. Trigger condition: Jieba npm package compilation fails in Windows/Node v22 environment.
b. System behavior: Automatically falls back to simple character-level tokenization.
c. User perception: Search function remains normally usable, with slightly lower Chinese tokenization accuracy.
#### 5.0.4 Feasibility Study on OpenClaw/ClawBot Integration
##### Business Rules
- Scope of Study: The study shall confirm the following three items: (a) Whether the OpenClaw CLI is publicly available; (b) Whether the ClawBot plugin is open to third-party developers; (c) The entry barrier for iLink protocol integration.
a. Acceptance Criteria: [Study Completed] → [A study report is produced, clearly stating the conclusions (feasible/infeasible/pending) and rationale for the three items.]
- Alternative Solution Evaluation: When OpenClaw/ClawBot is infeasible, the study shall evaluate three alternative solutions: building an in-house WeChat Work application, using Official Account + Customer Service Message APIs, and embedding a dialog within a Mini Program.
a. Acceptance Criteria: [OpenClaw Infeasible] → [The study report includes feasibility assessment, effort estimation, and recommended ranking for the three alternative solutions.]
- Study Deliverable: The study shall produce a written report containing conclusions, rationale, recommended solution, and risk points.
a. Acceptance Criteria: [Study Report Delivered] → [The report contains clear "Recommended Solution" and "Next Steps" sections.]
##### Exception Scenarios
- Insufficient Study Information
a. Trigger Condition: Missing OpenClaw/iLink documentation or non-public APIs.
b. System Behavior: Mark as "Pending," provide alternative solutions.
c. User Perception: The study report clearly indicates uncertainties without impacting subsequent development decisions.
Phase 1 — Quick Wins
#### 5.1.1 WeChat Channel Integration
##### Business Rules
- WeChat Message Reception: When a user sends a message via WeChat, the BossAgents system shall receive the message via ClawBot or a WeChat Work in-house application and forward it to the CapabilityDispatcher.
a. Acceptance Condition: [WeChat user sends 'Query BOM A001'] → [CapabilityDispatcher receives request with source='wechat' and executes]
- WeChat Message Reply: When the digital employee completes execution, the system shall return the result to the user via the WeChat channel.
a. Acceptance Condition: [Digital employee returns execution result] → [WeChat user receives result message (text/card format)]
- Channel Routing: The CapabilityDispatcher shall route and distribute messages based on the source (wechat/feishu/web/miniapp), with existing channel functionality unaffected.
a. Acceptance Condition: [WeChat message enters Dispatcher] → [Routed by source='wechat', without affecting Feishu/Web channels]
b. Acceptance Condition: [Feishu message enters Dispatcher] → [Routed by source='feishu', functionality remains completely consistent as before WeChat integration]
- Enterprise WeChat Custom App Alternative: Where ClawBot is unavailable, the system shall support access via an Enterprise WeChat custom-built application.
a. Acceptance Condition: [Configure Enterprise WeChat custom app parameters] → [System can receive and reply to Enterprise WeChat messages]
##### Interaction Flow
@startuml
actor "微信用户" as user
participant "WeChat/企微平台" as wechat
participant "BossAgents\nWeChatChannel" as channel
participant "CapabilityDispatcher" as dispatcher
participant "Digital Staff" as staff
user -> wechat : 发送消息
wechat -> channel : 消息回调
channel -> dispatcher : source='wechat'
dispatcher -> staff : 执行任务
staff -> dispatcher : 返回结果
dispatcher -> channel : 格式化结果
channel -> wechat : 发送回复
wechat -> user : 收到结果
@enduml
##### 异常场景
- WeChat Channel Disconnection
a. Trigger Condition: WeChat callback URL is unreachable or Token verification fails.
b. System Behavior: Log error, trigger alert, and automatically retry connection.
c. User Perception: No reply to WeChat messages, management interface displays channel abnormal alert.
- Message format incompatible
a. Trigger condition: WeChat message type not supported (e.g., video/file)
b. System behavior: Reply with "This message type is not currently supported" prompt
c. User perception: Receives a friendly unsupported prompt
#### 5.1.2 Mini Program Auto Mode Integration with WeChat AI + JWT Fix
##### Business Rules
- JWT key fix (related to Phase 0): The miniapp-auth module shall complete the JWT key hardcoding fix before integrating with WeChat AI (see 5.0.1)
a. Acceptance criteria: [Mini Program Login] → [Token issuance uses environment variable key, not hardcoded fallback]
- Auto mode integration: Where WeChat opens its mini program AI ecosystem for integration, the bossagents-miniapp shall support authorizing WeChat to read the mini program source code upon review submission, enabling AI capability integration with zero extra development
a. Acceptance criteria: [Mini Program submitted for review and AI access authorized] → [WeChat AI can read the mini program source code and provide intelligent services]
b. Acceptance criteria: [WeChat AI policy confirmation] → [Clarify specific policies and restrictions for WeChat's mini program AI ecosystem access opening on June 8, 2026]
- Mini Program chat entry: The bossagents-miniapp ai-chat page shall interface with the backend CapabilityDispatcher to support text dialogue
a. Acceptance criteria: [Enter "Help me check BOM" in the mini program ai-chat page] → [Calls backend API, returns digital employee execution result]
##### Exception Scenarios
- WeChat AI policy not yet opened
a. Trigger condition: WeChat Mini Program AI ecosystem access policy not open to third parties
b. System behavior: Auto mode marked as unavailable, guides user to use development mode
c. User Perception: The mini-program AI feature prompts "Not yet available" and provides an entry to development mode.
#### 5.1.3 Layer 1-3 Implementation of the Memory System
##### Business Rules
- Layer 1 Atomic Traces: The Memory Service shall reuse the existing two-phase logs (start/complete) from audit-log.js as atomic traces and provide the /api/memory/traces query replay interface.
a. Acceptance Criteria: [Digital employee executes a task] → [Memory Service records the two-phase atomic traces (start/complete)].
b. Acceptance Criteria: [Call GET /api/memory/traces?staffId=xxx] → [Returns the list of atomic traces for that employee, including timestamp, operation type, and parameter summary].
- Layer 2 Atomic Fact Extraction: When CapabilityDispatcher.execute() completes an execution, the Memory Service shall extract key facts (boss preferences, supplier preferences, common operations) from the interaction and store them in memory/facts.json.
a. Acceptance Criteria: [Boss says "I prefer Supplier A"] → [A new entry {category: "supplier_preference", value: "A", confidence: 0.9} is added to facts.json].
b. Acceptance Criteria: [Boss selects the same operation mode three times] → [The confidence for that operation mode in facts.json increases].
- Layer 3 User Profile Construction: The Memory Service shall build a user profile for the enterprise/boss, including enterprise information, role, frequently used object types, approval preferences, and store it in memory/profiles/{tenantId}.json
a. Acceptance Criteria: [Boss uses the system for the first time] → [A basic profile is automatically created, containing tenantId and default role values]
b. Acceptance Criteria: [Boss completes 3 BOM queries] → [The "frequently used object types" in the profile is updated to ["BOM"]]
- System 1 Real-time Writing: The Memory Service shall extract facts in real-time and write them within the finally block of CapabilityDispatcher.execute(), reusing the existing finally block pattern of the self-evolving learner
a. Acceptance Criteria: [Any capability execution completes] → [The finally block triggers fact extraction, and facts.json is updated in real-time]
- Integration with Tenant Middleware: The Memory Service shall integrate with tenant-middleware.js to ensure memory data is isolated by tenant
a. Acceptance Criteria: [Operations by Boss of Tenant A] → [Only the profile and facts of Tenant A are updated, without affecting Tenant B]
##### Interaction Flow
@startuml
participant "CapabilityDispatcher" as dispatcher
participant "Memory Service" as memory
participant "tenant-middleware" as tenant
database "memory/facts.json" as facts
database "memory/profiles/" as profiles
dispatcher -> memory : execute() finally块触发
memory -> tenant : 获取tenantId
tenant -> memory : 返回tenantId
memory -> facts : 提取事实并写入
memory -> profiles : 更新用户画像
@enduml
##### 异常场景
- Fact Extraction Failure
a. Trigger Condition: LLM call failure leads to fact extraction exception
b. System Behavior: Skip this fact extraction, log a warning, and do not affect the main process
c. User Perception: Business operation completes normally, memory update is delayed
- Image file corrupted
a. Trigger condition: memory/profiles/{tenantId}.json file format error
b. System behavior: Restore from backup or rebuild basic profile
c. User perception: Profile data reset to default values, historical preferences lost
#### 5.1.4 One-Click Deployment Package Optimization
##### Business Rules
- Environment check: When executing start.bat, the startup script shall check Node.js version, pnpm installation, and .env file existence
a. Acceptance criteria: [Node.js version lower than 18] → [Script outputs "Node.js 18+ required" and exits]
b. Acceptance criteria: [pnpm not installed] → [Script outputs "pnpm not found" and provides installation guidance]
c. Acceptance criteria: [.env file does not exist] → [Automatically copy from .env.example and prompt user to configure]
- Automatic dependency installation: When the node_modules directory does not exist, the startup script shall automatically execute pnpm install
a. Acceptance criteria: [First deployment, node_modules does not exist] → [Automatically execute pnpm install, continue startup after installation completes]
- Automatic DB initialization: When the database file does not exist, the startup script shall automatically call db-schema-init.js to initialize the database
a. Acceptance criteria: [First startup, SQLite file does not exist] → [Automatically create database and initialize table structure]
- Docker Single-Command Deployment: The system shall support single-command startup via docker run (including Node.js + SQLite + nginx).
a. Acceptance Criteria: [Execute docker run command] → [Complete service stack contained within a single container, accessible after health check passes].
##### Exception Scenarios
- Dependency Installation Failure
a. Trigger Condition: pnpm install fails due to network or permission issues.
b. System Behavior: Output detailed error information and provide suggestions for switching mirror sources.
c. User Perception: Script exits displaying "Dependency installation failed" along with remediation suggestions.
- Port Occupied
a. Trigger Condition: Port 3006 is already in use.
b. System Behavior: Prompt about port occupation, providing options to terminate the occupying process or change the port.
c. User Perception: Sees clear port conflict prompt and resolution options.
Phase 2 — Deep Enhancement
#### 5.2.1 Memory System Layer 4-6 + System 2
##### Business Rules
- Layer 4 Session Summarization: The Memory Service shall enhance the ConversationManager to aggregate session summaries by "business topic" (BOM/Purchasing/Change) and store them in the staff_session_summaries table.
a. Acceptance Criteria: [Complete a BOM query dialogue] → [A new BOM-topic summary, containing key decisions and results, is added to the session_summaries table].
b. Acceptance Criteria: [Query a tenant's historical session summaries] → [Summaries are displayed categorized by business topic, supporting time range filtering].
- Layer 5 Mental Models: The Memory Service shall construct a deep decision model of the boss (risk appetite, cost sensitivity, innovation willingness), stored in memory/mental-models/{tenantId}.json, asynchronously built by System 2.
a. Acceptance criteria: [After System 2 analyzes 30 days of audit logs] → [Generate {riskPreference: "conservative", costSensitivity: "high", innovationWillingness: "low"} in mental-models]
b. Acceptance criteria: [When the boss chooses low-cost solutions 3 times consecutively] → [Increase the weight of costSensitivity in the mental model]
- Layer 6 Forward-looking Intent: The Memory Service shall predict the boss's next need and store it in memory/intentions/{tenantId}.json, updated periodically by a heartbeat task (reusing the LiteScheduler cron mechanism)
a. Acceptance criteria: [After the boss completes BOM approval] → [Add {predicted: "Purchase order", confidence: 0.7, basedOn: "90% of historical BOM approvals trigger purchase"} to intentions]
b. Acceptance criteria: [When the heartbeat task runs every 15 minutes] → [Update the confidence and basedOn fields of the forward-looking intent]
- System 2 Asynchronous Analysis: The Memory Service shall add a cron job to analyze audit logs overnight and update Mental Models, reusing the LiteScheduler cron scheduling mechanism
a. Acceptance criteria: [Cron job executes daily at 2:00 AM] → [Analyzes the previous day's audit logs, updates the mental model and forward-looking intent]
b. Acceptance criteria: [During System 2 analysis] → [Does not affect System 1's real-time writes]
- Evolution chain: The Memory Service shall link old/new memory versions via supersedes pointers, reusing the version management approach of RuleEvolution, and store to memory/evolution-chain.json
a. Acceptance criteria: [Boss's preference changes from "Supplier A" to "Supplier B"] → [Evolution chain records {oldFact: "Preference A", newFact: "Preference B", supersedes: oldFactId, timestamp: ...}]
b. Acceptance criteria: [Querying the evolution history of a fact] → [Returns the complete supersedes chain, from earliest to latest]
##### Exception Scenarios
- System 2 Analysis Timeout
a. Trigger condition: Nightly cron job execution exceeds 1 hour
b. System behavior: Logs timeout, interrupts current analysis, retains partially processed results
c. User perception: Mental model update delayed, can be completed normally the next day
- Evolution Chain Break
a. Trigger condition: The memory record pointed to by a supersedes pointer is accidentally deleted
b. System behavior: Marks it as an orphaned record, rebuilds the chain from the current valid fact
c. User perception: Evolution history is incomplete, but does not affect current memory usage
#### 5.2.2 Multi-Agent Parallel Execution + Mutex Lock Upgrade
##### Business Rules
- Task Decomposition: When the boss assigns a complex task (e.g., "Compare quotes from three suppliers"), the TaskDecomposer shall use LLM to break it down into multiple subtasks.
a. Acceptance Criteria: [Input "Compare quotes from suppliers A/B/C"] → [Decomposed into 3 subtasks: Query quote for A, Query quote for B, Query quote for C]
b. Acceptance Criteria: [No dependencies between subtasks] → [Marked as eligible for parallel execution]
- Parallel Scheduling: The LiteScheduler shall add a runParallel(staffIds[], subTasks[]) method to support multiple staff executing tasks simultaneously.
a. Acceptance Criteria: [3 subtasks scheduled in parallel] → [3 staff start execution concurrently, total duration ≈ single execution duration]
b. Acceptance Criteria: [If any subtask fails] → [Other subtasks continue execution, failed items are annotated during final aggregation]
- Result Aggregation: The ResultAggregator shall use LLM to aggregate the execution results of multiple subtasks, resolve conflicts, and generate comprehensive recommendations.
a. Acceptance Criteria: [Aggregation of results from 3 supplier quotes] → [Generate a comprehensive recommendation such as "Recommend Supplier B, highest overall score"]
b. Acceptance Criteria: [If subtask results are contradictory] → [Annotate the contradictions for LLM judgment or request confirmation from the boss]
- Mutex Lock Timeout Release: While a staff task execution exceeds 30 seconds, the mutex lock shall be released automatically.
a. Acceptance condition: [Employee A's task card deadlocked for over 30 seconds] → [Mutex lock automatically released, Employee A can be rescheduled]
- Deadlock detection: The mutex lock system shall implement a deadlock detection mechanism, automatically resolving when a circular wait is detected
a. Acceptance condition: [Circular wait where Employee A waits for B, and B waits for A] → [System detects deadlock and automatically releases one of the locks]
- Existing collaboration chain compatibility: Where new parallel execution capability is added, the LiteScheduler shall maintain existing collaboration chain (onComplete trigger) functionality unaffected
a. Acceptance condition: [Tasks using onComplete collaboration chain] → [Serial execution behavior remains completely consistent with pre-upgrade]
##### Interaction Flow
@startuml
actor "老板" as boss
participant "CapabilityDispatcher" as dispatcher
participant "TaskDecomposer" as decomposer
participant "LiteScheduler" as scheduler
participant "员工A" as staffA
participant "员工B" as staffB
participant "员工C" as staffC
participant "ResultAggregator" as aggregator
boss -> dispatcher : "比较三家供应商报价"
dispatcher -> decomposer : 拆解任务
decomposer -> scheduler : 3个子任务并行调度
scheduler -> staffA : 查询供应商A报价
scheduler -> staffB : 查询供应商B报价
scheduler -> staffC : 查询供应商C报价
staffA -> aggregator : 报价A结果
staffB -> aggregator : 报价B结果
staffC -> aggregator : 报价C结果
aggregator -> dispatcher : 综合建议
dispatcher -> boss : "推荐供应商B"
@enduml
##### 异常场景
- Task decomposition failure
a. Trigger condition: LLM cannot understand complex task intent
b. System behavior: Fallback to serial execution, request boss confirmation for decomposition method
c. User perception: Receives "Task is complex, recommend stepwise execution" prompt
- Partial parallel execution failure
a. Trigger condition: 1 out of 3 parallel subtasks fails
b. System behavior: Annotate failed items during summarization, generate partial suggestions based on successful results
c. User perception: Receives "Supplier C quote query failed, suggestion based on A/B results..." prompt
- Result conflict
a. Trigger condition: Different subtasks return contradictory results
b. System behavior: Annotate contradictions, judged by LLM or request boss confirmation
c. User perception: Receives "Results contain contradictions, please confirm" prompt
#### 5.2.3 Hunyuan Large Model Integration + Semantic Classification
##### Business Rules
- Hunyuan Provider integration: The SmartLLMRouter shall add a hunyuan provider, inserted in the fallback chain after DeepSeek and before the rule engine (priority: 4.5)
a. Acceptance Condition: [DeepSeek unavailable] → [Automatic fallback to Hunyuan model]
b. Acceptance Condition: [Hunyuan model unavailable] → [Continue fallback to rule engine]
c. Acceptance Condition: [HUNYUAN_API_KEY environment variable configured] → [Hunyuan provider available, supporting both fast and think models]
- Semantic-Level Classification: The SmartLLMRouter shall upgrade keyword matching to semantic-level classification (embedding vectors), improving task classification accuracy
a. Acceptance Condition: [Input "Help me check if there are any issues with this BOM"] → [Semantically classified as "identify" capability, not a keyword matching failure]
b. Acceptance Condition: [Semantic classification confidence below 0.6] → [Fallback to keyword matching]
- Dynamic Routing: The SmartLLMRouter shall dynamically adjust model selection strategy based on historical accuracy rates
a. Acceptance Condition: [Hunyuan model's accuracy on BOM query tasks consistently higher than DeepSeek] → [BOM query tasks prioritized for routing to Hunyuan]
b. Acceptance Condition: [A specific model times out for 5 consecutive times] → [Automatically lower that model's priority]
- Maintain existing 5-level fallback chain: Where new Hunyuan provider and semantic classification are added, the SmartLLMRouter shall keep the existing MTCLAW→AscendNPU→Ollama→DeepSeek→Rule Engine→simulatedThinking fallback chain intact
a. Acceptance Condition: [When Hunyuan provider is disabled] → [Fallback chain remains completely consistent with pre-integration state]
- A/B Testing Support: The SmartLLMRouter shall support comparing the effects of different models for the same task.
a. Acceptance Criteria: [Enable A/B testing mode] → [Send the same request to two models simultaneously and record comparison results].
##### Exception Scenarios
- Hunyuan API Unavailable
a. Trigger Condition: HUNYUAN_API_KEY is not configured or API times out.
b. System Behavior: Skip the Hunyuan provider and continue with the fallback chain.
c. User Perception: The request responds normally, with Hunyuan fallback events logged.
- Semantic Classification Service Exception
a. Trigger Condition: Embedding vector service is unavailable.
b. System Behavior: Fall back to keyword matching.
c. User Perception: Classification accuracy slightly decreases; functionality remains unaffected.
#### 5.2.4 Deep Integration with Mini Program Development Mode
##### Business Rules
- AI Chat Deep Integration: The bossagents-miniapp ai-chat page shall be built based on the WeChat Mini Program AI SDK for custom integration, supporting text/voice input.
a. Acceptance Criteria: [Click the voice button on the mini program ai-chat page] → [Call WeChat voice recognition, convert to text, and send to the backend].
b. Acceptance Criteria: [Input "Help me create an ECR"] → [Call CapabilityDispatcher and return structured ECR creation results].
- Execution Progress Real-time Push: The bossagents-miniapp shall display digital employee execution progress in real-time via WebSocket (reusing ws-push-service.js + useWebSocket.js).
a. Acceptance Criteria: [Digital employee starts executing a task] → [Mini program displays "Querying BOM..." progress in real-time].
b. Acceptance criteria: [Task execution completed] → [Mini-program displays execution results in real time]
- Dashboard data integration: The bossagents-miniapp Dashboard page shall integrate with Memory Service profile data to display boss preferences and frequently used operations
a. Acceptance criteria: [Dashboard page loaded] → [Displays user profile summary retrieved from Memory Service]
##### Exception scenarios
- WeChat AI SDK version incompatibility
a. Trigger condition: WeChat Mini Program AI SDK API changes
b. System behavior: Degrades to plain text conversation mode
c. User perception: Voice functionality temporarily unavailable, text conversation remains normal
Phase 3 — Ecosystem expansion
#### 5.3.1 OpenClaw Skill packaging
##### Business rules
- Skill packaging and release: Where the OpenClaw ecosystem is available, the BossAgents shall package core capabilities as OpenClaw Skill format and release them
a. Acceptance criteria: [Six core capabilities of BossAgents packaged as Skills] → [Can be installed and invoked via OpenClaw CLI]
b. Acceptance criteria: [OpenClaw unavailable] → [Skill packaging postponed, without affecting BossAgents' own functionality]
- Skill interface standardization: The Skill packaging shall comply with OpenClaw Skill specifications, defining standard input and output interfaces
a. Acceptance criteria: [Skill definition includes name, description, inputSchema, outputSchema] → [Complies with OpenClaw Skill registration requirements]
##### Exception scenarios
- OpenClaw ecosystem unavailable
a. Trigger condition: OpenClaw platform does not open Skill publishing to third parties
b. System behavior: Skill encapsulation is suspended, interface definitions are retained for future use
c. User perception: BossAgents functionality is unaffected, Skill publishing awaits platform availability
#### 5.3.2 Hy-Memory Plugin / Self-built Alternative
##### Business rules
- Prioritize self-built: The memory system shall prioritize using the self-built Memory Service (implemented in Phase 1-2), without relying on the Hy-Memory plugin.
a. Acceptance criteria: [Memory Service Layer 1-6 fully implemented] → [Memory functionality is complete and usable, independent of external plugins]
- Hy-Memory plugin compatibility: Where BossAgents run on OpenClaw and the Hy-Memory plugin is available, the system shall support one-click switching to the Hy-Memory plugin.
a. Acceptance criteria: [Configure memory.provider=hy-memory] → [Memory read/write switches to the Hy-Memory plugin]
b. Acceptance criteria: [Configure memory.provider=self-built] → [Memory read/write uses the self-built Memory Service]
##### Exception scenarios
- Hy-Memory plugin and self-built data format incompatibility
a. Trigger condition: Inconsistent data format after switching providers
b. System behavior: Provide data migration tool to automatically convert formats
c. User perception: Brief unavailability during switchover, data integrity preserved
#### 5.3.3 Agentic RAG Knowledge Retrieval
##### Business Rules
- Agent self-evaluates retrieval quality: The Agentic RAG shall support the Agent in autonomously evaluating the quality of retrieval results, and automatically re-retrieve or switch strategies when quality is unsatisfactory
a. Acceptance condition: [Retrieval result relevanceScore below 0.5] → [Agent automatically adjusts query terms and re-retrieves]
b. Acceptance condition: [Retrieval quality unsatisfactory for 2 consecutive attempts] → [Agent switches to a different retrieval strategy (e.g., from FTS5 to vector retrieval)]
- Multi-strategy retrieval: The Agentic RAG shall support automatic switching among three strategies: FTS5 full-text search, LIKE fuzzy matching, and vector semantic retrieval
a. Acceptance condition: [FTS5 retrieval returns no results] → [Automatically switch to LIKE fuzzy matching]
b. Acceptance condition: [LIKE retrieval returns too many results] → [Automatically switch to vector semantic retrieval for fine-ranking]
- Prerequisite: Where Agentic RAG is implemented, the knowledge base frontend and backend must already be connected (Phase 0 Task 0c completed)
a. Acceptance condition: [Phase 0 Task 0c not completed] → [Agentic RAG cannot be implemented, return prerequisite dependency prompt]
##### Exception Scenarios
- All retrieval strategies return no results
a. Trigger condition: FTS5, LIKE, and vector retrieval all return empty results
b. System behavior: Returns a "No relevant knowledge found" prompt, suggesting the user to supplement the knowledge base.
c. User perception: Receives a clear no-result prompt and a suggestion to supplement the knowledge base.
#### 5.3.4 Team Collaboration Chain + Role Permissions
##### Business Rules
- Role permission definition: The system shall define three roles: Boss, Administrator, and Regular Employee, each with different operation permissions.
a. Acceptance criteria: [Regular employee attempts to approve an ECR] → [Returns an "Insufficient permissions" error].
b. Acceptance criteria: [Boss approves an ECR] → [Approval succeeds, process continues].
- Team collaboration chain: The system shall support cross-role collaboration chains, e.g., Employee submits → Supervisor reviews → Boss approves.
a. Acceptance criteria: [Employee submits an ECR] → [Automatically routes to Supervisor for review, then to Boss for approval after Supervisor review].
b. Acceptance criteria: [Supervisor rejects] → [Process returns to the employee with rejection reason].
- Permission and memory isolation: The Memory Service shall isolate memory data by role; regular employees cannot access the boss's mental model.
a. Acceptance criteria: [Regular employee queries mental model] → [Returns an "Unauthorized access" error].
##### Exception Scenarios
- Collaboration chain interruption
a. Trigger condition: A role in the collaboration chain does not process the task for an extended period.
b. System behavior: Timeout reminder, configurable for automatic escalation or skipping.
c. User perception: Receives a "Pending task timeout reminder" notification.
#### 5.3.5 Exploration of WeCom Integration
##### Business Rules
- WeCom "Dayuan" integration research: The system shall research the feasibility of integrating with the Enterprise WeChat "Dayuan" (AI assistant), evaluating integration methods with BossAgents digital employees.
a. Acceptance criteria: [Research completed] → [Produces a research report containing integration methods, workload estimation, and risk assessment].
- WeChat Work message channel: Where WeChat Work integration is feasible, the system shall support sending and receiving instructions via the WeChat Work message channel.
a. Acceptance criteria: [WeChat Work user sends a message] → [BossAgents receives and processes it, then returns the result to WeChat Work]
##### Exception scenarios
- WeChat Work API limitations
a. Trigger condition: WeChat Work API imposes restrictions on message frequency or format
b. System behavior: Implement message queue buffering and comply with frequency limits
c. User perception: Slight delay in message replies, functionality remains normal
#### 5.3.6 UI for Self-Evolution Closed Loop
##### Business rules
- Evolution log persistence: The RuleEvolution shall independently persist evolution logs to the sciot_evolution_logs table, no longer relying solely on memory
a. Acceptance criteria: [Rule evolution suggestion generated] → [A new record is added to the sciot_evolution_logs table, containing suggestion content, status, and timestamp]
b. Acceptance criteria: [After service restart] → [Evolution logs are fully preserved, and historical evolution records can be queried]
- UI for approval and deployment: The system shall provide a front-end management interface supporting approval, deployment, and rollback operations for rule evolution suggestions
a. Acceptance criteria: [Administrator views the evolution suggestion list on the front-end] → [Displays a list of rules with statuses such as pending approval, approved, or deployed]
b. Acceptance criteria: [Administrator clicks "Approve"] → [The rule is automatically deployed to the rule engine, and its status is updated to "deployed"]
c. Acceptance criteria: [Administrator clicks "Rollback"] → [The rule reverts to the previous version, and the rollback operation is recorded in the evolution chain]
- Evolution History Visualization: The system shall display the complete evolution history of rules on the frontend, including supersedes chains.
a. Acceptance Criteria: [View a rule's evolution history] → [Display all version changes from creation to current in a timeline format]
##### Exception Scenarios
- Approval and Deployment Failure
a. Trigger Condition: An error occurs when deploying a rule to the rule engine.
b. System Behavior: Automatic rollback, preserving the original rule, and logging the failure.
c. User Perception: Frontend displays a "Deployment Failed" prompt; the original rule remains unaffected.
6. Data Constraints
6.1 Atomic Fact
- factId: Unique identifier, UUID format, required.
- tenantId: Tenant identifier, linked to tenant-middleware, required.
- category: Fact category (supplier_preference / operation_habit / approval_preference / other), required.
- value: Fact value, string, required, max 500 characters.
- confidence: Confidence level, float between 0.0-1.0, default 0.5.
- source: Source (interaction / inference / manual), required.
- createdAt: Creation time, ISO8601 format, required.
- supersededBy: Which new fact supersedes this one, factId or null.
6.2 Identity Profile
- tenantId: Tenant identifier, unique key, required.
- role: Boss role (decision_maker / technical_lead / operations_manager), default decision_maker.
- industry: industry sector, string
- frequentObjectTypes: list of common object types, e.g., ["BOM", "ECR", "PurchaseOrder"]
- approvalPreference: approval preference (conservative / moderate / aggressive), default moderate
- preferredSuppliers: list of preferred suppliers
- lastUpdated: last updated time, ISO8601 format
6.3 Session Summary
- summaryId: unique identifier, UUID format, required
- tenantId: tenant identifier, required
- sessionId: session identifier, linked to ConversationManager, required
- topic: business topic (BOM / Procurement / Change / Supplier / Other), required
- keyDecisions: list of key decisions, array of strings
- outcome: summary of session outcome, string, max 1000 words
- createdAt: creation time, ISO8601 format, required
6.4 Mental Model
- tenantId: tenant identifier, unique key, required
- riskPreference: risk preference (conservative / moderate / aggressive), default moderate
- costSensitivity: cost sensitivity (low / medium / high), default medium
- innovationWillingness: Innovation willingness (low / medium / high), default medium
- decisionPatterns: List of decision patterns, array of strings
- lastAnalyzedAt: Last analysis time, ISO8601 format
- analysisVersion: Analysis version number, integer, incremental
6.5 Forward-looking Intention
- intentionId: Unique identifier, UUID format, required
- tenantId: Tenant identifier, required
- predicted: Predicted next requirement, string, required
- confidence: Confidence level, 0.0-1.0 floating point number
- basedOn: Basis for prediction, string, describes historical patterns
- triggerCondition: Trigger condition, string
- createdAt: Creation time, ISO8601 format
- updatedAt: Last update time, ISO8601 format
6.6 Evolution Chain Entry
- entryId: Unique identifier, UUID format, required
- type: Record type (fact / rule / profile), required
- refId: Associated fact/rule/profile ID, required
- action: Operation type (created / updated / superseded / rolled_back), required
- previousValue: Value before change, JSON string
- newValue: Value after change, JSON string
- supersedes: Superseded entryId, or null
- timestamp: Operation time, ISO8601 format, required
7. Requirements Traceability Matrix
Phase 0 — Pre-fixes
| Requirement ID | Priority | Type | Description | Corresponding v2 Fix Point |
|---|---|---|---|---|
| REQ-0-01 | P0 | Security | Fix JWT key hardcoded fallback | Fix Point #7 |
| REQ-0-02 | P0 | Functional | Audit log DB write confirmation and fix | Fix Point #1 |
| REQ-0-03 | P0 | Functional | Audit log query API | Fix Point #1 |
| REQ-0-04 | P0 | Functional | Knowledge base frontend integration with backend search API | Fix Point #6 |
| REQ-0-05 | P0 | Functional | Search fallback strategy (FTS5 → LIKE) | Fix Point #6 |
| REQ-0-06 | P1 | Functional | Feasibility study for OpenClaw/ClawBot integration | Fix Point #5 |
Phase 1 — Quick Wins
| Requirement ID | Priority | Type | Description | Corresponding v2 Fix Point |
|---|---|---|---|---|
| REQ-1-01 | P0 | Functional | WeChat message reception and forwarding | Fix Point #5 |
| REQ-1-02 | P0 | Function | WeChat Message Reply | Fix #5 |
| REQ-1-03 | P1 | Function | Channel Routing & Distribution | - |
| REQ-1-04 | P1 | Function | Enterprise WeChat Self-built App Alternative | Fix #5 |
| REQ-1-05 | P0 | Security | Mini Program JWT Key Fix | Fix #7 |
| REQ-1-06 | P1 | Function | Mini Program Auto Mode Integration with WeChat AI | - |
| REQ-1-07 | P1 | Function | Mini Program Conversation Entry | - |
| REQ-1-08 | P0 | Function | Memory Layer 1 Atomic Trace | Fix #1 |
| REQ-1-09 | P0 | Function | Memory Layer 2 Atomic Fact Extraction | Fix #1 |
| REQ-1-10 | P0 | Function | Memory Layer 3 User Profile Construction | Fix #1 |
| REQ-1-11 | P0 | Function | Memory System 1 Real-time Write | Fix #1 |
| REQ-1-12 | P1 | Function | Memory Tenant Isolation | - |
| REQ-1-13 | P1 | Function | Environment Check & Auto Dependency Installation | - |
| REQ-1-14 | P1 | Function | Automatic DB Initialization | - |
| REQ-1-15 | P2 | Function | Docker Single-Command Deployment | - |
Phase 2 — Deep Enhancement
| Requirement ID | Priority | Type | Description | Corresponding v2 Fix Point |
|---|---|---|---|---|
| REQ-2-01 | P0 | Functional | Memory Layer 4 Session Summary | Fix Point #1 |
| REQ-2-02 | P1 | Functional | Memory Layer 5 Mental Model | Fix Point #1 |
| REQ-2-03 | P1 | Functional | Memory Layer 6 Prospective Intent | Fix Point #1 |
| REQ-2-04 | P1 | Functional | Memory System 2 Asynchronous Analysis | Fix Point #1 |
| REQ-2-05 | P1 | Functional | Evolution Chain supersedes pointer | Fix Point #1 |
| REQ-2-06 | P0 | Functional | Task Decomposer | Fix Point #3 |
| REQ-2-07 | P0 | Functional | Parallel Scheduling runParallel | Fix Point #3 |
| REQ-2-08 | P0 | Functional | Result Aggregator | Fix Point #3 |
| REQ-2-09 | P0 | Security | Mutex Timeout Release | Fix Point #3 |
| REQ-2-10 | P1 | Security | Deadlock Detection | Fix Point #3 |
| REQ-2-11 | P1 | Functional | Hunyuan Provider Integration | Fix Point #4 |
| REQ-2-12 | P1 | Function | Semantic-level Classification | Correction Point #4 |
| REQ-2-13 | P2 | Function | Dynamic Routing | Correction Point #4 |
| REQ-2-14 | P2 | Function | A/B Testing Support | Correction Point #4 |
| REQ-2-15 | P1 | Function | Mini Program AI Dialogue Deep Integration | - |
| REQ-2-16 | P1 | Function | Real-time Execution Progress Push | - |
| REQ-2-17 | P2 | Function | Dashboard Profile Data Integration | - |
Phase 3 — Ecosystem Expansion
| Requirement ID | Priority | Type | Description | Corresponding v2 Correction Point |
|---|---|---|---|---|
| REQ-3-01 | P2 | Function | OpenClaw Skill Packaging and Release | Correction Point #5 |
| REQ-3-02 | P2 | Function | Skill Interface Standardization | Correction Point #5 |
| REQ-3-03 | P2 | Function | Hy-Memory Plugin/Self-built Switching | - |
| REQ-3-04 | P1 | Function | Agentic RAG Self-evaluation of Retrieval Quality | Correction Point #6 |
| REQ-3-05 | P1 | Function | Multi-strategy Retrieval Auto-switching | Correction Point #6 |
| REQ-3-06 | P1 | Function | Role Permission Definition | - |
| REQ-3-07 | P1 | Function | Team Collaboration Chain | - |
| REQ-3-08 | P1 | Security | Permission and Memory Isolation | - |
| REQ-3-09 | P2 | Function | Enterprise WeChat "Da Yuan" Integration Research | - |
| REQ-3-10 | P2 | Function | Enterprise WeChat Message Channel | - |
| REQ-3-11 | P1 | Function | Evolution Log Persistence | Correction #8 |
| REQ-3-12 | P1 | Function | Approval Deployment UI | Correction #8 |
| REQ-3-13 | P2 | Function | Evolution History Visualization | Correction #8 |
8. Statistical Summary
| Metric | Value |
|------|------|
| Total Requirements | 42 |
| P0 Requirements | 13 |
| P1 Requirements | 20 |
| P2 Requirements | 9 |
| Functional Requirements | 35 |
| Security Requirements | 5 |
| Performance Requirements | 2 |
| Phase 0 Requirements | 6 |
| Phase 1 Requirements | 15 |
| Phase 2 Requirements | 17 |
| Phase 3 Requirements | 13 |
Note: Performance requirements are distributed in the DFX constraints section (Section 4.1) and are not individually numbered as REQ-IDs. The "2 performance requirements" above refer to the performance constraint items within DFX. All 42 items in the core requirements traceability matrix are of the functional/security type.
BossAgents