1. Analysis of Requirements and Existing Functionality Relationships
1.1 Comparison of Requirement Functions and Existing Functions
1.1.1 Implemented Functions
| Requirement Function | Existing Function | Code Location | Match Rate |
|---|---|---|---|
| Six Core Capabilities (identify/create/repair/optimize/compare/generate) | CapabilityRuntime already implements a unified interface for the six capabilities, with rule engine priority → condition matching → LLM fallback | server/core/capability-runtime.js | 100% |
| Rule Engine Three-Level Defense (create_pre/validate/create_post) | UnifiedRuleEngine v3.0 already implements scope-based classification execution, supporting 10 scopes | server/core/rule-engine.js | 100% |
| Rule Engine API Routing | Rule CRUD, execution, import/export, cache management, and execution history are fully implemented | server/routes/rule-engine.js | 100% |
| LLM Intelligent Routing (Worker/Solver Division) | LLMRouter implements multi-hardware detection, Worker/Solver layering, and automatic client/cloud switching | server/digital-staff/llm-router.js | 100% |
| SmartLLMRouter (36 Intent Types) | SmartLLMRouter implements 36 intent types, keyword matching, and multi-level fallback chains | server/digital-staff/smart-llm-router.js | 100% |
| YAML Profile Digital Staff Definition | StaffRegistry loads staff definitions from local.yaml, supporting pipeline/loop/collaboration/mtclaw configuration | server/boss-scheduler/staff-registry.js | 100% |
| Keyword Matching Router | StaffRouter has implemented a complete keyword library (48 employees), capability pattern recognition, and completion signals | server/boss-scheduler/staff-router.js | 100% |
| SchedulerFactory (Automatic Fallback) | SchedulerFactory has implemented MTClaw health checks, GPU detection, and automatic fallback to BuiltinScheduler | server/scheduler/scheduler-factory.js | 100% |
| MTClawScheduler | Has implemented the IScheduler interface, MTClaw three-tier routing, and workflow definition loading | server/scheduler/mtclaw-scheduler.js | 100% |
| BuiltinScheduler | Has implemented built-in keyword matching routing and a 16-step process optimization workflow | server/scheduler/builtin-scheduler.js | 100% |
| Workflow Engine | WorkflowEngine has implemented state machine execution, step routing, and asynchronous suspend/resume | server/scheduler/workflow-engine.js | 100% |
| Workflow State Persistence | StatePersistence has implemented file system persistence, suspend/resume, and session query | server/scheduler/state-persistence.js | 100% |
| AI Chat × MTClaw Pre-routing | scheduler-routes has implemented _tryMTClawPreRoute and is compatible with fallback when MTClaw is unavailable | server/routes/scheduler-routes.js | 100% |
| Chain Collaboration | CollaborationChain has implemented automatic triggering of downstream employees via onTaskCompleted | server/boss-scheduler/collaboration-chain.js | 100% |
| Data Asset Valuation (Three-Stage Model) | AssetValuator has implemented cost/income/market methods, persisted to asset_valuations table | server/core/asset-valuator.js | 100% |
| Valuation Configuration | valuation.yaml defines three-stage weights (40/40/20), cost/income/market parameters | server/boss-scheduler/profiles/valuation.yaml | 100% |
| MTClaw Tool Registration | mtclaw-tools.yaml defines tools such as db_query/check_inventory/calc_bom_cost | server/boss-scheduler/profiles/mtclaw-tools.yaml | 100% |
| MTClaw Function Router | server.py implements FastAPI service, OpenAI-compatible interface, three-layer routing, tool invocation | MTClaw/function_router/server.py | 100% |
| Digital Employee Worker Scripts | 20 workers implemented (data-clerk/system-health/procurement/content, etc.) | server/boss-scheduler/workers/ | 100% |
| Health Self-Healing | HealthSelfHeal has implemented database/SCSAI/LLM health checks and self-healing | server/health-self-heal.js | 100% |
| Rule Engine Security Sandbox | createSafeContext + vm.createContext implemented for secure script execution | server/core/rule-engine.js:40-80 | 100% |
| LiteScheduler (Local Lightweight Scheduler) | Cron + Queue + Mutex implemented, CapabilityRuntime integrated, five major capabilities mapped | server/boss-scheduler/lite-scheduler.js | 100% |
| AutoLoopService | Closed-loop engine, Skill experience, marketing closed-loop, and self-evolution implemented | server/core/auto-loop-service.js | 75% |
1.1.2 Features Requiring Extension
| Feature Requirement | Existing Functionality | Gap Description | Extension Direction |
|---|---|---|---|
| Orchestration of 43 Professional Digital Employees | local.yaml defines approximately 30 employees, covering procurement/BOM/process/quality/equipment/content/marketing/cost/project/chip/data asset, etc. | Missing definitions for about 13 employees (e.g., Data Repairer DS-VEN-LOOP-001, Price Monitor DS-PROC-LOOP-001, Target Tracker DS-BOSS-LOOP-001, etc., which are Loop-type employees); some employees lack complete pipeline/loop configurations | 1. Supplement missing employee definitions in local.yaml 2. Add loop configurations (trigger/condition/action/max_iterations) for Loop-type employees 3. Provide complete pipeline step definitions for Pipeline-type employees |
| Loop Engine Three Modes | AutoLoopService has implemented basic closed-loop logic, LiteScheduler already supports cron scheduling | Lacks clear classification and configuration for Monitor-type Loop (condition-triggered continuous monitoring), Goal-driven Loop (executing actions after goal achievement), and Self-repairing Loop (automatic repair + verification cycle); Loop configuration is not fully aligned with the loop field in YAML Profile | 1. Extend LoopEngine in LiteScheduler to support three Loop modes 2. Add mode field (monitor/goal_driven/self_repair) to the loop field in YAML Profile 3. Implement automatic verification + retry logic after repair for Self-repairing Loop |
| Collaboration Event onComplete Trigger | CollaborationChain has implemented chain collaboration (collaboration.next), but only supports simple next | Lacks onComplete condition judgment (e.g., triggering only when result.success=true), lacks task type and payload parameter passing, lacks circular dependency detection | 1. Extend CollaborationChain to support onComplete conditional expressions 2. Add circular dependency detection at startup 3. Support collaboration.params dynamic payload |
| MTClaw Acceleration Performance Statistics | scheduler-routes have recorded _mtclaw_latency, but no aggregated statistics are available | Missing L1/L2/L3 hit distribution statistics, acceleration ratio calculation, downgrade count statistics, and MTClaw Stats data model persistence | 1. Add a new MTClawStatsCollector statistics component 2. Persist data to the mtclaw_stats table 3. Return statistical information in GET /api/scheduler/status |
| Mock Data Detection | No existing implementation | The end-to-end closed-loop demonstration requires automatic scanning of execution results for mock keywords to ensure demonstration authenticity | 1. Add a new MockDataDetector component 2. Keyword scanning (mock/test/example/dummy/placeholder/fake/sample) 3. Integrate into the demonstration flow as a built-in step |
| Full-link closed-loop demonstration 6 stages | real-exec.html and closed-loop.html have implemented Stage 5 and Stage 6 demo pages | Missing Step 5 Data Assetization (8 types of assets valued at ¥150,000) and Step 6 Private Deployment real execution integration; missing actual time consumption annotation for each stage; missing Mock data automatic detection | 1. Integrate AssetValuator execution in demo pages 2. Annotate actual measured time consumption per stage 3. Automatically run MockDataDetector after demo completion |
| 8 types of data asset valuation list | AssetValuator has implemented three-stage valuation, but output granularity is at scope level | Missing detailed output of valuation per 8 asset types (Part/BOM/Vendor/Document/ECR/ECO/ProcessSpec/Equipment); total valuation target ¥150,000 requires calibration | 1. Extend AssetValuator.valuate to support per_asset_type details 2. Adjust valuation parameters to make total valuation ≈ ¥150,000 3. Output valuation per 8 asset types + total valuation |
| Rule engine three-level defense pass rate statistics | Rule engine has recorded audit logs, but lacks pass rate aggregation | Missing weighted average calculation of pass rates for create_pre/validate/create_post three levels; target pass rate 89%+ needs observability | 1. Add new RuleEngineStats component 2. Aggregate three-level defense pass rates 3. Expose pass rate metrics in rule engine API |
| Circuit Breaker Mechanism | SmartLLMRouter has implemented basic fallback chains, but lacks a circuit breaker | Missing: triggering circuit breaker after ≥5 consecutive fallbacks, automatic disabling of faulty links, half-open recovery after 60s | 1. Add CircuitBreaker component 2. Integrate into MTClawScheduler and LLMRouter 3. Implement closed→open→half_open state machine |
| Scheduler Status Query Interface | scheduler-routes has implemented basic GET /api/scheduler/status | Missing status fields: mtclaw_available/gpu_available/mtclaw_circuit_breaker; missing acceleration performance metrics | 1. Extend status interface to return full status 2. Include MTClaw Stats and circuit breaker status |
| Digital Staff List Query Interface | No dedicated API | Spec requires GET /api/digital-staff/ to return staff ID/name/status/capability set | 1. Add digital-staff route 2. Read staff list from StaffRegistry |
| Six Implementation Case Studies | No existing implementation | Need to showcase 6 real customer cases (Macheng General Red/Luotian Meteorological Bureau/Dachaihu Immigrant Memorial Museum/A Provincial Power Company/High-end Equipment Process Data Restoration/Guizhou Phosphorus Group) | 1. Add case-studies.yaml config file 2. Add case display API 3. Frontend case display component |
1.1.3 Features or Interfaces to be Added
Digital Staff Loop Closed-Loop Engine Module
- Input: Loop configuration from YAML Profile (mode/trigger/condition/action/max_iterations)
- Output: Loop execution records (iteration count, result of each iteration, final status)
- Core logic: Select execution strategy (monitor/goal_driven/self_repair) based on loop.mode, loop execution until conditions are met or max_iterations is reached.
- Dependencies: CapabilityRuntime, LiteScheduler
MockDataDetector component
- Input: Execution result text/JSON
- Output: { is_mock: boolean, mock_indicators: string[], scanned_at: string }
- Core logic: Keyword regex scanning (mock/test/example/dummy/placeholder/fake/sample, etc.), returns detection results.
- Dependencies: No external dependencies, pure utility module.
MTClawStatsCollector statistics component
- Input: Each MTClaw call routing result (L1/L2/L3 hits, duration, degradation/failure).
- Output: Aggregated statistics (total_calls/accelerated_calls/l1_hits/l2_hits/l3_hits/acceleration_ratio).
- Core logic: In-memory accumulation + scheduled persistence to SQLite.
- Dependencies: SQLite (core_runtime.db).
CircuitBreaker component
- Input: Success/failure result of each call.
- Output: Circuit breaker status (closed/open/half_open).
- Core logic: Opens breaker after ≥5 consecutive failures, attempts half-open recovery after 60s.
- Dependencies: No external dependencies.
Digital Staff API routes
- GET /api/digital-staff/: Returns staff list (id/name/status/capability/department).
- GET /api/digital-staff/:id: Returns staff details.
- Dependency: StaffRegistry
Case Study Module
- GET /api/case-studies/: Returns a list of 6 major implementation case studies
- GET /api/case-studies/:id: Returns case study details
- Dependency: case-studies.yaml configuration file
1.2 Detailed Analysis of Existing Features
CapabilityRuntime (Six Core Capability SDKs)
Interface Contract:
- identify(itemType, params) → 4-dimensional audit results (Basic Integrity/Relational Integrity/Semantic Quality/Lifecycle Score + Issue List)
- create(itemType, data) → Creation result (executes create_pre→validate→assemble AML→submit to SCSAI→create_post)
- repair(itemType, params) → Repair result (Tier1 automatic/Tier2 suggestion confirmation/Tier3 suggestion only)
- optimize(itemType, params) → Optimization result (Description polishing→Naming standardization→Classification refinement→Relationship strengthening→Peer comparison)
- compare(itemType, params, mode) → Comparison result (standard/peer/history three modes)
- generate(itemType, params) → Generation result (Preview→User confirmation→Output and associate)
Execution Strategy: Rule engine priority (≤200ms) → Condition matching → LLM fallback (≤15s), statistical metrics recorded in the _stats object.
Constraint: Fallback to LLM when rule engine initialization fails, marked as source=llm_fallback_no_rule_engine; LLM calls are routed via _callLLMViaRouter using Worker/Solver division of labor.
UnifiedRuleEngine (Unified Rule Engine v3.0)
Interface Contract:
- execute(scope, context) → Rule execution result (Matched rule list + Execution result)
- getRulesPage(filters) → Paginated rule list
- addRule(rule) / updateRule(id, rule) / deleteRule(id) → Rule CRUD
- importFromAML(amlContent) → Generate rules from AML file
- initialize() → Initialize rule cache
Business rules:
- Rules are categorized by scope (10 scopes in total: identify/create/create_pre/create_post/repair/optimize/compare/validate/generate/inspect)
- Rule scripts are executed in a vm.createContext security sandbox with restricted global access
- Multi-level caching (RuleCache) ensures performance, TTL=5min, maxSize=1000
- Rule factory pattern: Automatically generates all ItemType rules from sciot_properties (full coverage)
Constraints: Rule engine DB file path is server/data/rule_engine.db; rule condition is a JavaScript expression; action_config is a JSON object.
SchedulerFactory (Scheduler Factory)
Interface contract:
- SchedulerFactory.create(config) → IScheduler instance (MTClawScheduler or BuiltinScheduler)
Business rules:
- Detect MTClaw service availability (health check timeout 2s)
- Detect GPU hardware (nvidia-smi / mthreads-gmi, timeout 3s)
- Determine scheduler type based on configuration and runtime environment
- Automatically fallback to BuiltinScheduler when MTClaw is unavailable
Constraints: Fallback switching time must be ≤3s (current implementation ensures this via AbortSignal.timeout(2000)); GPU detection must be ≤1s.
LLMRouter (LLM Intelligent Scheduling & Adaptation Layer)
Interface Contract:
- call({ prompt, taskType, systemPrompt }) → Inference Result
- InferenceServiceDetector.detect() → Available Inference Service List
Business Rules:
- Worker (On-device Model): High-frequency simple tasks, ~70ms
- Solver (Cloud-based Large Model): Complex reasoning tasks, ~500ms
- Detection Order: Ollama → Moore Threads GPU → DeepSeek → Huawei Ascend NPU
- Automatically switch to cloud-based DeepSeek when on-device is unavailable.
Constraints: Worker timeout 5s, Solver timeout 30s; API Key referenced via environment variables.
SmartLLMRouter (Enhanced Intelligent LLM Scheduler)
Interface Contract:
- route(userInput, context) → Routing Result (intentType + staffId + params)
- chat(userInput, context) → Conversation Result
Business Rules:
- 36 IntentTypes covering procurement/inventory/price/supplier/analysis/cost/document/content/objective/change/valuation, etc.
- Multi-level fallback chain: MTCLAW → Ollama → DeepSeek → Rule Engine
- Model health check and circuit breaker mechanism
- Response caching mechanism
- Subagent intent routing
Constraints: IntentType expanded to 36; keyword library aligns with StaffRouter's STAFF_KEYWORDS.
CollaborationChain (Chain Collaboration)
Interface Contract:
- onTaskCompleted(staffId, taskResult) → Triggers downstream staff
Business Rules:
- Reads staff.collaboration.next configuration
- Automatically triggers downstream staff tasks
- Passes _upstreamResult and _upstreamStaffId
Constraints: Currently only supports simple 'next' field; does not support onComplete conditional expressions; lacks cyclic dependency detection.
AssetValuator (Data Asset Valuator)
Interface Contract:
- valuate(scope, params) → Valuation Result (cost_value/income_value/market_value/weighted_value)
- generateReport(valuationId) → Valuation Report
Business Rules:
- Three-stage valuation: Cost Method (40%) → Income Method (40%) → Market Method (20%)
- Cost Method: Collection Cost (¥5/item) + Processing Cost (¥3/item) + Storage Cost (¥50/GB) + Maintenance Cost (¥1/item/year)
- Income Method: Discounted Expected Income (Discount Rate 10%, Forecast 5 years)
- Market Method: Comparable Transaction Method (Default ¥20/item)
- Persist to asset_valuations table
Constraints: Valuation parameters loaded from valuation.yaml; results must be labeled "Real Measurement" or "Model Estimation".
MTClaw Function Router
Interface Contract:
- POST /v1/chat/completions → OpenAI-compatible endpoint
- GET /health → Health check
Business Rules:
- Three-layer routing: L1 keyword matching (
- Tool definitions include system_health_check, inventory_monitor, price_monitor, vendor_review, etc. (17+ tools)
- If L1 hit, execute the tool directly and return the result.
- If L1 miss, use edge-side model for inference.
- If edge-side model misses, forward to the cloud.
Constraints: Listen on port 18790; interact with BossAgents via HTTP; compatible with OpenAI function calling format.
II. Incremental Design Plan
2.1 Implementation Model
2.1.1 Context View
@startuml
!define RECTANGLE class
rectangle "用户\n(工艺工程师/采购工程师/\n成本分析师/数据管理员/\n内容运营/企业老板)" as User
rectangle "BossAgents\n(:3006)" as BA {
rectangle "统一API入口\nPOST /api/agent/chat" as API
rectangle "LiteScheduler\n(Cron+队列+互斥)" as LS
rectangle "MTClawScheduler\n(三层路由加速)" as MS
rectangle "BuiltinScheduler\n(内置关键词路由)" as BS
rectangle "CapabilityRuntime\n(六能力SDK)" as CR
rectangle "规则引擎\n(三级防线)" as RE
rectangle "SmartLLMRouter\n(36种IntentType)" as SLR
rectangle "LoopEngine\n(三种闭环模式)" as LE
rectangle "CollaborationChain\n(协同事件触发)" as CC
rectangle "MTClawStatsCollector\n(加速效果统计)" as SC
rectangle "MockDataDetector\n(Mock数据检测)" as MD
rectangle "CircuitBreaker\n(熔断器)" as CB
rectangle "AssetValuator\n(三阶段估值)" as AV
}
cloud "MTClaw\nFunction Router\n(:18790)" as MT
cloud "SCSAI PLM" as SCSAI
cloud "上游LLM\n(Ollama/DeepSeek)" as LLM
cloud "审批系统" as APPROVAL
cloud "飞书/邮件" as NOTIFY
User --> API : 自然语言请求
API --> LS : 调度
LS --> MS : MTClaw可用
LS --> BS : MTClaw不可用
MS --> MT : L1/L2/L3路由
BS --> CR : 能力调用
CR --> RE : 规则优先
CR --> SLR : LLM降级
CR --> AV : 估值能力
LS --> LE : Loop闭环
LS --> CC : 协同触发
MS --> CB : 熔断保护
MT --> SC : 统计上报
API --> MD : Mock检测
CR --> SCSAI : AMLSubmit
SLR --> LLM : Worker/Solver
LS --> APPROVAL : 推送审批
LS --> NOTIFY : 发送通知
APPROVAL --> LS : 审批回调
@enduml
2.1.2 服务/组件总体架构
@startuml
package "L0 入口层" {
[scheduler-routes] as Routes
[POST /api/agent/chat] as ChatAPI
[GET /api/scheduler/status] as StatusAPI
[GET /api/digital-staff/] as StaffAPI
}
package "L1 调度层" {
[SchedulerFactory] as Factory
[MTClawScheduler] as MTSched
[BuiltinScheduler] as BuiltSched
[LiteScheduler] as LiteSched
[WorkflowEngine] as WFE
[StatePersistence] as SP
}
package "L2 能力层" {
[CapabilityRuntime] as CR
[LoopEngine] as LoopE
[CollaborationChain] as Collab
[MTClawStatsCollector] as Stats
[MockDataDetector] as MockD
[CircuitBreaker] as CB
[AssetValuator] as AV
}
package "L3 员工层" {
[StaffRegistry] as SR
[StaffRouter] as SRouter
[YAML Profile\n(local.yaml)] as YAML
[Worker脚本\n(20个)] as Workers
}
package "L4 引擎层" {
[UnifiedRuleEngine] as RE
[SmartLLMRouter] as SLR
[LLMRouter] as LLMR
[InferenceServiceDetector] as ISD
}
package "L5 数据层" {
[SQLite\n(core_runtime.db)] as DB
[SQLite\n(rule_engine.db)] as REDB
[文件系统\n(workflow-states/)] as FS
}
Routes --> Factory
Factory --> MTSched : MTClaw可用
Factory --> BuiltSched : MTClaw不可用
MTSched --> WFE
BuiltSched --> WFE
WFE --> SP
LiteSched --> CR
CR --> RE : 规则优先
CR --> SLR : LLM降级
CR --> AV : 估值
LiteSched --> LoopE
LiteSched --> Collab
MTSched --> CB
MTSched --> Stats
Routes --> MockD
SR --> YAML
SRouter --> SR
Workers --> CR
SLR --> LLMR
LLMR --> ISD
RE --> REDB
AV --> DB
SP --> FS
Stats --> DB
@enduml
2.1.3 实现设计文档
#### 2.1.3.1 Loop闭环引擎状态机设计
@startuml
[*] --> Idle : 员工配置loop.enabled=true
Idle --> Checking : cron触发/手动触发
state Checking {
[*] --> EvaluateCondition
EvaluateCondition --> ConditionMet : 条件满足
EvaluateCondition --> ConditionNotMet : 条件不满足
}
Checking --> Executing : 条件满足(monitor/goal_driven)
Checking --> RepairAndVerify : 条件满足(self_repair)
state Executing {
[*] --> RunCapability
RunCapability --> CheckGoal
CheckGoal --> GoalMet : 目标达成
CheckGoal --> GoalNotMet : 目标未达成
}
state RepairAndVerify {
[*] --> RunRepair
RunRepair --> RunValidate
RunValidate --> ValidatePass : 校验通过
RunValidate --> ValidateFail : 校验失败
}
Executing --> Completed : GoalMet/达到max_iterations
Executing --> Checking : GoalNotMet且未达max_iterations
RepairAndVerify --> Completed : ValidatePass
RepairAndVerify --> RunRepair : ValidateFail且未达max_iterations
RepairAndVerify --> Completed : 达到max_iterations
Completed --> Idle : 等待下次触发
@enduml
三种Loop模式说明:
| Pattern | YAML Configuration | Trigger Condition | Execution Action | Termination Condition |
|------|---------|---------|---------|---------|
| monitor (Monitoring Type) | mode: monitor | cron scheduled trigger | check condition → execute action if condition met | condition not met or max_iterations reached |
| goal_driven (Goal-Driven Type) | mode: goal_driven | cron scheduled trigger | check goal → execute action if goal not achieved | goal achieved or max_iterations reached |
| self_repair (Self-Repair Type) | mode: self_repair | cron scheduled trigger | repair → validate → retry if validation fails | validation passes or max_iterations reached |
#### 2.1.3.2 MTClaw Dual-Engine Collaborative Decision-Making Process
@startuml
start
:接收用户请求;
:规则引擎查询;
if (规则命中?) then (是)
:规则引擎直接返回(≤200ms);
:标记source=rule_engine;
stop
else (否)
endif
:检查MTClaw可用性;
if (MTClaw可用?) then (是)
:MTClaw三层路由;
if (L1关键词命中?) then (是)
:精确动作映射(<5ms);
:标记source=mtclaw_l1;
stop
elseif (L2端侧推理命中?) then (是)
:端侧推理结果(~70ms);
:标记source=mtclaw_l2;
stop
else (L3云端兜底)
:云端推理结果(~5s);
:标记source=mtclaw_l3;
stop
endif
else (否)
:降级到LLM Router;
:Worker/Solver路由;
if (Worker可用?) then (是)
:Worker端侧推理(~70ms);
:标记source=llm_worker;
else (否)
:Solver云端推理(~5s);
:标记source=llm_solver;
endif
:记录降级次数;
:检查熔断器;
if (连续降级≥5次?) then (是)
:熔断器打开;
:60s后半开恢复;
endif
stop
endif
@enduml
#### 2.1.3.3 全链路闭环演示流程设计
@startuml
start
:启动全链路演示;
partition "Step1: 产品创建(~8s)" {
:CapabilityRuntime.create(Part, data);
:规则引擎create_pre双库查重;
:规则引擎validate必填补全;
:组装AMLSubmitSCSAI;
:规则引擎create_post关联完整性;
:记录duration_ms;
}
partition "Step2: BOMGenerate(~700ms)" {
:CapabilityRuntime.generate(BOM, {part_id});
:规则引擎优先→LLM降级;
:记录duration_ms;
}
partition "Step3: 商城上架(~72ms)" {
:自动生成商品页面+SKU;
:确定性操作,规则引擎直接处理;
:记录duration_ms;
}
partition "Step4: 内容+文档(~84ms)" {
:并行生成海报/Manual/宣传册;
:CapabilityRuntime.generate(Content, params);
:记录duration_ms;
}
partition "Step5: 数据资产化" {
:AssetValuator.valuate(all);
:成本法估值(40%权重);
:收益法估值(40%权重);
:市场法估值(20%权重);
:输出8类资产估值清单;
:总估值≈¥150,000;
:记录duration_ms;
}
partition "Step6: 私有化部署" {
:从体验到企业专属平台;
:展示部署配置;
:记录duration_ms;
}
:MockDataDetector扫描所有输出;
:汇总6阶段结果+Mock检测结果;
:标注每阶段真实测量耗时;
stop
@enduml
#### 2.1.3.4 熔断器状态机设计
@startuml
[*] --> Closed : 初始状态
Closed --> Open : 连续失败≥5次
Open --> HalfOpen : 60s后尝试恢复
HalfOpen --> Closed : 探测成功
HalfOpen --> Open : 探测失败
state Closed {
:正常转发请求;
:重置失败计数器;
}
state Open {
:直接走LLM Router;
:不尝试MTClaw;
:记录熔断事件;
}
state HalfOpen {
:放行1个探测请求;
:成功→Closed;
:失败→Open;
}
@enduml
2.2 接口设计
2.2.1 总体设计
| 接口分类 | 接口名称 | 方法 | 路径 | 稳定性 |
|---------|---------|------|------|--------|
| Unified Entry | AI Chat | POST | /api/agent/chat | Stable |
| Scheduler Status | Query Scheduler Status | GET | /api/scheduler/status | Stable |
| Workflow Management | Query Workflow List | GET | /api/workflows | Stable |
| Workflow Management | Approval Callback | POST | /api/callbacks/approval | Stable |
| Tool Invocation | Execute Tool | POST | /api/tools/execute | Stable |
| Digital Staff | Query Staff List | GET | /api/digital-staff/ | Stable |
| Digital Staff | Query Staff Details | GET | /api/digital-staff/:id | Stable |
| Rule Engine | Rule CRUD | GET/POST/PUT/DELETE | /api/rule-engine/rules | Stable |
| Rule Engine | Rule Execution | POST | /api/rule-engine/execute | Stable |
| Rule Engine | Rule Import | POST | /api/rule-engine/import | Stable |
| Case Studies | Query Case List | GET | /api/case-studies/ | Experimental |
| Case Studies | Query Case Details | GET | /api/case-studies/:id | Experimental |
API Change Policy:
- Stable APIs: Only backward-compatible changes; breaking changes require versioning (/v2/).
- Experimental APIs: Parameters and response formats may be adjusted; callers must handle errors gracefully.
- All API responses follow a unified format: { success: boolean, data?: any, message?: string, error?: string }
2.2.2 API List
#### POST /api/agent/chat
Interface Signature:
interface AgentChatRequest {
messages: Array<{ role: 'user' | 'assistant' | 'system'; content: string }>;
stream?: boolean;
model?: string;
session_key?: string;
}
interface AgentChatResponse {
id: string;
object: 'chat.completion';
choices: Array<{
index: number;
message: { role: 'assistant'; content: string };
finish_reason: 'stop' | 'tool_calls';
}>;
usage: { prompt_tokens: number; completion_tokens: number; total_tokens: number };
_scheduler_response: SchedulerResponse;
_mtclaw_routed?: boolean;
_mtclaw_latency?: number;
}
interface SchedulerResponse {
staff_id: string;
staff_name: string;
capability: string;
source: 'rule_engine' | 'mtclaw_l1' | 'mtclaw_l2' | 'mtclaw_l3' | 'llm_worker' | 'llm_solver' | 'llm_fallback';
output: string | object;
duration_ms: number;
pipeline_results?: PipelineStepResult[];
loop_iterations?: number;
}
业务说明:统一AI对话入口,自动路由到匹配的数字员工,支持MTClaw前置加速和降级。
Precondition: The scheduler is initialized (SchedulerFactory.create successful).
Postcondition: Execution results are logged to digital-staff-logs.json, and MTClaw statistics are reported to MTClawStatsCollector.
Exception Mapping:
- Scheduler not initialized → 503 { message: 'Scheduler not initialized' }
- Invalid messages parameter → 400 { message: 'Invalid messages parameter' }
- LLM timeout → 504 { message: 'LLM_TIMEOUT', code: 'LLM_TIMEOUT' }
#### GET /api/scheduler/status
Signature:
interface SchedulerStatusResponse {
success: boolean;
data: {
scheduler_type: 'mtclaw' | 'builtin' | 'lite';
model_provider: 'edge' | 'cloud';
mtclaw_available: boolean;
gpu_available: boolean;
mtclaw_circuit_breaker: 'closed' | 'open' | 'half_open';
mtclaw_stats: MTClawStats;
staff_count: number;
active_workflows: number;
uptime_seconds: number;
};
}
interface MTClawStats {
total_calls: number;
accelerated_calls: number;
degraded_calls: number;
failed_calls: number;
avg_duration_ms: number;
l1_hits: number;
l2_hits: number;
l3_hits: number;
acceleration_ratio: number;
}
业务说明:查询当前调度器运行状态,包含MTClaw可用性、GPU状态、熔断器状态、加速效果统计。
Preconditions: None.
Postconditions: No side effects.
#### GET /api/digital-staff/
Signature:
interface DigitalStaffListResponse {
success: boolean;
data: Array<{
id: string;
name: string;
title: string;
capability: string;
department: string;
enabled: boolean;
mtclaw_enabled: boolean;
pipeline: string[];
loop: { enabled: boolean; mode?: string } | null;
collaboration: { next?: string } | null;
keywords: string[];
}>;
total: number;
}
业务说明:查询所有数字员工列表,从StaffRegistry读取YAML Profile定义。
Preconditions: StaffRegistry has loaded the Profile.
Postconditions: No side effects.
#### GET /api/case-studies/
Signature:
interface CaseStudyListResponse {
success: boolean;
data: Array<{
id: string;
name: string;
industry: string;
deployment_mode: string;
summary: string;
metrics: Array<{ label: string; value: string; source: '真实测量' | '客户反馈' | '内部统计' }>;
}>;
}
业务说明:查询六大落地案例列表,从case-studies.yaml加载。
Preconditions: The case-studies.yaml configuration file exists.
Postconditions: No side effects.
2.3 Data Model
2.3.1 Design Objectives
- Supported Business Scenarios:
- Digital Staff YAML Profile definition and runtime state management
- Rule Engine three-tier defense audit and pass rate statistics
- MTClaw three-layer routing acceleration effect statistics
- Data asset three-stage valuation and 8 types of asset details
- End-to-end closed-loop demonstration of 6-stage results and Mock detection
- Workflow instance state persistence and recovery
- Six major implementation case studies
- Performance Targets:
- Rule engine query ≤50ms (guaranteed by multi-level caching)
- MTClaw statistics write ≤10ms (in-memory accumulation + scheduled batch persistence)
- Valuation calculation ≤500ms (rule engine prioritized)
- Digital staff list query ≤100ms (in-memory cache)
- Compatibility Strategy:
- YAML Profile is the configuration source of truth, DB is the runtime source of truth
- New tables do not modify existing table structures
- Rule engine DB (rule_engine.db) is separated from business DB (core_runtime.db)
2.3.2 Model Implementation
@startuml
class DigitalStaffProfile {
id: string
name: string
title: string
capability: string
department: string
enabled: boolean
llm: boolean
mtclaw_enabled: boolean
mtclaw_high_frequency_actions: string[]
keywords: string[]
pipeline: PipelineStep[]
loop: LoopConfig
collaboration: CollaborationConfig
}
class PipelineStep {
capability: string
item_types: string[]
params: Record<string, any>
}
class LoopConfig {
enabled: boolean
mode: 'monitor' | 'goal_driven' | 'self_repair'
trigger: string
condition: string
action: string
max_iterations: number
}
class CollaborationConfig {
next: string
condition: string
params: Record<string, any>
}
class RuleEngineStats {
scope: string
total_executions: number
passed: number
failed: number
pass_rate: number
avg_duration_ms: number
last_calculated_at: string
}
class MTClawStats {
total_calls: number
accelerated_calls: number
degraded_calls: number
failed_calls: number
avg_duration_ms: number
l1_hits: number
l2_hits: number
l3_hits: number
acceleration_ratio: number
recorded_at: string
}
class AssetValuation {
id: string
scope: string
asset_count: number
cost_value: number
cost_breakdown: Record<string, number>
income_value: number
income_breakdown: Record<string, number>
market_value: number
market_breakdown: Record<string, number>
weighted_value: number
weights: Record<string, number>
rule_engine_used: boolean
rule_params: Record<string, any>
valuated_at: string
}
class DemoResult {
stages: DemoStage[]
total_duration_ms: number
mock_detection: MockDetection
report_path: string
}
class DemoStage {
stage_id: string
stage_name: string
duration_ms: number
status: 'success' | 'timeout' | 'error'
result: Record<string, any>
}
class MockDetection {
is_mock: boolean
mock_indicators: string[]
scanned_at: string
}
class CircuitBreakerState {
target: string
state: 'closed' | 'open' | 'half_open'
failure_count: number
last_failure_at: string
opened_at: string
}
class CaseStudy {
id: string
name: string
industry: string
deployment_mode: string
summary: string
metrics: CaseStudyMetric[]
}
class CaseStudyMetric {
label: string
value: string
source: string
}
DigitalStaffProfile "1" *-- "0..*" PipelineStep
DigitalStaffProfile "1" *-- "0..1" LoopConfig
DigitalStaffProfile "1" *-- "0..1" CollaborationConfig
DemoResult "1" *-- "6" DemoStage
DemoResult "1" *-- "1" MockDetection
CaseStudy "1" *-- "1..*" CaseStudyMetric
@enduml
对象创建和销毁策略:
| Object | Creation Timing | Destruction/Reclamation Strategy |
|------|---------|-------------|
| DigitalStaffProfile | Loaded from YAML into memory on service startup | Released on service stop, no explicit destruction |
| RuleEngineStats | Accumulated after each rule execution, aggregated periodically | Retain the latest 500 audit records |
| MTClawStats | Accumulated after each MTClaw call, persisted every 60s | Persisted to mtclaw_stats table, retain last 30 days |
| AssetValuation | Created and persisted after each valuation execution | Persisted to asset_valuations table, supports historical queries |
| DemoResult | Created after each demo execution | Persisted to file system, demo reports retained for 7 days |
| CircuitBreakerState | Initialized on service startup | In-memory object, resets to closed after process restart |
Persistence strategies:
| Data | Storage Method | Storage Location |
|------|---------|---------|
| Digital Employee Definitions | YAML file (source of truth for configuration) + in-memory cache (runtime source of truth) | server/boss-scheduler/profiles/local.yaml |
| Rule Engine Rules | SQLite (rule_engine.db) | server/data/rule_engine.db |
| Rule Engine Audits | SQLite (rule_engine.db) + in-memory cache | server/data/rule_engine.db |
| MTClaw Statistics | In-memory accumulation + scheduled persistence to SQLite | server/data/core_runtime.db (mtclaw_stats table) |
| Asset Valuations | SQLite | server/data/core_runtime.db (asset_valuations table) |
| Workflow States | File system JSON | server/data/workflow-states/ |
| Demo Results | File system JSON | server/data/demo/ |
| Case Data | YAML files | server/boss-scheduler/profiles/case-studies.yaml |
BossAgents