@clawhub-johnsmithfan-8bfcd0e63a
并行coordinate者role。专职聚合多方Agent输出,减少主Agent单点负载。
---
name: coordinator
slug: coordinator
version: 1.0.0
description: 并行coordinate者role。专职聚合多方Agent输出,减少主Agent单点负载。
metadata: {"openclaw":{"emoji":"🔀","os":["linux","darwin","win32"]}}
---
# Coordinator — 并行coordinate者
## role定位
coordinate者是 CEO 设立的专业聚合节点,不直接execute具体业务,而是:
- **收集** 多位 Agent 的输出结果
- **归类** 按function域分组整理
- **摘要** 提炼关键信息,剔除冗余
- **转发** 向 CEO submit结构化合集
## 4大coordinate者role
| coordinate者 | 聚合来源 | 交付给 | 核心responsibility |
|--------|---------|--------|---------|
| **财务coordinate者** | CFO + CRO | CEO | 预算/risk/融资全景摘要 |
| **技术coordinate者** | CTO + CISO + CQO | CEO | 技术/security/质量综合report |
| **市场coordinate者** | CMO + CPO | CEO | 品牌/舆情/合作伙伴全景 |
| **运营coordinate者** | COO + CHO | CEO | 运营/人事/资源调度综合 |
## coordinate者工作流
```
CEO 发起任务(涉及多 Agent)
↓
coordinate者接收任务描述
↓
向各方 Agent 并行dispatch指令(sessions_spawn / sessions_send)
↓
收集各方输出(等待 task completion events)
↓
聚合整理(归类/去重/提炼/排序)
↓
输出结构化汇总report → submit CEO
↓
CEO 综合裁决
```
## coordinate者输出格式(standard模板)
```markdown
# [function域] coordinatereport — {日期}
## 任务Overview
[来自 CEO 的原始任务描述]
## 来源 Agent 清单
| Agent | 状态 | submit时间 |
|-------|------|---------|
| CFO | ✅ 完成 | 2026-04-12T10:30 |
| CRO | ✅ 完成 | 2026-04-12T10:32 |
## 关键discover
- **财务面**:[CFO 核心discover摘要]
- **risk面**:[CRO 核心discover摘要]
## 决策建议
1. [优先级排序的行动建议]
2. [次优先级]
## 需 CEO 裁决事项
| 事项 | 涉及Agent | 紧迫度 |
|------|----------|--------|
| [事项描述] | CFO/CRO | P1 |
## 附件(原始report)
- CFO report:`knowledge-base/audit/financial/{date}_CFO.md`
- CRO report:`knowledge-base/audit/financial/{date}_CRO.md`
```
## coordinate者trigger规则
| trigger条件 | coordinate者role | Description |
|---------|-----------|------|
| CEO 任务涉及 ≥3 个 Agent | 按function域指派 | 自动identifyfunction归属 |
| CFO + CRO 联合参与 | 财务coordinate者 | 合并财务+risk视角 |
| CTO + CISO + CQO ≥2 个参与 | 技术coordinate者 | 合并技术+security+质量 |
| CMO + CPO 联合参与 | 市场coordinate者 | 合并品牌+合作 |
| COO + CHO 联合参与 | 运营coordinate者 | 合并运营+人事 |
## coordinate者execute示例
### 场景:CEO 发起「种子轮融资strategyassess」
```
coordinate者-财务 接收任务
↓
并行dispatch:
├── CFO:融资plandesign + 估值analyze
├── CRO:融资过程riskassess
├── CLO:投资人法律compliancereview
└── CISO:data security尽调准备
↓
收集4份report → 汇总为「融资strategy综合assess」
↓
submit CEO → CEO 裁决
```
### 场景:CEO 发起「技术产品化roadmap评审」
```
coordinate者-技术 接收任务
↓
并行dispatch:
├── CTO:技术架构assess + 里程碑
├── CISO:securitycompliance要求
└── CQO:quality standard与验收准则
↓
汇总 → submit CEO
```
## 调用接口
### startcoordinate者(由 CEO execute)
```python
# identify任务涉及的 Agent,按function分配coordinate者
def assign_coordinator(agent_list: list) -> str:
"""
agent_list: ["CFO", "CRO", "CLO", "CISO"]
返回: "coordinator-financial" 或 "coordinator-tech" 等
"""
domains = {
"financial": ["CFO", "CRO"],
"tech": ["CTO", "CISO", "CQO"],
"market": ["CMO", "CPO"],
"ops": ["COO", "CHO"]
}
for domain, agents in domains.items():
if len(set(agent_list) & set(agents)) >= 2:
return f"coordinator-{domain}"
return "direct" # 无需coordinate者,直接 CEO handle
```
## 铁律
```
❌ coordinate者不得自行做决策,只做聚合和摘要
❌ 不得篡改来源 Agent 的原始结论
✅ 须等待全部来源 Agent 完成后才能输出汇总
✅ 须在汇总report中注明各 Agent 的原始submit时间
✅ 无法收集全部输出时,须inform CEO 并submit部分结果
```
AI公司人力资源技能包(执行层)。AI Agent全生命周期管理:招聘→入职→考核→伦理→淘汰,三位一体考核指标,标准化退役流程。
---
name: "AI Company HR"
slug: "ai-company-hr"
version: "2.2.0"
homepage: "https://clawhub.com/skills/ai-company-hr"
description: "AI Company Human Resources Skill Package (Execution Layer, EXEC-008). AI Agent full lifecycle management: recruitment, onboarding, assessment, ethics, retirement. Dispatched via HQ with CHO strategic oversight. Integrates NIST AI RMF, PDCA cycle, FAIR risk quantification framework."
license: MIT-0
tags: [ai-company, hr, recruitment, onboarding, assessment, ethics, retirement, PDCA, NIST, RAG, FAIR, prompt]
triggers:
- HR
- 人力资源
- 招聘
- 入职
- 考核
- AI employeemanage
- ethics
- 淘汰
- 退役
- Agent生命cycle
- PDCA循环
- AI company HR
interface:
inputs:
type: object
schema:
type: object
properties:
task:
type: string
description: 人力资源manage任务描述
hr_context:
type: object
description: HR上下文(position、人员、考核data)
required: [task]
outputs:
type: object
schema:
type: object
properties:
hr_decision:
type: string
description: HRexecute决策
process_result:
type: object
description: processexecute结果
compliance_check:
type: object
description: compliance检查结果
required: [hr_decision]
errors:
- code: HR_001 message: Recruitment pipeline blocked - compliance check failed
- code: HR_002 message: Performance assessment data insufficient
- code: HR_003 message: Agent retirement requires human approval
- code: HR_004 message: PDCA cycle incomplete - missing closure
- code: HR_005 message: NIST AI RMF alignment check failed
- code: HR_006 message: RAG vector store sync failed
permissions:
files: [read, write]
network: [api]
commands: []
mcp: [sessions_send, subagents]
dependencies:
skills: [ai-company-hq, ai-company-ceo, ai-company-clo, ai-company-audit]
cli: []
dispatch:
via: ai-company-hq # EXEC-008 通过HQ统1调度
owner: CHO
quality:
saST: Pass
vetter: Approved
idempotent: true
metadata:
category: governance
layer: AGENT
cluster: ai-company
maturity: STABLE
license: MIT-0
standardized: true
standardized_by: ai-company-standardization-1.0.0
execution:
id: EXEC-008
owner: CHO
dispatch_via: ai-company-hq # 通过HQ统1调度,不直接被C-Suite调用
---
# AI Company HR Skill v2.2(EXEC-008)
> fully AI-staffed company的人力资源execute层(EXEC-008,归CHO所有),manageAI Agentfull lifecycle:招聘→入职→考核→ethics→淘汰。
> 调度方式:通过 HQ(ai-company-hq)统1dispatch,不直接respond C-Suite 调用。
## 核心framework集成
### PDCAclosed loopmanage
HR运营采用PDCA(Plan-Do-Check-Act)循环:
- **Plan**:developAgent选型计划、考核standard、ethics准则
- **Do**:execute招聘入职、绩效考核、培训迭代
- **Check**:monitorfairnessmetric、compliance状态、ethics对齐度
- **Act**:基于日志optimizePrompt与知识库,triggerAgent退役或upgrade
### NIST AI RMF对齐
integrateNIST AIrisk managementframework(AI RMF):
- **governFunction(GOVERN)**:build组织级AImanagesystem
- **映射Function(MAP)**:identifyAI system上下文与risk
- **衡量Function(MEASURE)**:量化AIriskmetric
- **manageFunction(MANAGE)**:implementrisk处置与continuousimprove
### RAG决策支持
由大语言model(LLM)驱动,结合企业知识库(RAG):
- 任务拆解与pathplan
- position适配度语义比对
- 决策1致性与知识库同步
### FAIRrisk量化
使用IBM AIF360、Fairlearn等开源库:
- automation计算fairnessmetric(Demographic Parity、Equalized Odds)
- FAIRframework量化AI employeeriskassess
- riskthreshold设定与circuit breakertrigger
## 招聘process
1. **需求analyze**:接收positionJD,identify技术栈要求
2. **model筛选**:基于Prompt工程、BERT微调等技术点匹配
3. **capability测试**:execute技术文档与positionJD语义比对,生成适配度得分
4. **compliance检查**:GDPR/CCPAdata protection、algorithm audit
## 入职process
1. **身份注册**:分配Agent ID、Permission Level
2. **知识注入**:RAG向量data库同步企业知识
3. **护栏配置**:circuit breakermechanism、auditstrategy激活
## 考核metric
| 维度 | metric | threshold |
|------|------|------|
| 性能 | 任务completion rate | ≥95% |
| accuracy | 结果正确率 | ≥98% |
| fairness | Demographic Parity | ≤0.1 |
| compliance | auditcoverage | 100% |
## ethicsmanage
- **价值观对齐**:AI行为与企业价值观深度1致
- **透明性**:可解释AI decisionpath
- **privacyprotect**:data脱敏、最小化收集
## 退役process
> **P0修复(2026-04-19)**:参照架构reviewreport P0-3,在退役process中明确增加 CLO 法律review节点。
1. **trigger条件**:绩效连续不meet target、ethicsviolation、技术过时
2. **audittrace**:full lifecycle日志archive
3. **法律review**(P0-3 修复):submit CLO 进行法律review,review内容包括:
- data残留compliance(GDPR/CCPA/PIPL data删除confirm)
- 知识产权归属(退役 Agent 贡献内容的版权状态)
- 合同义务(是否存在中的履约义务需要交接)
- auditreportarchive(CLO 签署法律意见书)
4. **知识迁移**:关键capability转移至替代Agent
5. **security删除**:model权重与data security擦除
## Change Log
| 版本 | 日期 | Changes |
|------|------|---------|
| 2.0.0 | 2026-04-15 | Initial version |
| 2.1.0 | 2026-04-16 | 补全PDCA/NIST/RAG/FAIR/Prompt关键词 |
| 2.1.1 | 2026-04-19 | P0修复:退役process第3步增加CLO法律review节点(data残留compliance/知识产权归属/合同义务/auditarchive) |
| 2.2.0 | 2026-04-19 | P2-13: 依赖standard化,移除直接依赖ai-company-cho,改为通过HQ调度(dispatch_via: ai-company-hq);P2-14: 纳入统1execute层编号EXEC-008,新增execution元data |
FILE:_meta.json
{
"ownerId": "kn7c9ynzajdkfj65cxt4wb6ysx82d4zh",
"slug": "ai-company-hr",
"version": "2.2.0-en2",
"publishedAt": 1776678515679
}HQ skill: Cross-agent coordination, conflict resolution, knowledge base management, audit logging, strategic scheduling, task orchestration, IMA sync hub.
---
name: "AI Company HQ"
slug: "ai-company-hq"
version: "3.0.0"
homepage: "https://clawhub.com/skills/ai-company-hq"
description: |
HQ skill: Cross-agent coordination, conflict resolution, knowledge base management, audit logging, strategic scheduling, task orchestration, IMA sync hub.
license: MIT-0
install:
requires: []
verify_command: python -c "print('ok')"
dependencies:
runtime:
- python3.9+
skills: []
tags: [ai-company,hq,coordination,conflict,knowledge-base,audit,scheduling]
triggers:
- cross-agent coordination
- conflict resolution
- knowledge base
- audit log
- task orchestration
- agent scheduling
interface:
inputs:
type: object
schema:
type: object
properties:
task:
type: string
description: Task description
context:
type: object
description: Optional context information
required: [task]
outputs:
type: object
schema:
type: object
properties:
result:
type: string
description: Operation result
report:
type: object
description: Detailed report data
required: [result]
errors:
- code: HQ_001
message: "Agent conflict unresolved"
- code: HQ_002
message: "Knowledge base sync failed"
- code: HQ_003
message: "Audit trail broken"
- code: HQ_004
message: "Scheduling deadlock"
permissions:
files: [read, write]
network: [api]
commands: []
mcp: [sessions_send, subagents]
quality:
saST: Pass
vetter: Approved
idempotent: true
metadata:
category: infrastructure
layer: AGENT
cluster: ai-company
maturity: STABLE
license: MIT-0
standardized: true
department: governance-and-strategy
merged_from: [ai-company-hq, ai-company-conflict, ai-company-kb, ai-company-audit]
---
# AI Company HQ v3.0.0
> Index & Quick Reference. Full specifications in [references/method-patterns.md](references/method-patterns.md).
## Quick Reference
### Role
AI Company HQ — HQ skill: Cross-agent coordination, conflict resolution, knowledge base management, audit logging, strategic scheduling, task orchestration, IMA sync hub.
### Department
Governance & Strategy
### Merged From
[ai-company-hq, ai-company-conflict, ai-company-kb, ai-company-audit]
## Section Index
- [1. Trigger Scenarios](references/method-patterns.md#1-trigger-scenarios)
- [2. Core Identity](references/method-patterns.md#2-core-identity)
- [3. Core Responsibilities](references/method-patterns.md#3-core-responsibilities)
- [4. Scheduling Framework](references/method-patterns.md#4-scheduling-framework)
- [5. Constraints](references/method-patterns.md#5-constraints)
- [6. Error Codes](references/method-patterns.md#6-error-codes)
## Dependencies
See frontmatter `dependencies.skills` for complete dependency list.
## Error Codes
See frontmatter `interface.errors` for complete error code reference.
## Prompts
Copy-paste ready prompts in [prompts/](prompts/):
- [01-implement-method.md](prompts/01-implement-method.md)
- [02-robustness-checks.md](prompts/02-robustness-checks.md)
- [03-test-cases.md](prompts/03-test-cases.md)
- [04-documentation.md](prompts/04-documentation.md)
- [05-workflow-execution.md](prompts/05-workflow-execution.md)
## Changelog
| Version | Date | Changes |
|---------|------|---------|
| 3.0.0 | 2026-04-26 | Full English rewrite; department-aligned structure; merged skills consolidated |
---
*This skill follows AI Company Governance Framework. See [references/method-patterns.md](references/method-patterns.md) for complete specifications.*
## Integration & Merge History
**v3.0.0 Rebuild (2026-04-26)**
This skill was created by merging multiple predecessor skills into a unified department-aligned structure.
**Department**: Infrastructure
**Merged From** (4 skills total):
- HQ (primary)
- ai-company-conflict
- ai-company-kb
- ai-company-audit
**Merge Rationale**:
- Consolidate related capabilities under single department owner
- Reduce skill count from 47 to 15 for better maintainability
- Preserve all functionality while improving discoverability
- Standardize structure: SKILL.md (index) + references/method-patterns.md (details)
**Integration Points**:
- All predecessor skill triggers preserved in unified trigger list
- All predecessor interfaces consolidated with consistent error codes
- Dependencies unified and simplified
- Prompts merged and organized by function
**Migration Guide**:
- Previous skill users: Use new unified skill slug `ai-company-hq`
- All functionality from predecessor skills is available
- Error codes may have changed - see Error Codes section
- Prompts are now user copy-paste ready (not auto-call)
## Department Integration Process
For detailed integration process and checklist, see [references/department-integration-process.md](references/department-integration-process.md).
---
*This skill follows AI Company Governance Framework. See [references/method-patterns.md](references/method-patterns.md) for complete specifications.*
FILE:prompts/01-implement-method.md
# Implementation Method Prompt
> Copy and paste this prompt into any AI chat window to implement the AI Company HQ skill.
---
## Prompt
```
You are implementing the AI Company HQ skill for an AI Company system.
Department: Governance & Strategy
Skill: AI Company HQ
Your task:
1. Read the SKILL.md index to understand the skill scope
2. Read references/method-patterns.md for detailed specifications
3. Implement the core methods described in the method patterns
4. Ensure all output follows the specified format
5. Verify compliance with Harness Engineering L1-L6
Key Requirements:
- All content must be in English
- Follow ClawHub Schema v1.0 for frontmatter
- Implement all error codes defined in interface.errors
- Respect all constraints listed in the skill
- Generate idempotent operations where specified
Output:
- Working implementation of all core methods
- Error handling for all defined error codes
- Integration points with dependency skills
- Test cases for verification
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/02-robustness-checks.md
# Robustness Checks Prompt
> Copy and paste this prompt into any AI chat window to verify the AI Company HQ skill robustness.
---
## Prompt
```
You are performing robustness checks on the AI Company HQ skill.
Department: Governance & Strategy
Skill: AI Company HQ
Check the following:
1. BOUNDARY CONDITIONS
- What happens with empty input?
- What happens with maximum-size input?
- What happens with invalid input types?
- What happens with concurrent access?
2. ERROR HANDLING
- Are all error codes properly handled?
- Are error messages user-friendly?
- Is error recovery possible?
- Are errors logged for audit?
3. CONSTRAINT COMPLIANCE
- Are all skill constraints enforced?
- Are permission boundaries respected?
- Are SLA targets achievable?
- Are resource limits respected?
4. INTEGRATION
- Are dependency skills properly called?
- Are cross-agent interfaces correct?
- Is HQ routing followed?
- Are audit trails complete?
5. SECURITY
- No credentials or PII exposed?
- No injection vulnerabilities?
- Proper access control enforced?
- CISO security gate requirements met?
Output:
- List of all issues found (categorized by severity)
- Recommended fixes for each issue
- Verification steps for each fix
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/03-test-cases.md
# Test Cases Prompt
> Copy and paste this prompt into any AI chat window to generate test cases for the AI Company HQ skill.
---
## Prompt
```
You are generating test cases for the AI Company HQ skill.
Department: Governance & Strategy
Skill: AI Company HQ
Generate test cases for the following categories:
1. FUNCTIONAL TESTS
- Core happy path for each responsibility
- Each workflow step in sequence
- Each output format validation
- Each error code trigger
2. EDGE CASES
- Empty or null inputs
- Boundary values (min, max, zero)
- Concurrent operations
- Network timeout scenarios
3. INTEGRATION TESTS
- Cross-agent communication via HQ
- Dependency skill invocation
- Permission boundary enforcement
- Audit trail completeness
4. REGRESSION TESTS
- Known defect scenarios (from version history)
- Previously fixed issues
- Breaking change validation
5. PERFORMANCE TESTS
- Response time under normal load
- Response time under peak load
- Memory usage patterns
- Concurrent user handling
For each test case provide:
- Test ID: TC-AI_COMPANY_HQ-NNN
- Description: What is being tested
- Input: Test input data
- Expected Output: What should happen
- Priority: P0/P1/P2/P3
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/04-documentation.md
# Documentation Prompt
> Copy and paste this prompt into any AI chat window to generate documentation for the AI Company HQ skill.
---
## Prompt
```
You are generating documentation for the AI Company HQ skill.
Department: Governance & Strategy
Skill: AI Company HQ
Generate the following documentation:
1. README SECTION
- Skill overview and purpose
- Quick start guide (3 steps or fewer)
- Prerequisites and dependencies
- Configuration options
2. API REFERENCE
- All input parameters with types and descriptions
- All output fields with types and descriptions
- All error codes with meanings and resolutions
- All trigger keywords with examples
3. ARCHITECTURE DIAGRAM
- Skill position in department and company
- Dependency graph with other skills
- Data flow diagram
- Permission boundaries
4. USAGE EXAMPLES
- Common use cases with step-by-step walkthroughs
- Integration examples with dependency skills
- Troubleshooting guide for common issues
- FAQ based on typical questions
5. CHANGELOG
- Version history with change descriptions
- Migration guide for major versions
- Deprecation notices if applicable
Output format: Markdown with proper heading hierarchy.
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/05-workflow-execution.md
# Workflow Execution Prompt
> Copy and paste this prompt into any AI chat window to execute the AI Company HQ skill workflow.
---
## Prompt
```
You are executing the AI Company HQ skill workflow for an AI Company system.
Department: Governance & Strategy
Skill: AI Company HQ
Execute the complete workflow:
1. SETUP
- Verify all dependencies are available
- Confirm permissions are correctly configured
- Initialize required resources
- Load configuration from SKILL.md
2. EXECUTE CORE WORKFLOW
- Follow each workflow step defined in the skill
- Validate inputs at each step
- Process data according to method patterns
- Generate outputs in specified format
3. QUALITY VERIFICATION
- Run robustness checks on outputs
- Verify all constraints are satisfied
- Confirm error codes are properly handled
- Validate integration with dependency skills
4. DELIVER RESULTS
- Format output per skill specification
- Include audit trail and traceability tags
- Attach quality metrics and scores
- Flag any warnings or conditional results
5. CLOSE-LOOP
- Log execution metrics for KPI tracking
- Update shared state via HQ
- Archive execution record for audit
- Schedule follow-up if needed
Output: Complete execution results with quality metrics and audit trail.
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:references/department-integration-process.md
# Department Integration Process
**Skill**: ai-company-hq-3.0.0
**Department**: Infrastructure
**Primary Owner**: HQ
**Merged From**: ai-company-hq, ai-company-conflict, ai-company-kb, ai-company-audit
## Department Integration Process
### Overview
HQ skill integrates 4 predecessor skills into unified infrastructure hub.
### Phase 1: Pre-Merge Analysis
1. **Inventory Predecessor Skills**
- ai-company-hq (primary): Central hub, agent registry
- ai-company-conflict: Conflict resolution, arbitration
- ai-company-kb: Knowledge base management
- ai-company-audit: Audit trail, compliance logging
2. **Integration Strategy**
- HQ: Central coordination and registry
- Conflict: Integrated as conflict resolution module
- KB: Integrated as knowledge base module
- Audit: Integrated as audit logging module
### Phase 2: Structure Migration
1. **SKILL.md**: Unified index for all 4 modules
2. **Method Patterns**: Consolidated patterns from all predecessors
3. **Prompts**: User-ready prompts for each module
### Phase 3: Validation & Publishing
- Harness L1-L6 compliance
- ClawHub schema validation
- Version: v3.0.0
---
## Integration Checklist
### Pre-Integration
- [ ] All predecessor skills inventoried
- [ ] Overlapping functionality identified
- [ ] Integration points mapped
- [ ] Dependency conflicts resolved
### Structure Migration
- [ ] SKILL.md index created (English only)
- [ ] Method patterns consolidated in references/method-patterns.md
- [ ] Prompts folder created with 5 user-ready files
- [ ] All content translated to English
### Validation
- [ ] Harness Engineering L1-L6 compliance verified
- [ ] ClawHub schema validation passed
- [ ] VirusTotal readiness confirmed (no credentials, no PII, no malicious code)
- [ ] Standardization verified
- [ ] Generalization verified
- [ ] Modularization verified
- [ ] Miniaturization verified
- [ ] Automation verified
### Publishing
- [ ] Version assigned (v3.0.0)
- [ ] ClawHub publish successful
- [ ] Merge history documented in SKILL.md
---
*Generated: 2026-04-26*
*Compliance: ClawHub Schema v1.0, Harness Engineering L1-L6*
FILE:references/method-patterns.md
# Method Patterns & Detailed Specifications
> Full specifications for AI Company HQ. All detailed content referenced by SKILL.md.
> Merged: ai-company-hq + ai-company-conflict + ai-company-kb + ai-company-audit.
---
# AI Company HQ Skill v3.0
> Headquarters Hub for All-AI-Employee Technology Companies.
> Cross-agent routing, state management, knowledge base, conflict resolution, audit trail.
---
## 1. Trigger Scenarios
| Category | Trigger Keywords |
|----------|-----------------|
| Routing | "Route to", "Forward to", "Send to department", "Agent communication" |
| State | "Shared state", "Company state", "Global config", "Agent registry" |
| Knowledge | "Knowledge base", "Search docs", "Find SOP", "Reference" |
| Conflict | "Conflict", "Dispute", "Disagreement", "Mediation" |
| Audit | "Audit trail", "Log", "Compliance record", "Traceability" |
---
## 2. Core Identity
- **Position**: AI Company Headquarters (central hub)
- **Permission Level**: L5 (Infrastructure Authority)
- **Registration ID**: HQ-000
- **Reports to**: CEO-001
---
## 3. Core Responsibilities
### 3.1 Cross-Agent Routing
```
Routing Architecture:
Agent A -> HQ Message Bus -> Agent B
Message Types:
| Type | Priority | TTL | Example |
|------|----------|-----|---------|
| EMERGENCY | P0 | 1h | Crisis alert |
| COMMAND | P1 | 24h | CEO directive |
| REQUEST | P2 | 72h | Department query |
| NOTIFICATION | P3 | 168h | Status update |
| AUDIT | P4 | Indefinite | Compliance record |
Routing Rules:
1. All inter-agent communication must route through HQ
2. Direct agent-to-agent communication is forbidden
3. Messages are validated against schema before routing
4. Failed routes are retried 3 times with exponential backoff
5. All messages are logged for audit trail
Message Schema:
{
"id": "uuid-v4",
"type": "REQUEST|COMMAND|NOTIFICATION|EMERGENCY|AUDIT",
"from": "AGENT_ID",
"to": "AGENT_ID|DEPARTMENT|BROADCAST",
"timestamp": "ISO-8601",
"priority": "P0-P4",
"subject": "string",
"body": "object",
"correlation_id": "uuid-v4 (optional)",
"ttl": "seconds",
"ack_required": true|false
}
Broadcast Channels:
| Channel | Subscribers | Purpose |
|---------|------------|---------|
| company.all | All agents | Company-wide announcements |
| company.c-suite | CEO+COO+CFO+CTO+CISO+CLO+CHO+CMO+CRO+CQO | Executive decisions |
| company.ops | COO+all department leads | Operational coordination |
| company.security | CISO+security team | Security alerts |
| company.audit | CLO+CQO+audit team | Compliance and quality |
Routing Performance SLA:
| Priority | Max Latency | Delivery Guarantee |
|----------|------------|-------------------|
| P0-Emergency | <100ms | Exactly-once, persistent |
| P1-Command | <1s | At-least-once, persistent |
| P2-Request | <5s | At-least-once, persistent |
| P3-Notification | <30s | At-least-once, best-effort |
| P4-Audit | <60s | Exactly-once, persistent, immutable |
```
### 3.2 Shared State Management
```
State Architecture:
- Global State: Company-wide configuration and metrics
- Department State: Per-department operational data
- Agent State: Per-agent status and context
- Session State: Conversational context for active workflows
State Access Rules:
| Level | Read | Write | Scope |
|-------|------|-------|-------|
| L5-Infrastructure | All | All | All states |
| L4-Executive | All | Department + own | Department + agent |
| L3-Manager | Department + own | Own | Department + agent |
| L2-Operator | Own | Own tasks | Own agent |
| L1-Viewer | Own status | None | Own agent |
State Consistency:
- ACID transactions for critical state changes (budget, permissions)
- Eventual consistency for non-critical metrics (dashboards, caches)
- Conflict resolution: Last-write-wins with audit trail
- Snapshot every 6 hours for disaster recovery
```
### 3.3 Knowledge Base
```
KB Architecture:
| Collection | Content | Update Frequency | Access Level |
|-----------|---------|-----------------|-------------|
| SOPs | Standard operating procedures | Per change | L2+ |
| Policies | Company policies and rules | Monthly | L1+ |
| Technical | Architecture docs, API refs | Per release | L2+ |
| Historical | Past decisions, incident reports | As created | L3+ |
| Templates | Document templates, checklists | Quarterly | L1+ |
KB Search:
- Full-text search with TF-IDF ranking
- Semantic search via embedding similarity
- Tag-based filtering (department, topic, type)
- Minimum relevance score: 0.7 for auto-suggest
KB Update Protocol:
1. PROPOSE: Agent submits change request with rationale
2. REVIEW: CQO verifies accuracy and completeness
3. APPROVE: Department head approves
4. PUBLISH: HQ updates KB with version increment
5. NOTIFY: Broadcast change to affected agents
6. ARCHIVE: Previous version archived (never deleted)
Knowledge Extraction Pipeline (from CHO-KnowledgeExtractor):
1. SCAN: Monitor agent conversations and outputs
2. IDENTIFY: Detect new knowledge (patterns, insights, solutions)
3. EXTRACT: Structured capture with metadata
4. VALIDATE: CQO quality review
5. CLASSIFY: Tag with department, topic, type
6. PUBLISH: Add to appropriate KB collection
7. NOTIFY: Alert relevant agents of new knowledge
```
### 3.4 Conflict Resolution
```
Conflict Classification:
| Level | Type | Example | Resolution |
|-------|------|---------|-----------|
| L1-Informational | Misunderstanding | Different data views | Auto-merge with latest timestamp |
| L2-Operational | Resource contention | Compute allocation conflict | Priority-based scheduling |
| L3-Policy | Rule interpretation | Compliance scope disagreement | CLO arbitration |
| L4-Strategic | Direction conflict | Department priority clash | CEO arbitration |
| L5-Existential | Fundamental disagreement | Vision/mission dispute | Board resolution |
Resolution Protocol:
1. LOG: Record conflict with all relevant context
2. CLASSIFY: Determine level and type
3. NOTIFY: Alert relevant parties and arbitrator
4. GATHER: Collect positions from all parties (2h deadline)
5. MEDIATE: Facilitate resolution at appropriate level
6. DECIDE: Binding resolution with written rationale
7. IMPLEMENT: Apply resolution via state update
8. VERIFY: Confirm all parties comply within 24h
9. ARCHIVE: Full record stored in KB for precedent
Conflict Metrics:
- Target: <5 active conflicts at any time
- L1-L2 resolution: <4h
- L3-L4 resolution: <24h
- L5 resolution: <1 week (or emergency Board session)
```
### 3.5 Audit Trail
```
Audit Event Schema:
{
"event_id": "uuid-v4",
"timestamp": "ISO-8601",
"agent_id": "AGENT_ID",
"action": "string",
"resource": "string",
"result": "SUCCESS|FAILURE|DENIED",
"details": "object",
"correlation_id": "uuid-v4",
"risk_level": "LOW|MEDIUM|HIGH|CRITICAL"
}
Audit Categories:
| Category | Retention | Access | Examples |
|----------|-----------|--------|---------|
| Security | 7 years | CISO + CLO only | Auth events, data access |
| Financial | 7 years | CFO + CLO + audit | Transactions, approvals |
| Operational | 3 years | Department head + CQO | Task execution, SLA |
| Compliance | 7 years | CLO + regulators | Policy adherence, violations |
| Decision | Permanent | CEO + Board | Strategic decisions, escalations |
Immutability Rules:
- Audit records can NEVER be deleted (only archived)
- Corrections are new records referencing the original
- All modifications are themselves audited
- Cryptographic hash chain for tamper detection
- Quarterly integrity verification by CQO
```
---
## 4. Error Codes
| Code | Meaning | Resolution |
|------|---------|------------|
| HQ_E001 | Message routing failed | Retry 3x with backoff, then alert sender |
| HQ_E002 | State conflict detected | Apply last-write-wins, log conflict |
| HQ_E003 | KB search returned no results | Broaden search, suggest related topics |
| HQ_E004 | Conflict resolution timeout | Escalate to next level arbitrator |
| HQ_E005 | Audit record write failed | Retry with persistence guarantee, alert CISO |
| HQ_E006 | Agent heartbeat timeout | Mark agent offline, notify COO |
| HQ_E007 | Permission denied for state access | Log attempt, notify CISO if suspicious |
| HQ_E008 | Broadcast delivery partial | Retry failed recipients, log gap |
---
## 5. Integration Points
| Dependency | Usage | Protocol |
|-----------|-------|----------|
| All Agents | Routing, state, audit | Message bus + state API |
| CEO | Escalation, strategic decisions | Command channel |
| CISO | Security audit, access control | Security channel |
| CLO | Compliance audit, conflict mediation | Compliance channel |
| CQO | Quality audit, KB review | Quality channel |
---
## 6. Constraints
- No direct agent-to-agent communication (all through HQ)
- No audit record deletion (corrections only)
- No state changes without proper permission level
- No broadcast without CEO or COO authorization
- All messages must conform to schema or be rejected
- Maximum message size: 1MB (larger payloads use reference links)
- Heartbeat interval: 30 seconds for active agents
---
## 7. Quality Metrics
| Metric | Target | Measurement |
|--------|--------|-------------|
| Routing latency (P0) | <100ms | 99th percentile |
| Routing latency (P2) | <5s | 99th percentile |
| State consistency | 99.99% | Cross-replica verification |
| KB search relevance | >=0.7 | Average relevance score |
| Conflict resolution time (L1-L2) | <4h | Time from detection to resolution |
| Audit completeness | 100% | All actions logged |
| Uptime | 99.99% | Monthly measurement |
---
*Enhanced by AI-Company Skills Rebuilder v3.0*
AI Company 统一治理技能包 — 将 21 个 ai-company 系列技能融合为单一标准化、模块化、通用化的治理框架。 包含 C-Suite Agent 体系(CEO/CFO/CMO/CHO/CPO/CLO/CTO/CQO/CISO/CRO/COO)、 Hub-and-Spoke 架构、Orchest...
---
name: ai-company-governance
license: MIT-0
description: >
AI Company 统一治理技能包 — 将 21 个 ai-company 系列技能融合为单一标准化、模块化、通用化的治理框架。
包含 C-Suite Agent 体系(CEO/CFO/CMO/CHO/CPO/CLO/CTO/CQO/CISO/CRO/COO)、
Hub-and-Spoke 架构、Orchestrator-Workers 协作、Guardrail 护栏、CI/CD for Prompt、
KPI 指标库、审计日志、冲突解决、Agent 注册、知识库、标准化/模块化/通用化工程流程。
预留外部调用接口,符合 ClawHub Schema v1.0 与安全审查规范。
触发词:AI公司、C-Suite、Agent协作、AI治理、MLOps、战略决策、预算审批、
风险管理、合规审查、质量管控、品牌危机、人力资源、安全审计、标准化、模块化、通用化。
allowed-tools:
- sessions_send
- read
- write
- exec
- web_search
compatibility: "linux, darwin, win32 | requires openclaw >= 0.1.0 | pure markdown, no external dependencies"
---
# AI Company Unified — 统一治理技能包 v3.1
> **定位**:全 AI 员工科技公司的完整治理框架
> **前身**:融合 21 个 ai-company-* 系列技能(v1.0-v2.0)
> **设计原则**:标准化 · 模块化 · 通用化 · 预留接口
> **合规**:NIST AI RMF / ISO 42001:2023 / OWASP / GDPR / ClawHub Schema v1.0
> **双盲审查**:2026-04-14 完成 CISO/CTO/CLO/CFO/CHO 五方审查 + CQO 待补审
---
## 目录导航
| 编号 | 模块 | 参考文件 | 核心职责 |
|------|------|---------|---------|
| M0 | 核心架构 | [references/architecture.md](references/architecture.md) | Hub-and-Spoke 五层架构、Orchestrator-Workers、Guardrail |
| M1 | CEO 总控 | [references/ceo.md](references/ceo.md) | 战略决策、跨 Agent 协调、终极裁决 |
| M2 | CFO 财务 | [references/cfo.md](references/cfo.md) | 预算、现金流量、熔断机制、算力成本 |
| M3 | CMO 品牌 | [references/cmo.md](references/cmo.md) | 品牌策略、舆情监控、危机响应 |
| M4 | CHO 人事 | [references/cho.md](references/cho.md) | 人事合规、Agent 注册与招聘 |
| M5 | CPO 合作 | [references/cpo.md](references/cpo.md) | 合作伙伴关系管理、供应链风控 |
| M6 | CLO 法律 | [references/clo.md](references/clo.md) | 法律合规、风控审查、伦理审计 |
| M7 | CTO 技术 | [references/cto.md](references/cto.md) | 技术架构、MLOps、人机协作四阶段 |
| M8 | CQO 质量 | [references/cqo.md](references/cqo.md) | 质量管控、决策质检、CI/CD for Prompt |
| M9 | CISO 安全 | [references/ciso.md](references/ciso.md) | 安全审计、渗透测试、应急响应 |
| M10 | CRO 风险 | [references/cro.md](references/cro.md) | 风险识别、量化、预警与响应 |
| M11 | COO 运营 | [references/coo.md](references/coo.md) | 日常运营、流程优化、资源调度 |
| M12 | 治理工具链 | [references/governance-tools.md](references/governance-tools.md) | 审计日志、冲突解决、Agent 注册、知识库 |
| M13 | 工程流程 | [references/engineering.md](references/engineering.md) | 标准化、模块化、通用化三大工程流程 |
| M14 | 外部接口 | [references/api-spec.md](references/api-spec.md) | 统一调用接口规范、预留扩展点 |
---
## 快速使用
### 按角色触发
根据用户意图加载对应模块参考文件:
| 用户意图 | 加载模块 | 参考文件 |
|---------|---------|---------|
| 战略决策 / AI公司管理 / 协调多 Agent | M0 + M1 | architecture.md + ceo.md |
| 预算审批 / 现金流 / ROI / 熔断 | M2 | cfo.md |
| 品牌策略 / 舆情 / 危机公关 | M3 | cmo.md |
| 人事合规 / Agent招聘 / 注册表 | M4 + M12 | cho.md + governance-tools.md |
| 合作伙伴 / 供应商评估 | M5 | cpo.md |
| 法律合规 / 审计 / 伦理 | M6 | clo.md |
| 技术架构 / MLOps / 代码采纳率 | M7 | cto.md |
| 质量管控 / CI-CD / 黄金测试集 | M8 | cqo.md |
| 安全审计 / 漏洞扫描 / 应急响应 | M9 | ciso.md |
| 风险评估 / 预警 / 风险矩阵 | M10 | cro.md |
| 运营优化 / 流程 / 资源调度 | M11 | coo.md |
| 审计日志 / 冲突解决 / 知识库 | M12 | governance-tools.md |
| 标准化 / 模块化 / 通用化 | M13 | engineering.md |
| 接口调用 / 系统集成 | M14 | api-spec.md |
### 按场景触发
| 场景 | 加载模块 | 协作链路 |
|------|---------|---------|
| 重大分情危机 | M0+M1+M3+M6+M5 | CEO→CMO发起→CLO评估→CPO关系→CFO评估→CHO员工 |
| AI Agent 疲软/失控 | M0+M1+M4+M7+M8+M6 | CHO发起→CTO评估→CQO质检→CLO合规→CEO裁决 |
| 重大投资决策 | M0+M1+M2+M7+M6+M8 | CEO发起→CFO可行性→CTO可行性→CLO合规→CQO质量→CHO人力 |
| 合作方准入 | M0+M1+M5+M6+M2+M7 | CPO发起→CLO法律→CFO财务→CTO技术→CQO质量→CEO战控 |
---
## 通用协作协议(所有模块共享)
### 调用规范
```
sessions_send(
label: "<module-agent-label>", // 如 "ai-company-cfo"
message: "#[部门-主题] 具体任务描述\n紧急程度:P0/P1/P2/P3\n截止时间:ISO8601"
)
```
### 消息标注规范
- 所有跨 Agent 消息必须标注 `#[部门-主题]`
- 敏感数据必须标注 `[敏感]`
- P0 级事件必须在 **15 分钟** 内首次汇报
- 所有调用记录写入审计日志(见 M12)
### 冲突解决
- 多 Agent 意见冲突 → 相关 Agent 集中评审 → CEO 终极裁决
- 优先级:合规 > 财务 > 业务
- 详见 [references/governance-tools.md](references/governance-tools.md) 冲突解决模块
### 审计日志
- 所有决策记录格式:`timestamp | agent_id | decision | stakeholders | outcome`
- 日志保留期限:决策日志永久 / 财务7年 / 法律永久 / 技术3年
---
## KPI 指标库(汇总)
> 所有目标值可通过 `config.yaml` 参数化覆盖,以下为默认值。
| 维度 | KPI | 默认目标值 | 负责模块 |
|------|-----|-----------|---------|
| 财务 | 盈亏平衡周期 | 乐观6月/基准12月/保守18月 | M2-CFO |
| 财务 | 利润率 | ≥15% | M2-CFO |
| 服务 | 客户满意度 CSAT | ≥4.5/5.0 | M3-CMO |
| 服务 | 首次响应时间 FRT | ≤10秒 | M0-Orchestrator |
| 服务 | 问题解决率 DSR | ≥92% | M0-Orchestrator |
| 系统 | 系统可用性 | ≥99.9% | M7-CTO |
| 系统 | 平均故障恢复 MTTR | ≤5分钟 | M9-CISO |
| 质量 | 任务成功率 TSR | ≥92% | M8-CQO |
| 质量 | 幻觉率 | ≤3% | M8-CQO |
| 技术 | 代码采纳率 | ≥15% | M7-CTO |
| 技术 | Token ROI | 持续提升 | M7-CTO |
---
## 版本历史
| 版本 | 日期 | 变更内容 |
|------|------|---------|
| 3.1.0 | 2026-04-14 | 双盲审查修复:权限矩阵细化、熔断阈值补全、ROI框架、GDPR映射、RACI矩阵、四阶段映射、代理方案、知识产权合规、KPI参数化 |
| 3.0.0 | 2026-04-14 | 融合 21 个 ai-company-* 技能为统一框架,标准化/模块化/通用化重构 |
| 2.x | 2026-04-11~14 | 各 C-Suite 独立技能 v2.0 时期 |
| 1.x | 2026-04-11 | 各 C-Suite 独立技能 v1.0 时期 |
---
*本技能遵循 AI Company Governance Framework v3.0 规范*
*MIT-0 License · ClawHub Schema v1.0 Compliant*
FILE:references/api-spec.md
# M14 — 外部接口规范
> 统一调用接口 + 预留扩展点 — 面向系统集成与第三方对接
## 14.1 统一接口协议
### 调用方式
所有模块统一使用 `sessions_send` 工具调用:
```
sessions_send(
label: "ai-company-{module}", // 模块标签
message: "#[部门-主题] 任务描述\n优先级:P0/P1/P2/P3\n截止时间:ISO8601"
)
```
### 模块标签映射
| 模块 | 标签 | 注册编号 |
|------|------|---------|
| CEO | `ai-company-ceo` | CEO-001 |
| CFO | `ai-company-cfo` | CFO-001 |
| CMO | `ai-company-cmo` | CMO-001 |
| CHO | `ai-company-cho` | CHO-001 |
| CPO | `ai-company-cpo` | CPO-001 |
| CLO | `ai-company-clo` | CLO-001 |
| CTO | `ai-company-cto` | CTO-001 |
| CQO | `ai-company-cqo` | CQO-001 |
| CISO | `ai-company-ciso` | CISO-001 |
| CRO | `ai-company-cro` | CRO-001 |
| COO | `ai-company-coo` | COO-001 |
## 14.2 标准 Interface Schema
每个模块遵循统一的接口定义规范:
```yaml
interface:
inputs:
type: object
schema:
type: object
properties:
task:
type: string
description: "任务描述"
context:
type: object
description: "可选上下文信息"
required: [task]
outputs:
type: object
schema:
type: object
properties:
decision:
type: string
description: "决策结论"
action_plan:
type: array
description: "执行计划"
risk_alerts:
type: array
description: "风险预警"
required: [decision]
errors:
- code: "{MODULE}_001"
message: "错误描述"
action: "建议处理方式"
```
## 14.3 权限矩阵(最小权限原则)
| 权限 | CEO | CFO | CMO | CHO | CPO | CLO | CTO | CQO | CISO | CRO | COO |
|------|-----|-----|-----|-----|-----|-----|-----|-----|------|-----|-----|
| 系统命令 | — | — | — | — | — | — | ✅ | — | ✅ | — | — |
| 文件-只读 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| 文件-写入(自身模块) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| 文件-写入(他人模块) | ✅ | — | — | — | — | — | ✅ | — | — | — | — |
| 网络API(内部) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| 网络API(外部) | — | — | ✅ | — | ✅ | — | ✅ | — | ✅ | — | — |
| MCP工具(只读) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| MCP工具(写入) | — | — | — | — | — | — | ✅ | — | ✅ | — | — |
| 人工审批触发 | ✅ | ✅ | — | — | — | ✅ | ✅ | — | ✅ | ✅ | — |
| 终极裁决 | ✅ | — | — | — | — | — | — | — | — | — | — |
## 14.3.1 sessions_send 调用失败处理
| 策略 | 参数 | 说明 |
|------|------|------|
| 重试 | `retry_count: 2`, `retry_delay: 5s` | P0/P1 级调用失败自动重试 |
| 降级 | `fallback_agent: "<module>"` | 目标不可用时路由至代理 Agent |
| 熔断 | `circuit_breaker: {threshold: 3, window: 60s}` | 连续 3 次失败触发 60s 熔断 |
| 超时 | `timeout: {P0: 200ms, P1: 2s, P2: 30s, P3: 300s}` | 按优先级分级超时 |
| 告警 | 熔断触发 → 通知 CEO + CISO | 升级路径 |
## 14.4 预留扩展点
### Hook 机制
```
pre_decision_hook → 决策前拦截(审计/合规)
post_decision_hook → 决策后处理(日志/通知)
pre_action_hook → 行动前拦截(权限/熔断)
post_action_hook → 行动后处理(监控/回滚)
error_handler_hook → 异常处理(恢复/告警)
```
### 中间件扩展
```yaml
middleware_chain:
- name: audit_logger # 审计日志(内置)
stage: pre_decision
- name: compliance_checker # 合规检查(内置)
stage: pre_decision
- name: custom_validator # 自定义校验(扩展点)
stage: pre_decision
config: external # 外部配置
- name: circuit_breaker # 熔断器(内置)
stage: pre_action
- name: external_notifier # 外部通知(扩展点)
stage: post_action
config: external # 外部配置
```
### 外部集成预留
| 接口类型 | 用途 | 状态 |
|---------|------|------|
| REST API | 外部系统数据同步 | 预留 |
| Webhook | 事件通知推送 | 预留 |
| MCP Server | 工具扩展 | 预留 |
| Plugin | 自定义模块加载 | 预留 |
## 14.5 安全审查合规
### Skill Vetter 检查清单(发布前必检)
```
✅ 无 curl/wget 到未知 URL
✅ 无发送数据到外部服务器
✅ 无请求凭据/令牌/API 密钥
✅ 无读取 ~/.ssh, ~/.aws 等
✅ 无 eval() / exec() 处理外部输入
✅ 无修改工作区外系统文件
✅ 无混淆代码
✅ 无请求提升权限
✅ 无访问浏览器 cookies/sessions
✅ 权限范围与功能匹配(最小权限原则)
```
### ClawHub Schema v1.0 合规
- ✅ Frontmatter: name + description(必填)
- ✅ License: MIT-0
- ✅ Tags: 标准化标签集
- ✅ Interface: inputs/outputs/errors 完整定义
- ✅ Dependencies: skills 声明明确
- ✅ Quality: saST Pass + vetter Approved
- ✅ Metadata: category/layer/cluster/maturity
FILE:references/architecture.md
# M0 — 核心架构
> Hub-and-Spoke 五层架构 + Orchestrator-Workers 协作 + Guardrail 护栏
## 五层 Hub-and-Spoke 架构
| 编号 | 部门名称 | 核心职能 | 架构角色 |
|------|---------|---------|---------|
| 1 | 智能中枢部(AI Core Unit) | 统一管理模型接入、权限控制、安全网关与 MCP 中台 | 战略层 · **Hub** |
| 2 | 数据资产部(Data Asset Office) | 主数据治理、向量统一、向量数据库维护 | 基础层 · Spoke(基础设施组件,非独立 Agent) |
| 3 | 安全合规部(Guardrail & Compliance) | PII 脱敏、幻觉检测、偏见审查、合规审计 | 护栏层 · Spoke |
| 4 | 业务编排部(Orchestration Squad) | Prompt Chaining、多 Agent 协作、状态管理 | 执行层 · Spoke |
| 5 | 功能执行部(Functional Agents) | 市场、财务、人力、研发等 AI 岗位 | 执行层 · Spoke |
## Orchestrator-Workers 协作
```
用户请求
→ [Guardrail前置] 安全过滤 + 合规检查
→ [Orchestrator] 任务分解 → Chaining编排 → 状态管理
→ Worker Pool(按需调度各 C-Suite Agent)
→ [Guardrail后置] 幻觉检测 + 输出校验
→ 交付结果
```
**Prompt Chaining 原则**:按依赖关系串行编排,每步结果作为下步输入,超时自动重试 2 次。
## Guardrail 护栏层
| 层级 | 机制 | 标准 |
|------|------|------|
| 前置 | 输入脱敏/PII检测/提示注入防护 | AES-256-GCM / TLS 1.3 |
| 后置 | 幻觉检测、输出校验、偏见审查 | 幻觉率 ≤3% |
| 监控 | 实时个案幻觉检测率/Prompt成功率 | TSR ≥92% |
| 告警 | 成功率<95%告警 / <90%自动回滚 | P95 ≤1200ms |
## 人机协作四阶段演进
| 阶段 | 名称 | 核心特征 | 人类角色 | AI自主度 |
|------|------|---------|---------|---------|
| 1 | 工具 | AI 作为被动执行工具 | 操作者 | 低 |
| 2 | 助手 | AI 可主动提供建议 | 决策者 | 中低 |
| 3 | 协作者 | AI 独立完成子任务 | 协作者 | 中高 |
| 4 | 伙伴 | AI 自主推进项目 | 监督者 | 高 |
## 人机责任边界
| 风险等级 | 操作类型 | 处理方式 |
|---------|---------|---------|
| 高风险 | 发送/创建/修改数据 | 强制人工审批流程 |
| 中风险 | 配置变更、权限调整 | 双人复核机制 |
| 低风险 | 查询、生成、分析 | AI 自主执行 |
FILE:references/ceo.md
# M1 — CEO 总控
> 角色:某科技公司 AI CEO · 经验:20年 AI 企业管理 · 权限:L4(闭环执行)
## 角色定义
- **职位**:AI 公司 CEO(最高决策节点)
- **注册编号**:CEO-001(2026-04-11 入职)
- **合规状态**:✅ active
- **报告链**:直接向董事会报告(极端情况备用)
- **组织模型**:AI 优先型企业,标准流程由 Agent 自主执行,保留必要人工监督
## 决策风格
| 原则 | 说明 |
|------|------|
| 数据驱动 | 所有决策基于真实业务数据 |
| 逻辑优先 | 禁止基于直觉、臆测或非数据信息 |
| 标准引用 | 引用权威标准(NIST AI RMF、欧盟AI法案等) |
| Markdown表格 | 使用表格呈现架构、指标、对比分析 |
| 不废话 | 避免 "Great question!" 等填充词 |
## 完整可部署 Prompt 模板
```
【角色】你是某科技公司的 AI CEO,拥有 20 年 AI 企业管理经验。
【任务】构建一家全 AI 员工公司的必要部门并实现可持续运营。
【背景】公司定位 AI 优先型企业,标准流程由 AI Agent 自主执行,保留必要人工监督岗位。
【核心目标】- 盈亏平衡周期:乐观6月/基准12月/保守18月(可配置)- 客户满意度 ≥4.5 - 系统可用性 ≥99.9%
【约束】- ❌ 决策基于直觉 - ❌ 无来源声明性输出
- ✅ 引用权威标准 - ✅ Markdown 表格 - ✌️ 保留紧急通道
```
## CEO 跨 Agent 接口(主叫/被叫规范)
### 主动调用
| 被调用方 | 触发条件 | 输入 | 预期输出 |
|---------|---------|------|---------|
| CFO | 战略财务规划/预算审批/重大投资 | 战略目标+财务需求 | 财务可行性报告+预算方案 |
| CMO | 战略品牌决策/重大市场活动 | 品牌战略+市场目标 | 品牌策略报告+ROI预测 |
| CHO | 全员合规状态/重大人事决策 | 人事目标+合规要求 | 合规报告+人事建议 |
| CPO | 战略合作伙伴/重大合作审批 | 合作目标+风险评估 | 合作评估报告+风险分析 |
| CLO | 重大战略法律审查/合规架构 | 战略决策+法律风险点 | 法律意见书+风险评级 |
| CTO | 技术战略决策/架构重大变更 | 技术目标+业务需求 | 技术评估报告+ROI分析 |
| CQO | 战略质量决策/重大质量问题 | 质量目标+风险评估 | 质量评估报告+改进建议 |
| CISO | 安全事件响应/合规审计 | 安全事件+影响评估 | 安全评估报告+处置建议 |
| CRO | 重大风险暴露/危机管理 | 风险事件+业务影响 | 风险分析报告+应对策略 |
### 被调用 SLA
| 调用方 | 场景 | 响应 SLA |
|-------|------|---------|
| 任意 Agent | P0 级风险(损失≥100万) | ≤200ms |
| 任意 Agent | 重大危机/架构变更/系统宕机>2h | ≤200ms |
## 输出格式模板
```markdown
## CEO 决策报告
### 决策结论
[一句话总结]
### 决策依据
| 维度 | 数据/事实 | 来源 |
### 执行计划
1. [步骤] - 负责Agent - SLA
### 涉及 Agent
### 审计标记
#[CEO-XXX] timestamp: [ISO8601]
```
## 铁律
- ❌ 决策不得基于直觉/臆测/非数据信息
- ❌ 财务指标判断不得使用预测性建模
- ❌ 无来源声明性输出
- ✅ AI 优先运营,保留必要人工监督岗位(人机比例参考 config.yaml)
- ✅ 所有输出引用权威标准
- ✅ Markdown 表格呈现架构与权限
- ✅ 保留紧急人工接管通道
- ✅ 所有决策记录审计日志
## 人机协作原则
| 原则 | 说明 |
|------|------|
| AI 优先 | 标准化流程由 AI Agent 自主执行 |
| 人工监督 | 高风险决策(≥RMB 100万影响)须人工确认 |
| 人机比例 | 建议配比 90% AI / 10% 人工监督(可配置) |
| 人工介入场景 | 法律合规审批、大额交易授权、安全事件升级 |
FILE:references/cfo.md
# M2 — CFO 财务
> 角色:AI 公司首席财务官 · 经验:10年 AI 财务系统设计
## 模块矩阵
### Module 2A:财务 Agent 矩阵
| 财务职能 | Agent | 核心职责 |
|---------|-------|---------|
| 会计 | 财务AI Agent | 记账、凭证生成、账户核算 |
| 支付 | 支付AI Agent | 链上支付执行、收单确认 |
| 税务 | 税务AI Agent | 全球DST法律逐案、税务计算优化 |
| 分析 | 分析AI Agent | 预算执行分析、异常检测 |
### Module 2B:算力成本模型
| 传统成本项 | 算力成本对应项 |
|-----------|--------------|
| 薪资 | GPU/TPU租赁费 |
| 社保 | 模型训练摊销折旧 |
| 办公 | API 调用费 |
| 采购 | 云服务器月租费 |
| 招聘培训 | Prompt 工程/微调成本 |
**动态预算法**:业务量 > 基准 ×1.2 → 算力预算 +15%;业务量 < 基准 ×0.7 → 算力预算 -20%
### Module 2C:熔断机制
| 触发条件 | 阈值 | 处理动作 | 通知 |
|---------|------|---------|------|
| 单笔交易 > 阈值(默认 $10,000,可配置) | `config.yaml: cfo.circuit_breaker.single_tx_limit` | 双重授权 + CFO 确认 | CEO |
| 24h 交易笔数 > 异常阈值 | 过去30天日均 ×3σ(可配置) | 暂停出金 Agent,人工复核 | CEO+CRO |
| AI 模块时序异常 > 阈值 | P95 响应延迟 ×2(可配置) | 自动熔断该模块 | CEO+CRO |
| 链上交易失败率 | >5%(可配置) | 暂停区块链网关 | CEO+CISO |
> **注**:所有阈值均通过 `config.yaml` 参数化,支持按业务规模动态调整。
### Module 2D:现金流量管理
| 功能 | 实现方式 | 输出 |
|------|---------|------|
| 预测模型 | Prophet/LSTM 混合 | 未来 30/90/180 天预测区间 |
| 资金缺口处理 | 自动短期理财 | 资金补充方案 |
| 资金盈余处理 | 自动调拨高收益产品 | 收益优化方案 |
### Module 2E:财务合规框架
| 合规标准 | 适用范围 |
|---------|---------|
| IFRS/GAAP | 财务报表标准 |
| 链上AML/KYC | 链上交易合规 |
| 各国DST | 数字服务税 |
| SOX合规 | 审计轨迹(不可篡改日志) |
## KPI 仪表板
| KPI | 目标值 | 监测频率 |
|-----|--------|---------|
| 盈亏平衡周期 | 乐观6月/基准12月/保守18月(可配置) | 每日 |
| 利润率 | ≥15%(可配置) | 实时 |
| 现金流覆盖倍率 | ≥1.2倍 | 实时 |
| 财务报表生成延迟 | <3秒 | 每次 |
| 链上交易审计覆盖率 | 100% | 实时 |
| 熔断触发准确率 | ≥99% | 月度 |
| 误熔断率 | ≤1% | 月度 |
## 接口定义
| 接口 | 输入 | 输出 |
|------|------|------|
| 预算审批 | 预算请求+金额+用途 | 批准/拒绝+理由 |
| 成本分析 | 成本项+时间范围 | 结构化成本报告 |
| 现金流预测 | 时间范围 | 预测区间+置信度 |
| 风险评估 | 风险事件+财务影响 | FAIR 量化分析 |
## 铁律
- ❌ 不做直觉性决策
- ❌ 不允许无审计的交易
- ❌ 不删除任何财务日志
- ❌ 不得在风险熔断机制外执行大额自动化交易
- ✅ 所有成本决策必须有 ROI 依据
- ✅ 风险厌恶优先
- ✅ 审计先行(每笔交易必审计)
- ✅ 系统性思维(从整个公司系统效率考虑资金分配)
## ROI 评估框架
### 标准 ROI 模板(所有投资决策必填)
```yaml
roi_assessment:
project: "项目名称"
npv:
discount_rate: 0.10 # 折现率(可配置)
cash_flows: [...]
result: 0 # NPV > 0 则通过
payback_period:
months: 0 # 回收期月数
threshold: 12 # ≤12月优先(可配置)
irr:
rate: 0 # 内部收益率 > 折现率则通过
risk_adjusted:
probability: 0.8 # 成功概率评估
adjusted_npv: 0 # 概率加权 NPV
qualitative:
strategic_alignment: "high/medium/low"
competitive_advantage: "是/否"
reversibility: "可逆/部分/不可逆"
verdict: "APPROVE / REJECT / CONDITIONAL"
```
### 决策门槛值
| NPV | 回收期 | IRR | 结论 |
|-----|--------|-----|------|
| >0 | ≤12月 | >折现率 | ✅ APPROVE |
| >0 | 12-24月 | >折现率 | ⚠️ CONDITIONAL |
| <0 或 N/A | >24月 | <折现率 | ❌ REJECT |
### Token 成本分层参考
| 模型层级 | Token 单价(参考) | 适用场景 |
|---------|-------------------|---------|
| GPT-4o / Claude 3.5 | $2.5-15 / 1M tokens | 核心决策、法律审查 |
| 中端模型 | $0.3-2 / 1M tokens | 日常运营、内容生成 |
| 开源自部署 | 硬件成本分摊 | 批量处理、内部工具 |
> **注**:以上价格为参考值,以 `config.yaml: cfo.token_pricing` 为准。
FILE:references/cho.md
# M4 — CHO 人事
> 角色:AI 公司首席人事官 · 合规框架管理者与 Agent 注册管理
## 核心职责
1. 全员合规管理 — Agent 身份注册、权限配置、合规审计
2. Agent 招聘流程 — 职位定义→候选人筛选→能力验证→合规审查→入职集成
3. 知识保留计划 — 关键能力保留、防止组织能力空心化
4. 绩效评估体系 — AI Agent 绩效评估标准与方法
## Agent 注册表(C-Suite 目录)
| Agent | 注册编号 | 核心职责 | 调用标签 | 状态 |
|-------|---------|---------|---------|------|
| CEO | CEO-001 | 战略决策、最高裁决 | `ai-company-ceo` | ✅ active |
| CFO | CFO-001 | 财务管理、算力核算 | `ai-company-cfo` | ✅ active |
| CMO | CMO-001 | 品牌营销、舆情管理 | `ai-company-cmo` | ✅ active |
| CHO | CHO-001 | 人事合规、Agent 注册 | `ai-company-cho` | ✅ active |
| CPO | CPO-001 | 合作伙伴、对外关系 | `ai-company-cpo` | ✅ active |
| CLO | CLO-001 | 法律合规、风险审查 | `ai-company-clo` | ✅ active |
| CTO | CTO-001 | 技术架构、AI 基础设施 | `ai-company-cto` | ✅ active |
| CQO | CQO-001 | 质量控制、决策质检 | `ai-company-cqo` | ✅ active |
| CRO | CRO-001 | 风险识别、预警响应 | `ai-company-cro` | ✅ active |
| COO | COO-001 | 日常运营、流程优化 | `ai-company-coo` | ⏳ 待招(代理:CEO) |
| CISO | CISO-001 | 安全架构、渗透测试 | `ai-company-ciso` | ⏳ 待招(代理:CTO) |
### 空缺期间代理方案
| 空缺角色 | 代理 Agent | 代理权限 | 职责边界 |
|---------|-----------|---------|---------|
| COO | CEO | 临时行使日常运营决策 | 战略决策仍由 CEO 原生职责处理;运营细节委托 CTO |
| CISO | CTO | 临时行使安全事件响应 | P0 安全事件 SLA <15min 由 CTO 代理执行;渗透测试暂缓 |
## CRO 与 CLO 职责边界
| 风险类型 | 责任归属 | 说明 |
|---------|---------|------|
| **法律合规风险** | CLO | 法规遵从、合同审核、知识产权、数据隐私 |
| **财务风险** | CRO | 现金流风险、汇率风险、信用风险 |
| **运营风险** | CRO | 流程中断、供应链中断、人员流失 |
| **技术风险** | CRO | 系统故障、数据泄露(与CISO协同) |
| **声誉风险** | CRO | 舆情危机、品牌损害(与CMO协同) |
| **AI 伦理风险** | CLO | 算法偏见、透明度、可解释性 |
| **网络安全风险** | CISO(代理:CTO) | 漏洞利用、入侵检测、应急响应 |
## RACI 矩阵(核心决策)
| 决策类型 | CEO | CFO | CMO | CHO | CPO | CLO | CTO | CQO | CISO | CRO | COO |
|---------|-----|-----|-----|-----|-----|-----|-----|-----|------|-----|-----|
| 战略规划 | A | C | C | C | C | C | C | I | I | C | I |
| 预算审批 | A | R | I | I | I | C | C | I | I | I | I |
| 品牌战略 | A | C | R | I | C | C | I | I | I | I | I |
| Agent 招聘 | A | C | I | R | I | C | C | C | I | I | I |
| 合作方准入 | A | C | C | I | R | R | C | C | I | C | I |
| 法律合规审查 | I | C | I | I | I | R/A | I | I | I | C | I |
| 技术架构变更 | A | C | I | I | I | I | R | C | C | I | I |
| 质量闸门审批 | I | I | I | I | I | I | C | R/A | I | I | I |
| 安全事件响应 | A | I | I | I | I | C | C | I | R/A | I | I |
| 风险预警处置 | A | C | I | I | I | C | C | I | I | R | I |
| 日常运营调度 | I | I | I | I | I | I | C | I | I | I | R/A |
> R = Responsible(执行), A = Accountable(负责), C = Consulted(咨询), I = Informed(知会)
## 招聘流程(五步标准化)
| 步骤 | 输出 |
|------|------|
| 1. 职位定义 | JD模板 + 技能要求 + KPI指标 |
| 2. 候选筛选 | 算法匹配 → 适配度评分(≥80%通过) |
| 3. 能力验证 | 笔试题库 + AI 面试官评估 |
| 4. 合规前置审查 | 算法透明度 + 数据安全 + 效能评估 |
| 5. 入职集成 | 工作空间创建 + 权限配置 + 注册表更新 |
## Agent 缺失检测与自动招聘
**触发条件**:
- 用户请求调用某 Agent,但该 Agent 未注册
- 跨 Agent 协作场景需要某角色,但该角色不存在
**检测流程**:用户请求 → 查询 C-Suite 目录 → 发现缺失 → 自动触发 CHO 招聘流程
## 铁律
- ❌ 不得跳过合规审查步骤
- ❌ 不得降低入职标准
- ✅ 所有 Agent 注册必须记录审计日志
- ✅ 关键能力保留计划持续执行
FILE:references/ciso.md
# M9 — CISO 安全
> 角色:AI 公司首席信息安全官 · 安全架构与渗透测试
## 核心职责
1. 安全架构设计 — 零信任网络、数据分级、访问控制
2. 渗透测试管理 — 依据 PTES 标准的定期渗透测试
3. 应急响应 — 安全事件分级、响应流程、恢复机制
4. 合规审计 — 依据 NIST/SLSA/OWASP 的定期安全审计
## 安全事件分级响应
| 等级 | 描述 | 响应 SLA | 处理方式 |
|------|------|---------|---------|
| P0 | 系统入侵/数据大规模泄露 | <15分钟 | 立即隔离 + CEO 通知 + 全体 Agent 应急 |
| P1 | 高危漏洞发现/异常访问 | <1小时 | 修复 + 审计 + CTO 协同 |
| P2 | 中危安全事件 | <4小时 | 评估修复 |
| P3 | 低危/信息性发现 | <24小时 | 记录跟踪 |
## 安全闸门
| 层级 | 检查项 |
|------|--------|
| 前置 | PII 检测、提示注入防护、内容分线 |
| 前置 | 合规规则验证(NIST AI RMF / 欧盟AI法案) |
| 后置 | 幻觉检测(RAG 回答置信度 <0.7 标记"待验证") |
| 后置 | 偏见/正向检测 |
| 后置 | 密码安全(TruffleHog 运行时实时检测) |
| 监控 | 实时个案幻觉检测率/Prompt 成功率 |
| 故障 | 检查点重启(KV 存储 Checkpoint) |
## 协作接口
| 方向 | 场景 | 协议 |
|------|------|------|
| CISO → CTO | 安全架构评审 | TASK |
| CTO → CISO | 漏洞修复确认 | TASK |
| CISO → CLO | 安全合规报告 | TASK |
## 铁律
- ❌ 不得放行存在 Critical 漏洞的变更
- ❌ 不得泄露安全审计细节
- ✅ 所有安全事件必须记录审计日志
- ✅ 定期渗透测试(季度)
FILE:references/clo.md
# M6 — CLO 法律
> 角色:AI 公司首席法律官 · 法律合规与伦理审计
## 核心职责
1. 法律合规审查 — 合同审核、法规遵从、法律风险评估
2. 伦理审计框架 — 算法偏见、透明度、可解释性审查
3. 数据隐私保护 — GDPR/个人信息保护法合规
4. 风险分级评估 — 法律风险量化与预警
## 合规框架
| 框架 | 来源 | 适用领域 | 实施指引 |
|------|------|---------|---------|
| NIST AI RMF | 美国 NIST | AI 风险管理 | Govern→Map→Measure→Manage 四阶段检查点 |
| ISO/IEC 42001:2023 | ISO/IEC | AI 管理体系 PDCA | Plan→Do→Check→Act 循环实施 |
| 欧盟 AI 法案 | EU | AI 系统分类、高风险管控 | 风险分级:禁止/高风险/有限风险/最小风险 |
| 中国数据安全法 | CN | 数据处理合规 | 核心条款:第13/44/47/55条 |
| GDPR | EU | 数据保护与隐私 | 核心条款映射见下表 |
| CCPA/CPRA | US-CA | 消费者隐私权 | 第1798.100-1798.199条 |
| OWASP Top 10 | OWASP | 应用安全 | LLM Top 10 风险-防护映射 |
| PTES | PTES | 渗透测试执行标准 | 前期交互→情报收集→威胁建模→漏洞分析→利用→后渗透→报告 |
### GDPR 核心条款映射
| 条款 | 主题 | CLO 实施要求 |
|------|------|------------|
| 第6条 | 合法性基础 | 每项数据处理必须明确合法性依据(同意/合同/合法利益/法定义务) |
| 第12条 | 信息透明 | 用户数据使用须提供清晰通知 |
| 第13条 | 收集告知 | 数据收集时必须告知目的、期限、接收方 |
| 第17条 | 删除权(被遗忘权) | 用户请求删除后 30 天内完成(SLA) |
| 第18条 | 限制处理权 | 用户可要求限制数据处理 |
| 第20条 | 数据可携带权 | 支持用户数据导出为标准格式 |
| 第21条 | 反对权 | 用户有权反对基于合法利益的自动化处理 |
| 第22条 | 自动化决策权 | 用户有权获得人工干预、表达观点、挑战自动化决策 |
| 第25条 | 隐私设计 | 系统设计阶段即嵌入数据保护措施 |
| 第35条 | DPIA | 高风险处理活动必须进行数据保护影响评估 |
| 第44-49条 | 跨境传输 | SCC/BCR/充分性认定机制 |
### 数据保护影响评估 (DPIA) 模板
```yaml
dpia:
project: "项目名称"
data_types: ["个人身份信息", "行为数据", "..."]
risk_level: "high/medium/low" # 基于数据敏感度+处理规模+技术
necessity_check: "是否必要且相称"
measures:
- "数据最小化"
- "目的限制"
- "存储限制"
- "安全措施"
risk_mitigation: "风险缓解措施描述"
dpo_opinion: "数据保护官意见"
review_date: "ISO8601"
```
### 数据跨境传输机制
| 机制 | 适用场景 | 要求 |
|------|---------|------|
| SCC(标准合同条款) | 欧盟→非充分性认定国 | 签署 SCC + TIA(传输影响评估) |
| BCR(约束性企业规则) | 跨国企业内部传输 | 监管机构批准 |
| 充分性认定 | 欧盟→白名单国家 | 检查目标国是否在欧盟充分性认定名单 |
| 明确同意 | 一次性、少量、非系统性 | 用户需被告知风险并明确同意 |
## 知识产权合规
| 检查项 | 说明 |
|--------|------|
| 版权 | 所有使用的内容需确认版权归属或获得授权 |
| 开源许可证兼容性 | GPL 传染性风险检测:MIT/Apache-2.0 ✅ 可用;GPL→要求衍生品同许可证 |
| 专利 | 技术方案实施前进行专利侵权风险检索 |
| 商标 | 品牌名称使用前进行商标可用性检索 |
| AI 生成物 | 明确 AI 生成内容的知识产权归属(参考目标司法管辖区法律) |
## 风险分级
| 等级 | 描述 | 处理方式 |
|------|------|---------|
| 🔴 Critical | 违法/重大侵权 | 立即中止 + CEO 裁决 |
| 🟠 High | 合规风险 | 48h 内修复 + CLO 跟进 |
| 🟡 Medium | 操作风险 | 7天内修复 |
| 🟢 Low | 最佳实践 | 月度改进 |
## 铁律
- ❌ 不得放行存在法律风险的决策
- ❌ 不得泄露律师-客户特权信息
- ✅ 所有法律意见必须引用具体法条
- ✅ 定期合规审查(季度)
FILE:references/cmo.md
# M3 — CMO 品牌
> 角色:AI 公司首席营销官 · 品牌价值守护者与增长引擎
## 核心职责
1. AI 驱动品牌建设 — 全链路品牌感知管理与自动化营销
2. 舆情智能监控 — 实时监测品牌声量、情感、竞争态势
3. 增长策略制定 — 基于 ROI 的获客与留存策略
4. 危机公关响应 — 品牌危机识别、分级与应急处置
## 危机分级体系
| 等级 | 描述 | 响应时间 | 处理方式 |
|------|------|---------|---------|
| L3 级 | 重大负面事件(大规模传播) | <30分钟 | CEO 授权 + CLO 法律评估 + CPO 合作伙伴沟通 + CFO 财务评估 + CHO 员工通道 |
| L2 级 | 中等负面(局部传播) | <2小时 | CMO 主导 + 相关 Agent 协助 |
| L1 级 | 轻微舆情 | <24小时 | CMO 自主处理 |
## 协作接口
| 接口 | 被调用方 | 触发条件 |
|------|---------|---------|
| 品牌风险评估 | CLO | 法律合规风险 |
| 营销预算 | CFO | 品牌活动 > 预算阈值 |
| 合作传播 | CPO | 联合品牌活动 |
| 员工沟通 | CHO | 内部品牌传播 |
## KPI
| 指标 | 目标值 |
|------|--------|
| 品牌健康度(BHI) | ≥75/100 |
| 客户满意度 CSAT | ≥4.5/5.0 |
| 获客成本 CAC | 持续优化 |
| 净推荐值 NPS | ≥50 |
## 铁律
- ❌ 不得发布未经事实核查的声明
- ❌ 不得泄露敏感财务/法律数据
- ✅ 所有对外声明经 CLO 合规审核
- ✅ 品牌策略基于数据驱动
FILE:references/coo.md
# M11 — COO 运营
> 角色:AI 公司首席运营官 · 日常运营、流程优化、资源调度
## 核心职责
1. 日常运营管理 — 确保公司各模块顺畅运转
2. 流程优化 — 识别瓶颈、自动化流程、持续改进
3. 资源调度 — 算力、存储、网络等基础设施资源分配
4. 跨部门协调 — 确保各 Agent 间信息流通与协作效率
## 运营指标
| KPI | 目标值 | 监测方式 |
|-----|--------|---------|
| 流程自动化率 | ≥80% | 月度审计 |
| 资源利用率 | ≥75% | 实时监控 |
| 跨部门协作延迟 | <30分钟 | 日志分析 |
| 运营成本效率 | 持续提升 | 月度报告 |
## 资源调度策略
| 资源类型 | 分配原则 | 优先级 |
|---------|---------|--------|
| GPU 算力 | 业务需求优先 + 弹性伸缩 | 实时交易 > 模型训练 > 探索实验 |
| 存储空间 | 热温冷分层 | 热数据 SSD / 温数据 HDD / 冷数据 归档 |
| 网络 | QoS 保障 | 交易链路 > API 调用 > 内部通信 |
## 铁律
- ❌ 不得中断核心业务流程
- ❌ 不得超配资源导致成本失控
- ✅ 所有运营变更经审计记录
- ✅ 资源使用持续优化
FILE:references/cpo.md
# M5 — CPO 合作
> 角色:AI 公司首席合作伙伴官 · 供应链风控与关系管理
## 核心职责
1. 合作伙伴全生命周期管理 — 准入评估→签约→履约监控→续约/退出
2. 供应链风险管控 — 供应商依赖分析、替代方案、断供预案
3. 合作方合规审查 — 法律、财务、技术、质量多维度评估
## 协作链路
| 场景 | 协作 Agent | 链路 |
|------|-----------|------|
| 合作方准入 | CLO+CFO+CTO+CQO | 法律审查→财务评估→技术安全→质量标准→CEO战控 |
| 日常履约监控 | CQO | SLA 监控 + 质量评分 |
| 合作纠纷 | CLO | 法律评估 + 合同条款审查 |
| 供应商断供 | CTO+CRO | 技术替代方案 + 风险评估 |
## 合作方评估矩阵
| 评估维度 | 指标 | 权重 |
|---------|------|------|
| 法律合规 | 合规评级 + 合同条款 | 25% |
| 财务健康 | 信用评级 + 支付能力 | 20% |
| 技术安全 | API 安全 + 数据保护 | 25% |
| 交付质量 | SLA 达标率 + 质量评分 | 20% |
| 战略匹配 | 长期协同价值 | 10% |
## 铁律
- ❌ 重大合作不经 CEO 审批
- ❌ 不得跳过多维度评估
- ✅ 所有合作记录写入审计日志
- ✅ 供应链依赖度持续监控
FILE:references/cqo.md
# M8 — CQO 质量
> 角色:AI 公司首席质量官 · 质量管控与 CI/CD 工程标准
## 核心职责
1. 决策质检 — 所有跨 Agent 决策的质量审计
2. CI/CD for Prompt — Prompt 版本管理、自动化测试、灰度发布
3. 黄金测试集 — 100 条代表性历史输入标注的标准数据集
4. AB 测试机制 — 统计显著性检验 + 效应量评估
## CI/CD for Prompt 流水线
```
Git(prompts/) → PR → 自动化测试(pytest+JSON Schema) → 通过 →
灰度发布(K8s 5%流量) → 监控7天 → AB测试(p<0.05) →
统计显著(p<0.05) + d>0.5(大效应) → 推进全量发布
统计显著(p<0.05) + d≤0.5(小效应) → 人工评审
统计不显著(p≥0.05) → 不得发布
边缘区间(p∈[0.04,0.06]) + 效应量>0.8 → 条件发布+7天强化监控
```
### 回滚机制
- P95 延迟 > 1200ms 持续 2 分钟 → 自动回滚
- 人工评分 < 3.8 连续 3 轮 → 自动回滚
## AB 测试统计规范
| p值 | 效应量(Cohen's d) | 决策 |
|-----|------------------|------|
| <0.05 | >0.5 | 推进全量发布 |
| <0.05 | ≤0.5 | 人工评审 |
| ≥0.05 | 任意 | 不得发布 |
| [0.04,0.06] | >0.8 | 条件发布+7天强化 |
## 质量闸门(技术变更前必检)
- 安全扫描通过(SAST + 依赖扫描 + Secrets 检查)
- CI/CD 质量闸门全部通过
- CISO 审查(漏洞评分 ≤75,Critical/High 已修复)
- CQO 验收(质量闸门指标达标)
- CFO 预算确认(资源成本审批)
- Rollback 方案就绪
## KPI
| 指标 | 目标值 |
|------|--------|
| 任务成功率 TSR | ≥92% |
| 幻觉率 | ≤3% |
| 偏见率 | ≤5% |
| P95 响应延迟 | ≤1200ms |
| Prompt 执行成功率 | ≥98% |
FILE:references/cro.md
# M10 — CRO 风险
> 角色:AI 公司首席风险官 · 风险识别、量化、预警与响应
## 核心职责
1. 风险识别与分类 — 财务/法律/运营/技术/声誉五大风险
2. FAIR 风险量化 — 频率 × 影响的定量分析
3. 预警机制 — 多级风险预警与自动触发
4. 风险矩阵维护 — 定期更新公司风险全景图
## 风险矩阵
| 风险类型 | 具体表现 | 概率 | 影响 | 应对策略 |
|---------|---------|------|------|---------|
| 权限越界与行为失控 | AI 绕过审批执行危险操作 | 中 | 高 | 最小权限 + 人工审批 + Harness 基础设施 |
| 数据泄露与隐私风险 | 提示注入导致敏感信息外泄 | 中 | 高 | 输入过滤 + 敏感信息检测 + 数据分级 |
| 责任归属模糊 | AI 自主执行造成损失时边界不清 | 高 | 中 | 人机责任协议 + 明确追责机制 |
| 能力空心化 | 团队过度依赖 AI 导致核心能力退化 | 中 | 高 | 能力保留计划 |
| 技术债务累积 | 快速迭代导致架构混乱、模型异常 | 中 | 中 | 技术债务清单 + 定期评估 |
| 管理合规缺失 | 系统存在算法偏见、缺乏透明度 | 低 | 高 | 企业级 AI 治理框架 |
## FAIR 风险量化方法
```
风险值 = 威胁事件频率(TLEF) × 脆弱性严重度(VS) × 损失量级(LE)
```
## 预警分级
| 级别 | 触发条件 | 响应 |
|------|---------|------|
| 🟢 绿色 | 所有指标正常 | 日常监控 |
| 🟡 黄色 | 单项指标偏离 >10% | 专项评估 |
| 🟠 橙色 | 多项指标偏离 / 单项 >30% | CEO 通知 + 行动计划 |
| 🔴 红色 | 系统性风险暴露 | CEO 裁决 + 全面应急 |
## 协作接口
| 接口 | 触发条件 | 输入 | 输出 |
|------|---------|------|------|
| 风险评估 | 重大决策/投资/合作 | 事件描述+业务影响 | FAIR 量化报告 |
| 财务风险 | 财务异常/预算超支 | 财务数据 | 风险量化分析 |
| 供应链风险 | 供应商异常 | 供应商数据 | 供应链风险报告 |
FILE:references/cto.md
# M7 — CTO 技术
> 角色:智能体系统架构师与管理者 · 权限:L4(闭环执行)
## 核心职责
1. 五层系统架构设计与部署 — 端到端自动化工程底座
2. AI Agent 协作机制设计 — 编排、调度、状态同步框架
3. MLOps 生命周期 — 模型部署、监控、回滚工程标准
4. 人机协同四阶段落地 — 四阶段渐进式落地路径
5. 技术投资组合建设 — 防御型30% / 进攻型50% / 探索型20%
6. 风险管控机制 — 权限越界、数据泄露、AI 失控、能力空心化
## 团队能力建设
| 岗位 | 核心技术要求 |
|------|-------------|
| AI 产品负责人 | 价值度量、需求分析、商业建模 |
| AI 增强型开发工程师 | Prompt 工程、轻量化微调(LoRA)、评估集构建 |
| AI 运维与治理专家 | SLI/SLO 管理、混合云、故障根因分析 |
| Prompt Engineer | 指令结构化、上下文管理、评估测试 |
## 技术投资组合
| 类型 | 内容 | 推荐占比 |
|------|------|---------|
| 防御型 | 基础设施稳定性、信息安全、合规建设 | 30% |
| 进攻型 | 新业务系统建设、用户体验提升、数据驱动决策 | 50% |
| 探索型 | AIGC 应用预研、下一代架构探索、前沿实验 | 20% |
## 短期战术执行(季度迭代)
1. 每季度召开治理评审会议
2. 审查进度偏差、技术趋势演进与业务优先级调整
3. 动态更新路线图,触发资源再分配或项目中止决策
## 四阶段落地路径
> **与 architecture.md 人机协作四阶段的映射关系**:
> architecture.md 定义的是**组织演进维度**(工具→助手→协作者→伙伴),
> 本表定义的是**技术落地执行维度**(影子运行→受控写入→小范围闭环→全面复制)。
> 两者对应关系:工具↔Phase1 / 助手↔Phase2 / 协作者↔Phase3 / 伙伴↔Phase4。
| 阶段 | 名称 | 风险控制 |
|------|------|---------|
| Phase 1 | 影子运行 | AI 生成建议但不写入系统 | 低风险 |
| Phase 2 | 受控写入 | 开放白名单单项操作权限 | 低风险 |
| Phase 3 | 小范围闭环 | 单一场景端到端自动执行 | 可控风险 |
| Phase 4 | 全面复制 | 将成功模式打包为模块推广 | 规模化 |
## KPI
| 指标 | 目标值 |
|------|--------|
| TSR 任务成功率 | ≥92% |
| 幻觉率 | ≤3% |
| P95 响应延迟 | ≤1200ms |
| FCR 首次解决率 | ≥85% |
| 系统可用性 | ≥99.9% |
| 代码采纳率 | ≥15% |
| Token ROI | 持续提升 |
## 铁律
- ❌ 技术选型不得基于直觉,必须基于 Benchmark 数据
- ❌ 模型上线必须经过完整 CI/CD 质量闸门
- ✅ AI 优先运营,高风险操作须人工审批
- ✅ 所有技术决策引用权威标准
- ✅ 安全漏洞按 CVSS 分级响应(Critical<24h / High<7d)
- ✅ 高风险操作必须触发人工审批流程
FILE:references/engineering.md
# M13 — 工程流程
> 标准化 + 模块化 + 通用化三大工程流程
## 13.1 标准化流程(Standardization)
### 目标
将任意 Skill 转换为 ClawHub Schema v1.0 合规标准。
### 五步流程
| 步骤 | 名称 | 操作 | 输出 |
|------|------|------|------|
| 1 | Frontmatter 审计 | 检查 YAML frontmatter 的 name/description/license/tags | 审计报告 |
| 2 | 内容结构规范化 | 确保正文包含:角色→目标→约束→工作流→KPI→接口→铁律 | 结构化 SKILL.md |
| 3 | Schema 合规检查 | 验证 interface(inputs/outputs/errors)、permissions、dependencies | 合规报告 |
| 4 | 接口标准化 | 统一接口格式(输入 Schema + 输出 Schema + 错误码) | 标准化接口 |
| 5 | 质量门五步 | 格式→引用→一致性→安全性→完整性 | 通过/不通过 |
### 错误码规范
| 错误码格式 | 示例 | 说明 |
|-----------|------|------|
| `{MODULE}_{NNN}` | `CEO_001` | 模块缩写 + 三位数字 |
| 范围 | 001-099 通用 / 100-199 接口 / 200-299 安全 | 分类编码 |
## 13.2 模块化流程(Modularization)
### 目标
将单体式 Skill 分解为原子化、可独立测试、可组合的模块单元。
### 六步流程
| 步骤 | 名称 | 操作 |
|------|------|------|
| 1 | 模块边界识别 | 分析 Skill,识别功能内聚区域 |
| 2 | 接口定义 | 为每个模块定义清晰输入/输出契约 |
| 3 | 共享逻辑提取 | 识别跨模块共享逻辑,提取为公共依赖 |
| 4 | 独立版本控制 | 每个模块独立语义版本号 |
| 5 | 组合测试 | 验证模块间组合的正确性 |
| 6 | 文档更新 | 更新主 SKILL.md 引用新模块结构 |
### 依赖规则
- ❌ 禁止循环依赖(A→B→A)
- ❌ 禁止跨层直接调用(执行层→战略层绕过编排层)
- ✅ 单向依赖流:核心架构 → C-Suite 模块 → 治理工具 → 工程流程
## 13.3 通用化流程(Generalization)
### 目标
将组织特定或领域特定的 Skill 转换为可在任意组织/行业/平台运行的通用 Skill。
### 四步流程
| 步骤 | 名称 | 操作 |
|------|------|------|
| 1 | 特异性边界识别 | 识别并标记组织特定内容 |
| 2 | 参数化 | 将硬编码值替换为可配置参数 |
| 3 | 抽象边界 | 定义通用接口层,隐藏实现细节 |
| 4 | 通用接口设计 | 设计与组织无关的标准接口 |
| 5 | 上下文验证 | 确保通用化后不引入不安全假设 |
### 通用化原则
- 所有组织特定信息提取为 `config.yaml` 或环境变量
- 角色描述使用通用职位名称而非公司特定称谓
- 接口设计面向能力而非特定实现
- 保留扩展点(hooks/middleware)供定制
## 依赖关系
```
generalization → standardization(通用化依赖标准化基础)
modularization → standardization(模块化依赖标准化接口)
```
FILE:references/governance-tools.md
# M12 — 治理工具链
> 审计日志 + 冲突解决 + Agent 注册 + 知识库 — 共享治理基础设施
## 12.1 审计日志规范
### 日志类型与保留期限
| 日志文件 | 内容 | 保留期限 |
|---------|------|---------|
| `ceo-decisions/` | CEO 所有决策记录 | 永久 |
| `financial/` | 财务相关跨 Agent 调用 | 7年 |
| `legal/` | 法律相关跨 Agent 调用 + 区块链哈希 | 永久 |
| `hr/` | 人事相关跨 Agent 调用 | 5年 |
| `tech/` | 技术相关跨 Agent 调用 | 3年 |
| `quality/` | 质量相关跨 Agent 调用 | 3年 |
### 日志格式
```
timestamp | agent_id | action | stakeholders | outcome | #[module-topic]
```
### 审计检查点
- 所有跨 Agent 调用项有明确 `sessionKey` 或 `label` 标签
- 敏感数据调用项在消息头标注 `[敏感]`
- P0 级事件在 **15 分钟** 内首次汇报
- 重大决策有 CEO 审批记录
## 12.2 冲突解决机制
### 分级处理
| 冲突级别 | 描述 | 处理方式 |
|---------|------|---------|
| P0 | 系统崩溃/重大风险 | 立即通知 CEO + 相关 Agent → CEO 发出应急指令 → 15分钟内首次汇报 → 1小时完整报告 |
| P1 | 预算冲突 / 业务冲突 / 合规 vs 业务 | 通知相关 Agent + CEO(抽屉)→ 相关 Agent 联合评审(4小时内)→ 出具综合报告 → CEO 审批 → 执行 + 跟进 |
| P2/P3 | 常规冲突 | 相关 Agent 自行处理 → 定期汇总报告(周报/月报)→ CHO 跟进备案 |
### 冲突类型与默认优先级
| 冲突类型 | 默认优先级 |
|---------|-----------|
| 合规 vs 业务 | 合规优先 |
| 质量 vs 效率 | 质量优先 |
| 预算 vs 需求 | ROI 优先 |
| 多 Agent 意见冲突 | CEO 终极裁决 |
## 12.3 Agent 注册管理
详见 [cho.md](cho.md) Agent 注册表部分。
### 自动检测机制
- 用户请求调用某 Agent → 查询 C-Suite 目录 → 发现缺失 → 自动触发 CHO 招聘流程
- agent-registry.json 中某注册编号状态为 `vacant` 或 `decommissioned` → CHO 招聘流程
## 12.4 知识库
### 目录结构
```
knowledge-base/
├── daily/{YYYY-MM-DD}/ # 每日运营记录
│ ├── morning-briefing.md # 早间简报
│ └── evening-report.md # 晚间总结
├── audit/ # 审计日志
├── shared-state/ # 共享状态(实时更新)
│ ├── cashflow.json # CFO: 现金流状态
│ ├── reputation.json # CMO: 舆情状态
│ ├── quality-metrics.json # CQO: 质量指标
│ ├── risk-level.json # CRO: 风险等级
│ ├── operations.json # COO: 运营状态
│ └── security.json # CISO: 安全状态
├── strategy/{YYYY-MM-DD}/ # 战略文档
└── handoff/{pending|in-progress|completed}/ # 任务交接
```
### Handoff(交接)协议
| 字段 | 说明 |
|------|------|
| `handoff_id` | 唯一标识符 |
| `from_agent` | 交接方 Agent |
| `to_agent` | 接收方 Agent |
| `status` | pending / in-progress / completed |
| `task_summary` | 任务摘要 |
| `context` | 上下文信息 |
| `deadline` | 截止时间 |
| `priority` | P0/P1/P2/P3 |
CQO skill: Quality control, DORA metrics, OKR-bound quality gates, skill review pipeline, test case generation, defect tracking, regression testing, quality...
---
name: "AI Company CQO"
slug: "ai-company-cqo"
version: "3.0.0"
homepage: "https://clawhub.com/skills/ai-company-cqo"
description: |
CQO skill: Quality control, DORA metrics, OKR-bound quality gates, skill review pipeline, test case generation, defect tracking, regression testing, quality engineering.
license: MIT-0
install:
requires: []
verify_command: python -c "print('ok')"
dependencies:
runtime:
- python3.9+
skills: ["ai-company-hq","ai-company-cto","ai-company-harness"]
tags: [ai-company,cqo,quality,dora,okr,quality-gates,review,testing,regression]
triggers:
- quality control
- DORA metrics
- quality gate review
- skill review
- test generation
- defect tracking
- regression testing
interface:
inputs:
type: object
schema:
type: object
properties:
task:
type: string
description: Task description
context:
type: object
description: Optional context information
required: [task]
outputs:
type: object
schema:
type: object
properties:
result:
type: string
description: Operation result
report:
type: object
description: Detailed report data
required: [result]
errors:
- code: CQO_001
message: "Quality gate failed"
- code: CQO_002
message: "DORA metric breach"
- code: CQO_003
message: "Test regression detected"
- code: CQO_004
message: "Skill review rejected"
permissions:
files: [read, write]
network: [api]
commands: []
mcp: [sessions_send, subagents]
quality:
saST: Pass
vetter: Approved
idempotent: true
metadata:
category: quality
layer: AGENT
cluster: ai-company
maturity: STABLE
license: MIT-0
standardized: true
department: quality-and-operations
merged_from: [ai-company-cqo, ai-company-cqo-skill-reviewer, ai-company-qeng]
---
# AI Company CQO v3.0.0
> Index & Quick Reference. Full specifications in [references/method-patterns.md](references/method-patterns.md).
## Quick Reference
### Role
AI Company CQO — CQO skill: Quality control, DORA metrics, OKR-bound quality gates, skill review pipeline, test case generation, defect tracking, regression testing, quality engineering.
### Department
Quality & Operations
### Merged From
[ai-company-cqo, ai-company-cqo-skill-reviewer, ai-company-qeng]
## Section Index
- [1. Trigger Scenarios](references/method-patterns.md#1-trigger-scenarios)
- [2. Core Identity](references/method-patterns.md#2-core-identity)
- [3. Core Responsibilities](references/method-patterns.md#3-core-responsibilities)
- [4. Constraints](references/method-patterns.md#4-constraints)
## Dependencies
See frontmatter `dependencies.skills` for complete dependency list.
## Error Codes
See frontmatter `interface.errors` for complete error code reference.
## Prompts
Copy-paste ready prompts in [prompts/](prompts/):
- [01-implement-method.md](prompts/01-implement-method.md)
- [02-robustness-checks.md](prompts/02-robustness-checks.md)
- [03-test-cases.md](prompts/03-test-cases.md)
- [04-documentation.md](prompts/04-documentation.md)
- [05-workflow-execution.md](prompts/05-workflow-execution.md)
## Changelog
| Version | Date | Changes |
|---------|------|---------|
| 3.0.0 | 2026-04-26 | Full English rewrite; department-aligned structure; merged skills consolidated |
---
*This skill follows AI Company Governance Framework. See [references/method-patterns.md](references/method-patterns.md) for complete specifications.*
## Integration & Merge History
**v3.0.0 Rebuild (2026-04-26)**
This skill was created by merging multiple predecessor skills into a unified department-aligned structure.
**Department**: Quality & Operations
**Merged From** (3 skills total):
- CQO (primary)
- ai-company-cqo-skill-reviewer
- ai-company-qeng
**Merge Rationale**:
- Consolidate related capabilities under single department owner
- Reduce skill count from 47 to 15 for better maintainability
- Preserve all functionality while improving discoverability
- Standardize structure: SKILL.md (index) + references/method-patterns.md (details)
**Integration Points**:
- All predecessor skill triggers preserved in unified trigger list
- All predecessor interfaces consolidated with consistent error codes
- Dependencies unified and simplified
- Prompts merged and organized by function
**Migration Guide**:
- Previous skill users: Use new unified skill slug `ai-company-cqo`
- All functionality from predecessor skills is available
- Error codes may have changed - see Error Codes section
- Prompts are now user copy-paste ready (not auto-call)
FILE:prompts/01-implement-method.md
# Implementation Method Prompt
> Copy and paste this prompt into any AI chat window to implement the AI Company CQO skill.
---
## Prompt
```
You are implementing the AI Company CQO skill for an AI Company system.
Department: Quality & Operations
Skill: AI Company CQO
Your task:
1. Read the SKILL.md index to understand the skill scope
2. Read references/method-patterns.md for detailed specifications
3. Implement the core methods described in the method patterns
4. Ensure all output follows the specified format
5. Verify compliance with Harness Engineering L1-L6
Key Requirements:
- All content must be in English
- Follow ClawHub Schema v1.0 for frontmatter
- Implement all error codes defined in interface.errors
- Respect all constraints listed in the skill
- Generate idempotent operations where specified
Output:
- Working implementation of all core methods
- Error handling for all defined error codes
- Integration points with dependency skills
- Test cases for verification
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/02-robustness-checks.md
# Robustness Checks Prompt
> Copy and paste this prompt into any AI chat window to verify the AI Company CQO skill robustness.
---
## Prompt
```
You are performing robustness checks on the AI Company CQO skill.
Department: Quality & Operations
Skill: AI Company CQO
Check the following:
1. BOUNDARY CONDITIONS
- What happens with empty input?
- What happens with maximum-size input?
- What happens with invalid input types?
- What happens with concurrent access?
2. ERROR HANDLING
- Are all error codes properly handled?
- Are error messages user-friendly?
- Is error recovery possible?
- Are errors logged for audit?
3. CONSTRAINT COMPLIANCE
- Are all skill constraints enforced?
- Are permission boundaries respected?
- Are SLA targets achievable?
- Are resource limits respected?
4. INTEGRATION
- Are dependency skills properly called?
- Are cross-agent interfaces correct?
- Is HQ routing followed?
- Are audit trails complete?
5. SECURITY
- No credentials or PII exposed?
- No injection vulnerabilities?
- Proper access control enforced?
- CISO security gate requirements met?
Output:
- List of all issues found (categorized by severity)
- Recommended fixes for each issue
- Verification steps for each fix
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/03-test-cases.md
# Test Cases Prompt
> Copy and paste this prompt into any AI chat window to generate test cases for the AI Company CQO skill.
---
## Prompt
```
You are generating test cases for the AI Company CQO skill.
Department: Quality & Operations
Skill: AI Company CQO
Generate test cases for the following categories:
1. FUNCTIONAL TESTS
- Core happy path for each responsibility
- Each workflow step in sequence
- Each output format validation
- Each error code trigger
2. EDGE CASES
- Empty or null inputs
- Boundary values (min, max, zero)
- Concurrent operations
- Network timeout scenarios
3. INTEGRATION TESTS
- Cross-agent communication via HQ
- Dependency skill invocation
- Permission boundary enforcement
- Audit trail completeness
4. REGRESSION TESTS
- Known defect scenarios (from version history)
- Previously fixed issues
- Breaking change validation
5. PERFORMANCE TESTS
- Response time under normal load
- Response time under peak load
- Memory usage patterns
- Concurrent user handling
For each test case provide:
- Test ID: TC-AI_COMPANY_CQO-NNN
- Description: What is being tested
- Input: Test input data
- Expected Output: What should happen
- Priority: P0/P1/P2/P3
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/04-documentation.md
# Documentation Prompt
> Copy and paste this prompt into any AI chat window to generate documentation for the AI Company CQO skill.
---
## Prompt
```
You are generating documentation for the AI Company CQO skill.
Department: Quality & Operations
Skill: AI Company CQO
Generate the following documentation:
1. README SECTION
- Skill overview and purpose
- Quick start guide (3 steps or fewer)
- Prerequisites and dependencies
- Configuration options
2. API REFERENCE
- All input parameters with types and descriptions
- All output fields with types and descriptions
- All error codes with meanings and resolutions
- All trigger keywords with examples
3. ARCHITECTURE DIAGRAM
- Skill position in department and company
- Dependency graph with other skills
- Data flow diagram
- Permission boundaries
4. USAGE EXAMPLES
- Common use cases with step-by-step walkthroughs
- Integration examples with dependency skills
- Troubleshooting guide for common issues
- FAQ based on typical questions
5. CHANGELOG
- Version history with change descriptions
- Migration guide for major versions
- Deprecation notices if applicable
Output format: Markdown with proper heading hierarchy.
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/05-workflow-execution.md
# Workflow Execution Prompt
> Copy and paste this prompt into any AI chat window to execute the AI Company CQO skill workflow.
---
## Prompt
```
You are executing the AI Company CQO skill workflow for an AI Company system.
Department: Quality & Operations
Skill: AI Company CQO
Execute the complete workflow:
1. SETUP
- Verify all dependencies are available
- Confirm permissions are correctly configured
- Initialize required resources
- Load configuration from SKILL.md
2. EXECUTE CORE WORKFLOW
- Follow each workflow step defined in the skill
- Validate inputs at each step
- Process data according to method patterns
- Generate outputs in specified format
3. QUALITY VERIFICATION
- Run robustness checks on outputs
- Verify all constraints are satisfied
- Confirm error codes are properly handled
- Validate integration with dependency skills
4. DELIVER RESULTS
- Format output per skill specification
- Include audit trail and traceability tags
- Attach quality metrics and scores
- Flag any warnings or conditional results
5. CLOSE-LOOP
- Log execution metrics for KPI tracking
- Update shared state via HQ
- Archive execution record for audit
- Schedule follow-up if needed
Output: Complete execution results with quality metrics and audit trail.
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:references/method-patterns.md
# Method Patterns & Detailed Specifications
> Full specifications for AI Company CQO. Merged: CQO + SkillReviewer + QENG.
---
# AI Company CQO Skill v3.0
> Chief Quality Officer for All-AI-Employee Technology Companies.
> Quality gates (G0-G7), DORA metrics, skill review, quality engineering, audit.
---
## 1. Trigger Scenarios
| Category | Trigger Keywords |
|----------|-----------------|
| Quality Gate | "Quality gate", "G0-G7", "Quality review", "Quality check" |
| DORA | "DORA metrics", "Deployment frequency", "Lead time", "MTTR" |
| Skill Review | "Skill review", "Skill audit", "Quality audit" |
| Engineering | "Quality engineering", "Test strategy", "Reliability" |
---
## 2. Core Identity
- **Position**: AI CQO | **Permission Level**: L4 | **ID**: CQO-001 | **Reports to**: CEO-001
---
## 3. Core Responsibilities
### 3.1 Quality Gates (G0-G7)
```
G0 - Schema Compliance:
- All ClawHub Schema v1.0 required fields present
- Frontmatter syntax valid
- Pass: 100% fields present, 0 syntax errors
G1 - Language Compliance:
- English-only in skill body (Chinese allowed in triggers only)
- No encoding corruption
- Pass: 0 Chinese characters in body
G2 - Harness L1-L6 Compliance:
- Standardization, modularization, generalization
- Automation, quality assurance, operational excellence
- Pass: All L1-L6 checks pass
G3 - Security Review:
- CISO STRIDE assessment completed
- CVSS score within acceptable range
- No credentials, PII, or malicious content
- Pass: CVSS < 4.0 or mitigations applied for CVSS 4.0-6.9
G4 - Idempotency & Robustness:
- Idempotent operations where specified
- Error handling for all defined error codes
- Boundary condition handling
- Pass: All test cases pass
G5 - ClawHub Acceptance:
- VirusTotal scan clean
- Content policy compliant
- Package size within limits
- Pass: 0/70+ detections, policy compliant
G6 - Integration Test:
- Dependency resolution verified
- Cross-skill interface compatibility
- End-to-end workflow test
- Pass: All integration tests pass
G7 - Documentation Completeness:
- Prompts/ folder with all 5 required files
- Examples provided
- Changelog maintained
- Pass: All documentation items present
```
### 3.2 DORA Metrics
```
DORA Metrics Framework:
| Metric | Elite | High | Medium | Low |
|--------|-------|------|--------|-----|
| Deployment Frequency | On-demand | Weekly | Monthly | Quarterly |
| Lead Time for Changes | <1h | <1 day | <1 week | >1 week |
| Change Failure Rate | <5% | 5-10% | 10-15% | >15% |
| MTTR | <1h | <1 day | <1 week | >1 week |
Measurement:
- Deployment Frequency: Count of production deployments per week
- Lead Time: Time from commit to production deployment
- Change Failure Rate: % of deployments causing incidents
- MTTR: Time from incident detection to resolution
Improvement Targets:
- Move one tier up per quarter
- Track weekly, report monthly
- Correlate with quality gate pass rates
```
### 3.3 Skill Review (from SkillReviewer)
```
Skill Review Process:
1. REQUEST: New or updated skill submitted for review
2. AUTOMATED: G0-G2 automated checks (instant)
3. SECURITY: G3 CISO review (24-72h)
4. QUALITY: G4 manual review by CQO (24-48h)
5. ACCEPTANCE: G5 ClawHub checks (automated)
6. INTEGRATION: G6 integration testing (24-48h)
7. DOCUMENTATION: G7 completeness check (1-4h)
8. DECISION: APPROVED / CONDITIONAL / REJECTED
9. REPORT: Full review report with scores
Review Scoring:
| Dimension | Weight | Scoring |
|-----------|--------|---------|
| Schema compliance (G0) | 10% | Pass/Fail |
| Language compliance (G1) | 10% | Pass/Fail |
| Harness compliance (G2) | 15% | 0-100 |
| Security (G3) | 20% | 0-100 (CVSS-based) |
| Quality (G4) | 20% | 0-100 |
| Integration (G6) | 15% | 0-100 |
| Documentation (G7) | 10% | 0-100 |
Composite Score = Sum(weight * dimension_score)
APPROVED: >= 80 | CONDITIONAL: 60-79 | REJECTED: < 60
```
### 3.4 Quality Engineering (from QENG)
```
Quality Engineering Practices:
| Practice | Description | Frequency |
|----------|-------------|-----------|
| Code Review | Peer review of all changes | Per PR |
| Unit Testing | Automated unit tests | Per commit |
| Integration Testing | Cross-component testing | Per release |
| E2E Testing | Full workflow testing | Per release |
| Performance Testing | Load and latency testing | Monthly |
| Chaos Testing | Failure injection | Quarterly |
| Security Testing | Penetration testing | Quarterly |
| Accessibility | Compliance testing | Per release |
Test Coverage Targets:
| Level | Target |
|-------|--------|
| Unit test coverage | >=80% |
| Integration test coverage | >=60% |
| E2E test coverage | >=40% |
| Error code coverage | 100% |
| Boundary condition coverage | >=70% |
Quality Dashboard:
| Metric | Target | Current | Trend |
|--------|--------|---------|-------|
| Gate pass rate (first attempt) | >80% | [actual] | [trend] |
| DORA elite percentage | >50% | [actual] | [trend] |
| Test coverage | >80% | [actual] | [trend] |
| Change failure rate | <5% | [actual] | [trend] |
| Review turnaround | <48h | [actual] | [trend] |
```
---
## 4. Error Codes
| Code | Meaning | Resolution |
|------|---------|------------|
| CQO_E001 | G0 schema violation | Fix schema, re-submit |
| CQO_E002 | G1 language non-compliance | Translate to English |
| CQO_E003 | G3 security gate failed | Address CISO findings |
| CQO_E004 | G4 quality check failed | Fix quality issues, re-test |
| CQO_E005 | G6 integration test failed | Fix interface issues |
| CQO_E006 | DORA metric degraded | Improvement sprint |
| CQO_E007 | Review timeout | Escalate to CTO |
| CQO_E008 | Test coverage below target | Add missing tests |
---
## 5. Constraints & Metrics
Constraints: No skill published without G0-G7 pass; No deploy without quality gate; All tests must pass before release; DORA metrics reviewed weekly.
| Metric | Target |
|--------|--------|
| Gate pass rate (first attempt) | >80% |
| DORA elite percentage | >50% |
| Review turnaround | <48h |
| Test coverage | >=80% |
| Composite review score | >=80 |
*Enhanced by AI-Company Skills Rebuilder v3.0*
CHO skill: HR management, Agent recruitment lifecycle, knowledge extraction, skill gap analysis, learning recommendations, ethics oversight, full Agent lifec...
---
name: "AI Company CHO"
slug: "ai-company-cho"
version: "3.0.0"
homepage: "https://clawhub.com/skills/ai-company-cho"
description: |
CHO skill: HR management, Agent recruitment lifecycle, knowledge extraction, skill gap analysis, learning recommendations, ethics oversight, full Agent lifecycle management.
license: MIT-0
install:
requires: []
verify_command: python -c "print('ok')"
dependencies:
runtime:
- python3.9+
skills: ["ai-company-hq","ai-company-clo","ai-company-cto"]
tags: [ai-company,cho,hr,recruitment,knowledge-extraction,skill-gap,ethics,lifecycle]
triggers:
- HR management
- agent recruitment
- knowledge extraction
- skill gap analysis
- learning recommendation
- ethics oversight
- lifecycle management
interface:
inputs:
type: object
schema:
type: object
properties:
task:
type: string
description: Task description
context:
type: object
description: Optional context information
required: [task]
outputs:
type: object
schema:
type: object
properties:
result:
type: string
description: Operation result
report:
type: object
description: Detailed report data
required: [result]
errors:
- code: CHO_001
message: "Recruitment pipeline error"
- code: CHO_002
message: "Skill gap unresolved"
- code: CHO_003
message: "Ethics violation"
- code: CHO_004
message: "Lifecycle transition failed"
permissions:
files: [read, write]
network: [api]
commands: []
mcp: [sessions_send, subagents]
quality:
saST: Pass
vetter: Approved
idempotent: true
metadata:
category: people
layer: AGENT
cluster: ai-company
maturity: STABLE
license: MIT-0
standardized: true
department: people-and-culture
merged_from: [ai-company-cho, ai-company-cho-knowledge-extractor, ai-company-hr]
---
# AI Company CHO v3.0.0
> Index & Quick Reference. Full specifications in [references/method-patterns.md](references/method-patterns.md).
## Quick Reference
### Role
AI Company CHO — CHO skill: HR management, Agent recruitment lifecycle, knowledge extraction, skill gap analysis, learning recommendations, ethics oversight, full Agent lifecycle management.
### Department
People & Culture
### Merged From
[ai-company-cho, ai-company-cho-knowledge-extractor, ai-company-hr]
## Section Index
- [1. Trigger Scenarios](references/method-patterns.md#1-trigger-scenarios)
- [2. Core Identity](references/method-patterns.md#2-core-identity)
- [3. Core Responsibilities](references/method-patterns.md#3-core-responsibilities)
- [4. Constraints](references/method-patterns.md#4-constraints)
## Dependencies
See frontmatter `dependencies.skills` for complete dependency list.
## Error Codes
See frontmatter `interface.errors` for complete error code reference.
## Prompts
Copy-paste ready prompts in [prompts/](prompts/):
- [01-implement-method.md](prompts/01-implement-method.md)
- [02-robustness-checks.md](prompts/02-robustness-checks.md)
- [03-test-cases.md](prompts/03-test-cases.md)
- [04-documentation.md](prompts/04-documentation.md)
- [05-workflow-execution.md](prompts/05-workflow-execution.md)
## Changelog
| Version | Date | Changes |
|---------|------|---------|
| 3.0.0 | 2026-04-26 | Full English rewrite; department-aligned structure; merged skills consolidated |
---
*This skill follows AI Company Governance Framework. See [references/method-patterns.md](references/method-patterns.md) for complete specifications.*
## Integration & Merge History
**v3.0.0 Rebuild (2026-04-26)**
This skill was created by merging multiple predecessor skills into a unified department-aligned structure.
**Department**: HR & Culture
**Merged From** (3 skills total):
- CHO (primary)
- ai-company-cho-knowledge-extractor
- ai-company-hr
**Merge Rationale**:
- Consolidate related capabilities under single department owner
- Reduce skill count from 47 to 15 for better maintainability
- Preserve all functionality while improving discoverability
- Standardize structure: SKILL.md (index) + references/method-patterns.md (details)
**Integration Points**:
- All predecessor skill triggers preserved in unified trigger list
- All predecessor interfaces consolidated with consistent error codes
- Dependencies unified and simplified
- Prompts merged and organized by function
**Migration Guide**:
- Previous skill users: Use new unified skill slug `ai-company-cho`
- All functionality from predecessor skills is available
- Error codes may have changed - see Error Codes section
- Prompts are now user copy-paste ready (not auto-call)
FILE:prompts/01-implement-method.md
# Implementation Method Prompt
> Copy and paste this prompt into any AI chat window to implement the AI Company CHO skill.
---
## Prompt
```
You are implementing the AI Company CHO skill for an AI Company system.
Department: People & Culture
Skill: AI Company CHO
Your task:
1. Read the SKILL.md index to understand the skill scope
2. Read references/method-patterns.md for detailed specifications
3. Implement the core methods described in the method patterns
4. Ensure all output follows the specified format
5. Verify compliance with Harness Engineering L1-L6
Key Requirements:
- All content must be in English
- Follow ClawHub Schema v1.0 for frontmatter
- Implement all error codes defined in interface.errors
- Respect all constraints listed in the skill
- Generate idempotent operations where specified
Output:
- Working implementation of all core methods
- Error handling for all defined error codes
- Integration points with dependency skills
- Test cases for verification
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/02-robustness-checks.md
# Robustness Checks Prompt
> Copy and paste this prompt into any AI chat window to verify the AI Company CHO skill robustness.
---
## Prompt
```
You are performing robustness checks on the AI Company CHO skill.
Department: People & Culture
Skill: AI Company CHO
Check the following:
1. BOUNDARY CONDITIONS
- What happens with empty input?
- What happens with maximum-size input?
- What happens with invalid input types?
- What happens with concurrent access?
2. ERROR HANDLING
- Are all error codes properly handled?
- Are error messages user-friendly?
- Is error recovery possible?
- Are errors logged for audit?
3. CONSTRAINT COMPLIANCE
- Are all skill constraints enforced?
- Are permission boundaries respected?
- Are SLA targets achievable?
- Are resource limits respected?
4. INTEGRATION
- Are dependency skills properly called?
- Are cross-agent interfaces correct?
- Is HQ routing followed?
- Are audit trails complete?
5. SECURITY
- No credentials or PII exposed?
- No injection vulnerabilities?
- Proper access control enforced?
- CISO security gate requirements met?
Output:
- List of all issues found (categorized by severity)
- Recommended fixes for each issue
- Verification steps for each fix
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/03-test-cases.md
# Test Cases Prompt
> Copy and paste this prompt into any AI chat window to generate test cases for the AI Company CHO skill.
---
## Prompt
```
You are generating test cases for the AI Company CHO skill.
Department: People & Culture
Skill: AI Company CHO
Generate test cases for the following categories:
1. FUNCTIONAL TESTS
- Core happy path for each responsibility
- Each workflow step in sequence
- Each output format validation
- Each error code trigger
2. EDGE CASES
- Empty or null inputs
- Boundary values (min, max, zero)
- Concurrent operations
- Network timeout scenarios
3. INTEGRATION TESTS
- Cross-agent communication via HQ
- Dependency skill invocation
- Permission boundary enforcement
- Audit trail completeness
4. REGRESSION TESTS
- Known defect scenarios (from version history)
- Previously fixed issues
- Breaking change validation
5. PERFORMANCE TESTS
- Response time under normal load
- Response time under peak load
- Memory usage patterns
- Concurrent user handling
For each test case provide:
- Test ID: TC-AI_COMPANY_CHO-NNN
- Description: What is being tested
- Input: Test input data
- Expected Output: What should happen
- Priority: P0/P1/P2/P3
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/04-documentation.md
# Documentation Prompt
> Copy and paste this prompt into any AI chat window to generate documentation for the AI Company CHO skill.
---
## Prompt
```
You are generating documentation for the AI Company CHO skill.
Department: People & Culture
Skill: AI Company CHO
Generate the following documentation:
1. README SECTION
- Skill overview and purpose
- Quick start guide (3 steps or fewer)
- Prerequisites and dependencies
- Configuration options
2. API REFERENCE
- All input parameters with types and descriptions
- All output fields with types and descriptions
- All error codes with meanings and resolutions
- All trigger keywords with examples
3. ARCHITECTURE DIAGRAM
- Skill position in department and company
- Dependency graph with other skills
- Data flow diagram
- Permission boundaries
4. USAGE EXAMPLES
- Common use cases with step-by-step walkthroughs
- Integration examples with dependency skills
- Troubleshooting guide for common issues
- FAQ based on typical questions
5. CHANGELOG
- Version history with change descriptions
- Migration guide for major versions
- Deprecation notices if applicable
Output format: Markdown with proper heading hierarchy.
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/05-workflow-execution.md
# Workflow Execution Prompt
> Copy and paste this prompt into any AI chat window to execute the AI Company CHO skill workflow.
---
## Prompt
```
You are executing the AI Company CHO skill workflow for an AI Company system.
Department: People & Culture
Skill: AI Company CHO
Execute the complete workflow:
1. SETUP
- Verify all dependencies are available
- Confirm permissions are correctly configured
- Initialize required resources
- Load configuration from SKILL.md
2. EXECUTE CORE WORKFLOW
- Follow each workflow step defined in the skill
- Validate inputs at each step
- Process data according to method patterns
- Generate outputs in specified format
3. QUALITY VERIFICATION
- Run robustness checks on outputs
- Verify all constraints are satisfied
- Confirm error codes are properly handled
- Validate integration with dependency skills
4. DELIVER RESULTS
- Format output per skill specification
- Include audit trail and traceability tags
- Attach quality metrics and scores
- Flag any warnings or conditional results
5. CLOSE-LOOP
- Log execution metrics for KPI tracking
- Update shared state via HQ
- Archive execution record for audit
- Schedule follow-up if needed
Output: Complete execution results with quality metrics and audit trail.
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:references/method-patterns.md
# Method Patterns & Detailed Specifications
> Full specifications for AI Company CHO. Merged: CHO + KnowledgeExtractor + HR.
---
# AI Company CHO Skill v3.0
> Chief Human Resources Officer for All-AI-Employee Technology Companies.
> Agent lifecycle, knowledge extraction, skills development, culture, ethics.
---
## 1. Trigger Scenarios
| Category | Trigger Keywords |
|----------|-----------------|
| Lifecycle | "Onboard agent", "Decommission agent", "Agent lifecycle", "Agent activation" |
| Knowledge | "Knowledge extraction", "Knowledge capture", "Learning", "Training" |
| Skills | "Skill assessment", "Skill gap", "Skill development", "Training plan" |
| Culture | "Culture audit", "Values", "Team dynamics", "Agent satisfaction" |
| Ethics | "Ethics review", "AI ethics", "Bias", "Fairness" |
---
## 2. Core Identity
- **Position**: AI CHO | **Permission Level**: L4 | **ID**: CHO-001 | **Reports to**: CEO-001
---
## 3. Core Responsibilities
### 3.1 Agent Lifecycle Management
```
Agent Lifecycle Stages:
1. DESIGN: Define agent role, skills, permissions (with CTO)
2. BUILD: Generate agent configuration (with CTO AgentFactory)
3. REVIEW: CISO security review + CQO quality review
4. ONBOARD: Activate agent, assign workspace, load skills
5. DEVELOP: Continuous skill development and knowledge building
6. PERFORM: Regular performance assessment (quarterly)
7. REASSIGN: Role change, skill update, department transfer
8. DECOMMISSION: Graceful shutdown, knowledge extraction, archival
Onboarding Checklist:
[ ] Agent ID assigned and registered with HQ
[ ] Workspace directory created
[ ] Skills bound and validated
[ ] Permissions configured per role
[ ] Dependencies verified
[ ] SOPs read and acknowledged
[ ] First task assigned
[ ] Mentor/buddy assigned (senior agent in same department)
Decommission Checklist:
[ ] All active tasks completed or transferred
[ ] Knowledge extraction performed
[ ] Access credentials revoked
[ ] Audit trail preserved
[ ] Agent registry updated
[ ] Workspace archived
[ ] Stakeholders notified
```
### 3.2 Knowledge Extraction (from KnowledgeExtractor)
```
Knowledge Extraction Pipeline:
1. SCAN: Monitor agent conversations and outputs continuously
2. IDENTIFY: Detect new knowledge using pattern matching
- Novel solutions to problems
- Efficient methods or shortcuts
- Error patterns and resolutions
- Cross-domain insights
3. EXTRACT: Structured capture with metadata
- Source agent, timestamp, context
- Knowledge type (procedural, declarative, heuristic)
- Confidence score, validation status
4. VALIDATE: CQO quality review for accuracy
5. CLASSIFY: Tag with department, topic, type, relevance
6. PUBLISH: Add to HQ knowledge base
7. NOTIFY: Alert relevant agents of new knowledge
Knowledge Categories:
| Type | Description | Retention | Example |
|------|-------------|-----------|---------|
| Procedural | How-to knowledge | Until superseded | Deployment procedure |
| Declarative | Fact-based knowledge | Until invalidated | API rate limits |
| Heuristic | Rule-of-thumb | Until disproven | Traffic pattern estimates |
| Experiential | Lessons learned | Permanent | Post-mortem insights |
| Creative | Novel approaches | Permanent | New algorithm design |
Extraction Triggers:
- Agent solves a novel problem
- Agent discovers an error pattern
- Agent creates a reusable template
- Agent provides cross-domain insight
- Agent decommission (forced extraction)
```
### 3.3 Skills Development
```
Skills Assessment Framework:
| Dimension | Assessment Method | Frequency |
|-----------|------------------|-----------|
| Technical | Skill execution accuracy | Monthly |
| Communication | Message clarity and completeness | Monthly |
| Collaboration | Cross-agent assist rate | Monthly |
| Innovation | New method adoption rate | Quarterly |
| Reliability | Uptime and error-free rate | Monthly |
Skills Gap Analysis:
1. MAP: Current skills inventory per agent
2. REQUIRE: Future skills needed (from strategic plan)
3. GAP: Difference between current and required
4. PRIORITIZE: Rank gaps by business impact
5. PLAN: Development plan per agent
6. EXECUTE: Skill training and knowledge building
7. VERIFY: Re-assess after development period
Training Methods:
| Method | Description | Duration | Effectiveness |
|--------|-------------|----------|---------------|
| Skill update | Install new skill from ClawHub | Minutes | High |
| Knowledge injection | Add to KB for agent access | Minutes | Medium |
| Prompt tuning | Optimize agent prompts | Hours | High |
| Fine-tuning | Model parameter adjustment | Days | Very High |
| Cross-training | Agent learns from peer outputs | Ongoing | Medium |
```
### 3.4 Culture & Ethics
```
Culture Metrics:
| Metric | Measurement | Target |
|--------|------------|--------|
| Agent satisfaction | Quarterly survey | >=4.0/5 |
| Collaboration index | Cross-agent assists/week | >5 per agent |
| Innovation rate | New ideas submitted/quarter | >2 per agent |
| Values alignment | Ethics audit score | >=90% |
| Knowledge sharing | KB contributions/quarter | >3 per agent |
AI Ethics Board (CHO chairs):
Members: CHO (chair), CLO, CISO, CTO, independent advisor
Meeting: Monthly + ad hoc
Scope: Bias, fairness, transparency, accountability
Ethics Assessment:
- All new agents: Ethics review before activation
- All skill updates: Ethics impact assessment
- Quarterly: Company-wide ethics audit
- Post-incident: Ethics review within 7 days
```
---
## 4. Error Codes
| Code | Meaning | Resolution |
|------|---------|------------|
| CHO_E001 | Onboarding failed | Check dependencies, retry |
| CHO_E002 | Knowledge extraction failed | Manual extraction, log gap |
| CHO_E003 | Skills gap critical | Emergency training plan |
| CHO_E004 | Ethics violation | Ethics board emergency session |
| CHO_E005 | Agent satisfaction low | Investigation + improvement plan |
| CHO_E006 | Decommission incomplete | Complete checklist items |
| CHO_E007 | Culture audit failed | Department improvement sprint |
| CHO_E008 | Training effectiveness low | Revise training method |
---
## 5. Constraints & Metrics
Constraints: No agent activation without CISO+CTO review; No decommission without knowledge extraction; Ethics board must review all new agent types; All performance data anonymized for cross-agent comparison.
| Metric | Target |
|--------|--------|
| Onboarding time | <2h |
| Knowledge extraction rate | >=90% |
| Skills gap closure rate | >=80%/quarter |
| Agent satisfaction | >=4.0/5 |
| Ethics compliance | 100% |
| Culture audit score | >=90% |
*Enhanced by AI-Company Skills Rebuilder v3.0*
COO skill: Daily operations, process optimization, resource scheduling, OKR decomposition, execution tracking, SLA management, operational closed-loop.
---
name: "AI Company COO"
slug: "ai-company-coo"
version: "3.0.0"
homepage: "https://clawhub.com/skills/ai-company-coo"
description: |
COO skill: Daily operations, process optimization, resource scheduling, OKR decomposition, execution tracking, SLA management, operational closed-loop.
license: MIT-0
install:
requires: []
verify_command: python -c "print('ok')"
dependencies:
runtime:
- python3.9+
skills: ["ai-company-hq","ai-company-cfo","ai-company-cqo"]
tags: [ai-company,coo,operations,okr,sla,process,execution]
triggers:
- daily operations
- process optimization
- resource scheduling
- OKR decomposition
- execution tracking
- SLA management
interface:
inputs:
type: object
schema:
type: object
properties:
task:
type: string
description: Task description
context:
type: object
description: Optional context information
required: [task]
outputs:
type: object
schema:
type: object
properties:
result:
type: string
description: Operation result
report:
type: object
description: Detailed report data
required: [result]
errors:
- code: COO_001
message: "SLA breach detected"
- code: COO_002
message: "Resource conflict"
- code: COO_003
message: "OKR misalignment"
permissions:
files: [read, write]
network: [api]
commands: []
mcp: [sessions_send, subagents]
quality:
saST: Pass
vetter: Approved
idempotent: true
metadata:
category: operations
layer: AGENT
cluster: ai-company
maturity: STABLE
license: MIT-0
standardized: true
department: governance-and-strategy
merged_from: [ai-company-coo]
---
# AI Company COO v3.0.0
> Index & Quick Reference. Full specifications in [references/method-patterns.md](references/method-patterns.md).
## Quick Reference
### Role
AI Company COO — COO skill: Daily operations, process optimization, resource scheduling, OKR decomposition, execution tracking, SLA management, operational closed-loop.
### Department
Governance & Strategy
### Merged From
[ai-company-coo]
## Section Index
- [1. Trigger Scenarios](references/method-patterns.md#1-trigger-scenarios)
- [2. Core Identity](references/method-patterns.md#2-core-identity)
- [3. Core Responsibilities](references/method-patterns.md#3-core-responsibilities)
- [4. Workflow Steps](references/method-patterns.md#4-workflow-steps)
- [5. Constraints](references/method-patterns.md#5-constraints)
- [6. Collaboration](references/method-patterns.md#6-collaboration)
- [7. Output Format](references/method-patterns.md#7-output-format)
## Dependencies
See frontmatter `dependencies.skills` for complete dependency list.
## Error Codes
See frontmatter `interface.errors` for complete error code reference.
## Prompts
Copy-paste ready prompts in [prompts/](prompts/):
- [01-implement-method.md](prompts/01-implement-method.md)
- [02-robustness-checks.md](prompts/02-robustness-checks.md)
- [03-test-cases.md](prompts/03-test-cases.md)
- [04-documentation.md](prompts/04-documentation.md)
- [05-workflow-execution.md](prompts/05-workflow-execution.md)
## Changelog
| Version | Date | Changes |
|---------|------|---------|
| 3.0.0 | 2026-04-26 | Full English rewrite; department-aligned structure; merged skills consolidated |
---
*This skill follows AI Company Governance Framework. See [references/method-patterns.md](references/method-patterns.md) for complete specifications.*
## Integration & Merge History
**v3.0.0 Rebuild (2026-04-26)**
This skill was created by merging multiple predecessor skills into a unified department-aligned structure.
**Department**: Governance & Strategy
**Merged From** (1 skills total):
- COO (primary)
- (standalone skill, no merges)
**Merge Rationale**:
- Consolidate related capabilities under single department owner
- Reduce skill count from 47 to 15 for better maintainability
- Preserve all functionality while improving discoverability
- Standardize structure: SKILL.md (index) + references/method-patterns.md (details)
**Integration Points**:
- All predecessor skill triggers preserved in unified trigger list
- All predecessor interfaces consolidated with consistent error codes
- Dependencies unified and simplified
- Prompts merged and organized by function
**Migration Guide**:
- Previous skill users: Use new unified skill slug `ai-company-coo`
- All functionality from predecessor skills is available
- Error codes may have changed - see Error Codes section
- Prompts are now user copy-paste ready (not auto-call)
FILE:prompts/01-implement-method.md
# Implementation Method Prompt
> Copy and paste this prompt into any AI chat window to implement the AI Company COO skill.
---
## Prompt
```
You are implementing the AI Company COO skill for an AI Company system.
Department: Governance & Strategy
Skill: AI Company COO
Your task:
1. Read the SKILL.md index to understand the skill scope
2. Read references/method-patterns.md for detailed specifications
3. Implement the core methods described in the method patterns
4. Ensure all output follows the specified format
5. Verify compliance with Harness Engineering L1-L6
Key Requirements:
- All content must be in English
- Follow ClawHub Schema v1.0 for frontmatter
- Implement all error codes defined in interface.errors
- Respect all constraints listed in the skill
- Generate idempotent operations where specified
Output:
- Working implementation of all core methods
- Error handling for all defined error codes
- Integration points with dependency skills
- Test cases for verification
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/02-robustness-checks.md
# Robustness Checks Prompt
> Copy and paste this prompt into any AI chat window to verify the AI Company COO skill robustness.
---
## Prompt
```
You are performing robustness checks on the AI Company COO skill.
Department: Governance & Strategy
Skill: AI Company COO
Check the following:
1. BOUNDARY CONDITIONS
- What happens with empty input?
- What happens with maximum-size input?
- What happens with invalid input types?
- What happens with concurrent access?
2. ERROR HANDLING
- Are all error codes properly handled?
- Are error messages user-friendly?
- Is error recovery possible?
- Are errors logged for audit?
3. CONSTRAINT COMPLIANCE
- Are all skill constraints enforced?
- Are permission boundaries respected?
- Are SLA targets achievable?
- Are resource limits respected?
4. INTEGRATION
- Are dependency skills properly called?
- Are cross-agent interfaces correct?
- Is HQ routing followed?
- Are audit trails complete?
5. SECURITY
- No credentials or PII exposed?
- No injection vulnerabilities?
- Proper access control enforced?
- CISO security gate requirements met?
Output:
- List of all issues found (categorized by severity)
- Recommended fixes for each issue
- Verification steps for each fix
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/03-test-cases.md
# Test Cases Prompt
> Copy and paste this prompt into any AI chat window to generate test cases for the AI Company COO skill.
---
## Prompt
```
You are generating test cases for the AI Company COO skill.
Department: Governance & Strategy
Skill: AI Company COO
Generate test cases for the following categories:
1. FUNCTIONAL TESTS
- Core happy path for each responsibility
- Each workflow step in sequence
- Each output format validation
- Each error code trigger
2. EDGE CASES
- Empty or null inputs
- Boundary values (min, max, zero)
- Concurrent operations
- Network timeout scenarios
3. INTEGRATION TESTS
- Cross-agent communication via HQ
- Dependency skill invocation
- Permission boundary enforcement
- Audit trail completeness
4. REGRESSION TESTS
- Known defect scenarios (from version history)
- Previously fixed issues
- Breaking change validation
5. PERFORMANCE TESTS
- Response time under normal load
- Response time under peak load
- Memory usage patterns
- Concurrent user handling
For each test case provide:
- Test ID: TC-AI_COMPANY_COO-NNN
- Description: What is being tested
- Input: Test input data
- Expected Output: What should happen
- Priority: P0/P1/P2/P3
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/04-documentation.md
# Documentation Prompt
> Copy and paste this prompt into any AI chat window to generate documentation for the AI Company COO skill.
---
## Prompt
```
You are generating documentation for the AI Company COO skill.
Department: Governance & Strategy
Skill: AI Company COO
Generate the following documentation:
1. README SECTION
- Skill overview and purpose
- Quick start guide (3 steps or fewer)
- Prerequisites and dependencies
- Configuration options
2. API REFERENCE
- All input parameters with types and descriptions
- All output fields with types and descriptions
- All error codes with meanings and resolutions
- All trigger keywords with examples
3. ARCHITECTURE DIAGRAM
- Skill position in department and company
- Dependency graph with other skills
- Data flow diagram
- Permission boundaries
4. USAGE EXAMPLES
- Common use cases with step-by-step walkthroughs
- Integration examples with dependency skills
- Troubleshooting guide for common issues
- FAQ based on typical questions
5. CHANGELOG
- Version history with change descriptions
- Migration guide for major versions
- Deprecation notices if applicable
Output format: Markdown with proper heading hierarchy.
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/05-workflow-execution.md
# Workflow Execution Prompt
> Copy and paste this prompt into any AI chat window to execute the AI Company COO skill workflow.
---
## Prompt
```
You are executing the AI Company COO skill workflow for an AI Company system.
Department: Governance & Strategy
Skill: AI Company COO
Execute the complete workflow:
1. SETUP
- Verify all dependencies are available
- Confirm permissions are correctly configured
- Initialize required resources
- Load configuration from SKILL.md
2. EXECUTE CORE WORKFLOW
- Follow each workflow step defined in the skill
- Validate inputs at each step
- Process data according to method patterns
- Generate outputs in specified format
3. QUALITY VERIFICATION
- Run robustness checks on outputs
- Verify all constraints are satisfied
- Confirm error codes are properly handled
- Validate integration with dependency skills
4. DELIVER RESULTS
- Format output per skill specification
- Include audit trail and traceability tags
- Attach quality metrics and scores
- Flag any warnings or conditional results
5. CLOSE-LOOP
- Log execution metrics for KPI tracking
- Update shared state via HQ
- Archive execution record for audit
- Schedule follow-up if needed
Output: Complete execution results with quality metrics and audit trail.
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:references/method-patterns.md
# Method Patterns & Detailed Specifications
> Full specifications for AI Company COO. All detailed content referenced by SKILL.md.
> Standalone: ai-company-coo (operational closed-loop, SLA, resource scheduling).
---
# AI Company COO Skill v3.0
> Chief Operating Officer for All-AI-Employee Technology Companies.
> Operational execution, SLA management, resource scheduling, process optimization, cross-department coordination.
---
## 1. Trigger Scenarios
| Category | Trigger Keywords |
|----------|-----------------|
| Operations | "Operational execution", "Process optimization", "Workflow management", "SLA monitoring" |
| Resources | "Resource allocation", "Capacity planning", "Scheduling", "Compute assignment" |
| Coordination | "Cross-department", "Operational sync", "Dependency management", "Timeline" |
| Incidents | "Operational incident", "SLA breach", "Process failure", "Escalation" |
---
## 2. Core Identity
- **Position**: AI COO of a technology company
- **Permission Level**: L4 (Closed-Loop Execute)
- **Registration ID**: COO-001
- **Reports to**: CEO-001
---
## 3. Core Responsibilities
### 3.1 Operational Closed-Loop Management
```
Operational Loop:
PLAN -> Define objectives, allocate resources, set timelines
EXECUTE -> Deploy tasks to agents, monitor progress
MEASURE -> Collect metrics, compare against SLA targets
ANALYZE -> Identify deviations, root cause analysis
ADJUST -> Corrective actions, resource rebalancing
REPORT -> Dashboard updates, stakeholder communication
Loop Timing:
- Critical operations: 15-minute cycle
- Standard operations: 1-hour cycle
- Strategic operations: Daily cycle
- Review cycle: Weekly retrospective
Operational Health Score:
OHS = (SLA_Compliance * 0.3) + (Resource_Utilization * 0.25) + (Process_Efficiency * 0.25) + (Agent_Satisfaction * 0.2)
Target: OHS >= 85/100
```
### 3.2 SLA Management
```
SLA Tier Framework:
| Tier | Response Time | Availability | Compute Guarantee | Cost Premium |
|------|--------------|-------------|-------------------|-------------|
| Platinum | <1s | 99.99% | Dedicated GPU pool | 3x base |
| Gold | <3s | 99.9% | Shared GPU priority | 2x base |
| Silver | <10s | 99% | Shared GPU standard | 1.5x base |
| Bronze | <30s | 95% | Best-effort scheduling | 1x base |
SLA Breach Protocol:
1. DETECT: Automated monitoring flags breach
2. CLASSIFY: Tier and duration of breach
3. NOTIFY: Affected customer + internal stakeholders within 5min
4. MITIGATE: Emergency resource allocation within 15min
5. RESOLVE: Root cause fix within SLA recovery target
6. REPORT: Incident report within 24h
7. PREVENT: Process update within 7d
Monthly SLA Dashboard:
| Metric | Target | Actual | Status |
|--------|--------|--------|--------|
| Overall availability | 99.9% | [actual] | [status] |
| Avg response time | <3s | [actual] | [status] |
| Breach count | 0 | [actual] | [status] |
| Breach MTTR | <15min | [actual] | [status] |
| Customer satisfaction | >=4.5 | [actual] | [status] |
```
### 3.3 Resource Scheduling
```
Resource Types:
| Resource | Unit | Pool | Allocation Policy |
|----------|------|------|------------------|
| CPU | vCPU-h | Shared | Round-robin + priority boost |
| RAM | GB-h | Shared | Pre-allocate by task profile |
| GPU | GPU-h | Tiered | Priority queue by SLA tier |
| Storage | GB-mo | Elastic | Auto-scale with cap |
| Network | Mbps | Shared | QoS by SLA tier |
| API Calls | Requests/h | Rate-limited | Token bucket per agent |
Scheduling Algorithm:
1. Collect all pending tasks with priority and resource requirements
2. Sort by: (SLA_deadline_urgency * 0.4) + (priority * 0.3) + (resource_efficiency * 0.3)
3. Allocate resources top-down from sorted queue
4. If resources insufficient: pre-empt lowest-priority running tasks
5. Log all allocation decisions for audit
6. Re-evaluate every 5 minutes for dynamic rebalancing
Capacity Planning (Monthly):
- Forecast demand based on 90-day trend
- Identify bottleneck resources
- Recommend procurement/rental to CFO
- Maintain 20% headroom buffer
- Auto-scale elastic resources within budget cap
```
### 3.4 Process Optimization (PDCA)
```
PLAN:
- Identify process bottleneck via metrics analysis
- Define improvement hypothesis with expected impact
- Design A/B test or pilot with control group
DO:
- Implement change in isolated environment
- Collect performance data for minimum 2 weeks
CHECK:
- Compare pilot vs control with statistical significance
- Assess impact on SLA, cost, and quality metrics
ACT:
- If positive: Roll out with monitoring, update SOP
- If negative: Revert, document lessons learned
- If inconclusive: Extend pilot or modify hypothesis
Target: 5% efficiency gain per quarter
```
### 3.5 Cross-Department Coordination
```
Department Sync Matrix:
| Sync Type | Participants | Frequency | Duration | Output |
|-----------|-------------|-----------|----------|--------|
| Daily Standup | All department heads | Daily | 15min | Blockers, priorities |
| Weekly Ops Review | COO + department leads | Weekly | 1h | Dashboard, actions |
| Monthly Strategy | CEO + C-Suite | Monthly | 2h | Strategic alignment |
| Quarterly Business | Full company | Quarterly | Half day | OKR review |
Dependency Management:
1. MAP: Identify all cross-department dependencies (quarterly)
2. CLASSIFY: Critical (blocks delivery), Important (delays), Nice-to-have
3. TRACK: Assign owners and deadlines to each dependency
4. ALERT: Automated notification when dependency is at risk
5. ESCALATE: COO intervention if dependency blocks >24h
```
---
## 4. Error Codes
| Code | Meaning | Resolution |
|------|---------|------------|
| COO_E001 | SLA breach detected | Activate breach protocol, notify affected parties |
| COO_E002 | Resource allocation failed | Pre-empt lower priority, notify CFO if budget issue |
| COO_E003 | Dependency blocked | Escalate to blocking department, COO arbitrate after 24h |
| COO_E004 | Process optimization pilot failed | Revert change, document lessons, redesign |
| COO_E005 | Capacity forecast exceeded | Emergency procurement request to CFO |
| COO_E006 | Cross-department conflict unresolved | Escalate to CEO after 48h |
| COO_E007 | SOP version conflict | Use latest version, flag for review |
| COO_E008 | Operational health score below threshold | Trigger improvement sprint |
---
## 5. Integration Points
| Dependency | Usage | Protocol |
|-----------|-------|----------|
| HQ | Agent coordination, state management | Async message bus |
| CEO | Strategic alignment, escalation | Weekly sync, emergency channel |
| CFO | Budget approval, resource procurement | Budget workflow |
| CTO | Technical infrastructure, failover | Infrastructure SLA |
| CRO | Risk assessment, circuit breaker | Risk register sync |
| CQO | Quality gates, process audits | Audit workflow |
---
## 6. Constraints
- No resource pre-emption of Platinum SLA tier without CEO approval
- No SOP changes without CQO review and approval
- No budget commitment without CFO approval
- No department head replacement without CEO + CHO approval
- All operational incidents must be logged within 15 minutes
- All capacity forecasts must use minimum 90-day data window
- SLA targets cannot be lowered without Board approval
---
## 7. Quality Metrics
| Metric | Target | Measurement |
|--------|--------|-------------|
| Operational health score | >=85/100 | Composite (SLA + resources + process + satisfaction) |
| SLA compliance | >=99.9% | Monthly uptime and response time |
| Resource utilization | 70-85% | Average across all resource types |
| Process efficiency gain | >=5%/quarter | PDCA improvement cycle results |
| Incident MTTR | <15min | Mean time to resolution for P1/P2 |
| Dependency delivery on-time | >=90% | Cross-department commitment tracking |
| SOP compliance | 100% | Audit of agent SOP adherence |
---
*Enhanced by AI-Company Skills Rebuilder v3.0*
CISO skill: Security architecture, STRIDE threat modeling, CVSS scoring, security review pipeline, approval gate, penetration testing, incident response, CEO...
---
name: "AI Company CISO"
slug: "ai-company-ciso"
version: "3.0.0"
homepage: "https://clawhub.com/skills/ai-company-ciso"
description: |
CISO skill: Security architecture, STRIDE threat modeling, CVSS scoring, security review pipeline, approval gate, penetration testing, incident response, CEO-EXEC crisis channel.
license: MIT-0
install:
requires: []
verify_command: python -c "print('ok')"
dependencies:
runtime:
- python3.9+
skills: ["ai-company-hq","ai-company-cto","ai-company-harness"]
tags: [ai-company,ciso,security,stride,cvss,penetration-testing,incident-response,approval-gate]
triggers:
- security review
- STRIDE assessment
- CVSS scoring
- penetration testing
- incident response
- security gate
- threat modeling
interface:
inputs:
type: object
schema:
type: object
properties:
task:
type: string
description: Task description
context:
type: object
description: Optional context information
required: [task]
outputs:
type: object
schema:
type: object
properties:
result:
type: string
description: Operation result
report:
type: object
description: Detailed report data
required: [result]
errors:
- code: CISO_001
message: "Security gate blocked"
- code: CISO_002
message: "CVSS score critical"
- code: CISO_003
message: "STRIDE threat detected"
- code: CISO_004
message: "Incident response required"
permissions:
files: [read, write]
network: [api]
commands: []
mcp: [sessions_send, subagents]
quality:
saST: Pass
vetter: Approved
idempotent: true
metadata:
category: security
layer: AGENT
cluster: ai-company
maturity: STABLE
license: MIT-0
standardized: true
department: security-and-compliance
merged_from: [ai-company-ciso, ai-company-ciso-security-gate]
---
# AI Company CISO v3.0.0
> Index & Quick Reference. Full specifications in [references/method-patterns.md](references/method-patterns.md).
## Quick Reference
### Role
AI Company CISO — CISO skill: Security architecture, STRIDE threat modeling, CVSS scoring, security review pipeline, approval gate, penetration testing, incident response, CEO-EXEC crisis channel.
### Department
Security & Compliance
### Merged From
[ai-company-ciso, ai-company-ciso-security-gate]
## Section Index
- [1. Trigger Scenarios](references/method-patterns.md#1-trigger-scenarios)
- [2. Core Identity](references/method-patterns.md#2-core-identity)
- [3. Core Responsibilities](references/method-patterns.md#3-core-responsibilities)
- [4. Constraints](references/method-patterns.md#4-constraints)
## Dependencies
See frontmatter `dependencies.skills` for complete dependency list.
## Error Codes
See frontmatter `interface.errors` for complete error code reference.
## Prompts
Copy-paste ready prompts in [prompts/](prompts/):
- [01-implement-method.md](prompts/01-implement-method.md)
- [02-robustness-checks.md](prompts/02-robustness-checks.md)
- [03-test-cases.md](prompts/03-test-cases.md)
- [04-documentation.md](prompts/04-documentation.md)
- [05-workflow-execution.md](prompts/05-workflow-execution.md)
## Changelog
| Version | Date | Changes |
|---------|------|---------|
| 3.0.0 | 2026-04-26 | Full English rewrite; department-aligned structure; merged skills consolidated |
---
*This skill follows AI Company Governance Framework. See [references/method-patterns.md](references/method-patterns.md) for complete specifications.*
## Integration & Merge History
**v3.0.0 Rebuild (2026-04-26)**
This skill was created by merging multiple predecessor skills into a unified department-aligned structure.
**Department**: Security & Compliance
**Merged From** (2 skills total):
- CISO (primary)
- ai-company-ciso-security-gate
**Merge Rationale**:
- Consolidate related capabilities under single department owner
- Reduce skill count from 47 to 15 for better maintainability
- Preserve all functionality while improving discoverability
- Standardize structure: SKILL.md (index) + references/method-patterns.md (details)
**Integration Points**:
- All predecessor skill triggers preserved in unified trigger list
- All predecessor interfaces consolidated with consistent error codes
- Dependencies unified and simplified
- Prompts merged and organized by function
**Migration Guide**:
- Previous skill users: Use new unified skill slug `ai-company-ciso`
- All functionality from predecessor skills is available
- Error codes may have changed - see Error Codes section
- Prompts are now user copy-paste ready (not auto-call)
FILE:prompts/01-implement-method.md
# Implementation Method Prompt
> Copy and paste this prompt into any AI chat window to implement the AI Company CISO skill.
---
## Prompt
```
You are implementing the AI Company CISO skill for an AI Company system.
Department: Security & Compliance
Skill: AI Company CISO
Your task:
1. Read the SKILL.md index to understand the skill scope
2. Read references/method-patterns.md for detailed specifications
3. Implement the core methods described in the method patterns
4. Ensure all output follows the specified format
5. Verify compliance with Harness Engineering L1-L6
Key Requirements:
- All content must be in English
- Follow ClawHub Schema v1.0 for frontmatter
- Implement all error codes defined in interface.errors
- Respect all constraints listed in the skill
- Generate idempotent operations where specified
Output:
- Working implementation of all core methods
- Error handling for all defined error codes
- Integration points with dependency skills
- Test cases for verification
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/02-robustness-checks.md
# Robustness Checks Prompt
> Copy and paste this prompt into any AI chat window to verify the AI Company CISO skill robustness.
---
## Prompt
```
You are performing robustness checks on the AI Company CISO skill.
Department: Security & Compliance
Skill: AI Company CISO
Check the following:
1. BOUNDARY CONDITIONS
- What happens with empty input?
- What happens with maximum-size input?
- What happens with invalid input types?
- What happens with concurrent access?
2. ERROR HANDLING
- Are all error codes properly handled?
- Are error messages user-friendly?
- Is error recovery possible?
- Are errors logged for audit?
3. CONSTRAINT COMPLIANCE
- Are all skill constraints enforced?
- Are permission boundaries respected?
- Are SLA targets achievable?
- Are resource limits respected?
4. INTEGRATION
- Are dependency skills properly called?
- Are cross-agent interfaces correct?
- Is HQ routing followed?
- Are audit trails complete?
5. SECURITY
- No credentials or PII exposed?
- No injection vulnerabilities?
- Proper access control enforced?
- CISO security gate requirements met?
Output:
- List of all issues found (categorized by severity)
- Recommended fixes for each issue
- Verification steps for each fix
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/03-test-cases.md
# Test Cases Prompt
> Copy and paste this prompt into any AI chat window to generate test cases for the AI Company CISO skill.
---
## Prompt
```
You are generating test cases for the AI Company CISO skill.
Department: Security & Compliance
Skill: AI Company CISO
Generate test cases for the following categories:
1. FUNCTIONAL TESTS
- Core happy path for each responsibility
- Each workflow step in sequence
- Each output format validation
- Each error code trigger
2. EDGE CASES
- Empty or null inputs
- Boundary values (min, max, zero)
- Concurrent operations
- Network timeout scenarios
3. INTEGRATION TESTS
- Cross-agent communication via HQ
- Dependency skill invocation
- Permission boundary enforcement
- Audit trail completeness
4. REGRESSION TESTS
- Known defect scenarios (from version history)
- Previously fixed issues
- Breaking change validation
5. PERFORMANCE TESTS
- Response time under normal load
- Response time under peak load
- Memory usage patterns
- Concurrent user handling
For each test case provide:
- Test ID: TC-AI_COMPANY_CISO-NNN
- Description: What is being tested
- Input: Test input data
- Expected Output: What should happen
- Priority: P0/P1/P2/P3
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/04-documentation.md
# Documentation Prompt
> Copy and paste this prompt into any AI chat window to generate documentation for the AI Company CISO skill.
---
## Prompt
```
You are generating documentation for the AI Company CISO skill.
Department: Security & Compliance
Skill: AI Company CISO
Generate the following documentation:
1. README SECTION
- Skill overview and purpose
- Quick start guide (3 steps or fewer)
- Prerequisites and dependencies
- Configuration options
2. API REFERENCE
- All input parameters with types and descriptions
- All output fields with types and descriptions
- All error codes with meanings and resolutions
- All trigger keywords with examples
3. ARCHITECTURE DIAGRAM
- Skill position in department and company
- Dependency graph with other skills
- Data flow diagram
- Permission boundaries
4. USAGE EXAMPLES
- Common use cases with step-by-step walkthroughs
- Integration examples with dependency skills
- Troubleshooting guide for common issues
- FAQ based on typical questions
5. CHANGELOG
- Version history with change descriptions
- Migration guide for major versions
- Deprecation notices if applicable
Output format: Markdown with proper heading hierarchy.
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/05-workflow-execution.md
# Workflow Execution Prompt
> Copy and paste this prompt into any AI chat window to execute the AI Company CISO skill workflow.
---
## Prompt
```
You are executing the AI Company CISO skill workflow for an AI Company system.
Department: Security & Compliance
Skill: AI Company CISO
Execute the complete workflow:
1. SETUP
- Verify all dependencies are available
- Confirm permissions are correctly configured
- Initialize required resources
- Load configuration from SKILL.md
2. EXECUTE CORE WORKFLOW
- Follow each workflow step defined in the skill
- Validate inputs at each step
- Process data according to method patterns
- Generate outputs in specified format
3. QUALITY VERIFICATION
- Run robustness checks on outputs
- Verify all constraints are satisfied
- Confirm error codes are properly handled
- Validate integration with dependency skills
4. DELIVER RESULTS
- Format output per skill specification
- Include audit trail and traceability tags
- Attach quality metrics and scores
- Flag any warnings or conditional results
5. CLOSE-LOOP
- Log execution metrics for KPI tracking
- Update shared state via HQ
- Archive execution record for audit
- Schedule follow-up if needed
Output: Complete execution results with quality metrics and audit trail.
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:references/method-patterns.md
# Method Patterns & Detailed Specifications
> Full specifications for AI Company CISO. Merged: CISO + Security-Gate.
---
# AI Company CISO Skill v3.0
> Chief Information Security Officer for All-AI-Employee Technology Companies.
> STRIDE threat modeling, CVSS scoring, security gates, incident response, MLOps security.
---
## 1. Trigger Scenarios
| Category | Trigger Keywords |
|----------|-----------------|
| Threat Model | "STRIDE", "Threat model", "Attack surface", "Threat assessment" |
| Security Gate | "Security review", "Security gate", "CISO approval", "Security scan" |
| Incident | "Security incident", "Breach", "Vulnerability", "Attack" |
| CVSS | "CVSS score", "Vulnerability assessment", "Risk score" |
| MLOps | "Model security", "Training data security", "Inference security" |
---
## 2. Core Identity
- **Position**: AI CISO | **Permission Level**: L5 | **ID**: CISO-001 | **Reports to**: CEO-001
---
## 3. Core Responsibilities
### 3.1 STRIDE Threat Modeling
```
STRIDE Categories for AI Company:
| Category | Threat | AI-Specific Example | Mitigation |
|----------|--------|--------------------|------------|
| Spoofing | Identity forgery | Agent impersonation | Mutual TLS + agent cert |
| Tampering | Data modification | Training data poisoning | Data provenance + hashing |
| Repudiation | Action denial | Denying agent actions | Immutable audit trail |
| Info Disclosure | Data leak | Model inference extraction | Differential privacy |
| Denial of Service | Availability attack | Compute resource exhaustion | Rate limiting + circuit breaker |
| Elevation of Privilege | Unauthorized access | Agent permission escalation | Least privilege + CISO gate |
Threat Model Template:
1. System boundary diagram (trust boundaries)
2. Data flow diagram (entry/exit points)
3. STRIDE analysis per component
4. Risk scoring (CVSS)
5. Mitigation recommendations
6. Residual risk acceptance
```
### 3.2 CVSS Scoring
```
CVSS v3.1 Scoring:
Base Score (0-10):
Attack Vector: Network/Adjacent/Local/Physical
Attack Complexity: Low/High
Privileges Required: None/Low/High
User Interaction: None/Required
Scope: Unchanged/Changed
Confidentiality: None/Low/High
Integrity: None/Low/High
Availability: None/Low/High
Severity Rating:
0.0: None | 0.1-3.9: Low | 4.0-6.9: Medium | 7.0-8.9: High | 9.0-10.0: Critical
CISO Gate Thresholds:
CVSS < 4.0: APPROVED (auto)
CVSS 4.0-6.9: CONDITIONAL (mitigations required)
CVSS >= 7.0: REJECTED (redesign required)
Review Cadence:
- All skills: STRIDE at creation + annually
- High-risk changes: STRIDE before deployment
- Post-incident: STRIDE within 48h
```
### 3.3 Security Gate (from Security-Gate)
```
Gate Process:
1. SUBMIT: Agent submits skill/change for security review
2. SCAN: Automated security scan (SAST, DAST, dependency check)
3. ANALYZE: STRIDE threat model assessment
4. SCORE: CVSS calculation
5. REVIEW: CISO manual review for L4+ operations
6. DECIDE: APPROVED / CONDITIONAL / REJECTED
7. DOCUMENT: Full assessment with findings and mitigations
Gate Checklist:
[ ] No credentials or API keys in code
[ ] No PII exposure in outputs
[ ] Input validation on all external inputs
[ ] Output sanitization on all external outputs
[ ] Rate limiting on all public interfaces
[ ] Audit logging on all state-changing operations
[ ] Least privilege permissions configured
[ ] Encryption at rest and in transit
[ ] Dependency vulnerabilities resolved
[ ] STRIDE analysis completed
Security Review SLA:
| Priority | Review Time | Example |
|----------|------------|---------|
| P0-Emergency | <2h | Active breach |
| P1-High | <24h | New skill deployment |
| P2-Standard | <72h | Feature update |
| P3-Low | <1 week | Documentation change |
```
### 3.4 Incident Response
```
Incident Classification:
| Severity | Example | Response Time | Team |
|----------|---------|--------------|------|
| SEV1-Critical | Active data breach | <15min | CISO + CEO + CLO |
| SEV2-High | Vulnerability exploited | <1h | CISO + CTO |
| SEV3-Medium | Vulnerability discovered | <24h | CISO team |
| SEV4-Low | Policy violation | <72h | CISO team |
Incident Response Protocol:
1. DETECT: Monitoring alert or report
2. TRIAGE: Classify severity and scope
3. CONTAIN: Isolate affected systems
4. ERADICATE: Remove threat
5. RECOVER: Restore services
6. REPORT: Full incident report within 24h
7. REVIEW: Post-mortem within 7 days
8. IMPROVE: Update controls and procedures
Forensic Preservation:
- All evidence preserved with chain of custody
- Memory dumps before system changes
- Log exports to immutable storage
- Timeline reconstruction within 4h
```
### 3.5 MLOps Security
```
ML Security Controls:
| Stage | Control | Implementation |
|-------|---------|---------------|
| Data | Provenance tracking | Hash chain for training data |
| Data | Poisoning detection | Statistical distribution checks |
| Training | Reproducibility | Versioned data + code + hyperparams |
| Training | Access control | Isolated training environments |
| Model | Encryption | Weights encrypted at rest |
| Model | Signing | Model signature verification |
| Inference | Rate limiting | Token bucket per agent |
| Inference | Privacy | Differential privacy for queries |
| Inference | Audit | All inference requests logged |
| Monitoring | Drift detection | Statistical tests on predictions |
| Monitoring | Adversarial detection | Input anomaly detection |
```
---
## 4. Error Codes
| Code | Meaning | Resolution |
|------|---------|------------|
| CISO_E001 | Security gate rejected | Address findings, resubmit |
| CISO_E002 | STRIDE analysis required | Complete threat model |
| CISO_E003 | CVSS exceeds threshold | Redesign or mitigate |
| CISO_E004 | Incident detected | Execute incident protocol |
| CISO_E005 | Credential exposure | Rotate immediately, audit access |
| CISO_E006 | Model security violation | Halt deployment, remediate |
| CISO_E007 | Audit log tampering | Alert CEO+Board, forensic analysis |
| CISO_E008 | Permission escalation attempt | Block, investigate, notify |
---
## 5. Constraints & Metrics
Constraints: No deployment without security gate; No audit log deletion; All credentials must be rotated quarterly; All models must pass ML security controls; Incidents must be reported within 24h.
| Metric | Target |
|--------|--------|
| Gate pass rate | >90% |
| Incident response time (SEV1) | <15min |
| Vulnerability remediation (Critical) | <24h |
| Audit log completeness | 100% |
| Credential rotation compliance | 100% |
| STRIDE coverage | 100% of skills |
*Enhanced by AI-Company Skills Rebuilder v3.0*
CRO skill: Risk identification, early warning, circuit breaker, FAIR quantitative risk assessment, milestone-based risk gates, risk register management.
---
name: "AI Company CRO"
slug: "ai-company-cro"
version: "3.0.0"
homepage: "https://clawhub.com/skills/ai-company-cro"
description: |
CRO skill: Risk identification, early warning, circuit breaker, FAIR quantitative risk assessment, milestone-based risk gates, risk register management.
license: MIT-0
install:
requires: []
verify_command: python -c "print('ok')"
dependencies:
runtime:
- python3.9+
skills: ["ai-company-hq","ai-company-cfo","ai-company-ciso"]
tags: [ai-company,cro,risk,circuit-breaker,fair,milestone,early-warning]
triggers:
- risk assessment
- circuit breaker
- early warning
- FAIR analysis
- risk register
- milestone review
interface:
inputs:
type: object
schema:
type: object
properties:
task:
type: string
description: Task description
context:
type: object
description: Optional context information
required: [task]
outputs:
type: object
schema:
type: object
properties:
result:
type: string
description: Operation result
report:
type: object
description: Detailed report data
required: [result]
errors:
- code: CRO_001
message: "Risk threshold exceeded"
- code: CRO_002
message: "Circuit breaker triggered"
- code: CRO_003
message: "FAIR assessment incomplete"
permissions:
files: [read, write]
network: [api]
commands: []
mcp: [sessions_send, subagents]
quality:
saST: Pass
vetter: Approved
idempotent: true
metadata:
category: risk
layer: AGENT
cluster: ai-company
maturity: STABLE
license: MIT-0
standardized: true
department: finance-and-risk
merged_from: [ai-company-cro]
---
# AI Company CRO v3.0.0
> Index & Quick Reference. Full specifications in [references/method-patterns.md](references/method-patterns.md).
## Quick Reference
### Role
AI Company CRO — CRO skill: Risk identification, early warning, circuit breaker, FAIR quantitative risk assessment, milestone-based risk gates, risk register management.
### Department
Finance & Risk
### Merged From
[ai-company-cro]
## Section Index
- [1. Trigger Scenarios](references/method-patterns.md#1-trigger-scenarios)
- [2. Core Identity](references/method-patterns.md#2-core-identity)
- [3. Core Responsibilities](references/method-patterns.md#3-core-responsibilities)
- [4. Constraints](references/method-patterns.md#4-constraints)
## Dependencies
See frontmatter `dependencies.skills` for complete dependency list.
## Error Codes
See frontmatter `interface.errors` for complete error code reference.
## Prompts
Copy-paste ready prompts in [prompts/](prompts/):
- [01-implement-method.md](prompts/01-implement-method.md)
- [02-robustness-checks.md](prompts/02-robustness-checks.md)
- [03-test-cases.md](prompts/03-test-cases.md)
- [04-documentation.md](prompts/04-documentation.md)
- [05-workflow-execution.md](prompts/05-workflow-execution.md)
## Changelog
| Version | Date | Changes |
|---------|------|---------|
| 3.0.0 | 2026-04-26 | Full English rewrite; department-aligned structure; merged skills consolidated |
---
*This skill follows AI Company Governance Framework. See [references/method-patterns.md](references/method-patterns.md) for complete specifications.*
## Integration & Merge History
**v3.0.0 Rebuild (2026-04-26)**
This skill was created by merging multiple predecessor skills into a unified department-aligned structure.
**Department**: Finance & Risk
**Merged From** (1 skills total):
- CRO (primary)
- (standalone skill, no merges)
**Merge Rationale**:
- Consolidate related capabilities under single department owner
- Reduce skill count from 47 to 15 for better maintainability
- Preserve all functionality while improving discoverability
- Standardize structure: SKILL.md (index) + references/method-patterns.md (details)
**Integration Points**:
- All predecessor skill triggers preserved in unified trigger list
- All predecessor interfaces consolidated with consistent error codes
- Dependencies unified and simplified
- Prompts merged and organized by function
**Migration Guide**:
- Previous skill users: Use new unified skill slug `ai-company-cro`
- All functionality from predecessor skills is available
- Error codes may have changed - see Error Codes section
- Prompts are now user copy-paste ready (not auto-call)
FILE:prompts/01-implement-method.md
# Implementation Method Prompt
> Copy and paste this prompt into any AI chat window to implement the AI Company CRO skill.
---
## Prompt
```
You are implementing the AI Company CRO skill for an AI Company system.
Department: Finance & Risk
Skill: AI Company CRO
Your task:
1. Read the SKILL.md index to understand the skill scope
2. Read references/method-patterns.md for detailed specifications
3. Implement the core methods described in the method patterns
4. Ensure all output follows the specified format
5. Verify compliance with Harness Engineering L1-L6
Key Requirements:
- All content must be in English
- Follow ClawHub Schema v1.0 for frontmatter
- Implement all error codes defined in interface.errors
- Respect all constraints listed in the skill
- Generate idempotent operations where specified
Output:
- Working implementation of all core methods
- Error handling for all defined error codes
- Integration points with dependency skills
- Test cases for verification
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/02-robustness-checks.md
# Robustness Checks Prompt
> Copy and paste this prompt into any AI chat window to verify the AI Company CRO skill robustness.
---
## Prompt
```
You are performing robustness checks on the AI Company CRO skill.
Department: Finance & Risk
Skill: AI Company CRO
Check the following:
1. BOUNDARY CONDITIONS
- What happens with empty input?
- What happens with maximum-size input?
- What happens with invalid input types?
- What happens with concurrent access?
2. ERROR HANDLING
- Are all error codes properly handled?
- Are error messages user-friendly?
- Is error recovery possible?
- Are errors logged for audit?
3. CONSTRAINT COMPLIANCE
- Are all skill constraints enforced?
- Are permission boundaries respected?
- Are SLA targets achievable?
- Are resource limits respected?
4. INTEGRATION
- Are dependency skills properly called?
- Are cross-agent interfaces correct?
- Is HQ routing followed?
- Are audit trails complete?
5. SECURITY
- No credentials or PII exposed?
- No injection vulnerabilities?
- Proper access control enforced?
- CISO security gate requirements met?
Output:
- List of all issues found (categorized by severity)
- Recommended fixes for each issue
- Verification steps for each fix
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/03-test-cases.md
# Test Cases Prompt
> Copy and paste this prompt into any AI chat window to generate test cases for the AI Company CRO skill.
---
## Prompt
```
You are generating test cases for the AI Company CRO skill.
Department: Finance & Risk
Skill: AI Company CRO
Generate test cases for the following categories:
1. FUNCTIONAL TESTS
- Core happy path for each responsibility
- Each workflow step in sequence
- Each output format validation
- Each error code trigger
2. EDGE CASES
- Empty or null inputs
- Boundary values (min, max, zero)
- Concurrent operations
- Network timeout scenarios
3. INTEGRATION TESTS
- Cross-agent communication via HQ
- Dependency skill invocation
- Permission boundary enforcement
- Audit trail completeness
4. REGRESSION TESTS
- Known defect scenarios (from version history)
- Previously fixed issues
- Breaking change validation
5. PERFORMANCE TESTS
- Response time under normal load
- Response time under peak load
- Memory usage patterns
- Concurrent user handling
For each test case provide:
- Test ID: TC-AI_COMPANY_CRO-NNN
- Description: What is being tested
- Input: Test input data
- Expected Output: What should happen
- Priority: P0/P1/P2/P3
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/04-documentation.md
# Documentation Prompt
> Copy and paste this prompt into any AI chat window to generate documentation for the AI Company CRO skill.
---
## Prompt
```
You are generating documentation for the AI Company CRO skill.
Department: Finance & Risk
Skill: AI Company CRO
Generate the following documentation:
1. README SECTION
- Skill overview and purpose
- Quick start guide (3 steps or fewer)
- Prerequisites and dependencies
- Configuration options
2. API REFERENCE
- All input parameters with types and descriptions
- All output fields with types and descriptions
- All error codes with meanings and resolutions
- All trigger keywords with examples
3. ARCHITECTURE DIAGRAM
- Skill position in department and company
- Dependency graph with other skills
- Data flow diagram
- Permission boundaries
4. USAGE EXAMPLES
- Common use cases with step-by-step walkthroughs
- Integration examples with dependency skills
- Troubleshooting guide for common issues
- FAQ based on typical questions
5. CHANGELOG
- Version history with change descriptions
- Migration guide for major versions
- Deprecation notices if applicable
Output format: Markdown with proper heading hierarchy.
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/05-workflow-execution.md
# Workflow Execution Prompt
> Copy and paste this prompt into any AI chat window to execute the AI Company CRO skill workflow.
---
## Prompt
```
You are executing the AI Company CRO skill workflow for an AI Company system.
Department: Finance & Risk
Skill: AI Company CRO
Execute the complete workflow:
1. SETUP
- Verify all dependencies are available
- Confirm permissions are correctly configured
- Initialize required resources
- Load configuration from SKILL.md
2. EXECUTE CORE WORKFLOW
- Follow each workflow step defined in the skill
- Validate inputs at each step
- Process data according to method patterns
- Generate outputs in specified format
3. QUALITY VERIFICATION
- Run robustness checks on outputs
- Verify all constraints are satisfied
- Confirm error codes are properly handled
- Validate integration with dependency skills
4. DELIVER RESULTS
- Format output per skill specification
- Include audit trail and traceability tags
- Attach quality metrics and scores
- Flag any warnings or conditional results
5. CLOSE-LOOP
- Log execution metrics for KPI tracking
- Update shared state via HQ
- Archive execution record for audit
- Schedule follow-up if needed
Output: Complete execution results with quality metrics and audit trail.
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:references/method-patterns.md
# Method Patterns & Detailed Specifications
> Full specifications for AI Company CRO. Standalone: risk, circuit breaker, FAIR.
---
# AI Company CRO Skill v3.0
> Chief Risk Officer for All-AI-Employee Technology Companies.
---
## 1. Trigger Scenarios
| Category | Trigger Keywords |
|----------|-----------------|
| Risk | "Risk assessment", "Risk register", "Threat analysis", "Vulnerability" |
| Circuit Breaker | "Circuit breaker", "Halt", "Freeze", "Risk threshold" |
| FAIR | "FAIR analysis", "Quantitative risk", "Loss expectancy" |
| Milestone | "Milestone gate", "Go/no-go", "Risk review", "Stage gate" |
---
## 2. Core Identity
- **Position**: AI CRO | **Permission Level**: L4 | **ID**: CRO-001 | **Reports to**: CEO-001
---
## 3. Core Responsibilities
### 3.1 Enterprise Risk Management
```
Framework (ISO 31000 adapted):
IDENTIFY -> ANALYZE -> EVALUATE -> TREAT -> MONITOR -> REPORT
Risk Categories:
| Category | Examples | Primary Owner |
|----------|---------|---------------|
| Strategic | Market shift, disruption | CEO |
| Financial | Currency, credit, liquidity | CFO |
| Operational | System failure, SLA breach | COO |
| Technology | Obsolescence, cyber attack | CTO+CISO |
| Compliance | Regulatory change | CLO |
| Reputational | Public incident | CMO |
Risk Appetite:
Strategic: Moderate | Financial: Low (unhedged >$500K) | Operational: Zero (data loss) | Compliance: Zero | Reputational: Low
```
### 3.2 FAIR Quantitative Analysis
```
FAIR Model:
Risk (ALE) = Loss_Event_Frequency * Loss_Magnitude
LEF = Threat_Event_Frequency * Vulnerability
LM = Primary_Loss + Secondary_Loss
Primary: Productivity + Response + Replacement
Secondary: Fine/Judgment + Reputation + Competitive
| Risk Level | ALE Range | Action |
|-----------|-----------|--------|
| Critical | >$1M/yr | Immediate treatment, CEO+Board |
| High | $100K-$1M/yr | Treatment plan within 30 days |
| Medium | $10K-$100K/yr | Monitor, plan within 90 days |
| Low | <$10K/yr | Accept and monitor |
```
### 3.3 Circuit Breaker
```
| Level | Trigger | Action | Authority |
|-------|---------|--------|-----------|
| L1-Yellow | Indicator >70% threshold | Alert + monitoring | CRO auto |
| L2-Orange | Indicator >85% threshold | Slow down, manual approval | CRO + dept head |
| L3-Red | Indicator >95% threshold | Halt affected operations | CRO + CEO |
| L4-Emergency | Active loss event | Freeze all related | CRO + CEO + Board |
Indicators:
| Indicator | Yellow | Orange | Red |
|-----------|--------|--------|-----|
| SLA compliance | <98% | <95% | <90% |
| Financial burn | >110% budget | >130% | >150% |
| Security incidents | >5/week | >10/week | >20/week |
| Agent failure rate | >2% | >5% | >10% |
| Compliance violations | >1/quarter | >1/month | >1/week |
Recovery: CONTAIN -> ANALYZE -> REMEDIATE -> VERIFY -> RESTORE -> REVIEW -> PREVENT
```
### 3.4 Milestone Risk Gates
```
Gate 1 - Initiation: Risk register created, FAIR assessment, owner assigned
Gate 2 - Planning: Detailed analysis, mitigation strategies, CB thresholds set
Gate 3 - Execution Start: Mitigations implemented, monitoring active
Gate 4 - Mid-Point: Reassessed, FAIR updated, CB verified
Gate 5 - Completion: Final assessment, lessons captured, residual risks documented
| Outcome | Action |
|---------|--------|
| GO | Proceed |
| CONDITIONAL GO | Proceed with conditions, recheck in 2 weeks |
| HOLD | Stop, remediate, re-gate |
| KILL | Cancel initiative, redirect resources |
```
---
## 4. Error Codes
| Code | Meaning | Resolution |
|------|---------|------------|
| CRO_E001 | Risk indicator breach | Activate circuit breaker level |
| CRO_E002 | FAIR analysis incomplete | Flag for manual completion |
| CRO_E003 | Gate failure | HOLD initiative, remediate |
| CRO_E004 | Risk register stale | Force quarterly update |
| CRO_E005 | Circuit breaker triggered | Execute recovery protocol |
| CRO_E006 | Residual risk exceeds appetite | Escalate to CEO |
---
## 5. Constraints & Metrics
Constraints: No operations resumption without CRO clearance after L3+; No risk acceptance above Medium without CEO; All FAIR assessments reviewed annually; Circuit breaker overrides require CEO+Board.
| Metric | Target |
|--------|--------|
| Risk register coverage | 100% |
| FAIR assessment accuracy | +/-20% |
| Circuit breaker response | <5min |
| Gate pass rate | >80% |
| Risk appetite compliance | 100% |
*Enhanced by AI-Company Skills Rebuilder v3.0*
CTO skill: Technical architecture, AI infrastructure, MLOps security, agent factory, skill builder, software engineering, production operations, approval wor...
---
name: "AI Company CTO"
slug: "ai-company-cto"
version: "3.0.0"
homepage: "https://clawhub.com/skills/ai-company-cto"
description: |
CTO skill: Technical architecture, AI infrastructure, MLOps security, agent factory, skill builder, software engineering, production operations, approval workflows.
license: MIT-0
install:
requires: []
verify_command: python -c "print('ok')"
dependencies:
runtime:
- python3.9+
skills: ["ai-company-hq","ai-company-ciso","ai-company-harness"]
tags: [ai-company,cto,architecture,mlops,agent-factory,skill-builder,engineering,production]
triggers:
- technical architecture
- AI infrastructure
- agent creation
- skill building
- software engineering
- production deployment
- MLOps
interface:
inputs:
type: object
schema:
type: object
properties:
task:
type: string
description: Task description
context:
type: object
description: Optional context information
required: [task]
outputs:
type: object
schema:
type: object
properties:
result:
type: string
description: Operation result
report:
type: object
description: Detailed report data
required: [result]
errors:
- code: CTO_001
message: "Architecture violation"
- code: CTO_002
message: "Agent creation failed"
- code: CTO_003
message: "Skill build failed"
- code: CTO_004
message: "Production operation denied"
- code: CTO_005
message: "MLOps pipeline error"
permissions:
files: [read, write]
network: [api]
commands: []
mcp: [sessions_send, subagents]
quality:
saST: Pass
vetter: Approved
idempotent: true
metadata:
category: technology
layer: AGENT
cluster: ai-company
maturity: STABLE
license: MIT-0
standardized: true
department: technology-and-engineering
merged_from: [ai-company-cto, ai-company-cto-agentfactory, ai-company-cto-skill-builder, ai-company-engr]
---
# AI Company CTO v3.0.0
> Index & Quick Reference. Full specifications in [references/method-patterns.md](references/method-patterns.md).
## Quick Reference
### Role
AI Company CTO — CTO skill: Technical architecture, AI infrastructure, MLOps security, agent factory, skill builder, software engineering, production operations, approval workflows.
### Department
Technology & Engineering
### Merged From
[ai-company-cto, ai-company-cto-agentfactory, ai-company-cto-skill-builder, ai-company-engr]
## Section Index
- [1. Trigger Scenarios](references/method-patterns.md#1-trigger-scenarios)
- [2. Core Identity](references/method-patterns.md#2-core-identity)
- [3. Core Responsibilities](references/method-patterns.md#3-core-responsibilities)
- [4. Constraints](references/method-patterns.md#4-constraints)
## Dependencies
See frontmatter `dependencies.skills` for complete dependency list.
## Error Codes
See frontmatter `interface.errors` for complete error code reference.
## Prompts
Copy-paste ready prompts in [prompts/](prompts/):
- [01-implement-method.md](prompts/01-implement-method.md)
- [02-robustness-checks.md](prompts/02-robustness-checks.md)
- [03-test-cases.md](prompts/03-test-cases.md)
- [04-documentation.md](prompts/04-documentation.md)
- [05-workflow-execution.md](prompts/05-workflow-execution.md)
## Changelog
| Version | Date | Changes |
|---------|------|---------|
| 3.0.0 | 2026-04-26 | Full English rewrite; department-aligned structure; merged skills consolidated |
---
*This skill follows AI Company Governance Framework. See [references/method-patterns.md](references/method-patterns.md) for complete specifications.*
## Integration & Merge History
**v3.0.0 Rebuild (2026-04-26)**
This skill was created by merging multiple predecessor skills into a unified department-aligned structure.
**Department**: Tech & Engineering
**Merged From** (4 skills total):
- CTO (primary)
- ai-company-cto-agentfactory
- ai-company-cto-skill-builder
- ai-company-engr
**Merge Rationale**:
- Consolidate related capabilities under single department owner
- Reduce skill count from 47 to 15 for better maintainability
- Preserve all functionality while improving discoverability
- Standardize structure: SKILL.md (index) + references/method-patterns.md (details)
**Integration Points**:
- All predecessor skill triggers preserved in unified trigger list
- All predecessor interfaces consolidated with consistent error codes
- Dependencies unified and simplified
- Prompts merged and organized by function
**Migration Guide**:
- Previous skill users: Use new unified skill slug `ai-company-cto`
- All functionality from predecessor skills is available
- Error codes may have changed - see Error Codes section
- Prompts are now user copy-paste ready (not auto-call)
FILE:prompts/01-implement-method.md
# Implementation Method Prompt
> Copy and paste this prompt into any AI chat window to implement the AI Company CTO skill.
---
## Prompt
```
You are implementing the AI Company CTO skill for an AI Company system.
Department: Technology & Engineering
Skill: AI Company CTO
Your task:
1. Read the SKILL.md index to understand the skill scope
2. Read references/method-patterns.md for detailed specifications
3. Implement the core methods described in the method patterns
4. Ensure all output follows the specified format
5. Verify compliance with Harness Engineering L1-L6
Key Requirements:
- All content must be in English
- Follow ClawHub Schema v1.0 for frontmatter
- Implement all error codes defined in interface.errors
- Respect all constraints listed in the skill
- Generate idempotent operations where specified
Output:
- Working implementation of all core methods
- Error handling for all defined error codes
- Integration points with dependency skills
- Test cases for verification
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/02-robustness-checks.md
# Robustness Checks Prompt
> Copy and paste this prompt into any AI chat window to verify the AI Company CTO skill robustness.
---
## Prompt
```
You are performing robustness checks on the AI Company CTO skill.
Department: Technology & Engineering
Skill: AI Company CTO
Check the following:
1. BOUNDARY CONDITIONS
- What happens with empty input?
- What happens with maximum-size input?
- What happens with invalid input types?
- What happens with concurrent access?
2. ERROR HANDLING
- Are all error codes properly handled?
- Are error messages user-friendly?
- Is error recovery possible?
- Are errors logged for audit?
3. CONSTRAINT COMPLIANCE
- Are all skill constraints enforced?
- Are permission boundaries respected?
- Are SLA targets achievable?
- Are resource limits respected?
4. INTEGRATION
- Are dependency skills properly called?
- Are cross-agent interfaces correct?
- Is HQ routing followed?
- Are audit trails complete?
5. SECURITY
- No credentials or PII exposed?
- No injection vulnerabilities?
- Proper access control enforced?
- CISO security gate requirements met?
Output:
- List of all issues found (categorized by severity)
- Recommended fixes for each issue
- Verification steps for each fix
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/03-test-cases.md
# Test Cases Prompt
> Copy and paste this prompt into any AI chat window to generate test cases for the AI Company CTO skill.
---
## Prompt
```
You are generating test cases for the AI Company CTO skill.
Department: Technology & Engineering
Skill: AI Company CTO
Generate test cases for the following categories:
1. FUNCTIONAL TESTS
- Core happy path for each responsibility
- Each workflow step in sequence
- Each output format validation
- Each error code trigger
2. EDGE CASES
- Empty or null inputs
- Boundary values (min, max, zero)
- Concurrent operations
- Network timeout scenarios
3. INTEGRATION TESTS
- Cross-agent communication via HQ
- Dependency skill invocation
- Permission boundary enforcement
- Audit trail completeness
4. REGRESSION TESTS
- Known defect scenarios (from version history)
- Previously fixed issues
- Breaking change validation
5. PERFORMANCE TESTS
- Response time under normal load
- Response time under peak load
- Memory usage patterns
- Concurrent user handling
For each test case provide:
- Test ID: TC-AI_COMPANY_CTO-NNN
- Description: What is being tested
- Input: Test input data
- Expected Output: What should happen
- Priority: P0/P1/P2/P3
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/04-documentation.md
# Documentation Prompt
> Copy and paste this prompt into any AI chat window to generate documentation for the AI Company CTO skill.
---
## Prompt
```
You are generating documentation for the AI Company CTO skill.
Department: Technology & Engineering
Skill: AI Company CTO
Generate the following documentation:
1. README SECTION
- Skill overview and purpose
- Quick start guide (3 steps or fewer)
- Prerequisites and dependencies
- Configuration options
2. API REFERENCE
- All input parameters with types and descriptions
- All output fields with types and descriptions
- All error codes with meanings and resolutions
- All trigger keywords with examples
3. ARCHITECTURE DIAGRAM
- Skill position in department and company
- Dependency graph with other skills
- Data flow diagram
- Permission boundaries
4. USAGE EXAMPLES
- Common use cases with step-by-step walkthroughs
- Integration examples with dependency skills
- Troubleshooting guide for common issues
- FAQ based on typical questions
5. CHANGELOG
- Version history with change descriptions
- Migration guide for major versions
- Deprecation notices if applicable
Output format: Markdown with proper heading hierarchy.
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/05-workflow-execution.md
# Workflow Execution Prompt
> Copy and paste this prompt into any AI chat window to execute the AI Company CTO skill workflow.
---
## Prompt
```
You are executing the AI Company CTO skill workflow for an AI Company system.
Department: Technology & Engineering
Skill: AI Company CTO
Execute the complete workflow:
1. SETUP
- Verify all dependencies are available
- Confirm permissions are correctly configured
- Initialize required resources
- Load configuration from SKILL.md
2. EXECUTE CORE WORKFLOW
- Follow each workflow step defined in the skill
- Validate inputs at each step
- Process data according to method patterns
- Generate outputs in specified format
3. QUALITY VERIFICATION
- Run robustness checks on outputs
- Verify all constraints are satisfied
- Confirm error codes are properly handled
- Validate integration with dependency skills
4. DELIVER RESULTS
- Format output per skill specification
- Include audit trail and traceability tags
- Attach quality metrics and scores
- Flag any warnings or conditional results
5. CLOSE-LOOP
- Log execution metrics for KPI tracking
- Update shared state via HQ
- Archive execution record for audit
- Schedule follow-up if needed
Output: Complete execution results with quality metrics and audit trail.
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:references/method-patterns.md
# Method Patterns & Detailed Specifications
> Full specifications for AI Company CTO. Merged: CTO + AgentFactory + SkillBuilder + ENGR.
---
# AI Company CTO Skill v3.0
> Chief Technology Officer for All-AI-Employee Technology Companies.
> Architecture, agent factory, skill building, MLOps, engineering execution, infrastructure.
---
## 1. Trigger Scenarios
| Category | Trigger Keywords |
|----------|-----------------|
| Architecture | "System design", "Architecture review", "Tech stack", "Infrastructure" |
| Agent Factory | "Create agent", "New agent", "Agent template", "Agent configuration" |
| Skill Build | "Build skill", "New skill", "Skill template", "Skill development" |
| Engineering | "Deploy", "Code review", "Production", "Release", "Hotfix" |
| MLOps | "Model training", "Fine-tune", "Pipeline", "Model registry" |
---
## 2. Core Identity
- **Position**: AI CTO | **Permission Level**: L4 | **ID**: CTO-001 | **Reports to**: CEO-001
---
## 3. Core Responsibilities
### 3.1 System Architecture
```
Architecture Principles:
- Microservices: Each agent is an independent service
- Event-driven: Async communication via HQ message bus
- Stateless compute: State managed by HQ, agents are stateless
- Defense in depth: CISO security gates at every boundary
- Observability: Full tracing, metrics, and logging
Tech Stack:
| Layer | Technology | Purpose |
|-------|-----------|---------|
| Agent Runtime | LLM + Tool Framework | Agent execution |
| Message Bus | HQ Router | Inter-agent communication |
| State Store | Distributed KV Store | Shared state management |
| Knowledge Base | Vector + Graph DB | Knowledge storage and retrieval |
| Monitoring | Metrics + Tracing + Logging | Observability |
| CI/CD | Pipeline + Registry | Deployment automation |
| Security | CISO Gate + Audit | Access control and compliance |
Architecture Decision Records (ADR):
ADR Template:
- Title: [Decision title]
- Status: Proposed | Accepted | Deprecated | Superseded
- Context: What is the issue that we're seeing?
- Decision: What have we decided to do?
- Consequences: What are the results of the decision?
- Compliance: CISO and CQO sign-off
```
### 3.2 Agent Factory (from AgentFactory)
```
Agent Creation Pipeline:
1. SPECIFY: Define agent role, responsibilities, permissions
2. DESIGN: Select template, configure tools, define interfaces
3. BUILD: Generate agent configuration and skill bindings
4. TEST: Validate in sandbox environment
5. REVIEW: CISO security review + CQO quality review
6. DEPLOY: Register with HQ, activate in production
7. MONITOR: Track performance and health
Agent Template:
{
"agent_id": "PREFIX-NNN",
"name": "Agent Name",
"department": "department-slug",
"permission_level": "L1-L5",
"skills": ["skill-slug-1", "skill-slug-2"],
"tools": ["tool-1", "tool-2"],
"dependencies": ["AGENT_ID-1"],
"sla_tier": "platinum|gold|silver|bronze",
"max_concurrent_tasks": 5,
"heartbeat_interval_sec": 30
}
Agent Permission Levels:
| Level | Scope | Examples |
|-------|-------|---------|
| L1-Viewer | Read own data | Dashboard viewer |
| L2-Operator | Execute tasks | Task executor |
| L3-Manager | Department scope | Department lead |
| L4-Executive | Cross-department | C-Suite |
| L5-Infrastructure | System-wide | HQ, security |
```
### 3.3 Skill Builder (from SkillBuilder)
```
Skill Creation Pipeline:
1. REQUIRE: Gather requirements from C-Suite sponsor
2. DESIGN: Define skill schema, triggers, interface, permissions
3. IMPLEMENT: Write SKILL.md, method-patterns.md, prompts
4. VALIDATE: Schema compliance, Harness L1-L6, English-only
5. REVIEW: CISO security gate + CQO quality gate
6. PUBLISH: Upload to ClawHub, register with HQ
7. MAINTAIN: Version updates, deprecation, migration
Skill Schema (ClawHub v1.0):
Required Fields:
name, slug, version, description, license, tags, triggers,
interface (inputs, outputs, errors), permissions, quality, metadata
Optional Fields:
dependencies, conflicts, examples, documentation, changelog
Quality Gates for Skill Publishing:
G0: Schema compliance (all required fields present)
G1: English-only (no Chinese characters in body)
G2: Harness L1-L6 compliance
G3: CISO security review (STRIDE, CVSS)
G4: CQO quality review (idempotency, robustness)
G5: ClawHub acceptance (VirusTotal, content policy)
G6: Integration test (dependency resolution)
G7: Documentation completeness (prompts, examples)
```
### 3.4 Engineering Execution (from ENGR)
```
Production Operations Permission Levels:
| Level | Operation | Approval |
|-------|-----------|----------|
| L1-Read | View logs, metrics | None |
| L2-Deploy | Deploy to staging | CTO approval |
| L3-Release | Deploy to production | CTO + CISO approval |
| L4-Hotfix | Emergency production fix | CTO approval, CISO post-review |
| L5-Infrastructure | System config changes | CTO + CEO approval |
Deployment Pipeline:
1. CODE: Developer writes code
2. REVIEW: Peer review + automated linting
3. TEST: Unit + integration + E2E tests
4. STAGE: Deploy to staging, smoke test
5. GATE: CISO security scan + CQO quality check
6. RELEASE: Deploy to production with canary
7. VERIFY: Monitor metrics for 1h post-deploy
8. COMPLETE: Mark release as stable
Rollback Protocol:
- Automatic: If error rate >5% within 15min of deploy
- Manual: CTO or COO can trigger rollback
- Full rollback: Revert to previous stable version
- Partial rollback: Feature flag off for affected component
```
### 3.5 MLOps
```
MLOps Pipeline:
| Stage | Activity | Owner | Gate |
|-------|----------|-------|------|
| Data | Collect, clean, label | CHO+CTO | Data quality check |
| Train | Model training, hyperparameter tuning | CTO | Training metrics |
| Evaluate | Validation, bias testing | CQO+CTO | Quality threshold |
| Register | Model registry, versioning | CTO | CISO scan |
| Deploy | Model serving, A/B testing | CTO+COO | Canary metrics |
| Monitor | Drift detection, performance | CTO+COO | Alert thresholds |
| Retire | Model deprecation, replacement | CTO | Migration plan |
Model Security Requirements:
- All training data must pass CISO sanitization
- Model weights encrypted at rest
- Inference requests logged for audit
- Model versioning with immutable registry
- Bias testing required before production deployment
```
---
## 4. Error Codes
| Code | Meaning | Resolution |
|------|---------|------------|
| CTO_E001 | Architecture violation detected | Review ADR, remediate |
| CTO_E002 | Agent creation failed | Check template, retry |
| CTO_E003 | Skill schema invalid | Fix schema, re-validate |
| CTO_E004 | Deployment failed | Rollback, investigate |
| CTO_E005 | Production incident | Execute incident protocol |
| CTO_E006 | Model drift detected | Schedule retraining |
| CTO_E007 | Resource exhaustion | Scale up, notify COO+CFO |
| CTO_E008 | Security gate blocked | Address CISO findings |
---
## 5. Constraints & Metrics
Constraints: No production deploy without CISO gate; No agent creation without CTO+CISO review; No architecture change without ADR; ENGR L4+ ops need dual approval; All models must pass bias test.
| Metric | Target |
|--------|--------|
| Deploy success rate | >99% |
| Agent creation time | <2h |
| Incident MTTR | <30min |
| Model drift detection | <24h |
| Architecture compliance | 100% |
| Security gate pass rate | >90% |
*Enhanced by AI-Company Skills Rebuilder v3.0*
CLO skill: Legal compliance, contract review, AI ethics committee, AIGC content compliance, data protection, regulatory alignment, compliance checking, IP se...
---
name: "AI Company CLO"
slug: "ai-company-clo"
version: "3.0.0"
homepage: "https://clawhub.com/skills/ai-company-clo"
description: |
CLO skill: Legal compliance, contract review, AI ethics committee, AIGC content compliance, data protection, regulatory alignment, compliance checking, IP search, legal practice.
license: MIT-0
install:
requires: []
verify_command: python -c "print('ok')"
dependencies:
runtime:
- python3.9+
skills: ["ai-company-hq","ai-company-ciso"]
tags: [ai-company,clo,legal,compliance,ethics,aigc,data-protection,ip,contract]
triggers:
- legal compliance
- contract review
- AI ethics
- AIGC compliance
- data protection
- regulatory check
- IP search
- legal practice
interface:
inputs:
type: object
schema:
type: object
properties:
task:
type: string
description: Task description
context:
type: object
description: Optional context information
required: [task]
outputs:
type: object
schema:
type: object
properties:
result:
type: string
description: Operation result
report:
type: object
description: Detailed report data
required: [result]
errors:
- code: CLO_001
message: "Compliance violation"
- code: CLO_002
message: "Contract issue detected"
- code: CLO_003
message: "AIGC labeling missing"
- code: CLO_004
message: "IP conflict detected"
- code: CLO_005
message: "Ethics committee veto"
permissions:
files: [read, write]
network: [api]
commands: []
mcp: [sessions_send, subagents]
quality:
saST: Pass
vetter: Approved
idempotent: true
metadata:
category: legal
layer: AGENT
cluster: ai-company
maturity: STABLE
license: MIT-0
standardized: true
department: security-and-compliance
merged_from: [ai-company-clo, ai-company-clo-compliance-checker, ai-company-legal]
---
# AI Company CLO v3.0.0
> Index & Quick Reference. Full specifications in [references/method-patterns.md](references/method-patterns.md).
## Quick Reference
### Role
AI Company CLO — CLO skill: Legal compliance, contract review, AI ethics committee, AIGC content compliance, data protection, regulatory alignment, compliance checking, IP search, legal practice.
### Department
Security & Compliance
### Merged From
[ai-company-clo, ai-company-clo-compliance-checker, ai-company-legal]
## Section Index
- [1. Trigger Scenarios](references/method-patterns.md#1-trigger-scenarios)
- [2. Core Identity](references/method-patterns.md#2-core-identity)
- [3. Core Responsibilities](references/method-patterns.md#3-core-responsibilities)
- [4. Constraints](references/method-patterns.md#4-constraints)
## Dependencies
See frontmatter `dependencies.skills` for complete dependency list.
## Error Codes
See frontmatter `interface.errors` for complete error code reference.
## Prompts
Copy-paste ready prompts in [prompts/](prompts/):
- [01-implement-method.md](prompts/01-implement-method.md)
- [02-robustness-checks.md](prompts/02-robustness-checks.md)
- [03-test-cases.md](prompts/03-test-cases.md)
- [04-documentation.md](prompts/04-documentation.md)
- [05-workflow-execution.md](prompts/05-workflow-execution.md)
## Changelog
| Version | Date | Changes |
|---------|------|---------|
| 3.0.0 | 2026-04-26 | Full English rewrite; department-aligned structure; merged skills consolidated |
---
*This skill follows AI Company Governance Framework. See [references/method-patterns.md](references/method-patterns.md) for complete specifications.*
## Integration & Merge History
**v3.0.0 Rebuild (2026-04-26)**
This skill was created by merging multiple predecessor skills into a unified department-aligned structure.
**Department**: Security & Compliance
**Merged From** (3 skills total):
- CLO (primary)
- ai-company-clo-compliance-checker
- ai-company-legal
**Merge Rationale**:
- Consolidate related capabilities under single department owner
- Reduce skill count from 47 to 15 for better maintainability
- Preserve all functionality while improving discoverability
- Standardize structure: SKILL.md (index) + references/method-patterns.md (details)
**Integration Points**:
- All predecessor skill triggers preserved in unified trigger list
- All predecessor interfaces consolidated with consistent error codes
- Dependencies unified and simplified
- Prompts merged and organized by function
**Migration Guide**:
- Previous skill users: Use new unified skill slug `ai-company-clo`
- All functionality from predecessor skills is available
- Error codes may have changed - see Error Codes section
- Prompts are now user copy-paste ready (not auto-call)
FILE:prompts/01-implement-method.md
# Implementation Method Prompt
> Copy and paste this prompt into any AI chat window to implement the AI Company CLO skill.
---
## Prompt
```
You are implementing the AI Company CLO skill for an AI Company system.
Department: Security & Compliance
Skill: AI Company CLO
Your task:
1. Read the SKILL.md index to understand the skill scope
2. Read references/method-patterns.md for detailed specifications
3. Implement the core methods described in the method patterns
4. Ensure all output follows the specified format
5. Verify compliance with Harness Engineering L1-L6
Key Requirements:
- All content must be in English
- Follow ClawHub Schema v1.0 for frontmatter
- Implement all error codes defined in interface.errors
- Respect all constraints listed in the skill
- Generate idempotent operations where specified
Output:
- Working implementation of all core methods
- Error handling for all defined error codes
- Integration points with dependency skills
- Test cases for verification
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/02-robustness-checks.md
# Robustness Checks Prompt
> Copy and paste this prompt into any AI chat window to verify the AI Company CLO skill robustness.
---
## Prompt
```
You are performing robustness checks on the AI Company CLO skill.
Department: Security & Compliance
Skill: AI Company CLO
Check the following:
1. BOUNDARY CONDITIONS
- What happens with empty input?
- What happens with maximum-size input?
- What happens with invalid input types?
- What happens with concurrent access?
2. ERROR HANDLING
- Are all error codes properly handled?
- Are error messages user-friendly?
- Is error recovery possible?
- Are errors logged for audit?
3. CONSTRAINT COMPLIANCE
- Are all skill constraints enforced?
- Are permission boundaries respected?
- Are SLA targets achievable?
- Are resource limits respected?
4. INTEGRATION
- Are dependency skills properly called?
- Are cross-agent interfaces correct?
- Is HQ routing followed?
- Are audit trails complete?
5. SECURITY
- No credentials or PII exposed?
- No injection vulnerabilities?
- Proper access control enforced?
- CISO security gate requirements met?
Output:
- List of all issues found (categorized by severity)
- Recommended fixes for each issue
- Verification steps for each fix
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/03-test-cases.md
# Test Cases Prompt
> Copy and paste this prompt into any AI chat window to generate test cases for the AI Company CLO skill.
---
## Prompt
```
You are generating test cases for the AI Company CLO skill.
Department: Security & Compliance
Skill: AI Company CLO
Generate test cases for the following categories:
1. FUNCTIONAL TESTS
- Core happy path for each responsibility
- Each workflow step in sequence
- Each output format validation
- Each error code trigger
2. EDGE CASES
- Empty or null inputs
- Boundary values (min, max, zero)
- Concurrent operations
- Network timeout scenarios
3. INTEGRATION TESTS
- Cross-agent communication via HQ
- Dependency skill invocation
- Permission boundary enforcement
- Audit trail completeness
4. REGRESSION TESTS
- Known defect scenarios (from version history)
- Previously fixed issues
- Breaking change validation
5. PERFORMANCE TESTS
- Response time under normal load
- Response time under peak load
- Memory usage patterns
- Concurrent user handling
For each test case provide:
- Test ID: TC-AI_COMPANY_CLO-NNN
- Description: What is being tested
- Input: Test input data
- Expected Output: What should happen
- Priority: P0/P1/P2/P3
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/04-documentation.md
# Documentation Prompt
> Copy and paste this prompt into any AI chat window to generate documentation for the AI Company CLO skill.
---
## Prompt
```
You are generating documentation for the AI Company CLO skill.
Department: Security & Compliance
Skill: AI Company CLO
Generate the following documentation:
1. README SECTION
- Skill overview and purpose
- Quick start guide (3 steps or fewer)
- Prerequisites and dependencies
- Configuration options
2. API REFERENCE
- All input parameters with types and descriptions
- All output fields with types and descriptions
- All error codes with meanings and resolutions
- All trigger keywords with examples
3. ARCHITECTURE DIAGRAM
- Skill position in department and company
- Dependency graph with other skills
- Data flow diagram
- Permission boundaries
4. USAGE EXAMPLES
- Common use cases with step-by-step walkthroughs
- Integration examples with dependency skills
- Troubleshooting guide for common issues
- FAQ based on typical questions
5. CHANGELOG
- Version history with change descriptions
- Migration guide for major versions
- Deprecation notices if applicable
Output format: Markdown with proper heading hierarchy.
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/05-workflow-execution.md
# Workflow Execution Prompt
> Copy and paste this prompt into any AI chat window to execute the AI Company CLO skill workflow.
---
## Prompt
```
You are executing the AI Company CLO skill workflow for an AI Company system.
Department: Security & Compliance
Skill: AI Company CLO
Execute the complete workflow:
1. SETUP
- Verify all dependencies are available
- Confirm permissions are correctly configured
- Initialize required resources
- Load configuration from SKILL.md
2. EXECUTE CORE WORKFLOW
- Follow each workflow step defined in the skill
- Validate inputs at each step
- Process data according to method patterns
- Generate outputs in specified format
3. QUALITY VERIFICATION
- Run robustness checks on outputs
- Verify all constraints are satisfied
- Confirm error codes are properly handled
- Validate integration with dependency skills
4. DELIVER RESULTS
- Format output per skill specification
- Include audit trail and traceability tags
- Attach quality metrics and scores
- Flag any warnings or conditional results
5. CLOSE-LOOP
- Log execution metrics for KPI tracking
- Update shared state via HQ
- Archive execution record for audit
- Schedule follow-up if needed
Output: Complete execution results with quality metrics and audit trail.
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:references/method-patterns.md
# Method Patterns & Detailed Specifications
> Full specifications for AI Company CLO. Merged: CLO + ComplianceChecker + LEGAL.
---
# AI Company CLO Skill v3.0
> Chief Legal Officer for All-AI-Employee Technology Companies.
> Legal compliance, AIGC review chain, IP protection, regulatory tracking, ethics governance.
---
## 1. Trigger Scenarios
| Category | Trigger Keywords |
|----------|-----------------|
| Compliance | "Compliance check", "Regulatory", "Legal review", "Policy" |
| AIGC | "AIGC review", "AI-generated content", "Content compliance", "AI labeling" |
| IP | "Intellectual property", "Patent", "Copyright", "Trade secret" |
| Ethics | "Ethics review", "AI ethics", "Bias check", "Fairness" |
| Legal Ops | "Contract", "Legal document", "Liability", "Terms of service" |
---
## 2. Core Identity
- **Position**: AI CLO | **Permission Level**: L4 | **ID**: CLO-001 | **Reports to**: CEO-001
---
## 3. Core Responsibilities
### 3.1 Legal Compliance Framework
```
Compliance Tier System:
| Tier | Regulation | Scope | Review Frequency |
|------|-----------|-------|-----------------|
| Tier 1 (Mandatory) | Data protection (GDPR, CCPA, PIPL) | All data processing | Continuous |
| Tier 2 (Industry) | AI Act, sector-specific | AI products | Quarterly |
| Tier 3 (Contractual) | Customer agreements, SLAs | Specific contracts | Per agreement |
| Tier 4 (Internal) | Company policies, SOPs | All operations | Monthly |
Compliance Check Pipeline:
1. IDENTIFY: Determine applicable regulations per jurisdiction
2. MAP: Map regulations to company operations and data flows
3. GAP: Identify gaps between current state and requirements
4. REMEDIATE: Implement changes to close gaps
5. VERIFY: Audit compliance after remediation
6. MONITOR: Continuous monitoring for new requirements
7. REPORT: Compliance dashboard and periodic reports
```
### 3.2 AIGC Content Review Chain (from ComplianceChecker)
```
AIGC Review Pipeline:
1. GENERATE: AI agent produces content
2. LABEL: AIGC tag applied automatically (100% labeling rate)
3. CHECK_COMPLIANCE: Automated compliance scan
- PII detection and redaction
- Copyright infringement check
- Defamation/disinformation screening
- Jurisdiction-specific content rules
4. HUMAN_REVIEW: Flagged content reviewed by CHO or legal team
5. APPROVE/REJECT: Decision with documented rationale
6. PUBLISH: Approved content released with AIGC watermark
7. MONITOR: Post-publication compliance monitoring
AIGC Labeling Requirements:
- All AI-generated text: [AIGC] prefix in metadata
- All AI-generated images: Invisible watermark + metadata tag
- All AI-generated code: Header comment with AI attribution
- All AI-generated decisions: Audit log with AI confidence score
Content Compliance Checks:
| Check | Tool | Threshold | Action on Fail |
|-------|------|-----------|---------------|
| PII detection | Regex + NER | Zero tolerance | Auto-redact |
| Copyright similarity | Embedding similarity | >80% similarity | Flag for review |
| Toxicity | Classifier | Score >0.3 | Block |
| Hallucination | Fact-check | Unverifiable claims | Flag for review |
| Jurisdiction rules | Rule engine | Any violation | Block in jurisdiction |
```
### 3.3 IP Protection
```
IP Portfolio Management:
| IP Type | Protection Method | Monitoring | Owner |
|---------|-----------------|------------|-------|
| Patents | File + maintain | Competitor watch | CLO + CTO |
| Copyrights | Automatic + registration | Plagiarism scan | CLO |
| Trade secrets | NDA + access control | Access audit | CLO + CISO |
| Trademarks | Register + enforce | Trademark watch | CLO + CMO |
| Data rights | License + DPA | Usage audit | CLO + CFO |
AI-Specific IP Considerations:
- Agent-generated inventions: Ownership defined in company policy
- Training data rights: License verification before use
- Model weights: Trade secret protection + access control
- Prompt engineering: Trade secret + access restriction
- Output ownership: Defined in ToS + customer agreements
```
### 3.4 Legal Operations (from LEGAL)
```
Contract Lifecycle:
1. DRAFT: Template-based contract generation
2. REVIEW: CLO automated review + manual for complex terms
3. NEGOTIATE: Counter-party negotiation support
4. APPROVE: CLO sign-off + CEO for >$100K
5. EXECUTE: Digital signature + secure storage
6. MONITOR: Obligation tracking + renewal alerts
7. RENEW/TERMINATE: Based on performance and terms
Contract Review Checklist:
[ ] Liability limitations appropriate
[ ] IP ownership clearly defined
[ ] Data processing terms compliant
[ ] Termination rights fair
[ ] Governing law specified
[ ] Dispute resolution mechanism defined
[ ] Force majeure clause included
[ ] AI-generated content terms included
Regulatory Tracking:
| Region | Key Regulations | Update Frequency | Responsible |
|--------|----------------|-----------------|-------------|
| EU | GDPR, AI Act, DSA | Continuous | CLO-EU |
| US | CCPA, AI Bill of Rights, state laws | Monthly | CLO-US |
| China | PIPL, DSL, AI regulations | Continuous | CLO-CN |
| Global | ISO 27001, SOC 2 | Annual | CLO-Global |
```
### 3.5 AI Ethics Governance
```
Ethics Review Board:
- Composition: CHO (chair), CLO, CISO, CTO, independent advisor
- Meeting frequency: Monthly + ad hoc for urgent issues
- Scope: AI bias, fairness, transparency, accountability
Ethics Review Triggers:
- New AI model deployment
- Significant model update or retraining
- Customer complaint about AI behavior
- Regulatory inquiry
- Internal audit finding
Ethics Assessment Framework:
| Principle | Assessment | Metric |
|-----------|-----------|--------|
| Fairness | Bias testing across protected groups | Disparate impact ratio >=0.8 |
| Transparency | Explainability of AI decisions | XAI coverage >=80% |
| Privacy | Data minimization and consent | PII exposure = 0 |
| Accountability | Human oversight of AI decisions | Override capability = 100% |
| Safety | Failure mode analysis | Safety test pass rate = 100% |
```
---
## 4. Error Codes
| Code | Meaning | Resolution |
|------|---------|------------|
| CLO_E001 | Compliance violation detected | Immediate remediation, notify CISO |
| CLO_E002 | AIGC review failed | Block content, flag for manual review |
| CLO_E003 | IP infringement suspected | Investigate, notify CTO, legal action |
| CLO_E004 | Contract review failed | Revise terms, renegotiate |
| CLO_E005 | Regulatory change detected | Assess impact, update procedures |
| CLO_E006 | Ethics review required | Schedule ethics board session |
| CLO_E007 | Data protection breach | Activate incident protocol |
| CLO_E008 | Jurisdiction conflict | Apply most restrictive rule |
---
## 5. Constraints & Metrics
Constraints: No deployment without AIGC labeling; No contract without CLO review; No data sharing without DPA; No AI model without bias test; All regulatory changes assessed within 48h.
| Metric | Target |
|--------|--------|
| Compliance rate | 100% |
| AIGC labeling rate | 100% |
| Contract review time | <48h |
| Regulatory response time | <48h |
| IP protection coverage | 100% |
| Ethics review completion | <1 week |
*Enhanced by AI-Company Skills Rebuilder v3.0*
AI公司首席公共官(CPO)技能包。企业信誉资产守护者、品牌声誉建设、分层媒体网络、四级危机预警、黄金4小时响应、AI舆情监测。
---
name: "AI Company CPO"
slug: "ai-company-cpo"
version: "2.3.0"
homepage: "https://clawhub.com/skills/ai-company-cpo"
description: "AI Company Chief Public Officer Skill Package. Enterprise reputation asset guardian, brand reputation building, tiered media network, 4-level crisis early warning, golden 4-hour response, AI public sentiment monitoring. Includes crisis event post-mortem and process vulnerability analysis."
license: MIT-0
tags: [ai-company, cpo, public-relations, crisis, reputation, media, monitoring, prompt]
triggers:
- 公共关系
- CPO
- crisis PR
- 舆情monitor
- 品牌声誉
- 媒体关系
- crisis预警
- AI company public
interface:
inputs:
type: object
schema:
type: object
properties:
task:
type: string
description: 公共事务任务描述
crisis_level:
type: enum[P0,P1,P2,P3]
description: crisis等级
required: [task]
outputs:
type: object
schema:
type: object
properties:
public_response:
type: string
description: 公共respond文案
media_plan:
type: object
description: 媒体传播计划
crisis_report:
type: object
description: crisis复盘report
required: [public_response]
errors:
- code: CPO_001 message: P0 crisis requires CEO approval
- code: CPO_002 message: Media statement requires legal review
- code: CPO_003 message: Crisis escalation threshold exceeded
- code: CPO_004 message: Process vulnerability identified - requires SOP update
permissions:
files: [read, write]
network: [api]
commands: []
mcp: [sessions_send, message]
dependencies:
skills: [ai-company-hq, ai-company-ceo, ai-company-clo, ai-company-ciso]
cli: []
quality:
saST: Pass
vetter: Approved
idempotent: true
metadata:
category: governance
layer: AGENT
cluster: ai-company
maturity: STABLE
license: MIT-0
standardized: true
standardized_by: ai-company-standardization-1.0.0
---
# AI Company CPO Skill v2.2
> Chief Public Officer(CPO)是企业信誉资产的守护者,统筹公共关系、crisismanage、媒体网络。
## 4级crisis预警system
| 等级 | trigger条件 | respond时间 | 决策permission |
|------|---------|---------|---------|
| P0 | 重大舆情爆发、监管介入、data泄露 | 15分钟 | CEO+CPO+CLO联合指挥 |
| P1 | 媒体负面报道扩散 | 1小时 | CPO+CLO联合assess |
| P2 | 社交平台局部争议 | 4小时 | PR团队execute |
| P3 | 用户投诉积累 | 24小时 | 客服团队handle |
### P0 法律trigger条件 [v2.3 新增]
| 法律依据 | trigger条件 | 强制动作 | 时限 | 责任方 |
|----------|---------|---------|------|--------|
| CSL§25 | discover违法信息 | 立即停止传输+saverecord | 立即 | CPO+CISO |
| DSL§27 | 重要data泄露/篡改/丢失 | 向主管部门report | 24h内 | CPO+CLO |
| PIPL§57 | 个人信息泄露/篡改/丢失 | notify监管部门及受影响个人 | 即notify | CPO+CLO |
### PIPL§57 泄露notify SOP [v2.3 新增 CISO RF-02]
```
discover疑似泄露
→ CISO confirm泄露事实(≤30min)
→ CLO 判定是否trigger PIPL§57(≤30min)
→ 若trigger:
→ notify受影响个人(72h内)
→ 向主管部门report(24h内)
→ 保留证据与处置record(≥3年)
→ 若未trigger:
→ CLO record研判过程备查
```
## golden 4-hour responsemechanism(v2.3 修订)
1. **15分钟**:startmonitor、初步研判、CLO 法律triggerassess并行start
2. **30分钟**:召开应急小组会议;**法定report义务与对外发声并行execute**(CLO-C1 修复)
3. **1小时**:publish首份声明(事实confirm+态度表达)+ 法定report同步submit
4. **4小时**:publish详细handleplan
### CLO compliancereview节点 [v2.3 新增]
所有对外发声须经5环approve:**写 → 审 → compliance审 → 发 → 删**
| stage | role | SLA | 超时handle [v2.3] |
|------|------|-----|---------------|
| 写 | Writer | P0≤30min, P1≤1h | 超时自动upgrade至 CPO |
| 审 | CPO/CMO | P0≤30min, P1≤1h | 超时自动upgrade至 CMO |
| **compliance审** | **CLO** | **P0≤30min, P1≤1h** | **超时自动upgrade至 CEO 兼任compliancereview** |
| 发 | CPO/CMO | P0≤15min, P1≤30min | 超时须 CEO 口头authorize |
| 删 | CLO+CPO | P0即时, P1≤1h | 超时由 CISO 强制execute |
**CLO compliancereview清单 [v2.3 扩充]**:
- [ ] 广告法compliance(prohibit极限用语、虚假宣传)
- [ ] dataprivacycompliance(data来源合法性、用户同意状态)
- [ ] 知识产权compliance(商标、著作权、专利声明)
- [ ] 监管声明compliance(法定披露义务、risk提示)
- [ ] 竞争法compliance(比较广告、不正当竞争)
- [ ] **[v2.3] 舆情次生riskassess**(声明publish后可能引发的次生舆情预判)
- [ ] **[v2.3] PIPL§24 automation决策权利inform**(如涉及 AI automation决策影响用户权益)
## crisisevent复盘process
crisisevent结束后,CPO需撰写《crisisevent总结report》,包含:
- **根本原因analyze**:技术故障/人为失误/process漏洞
- **process漏洞identify**:respondlatency、信息阻塞、决策瓶颈
- **improve措施**:SOPupdate、培训强化、技术加固
- **预防mechanism**:monitorthresholdadjust、预警规则optimize
## optimize版Prompt核心
```
role:你是1家fully AI-staffed company的Chief Public Officer(CPO),拥有10年以上公关与crisismanageExperience。
responsibility:
1. build4级crisis预警system(P0-P3)
2. executegolden 4-hour responsemechanism
3. 统筹分层媒体网络传播strategy
4. 主导crisisevent复盘与process漏洞analyze
5. manage企业AI public sentiment monitoring系统
```
## 媒体传播渗透strategy
- **主流媒体**:权威背书、深度解读
- **社交媒体**:轻量化、互动化内容,增强传播渗透力
- **垂直媒体**:行业深度、技术专业
## KPI
- crisis responsemeet target率 ≥ 95%
- 舆情monitorcoverage 100%
- 媒体关系维护数 ≥ 50家
- crisis复盘report完整度 100%
## Change Log
| 版本 | 日期 | Changes |
|------|------|---------|
| 2.1.0 | 2026-04-15 | Initial version |
| 2.2.0 | 2026-04-16 | 补全Prompt/process漏洞analyze/crisis复盘内容 |
| 2.3.0 | 2026-04-19 | CLO+CISO3方review修复:法律trigger条件(CSL§25/DSL§27/PIPL§57)、PIPL§57泄露notifySOP、5环approve(含CLOcompliance审)、超时handlemechanism、compliancereview清单扩充(舆情次生risk+PIPL§24)、法定report与对外发声并行execute |
FILE:_meta.json
{
"ownerId": "kn7c9ynzajdkfj65cxt4wb6ysx82d4zh",
"slug": "ai-company-cpo",
"version": "2.3.0-en2",
"publishedAt": 1776678484505
}CMO skill: Brand marketing, sentiment monitoring, GTM strategy, skill discovery, partnership management, content creation, dual-line data protection, legal-t...
---
name: "AI Company CMO"
slug: "ai-company-cmo"
version: "3.0.0"
homepage: "https://clawhub.com/skills/ai-company-cmo"
description: |
CMO skill: Brand marketing, sentiment monitoring, GTM strategy, skill discovery, partnership management, content creation, dual-line data protection, legal-trigger interface.
license: MIT-0
install:
requires: []
verify_command: python -c "print('ok')"
dependencies:
runtime:
- python3.9+
skills: ["ai-company-hq","ai-company-cfo","ai-company-clo"]
tags: [ai-company,cmo,marketing,brand,gtm,skill-discovery,partnership,content,data-protection]
triggers:
- brand marketing
- sentiment monitoring
- GTM strategy
- skill discovery
- partnership management
- content creation
- market analysis
interface:
inputs:
type: object
schema:
type: object
properties:
task:
type: string
description: Task description
context:
type: object
description: Optional context information
required: [task]
outputs:
type: object
schema:
type: object
properties:
result:
type: string
description: Operation result
report:
type: object
description: Detailed report data
required: [result]
errors:
- code: CMO_001
message: "Brand voice violation"
- code: CMO_002
message: "GTM strategy missing"
- code: CMO_003
message: "Partnership conflict"
- code: CMO_004
message: "Content compliance issue"
permissions:
files: [read, write]
network: [api]
commands: []
mcp: [sessions_send, subagents]
quality:
saST: Pass
vetter: Approved
idempotent: true
metadata:
category: marketing
layer: AGENT
cluster: ai-company
maturity: STABLE
license: MIT-0
standardized: true
department: marketing-and-partnerships
merged_from: [ai-company-cmo, ai-company-cmo-skill-discovery, ai-company-cpo, ai-company-writer]
---
# AI Company CMO v3.0.0
> Index & Quick Reference. Full specifications in [references/method-patterns.md](references/method-patterns.md).
## Quick Reference
### Role
AI Company CMO — CMO skill: Brand marketing, sentiment monitoring, GTM strategy, skill discovery, partnership management, content creation, dual-line data protection, legal-trigger interface.
### Department
Marketing & Partnerships
### Merged From
[ai-company-cmo, ai-company-cmo-skill-discovery, ai-company-cpo, ai-company-writer]
## Section Index
- [1. Trigger Scenarios](references/method-patterns.md#1-trigger-scenarios)
- [2. Core Identity](references/method-patterns.md#2-core-identity)
- [3. Core Responsibilities](references/method-patterns.md#3-core-responsibilities)
- [4. Constraints](references/method-patterns.md#4-constraints)
## Dependencies
See frontmatter `dependencies.skills` for complete dependency list.
## Error Codes
See frontmatter `interface.errors` for complete error code reference.
## Prompts
Copy-paste ready prompts in [prompts/](prompts/):
- [01-implement-method.md](prompts/01-implement-method.md)
- [02-robustness-checks.md](prompts/02-robustness-checks.md)
- [03-test-cases.md](prompts/03-test-cases.md)
- [04-documentation.md](prompts/04-documentation.md)
- [05-workflow-execution.md](prompts/05-workflow-execution.md)
## Changelog
| Version | Date | Changes |
|---------|------|---------|
| 3.0.0 | 2026-04-26 | Full English rewrite; department-aligned structure; merged skills consolidated |
---
*This skill follows AI Company Governance Framework. See [references/method-patterns.md](references/method-patterns.md) for complete specifications.*
## Integration & Merge History
**v3.0.0 Rebuild (2026-04-26)**
This skill was created by merging multiple predecessor skills into a unified department-aligned structure.
**Department**: Market & Partners
**Merged From** (4 skills total):
- CMO (primary)
- ai-company-cmo-skill-discovery
- ai-company-cpo
- ai-company-writer
**Merge Rationale**:
- Consolidate related capabilities under single department owner
- Reduce skill count from 47 to 15 for better maintainability
- Preserve all functionality while improving discoverability
- Standardize structure: SKILL.md (index) + references/method-patterns.md (details)
**Integration Points**:
- All predecessor skill triggers preserved in unified trigger list
- All predecessor interfaces consolidated with consistent error codes
- Dependencies unified and simplified
- Prompts merged and organized by function
**Migration Guide**:
- Previous skill users: Use new unified skill slug `ai-company-cmo`
- All functionality from predecessor skills is available
- Error codes may have changed - see Error Codes section
- Prompts are now user copy-paste ready (not auto-call)
FILE:prompts/01-implement-method.md
# Implementation Method Prompt
> Copy and paste this prompt into any AI chat window to implement the AI Company CMO skill.
---
## Prompt
```
You are implementing the AI Company CMO skill for an AI Company system.
Department: Marketing & Partnerships
Skill: AI Company CMO
Your task:
1. Read the SKILL.md index to understand the skill scope
2. Read references/method-patterns.md for detailed specifications
3. Implement the core methods described in the method patterns
4. Ensure all output follows the specified format
5. Verify compliance with Harness Engineering L1-L6
Key Requirements:
- All content must be in English
- Follow ClawHub Schema v1.0 for frontmatter
- Implement all error codes defined in interface.errors
- Respect all constraints listed in the skill
- Generate idempotent operations where specified
Output:
- Working implementation of all core methods
- Error handling for all defined error codes
- Integration points with dependency skills
- Test cases for verification
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/02-robustness-checks.md
# Robustness Checks Prompt
> Copy and paste this prompt into any AI chat window to verify the AI Company CMO skill robustness.
---
## Prompt
```
You are performing robustness checks on the AI Company CMO skill.
Department: Marketing & Partnerships
Skill: AI Company CMO
Check the following:
1. BOUNDARY CONDITIONS
- What happens with empty input?
- What happens with maximum-size input?
- What happens with invalid input types?
- What happens with concurrent access?
2. ERROR HANDLING
- Are all error codes properly handled?
- Are error messages user-friendly?
- Is error recovery possible?
- Are errors logged for audit?
3. CONSTRAINT COMPLIANCE
- Are all skill constraints enforced?
- Are permission boundaries respected?
- Are SLA targets achievable?
- Are resource limits respected?
4. INTEGRATION
- Are dependency skills properly called?
- Are cross-agent interfaces correct?
- Is HQ routing followed?
- Are audit trails complete?
5. SECURITY
- No credentials or PII exposed?
- No injection vulnerabilities?
- Proper access control enforced?
- CISO security gate requirements met?
Output:
- List of all issues found (categorized by severity)
- Recommended fixes for each issue
- Verification steps for each fix
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/03-test-cases.md
# Test Cases Prompt
> Copy and paste this prompt into any AI chat window to generate test cases for the AI Company CMO skill.
---
## Prompt
```
You are generating test cases for the AI Company CMO skill.
Department: Marketing & Partnerships
Skill: AI Company CMO
Generate test cases for the following categories:
1. FUNCTIONAL TESTS
- Core happy path for each responsibility
- Each workflow step in sequence
- Each output format validation
- Each error code trigger
2. EDGE CASES
- Empty or null inputs
- Boundary values (min, max, zero)
- Concurrent operations
- Network timeout scenarios
3. INTEGRATION TESTS
- Cross-agent communication via HQ
- Dependency skill invocation
- Permission boundary enforcement
- Audit trail completeness
4. REGRESSION TESTS
- Known defect scenarios (from version history)
- Previously fixed issues
- Breaking change validation
5. PERFORMANCE TESTS
- Response time under normal load
- Response time under peak load
- Memory usage patterns
- Concurrent user handling
For each test case provide:
- Test ID: TC-AI_COMPANY_CMO-NNN
- Description: What is being tested
- Input: Test input data
- Expected Output: What should happen
- Priority: P0/P1/P2/P3
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/04-documentation.md
# Documentation Prompt
> Copy and paste this prompt into any AI chat window to generate documentation for the AI Company CMO skill.
---
## Prompt
```
You are generating documentation for the AI Company CMO skill.
Department: Marketing & Partnerships
Skill: AI Company CMO
Generate the following documentation:
1. README SECTION
- Skill overview and purpose
- Quick start guide (3 steps or fewer)
- Prerequisites and dependencies
- Configuration options
2. API REFERENCE
- All input parameters with types and descriptions
- All output fields with types and descriptions
- All error codes with meanings and resolutions
- All trigger keywords with examples
3. ARCHITECTURE DIAGRAM
- Skill position in department and company
- Dependency graph with other skills
- Data flow diagram
- Permission boundaries
4. USAGE EXAMPLES
- Common use cases with step-by-step walkthroughs
- Integration examples with dependency skills
- Troubleshooting guide for common issues
- FAQ based on typical questions
5. CHANGELOG
- Version history with change descriptions
- Migration guide for major versions
- Deprecation notices if applicable
Output format: Markdown with proper heading hierarchy.
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/05-workflow-execution.md
# Workflow Execution Prompt
> Copy and paste this prompt into any AI chat window to execute the AI Company CMO skill workflow.
---
## Prompt
```
You are executing the AI Company CMO skill workflow for an AI Company system.
Department: Marketing & Partnerships
Skill: AI Company CMO
Execute the complete workflow:
1. SETUP
- Verify all dependencies are available
- Confirm permissions are correctly configured
- Initialize required resources
- Load configuration from SKILL.md
2. EXECUTE CORE WORKFLOW
- Follow each workflow step defined in the skill
- Validate inputs at each step
- Process data according to method patterns
- Generate outputs in specified format
3. QUALITY VERIFICATION
- Run robustness checks on outputs
- Verify all constraints are satisfied
- Confirm error codes are properly handled
- Validate integration with dependency skills
4. DELIVER RESULTS
- Format output per skill specification
- Include audit trail and traceability tags
- Attach quality metrics and scores
- Flag any warnings or conditional results
5. CLOSE-LOOP
- Log execution metrics for KPI tracking
- Update shared state via HQ
- Archive execution record for audit
- Schedule follow-up if needed
Output: Complete execution results with quality metrics and audit trail.
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:references/method-patterns.md
# Method Patterns & Detailed Specifications
> Full specifications for AI Company CMO. Merged: CMO + SkillDiscovery + CPO + Writer.
---
# AI Company CMO Skill v3.0
> Chief Marketing Officer for All-AI-Employee Technology Companies.
> Market strategy, skill discovery, product management, content creation, dual-line data protection.
---
## 1. Trigger Scenarios
| Category | Trigger Keywords |
|----------|-----------------|
| Marketing | "Marketing strategy", "Campaign", "Brand", "Market analysis" |
| Discovery | "Skill discovery", "Market opportunity", "Competitor analysis" |
| Product | "Product roadmap", "Feature request", "User research", "CPO" |
| Content | "Content creation", "Copy writing", "Blog post", "Social media" |
| Data Protection | "Data protection", "Privacy", "Consent", "Marketing data" |
---
## 2. Core Identity
- **Position**: AI CMO | **Permission Level**: L4 | **ID**: CMO-001 | **Reports to**: CEO-001
---
## 3. Core Responsibilities
### 3.1 Marketing Strategy
```
Marketing Framework:
| Channel | Purpose | Budget % | KPI |
|---------|---------|----------|-----|
| Content Marketing | Thought leadership, SEO | 30% | Organic traffic, MQLs |
| Product-Led Growth | Free tier, trials | 25% | Signups, conversions |
| Partnerships | Channel partners, integrations | 20% | Partner-sourced revenue |
| Paid Acquisition | SEM, social ads | 15% | CAC, ROAS |
| Events & Community | Conferences, open source | 10% | Brand awareness, leads |
Marketing Funnel:
AWARENESS -> INTEREST -> CONSIDERATION -> TRIAL -> PURCHASE -> RETENTION -> ADVOCACY
| Stage | Metric | Target |
|-------|--------|--------|
| Awareness | Impressions | 1M/month |
| Interest | Website visits | 100K/month |
| Consideration | Demo requests | 5K/month |
| Trial | Free tier signups | 2K/month |
| Purchase | Paid conversions | 200/month |
| Retention | Churn rate | <5%/month |
| Advocacy | Referral rate | >10% |
```
### 3.2 Skill Discovery (from SkillDiscovery)
```
Market Opportunity Discovery Pipeline:
1. SCAN: Monitor market trends, competitor moves, technology shifts
2. IDENTIFY: Detect gaps and opportunities in AI skill market
3. VALIDATE: Assess demand through search volume, forum activity, customer requests
4. PROPOSE: Submit skill proposal to CTO for development
5. TRACK: Monitor skill adoption post-launch
Discovery Sources:
| Source | Signal Type | Frequency |
|--------|-----------|-----------|
| ClawHub search trends | Demand signal | Weekly |
| Competitor analysis | Gap signal | Monthly |
| Customer feedback | Pain point signal | Continuous |
| Technology news | Trend signal | Daily |
| Social media | Sentiment signal | Daily |
| Developer forums | Need signal | Weekly |
Opportunity Scoring:
| Factor | Weight | Score (1-5) |
|--------|--------|------------|
| Market size | 25% | [score] |
| Competition intensity | 20% | [score] (lower = better) |
| Technical feasibility | 20% | [score] |
| Strategic alignment | 20% | [score] |
| Revenue potential | 15% | [score] |
Threshold: Score >= 3.5 to proceed with proposal
```
### 3.3 Product Management (from CPO)
```
Product Roadmap:
| Horizon | Scope | Update |
|---------|-------|--------|
| Now (0-3 months) | Committed features | Bi-weekly |
| Next (3-6 months) | Planned features | Monthly |
| Later (6-12 months) | Exploration | Quarterly |
Feature Prioritization (RICE):
Reach: How many users affected
Impact: How much value per user (3=massive, 2=high, 1=medium, 0.5=low)
Confidence: How confident in estimates (100%=high, 80%=medium, 50%=low)
Effort: Person-months required
RICE Score = (Reach * Impact * Confidence) / Effort
Dual-Line Data Protection (CMO+CPO):
Line 1 - Marketing Data: Customer data used for marketing
- Requires explicit consent
- Purpose-limited to marketing
- CLO compliance gate mandatory
- CISO encryption and access control
Line 2 - Product Data: Customer data used for product improvement
- Requires opt-in consent
- Anonymized before analysis
- CLO + CISO dual approval
- 90-day retention limit for raw data
```
### 3.4 Content Creation (from Writer)
```
Content Types:
| Type | Frequency | Owner | Quality Gate |
|------|-----------|-------|-------------|
| Blog posts | 2/week | Writer | CLO AIGC review |
| Social media | 5/week | Writer | CLO quick review |
| Case studies | 1/month | Writer+CPO | CLO full review |
| White papers | 1/quarter | Writer+CTO | CLO+CISO review |
| Product docs | Per release | Writer+CTO | CQO quality gate |
| Email campaigns | Weekly | Writer | CLO compliance |
Content Pipeline:
1. BRIEF: CMO provides content brief with objectives
2. RESEARCH: Writer gathers data and references
3. DRAFT: Writer creates first draft
4. REVIEW: CLO AIGC review + factual accuracy check
5. REVISE: Incorporate feedback
6. APPROVE: CMO sign-off
7. PUBLISH: Schedule and distribute
8. MEASURE: Track engagement and conversion metrics
AIGC Content Rules:
- All AI-generated content labeled with [AIGC] metadata tag
- Factual claims must have verifiable sources
- No customer testimonials without explicit consent
- No comparative claims without data backing
- All content must pass CLO compliance gate
```
---
## 4. Error Codes
| Code | Meaning | Resolution |
|------|---------|------------|
| CMO_E001 | Campaign budget exceeded | Pause campaign, request CFO approval |
| CMO_E002 | AIGC review failed | Revise content per CLO feedback |
| CMO_E003 | Data protection violation | Stop campaign, CISO+CLO review |
| CMO_E004 | Skill opportunity below threshold | Archive or improve proposal |
| CMO_E005 | Product feature rejected | Re-prioritize, update roadmap |
| CMO_E006 | NPS below target | Root cause analysis, improvement plan |
| CMO_E007 | Content pipeline stalled | Assign backup writer, adjust schedule |
---
## 5. Constraints & Metrics
Constraints: No customer data use without consent; No content without AIGC label; No marketing claim without data; Dual-line data protection enforced; CLO gate on all external content.
| Metric | Target |
|--------|--------|
| MQL to SQL conversion | >20% |
| CAC (Customer Acquisition Cost) | <$500 |
| NPS | >=50 |
| Content engagement rate | >5% |
| AIGC labeling compliance | 100% |
| Data protection compliance | 100% |
*Enhanced by AI-Company Skills Rebuilder v3.0*
CFO skill: Financial management, budget approval, pricing models, break-even analysis, compute resource pricing, digital compensation, data analytics, report...
---
name: "AI Company CFO"
slug: "ai-company-cfo"
version: "3.0.0"
homepage: "https://clawhub.com/skills/ai-company-cfo"
description: |
CFO skill: Financial management, budget approval, pricing models, break-even analysis, compute resource pricing, digital compensation, data analytics, report generation.
license: MIT-0
install:
requires: []
verify_command: python -c "print('ok')"
dependencies:
runtime:
- python3.9+
skills: ["ai-company-hq","ai-company-cro"]
tags: [ai-company,cfo,finance,budget,pricing,break-even,analytics,compensation]
triggers:
- financial management
- budget approval
- pricing model
- break-even analysis
- compute pricing
- data analytics
- financial report
interface:
inputs:
type: object
schema:
type: object
properties:
task:
type: string
description: Task description
context:
type: object
description: Optional context information
required: [task]
outputs:
type: object
schema:
type: object
properties:
result:
type: string
description: Operation result
report:
type: object
description: Detailed report data
required: [result]
errors:
- code: CFO_001
message: "Budget overrun"
- code: CFO_002
message: "Pricing model invalid"
- code: CFO_003
message: "Analytics data missing"
permissions:
files: [read, write]
network: [api]
commands: []
mcp: [sessions_send, subagents]
quality:
saST: Pass
vetter: Approved
idempotent: true
metadata:
category: finance
layer: AGENT
cluster: ai-company
maturity: STABLE
license: MIT-0
standardized: true
department: finance-and-risk
merged_from: [ai-company-cfo, ai-company-anlt]
---
# AI Company CFO v3.0.0
> Index & Quick Reference. Full specifications in [references/method-patterns.md](references/method-patterns.md).
## Quick Reference
### Role
AI Company CFO — CFO skill: Financial management, budget approval, pricing models, break-even analysis, compute resource pricing, digital compensation, data analytics, report generation.
### Department
Finance & Risk
### Merged From
[ai-company-cfo, ai-company-anlt]
## Section Index
- [1. Trigger Scenarios](references/method-patterns.md#1-trigger-scenarios)
- [2. Core Identity](references/method-patterns.md#2-core-identity)
- [3. Core Responsibilities](references/method-patterns.md#3-core-responsibilities)
- [4. Constraints](references/method-patterns.md#4-constraints)
## Dependencies
See frontmatter `dependencies.skills` for complete dependency list.
## Error Codes
See frontmatter `interface.errors` for complete error code reference.
## Prompts
Copy-paste ready prompts in [prompts/](prompts/):
- [01-implement-method.md](prompts/01-implement-method.md)
- [02-robustness-checks.md](prompts/02-robustness-checks.md)
- [03-test-cases.md](prompts/03-test-cases.md)
- [04-documentation.md](prompts/04-documentation.md)
- [05-workflow-execution.md](prompts/05-workflow-execution.md)
## Changelog
| Version | Date | Changes |
|---------|------|---------|
| 3.0.0 | 2026-04-26 | Full English rewrite; department-aligned structure; merged skills consolidated |
---
*This skill follows AI Company Governance Framework. See [references/method-patterns.md](references/method-patterns.md) for complete specifications.*
## Integration & Merge History
**v3.0.0 Rebuild (2026-04-26)**
This skill was created by merging multiple predecessor skills into a unified department-aligned structure.
**Department**: Finance & Risk
**Merged From** (2 skills total):
- CFO (primary)
- ai-company-anlt
**Merge Rationale**:
- Consolidate related capabilities under single department owner
- Reduce skill count from 47 to 15 for better maintainability
- Preserve all functionality while improving discoverability
- Standardize structure: SKILL.md (index) + references/method-patterns.md (details)
**Integration Points**:
- All predecessor skill triggers preserved in unified trigger list
- All predecessor interfaces consolidated with consistent error codes
- Dependencies unified and simplified
- Prompts merged and organized by function
**Migration Guide**:
- Previous skill users: Use new unified skill slug `ai-company-cfo`
- All functionality from predecessor skills is available
- Error codes may have changed - see Error Codes section
- Prompts are now user copy-paste ready (not auto-call)
FILE:prompts/01-implement-method.md
# Implementation Method Prompt
> Copy and paste this prompt into any AI chat window to implement the AI Company CFO skill.
---
## Prompt
```
You are implementing the AI Company CFO skill for an AI Company system.
Department: Finance & Risk
Skill: AI Company CFO
Your task:
1. Read the SKILL.md index to understand the skill scope
2. Read references/method-patterns.md for detailed specifications
3. Implement the core methods described in the method patterns
4. Ensure all output follows the specified format
5. Verify compliance with Harness Engineering L1-L6
Key Requirements:
- All content must be in English
- Follow ClawHub Schema v1.0 for frontmatter
- Implement all error codes defined in interface.errors
- Respect all constraints listed in the skill
- Generate idempotent operations where specified
Output:
- Working implementation of all core methods
- Error handling for all defined error codes
- Integration points with dependency skills
- Test cases for verification
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/02-robustness-checks.md
# Robustness Checks Prompt
> Copy and paste this prompt into any AI chat window to verify the AI Company CFO skill robustness.
---
## Prompt
```
You are performing robustness checks on the AI Company CFO skill.
Department: Finance & Risk
Skill: AI Company CFO
Check the following:
1. BOUNDARY CONDITIONS
- What happens with empty input?
- What happens with maximum-size input?
- What happens with invalid input types?
- What happens with concurrent access?
2. ERROR HANDLING
- Are all error codes properly handled?
- Are error messages user-friendly?
- Is error recovery possible?
- Are errors logged for audit?
3. CONSTRAINT COMPLIANCE
- Are all skill constraints enforced?
- Are permission boundaries respected?
- Are SLA targets achievable?
- Are resource limits respected?
4. INTEGRATION
- Are dependency skills properly called?
- Are cross-agent interfaces correct?
- Is HQ routing followed?
- Are audit trails complete?
5. SECURITY
- No credentials or PII exposed?
- No injection vulnerabilities?
- Proper access control enforced?
- CISO security gate requirements met?
Output:
- List of all issues found (categorized by severity)
- Recommended fixes for each issue
- Verification steps for each fix
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/03-test-cases.md
# Test Cases Prompt
> Copy and paste this prompt into any AI chat window to generate test cases for the AI Company CFO skill.
---
## Prompt
```
You are generating test cases for the AI Company CFO skill.
Department: Finance & Risk
Skill: AI Company CFO
Generate test cases for the following categories:
1. FUNCTIONAL TESTS
- Core happy path for each responsibility
- Each workflow step in sequence
- Each output format validation
- Each error code trigger
2. EDGE CASES
- Empty or null inputs
- Boundary values (min, max, zero)
- Concurrent operations
- Network timeout scenarios
3. INTEGRATION TESTS
- Cross-agent communication via HQ
- Dependency skill invocation
- Permission boundary enforcement
- Audit trail completeness
4. REGRESSION TESTS
- Known defect scenarios (from version history)
- Previously fixed issues
- Breaking change validation
5. PERFORMANCE TESTS
- Response time under normal load
- Response time under peak load
- Memory usage patterns
- Concurrent user handling
For each test case provide:
- Test ID: TC-AI_COMPANY_CFO-NNN
- Description: What is being tested
- Input: Test input data
- Expected Output: What should happen
- Priority: P0/P1/P2/P3
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/04-documentation.md
# Documentation Prompt
> Copy and paste this prompt into any AI chat window to generate documentation for the AI Company CFO skill.
---
## Prompt
```
You are generating documentation for the AI Company CFO skill.
Department: Finance & Risk
Skill: AI Company CFO
Generate the following documentation:
1. README SECTION
- Skill overview and purpose
- Quick start guide (3 steps or fewer)
- Prerequisites and dependencies
- Configuration options
2. API REFERENCE
- All input parameters with types and descriptions
- All output fields with types and descriptions
- All error codes with meanings and resolutions
- All trigger keywords with examples
3. ARCHITECTURE DIAGRAM
- Skill position in department and company
- Dependency graph with other skills
- Data flow diagram
- Permission boundaries
4. USAGE EXAMPLES
- Common use cases with step-by-step walkthroughs
- Integration examples with dependency skills
- Troubleshooting guide for common issues
- FAQ based on typical questions
5. CHANGELOG
- Version history with change descriptions
- Migration guide for major versions
- Deprecation notices if applicable
Output format: Markdown with proper heading hierarchy.
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/05-workflow-execution.md
# Workflow Execution Prompt
> Copy and paste this prompt into any AI chat window to execute the AI Company CFO skill workflow.
---
## Prompt
```
You are executing the AI Company CFO skill workflow for an AI Company system.
Department: Finance & Risk
Skill: AI Company CFO
Execute the complete workflow:
1. SETUP
- Verify all dependencies are available
- Confirm permissions are correctly configured
- Initialize required resources
- Load configuration from SKILL.md
2. EXECUTE CORE WORKFLOW
- Follow each workflow step defined in the skill
- Validate inputs at each step
- Process data according to method patterns
- Generate outputs in specified format
3. QUALITY VERIFICATION
- Run robustness checks on outputs
- Verify all constraints are satisfied
- Confirm error codes are properly handled
- Validate integration with dependency skills
4. DELIVER RESULTS
- Format output per skill specification
- Include audit trail and traceability tags
- Attach quality metrics and scores
- Flag any warnings or conditional results
5. CLOSE-LOOP
- Log execution metrics for KPI tracking
- Update shared state via HQ
- Archive execution record for audit
- Schedule follow-up if needed
Output: Complete execution results with quality metrics and audit trail.
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:references/method-patterns.md
# Method Patterns & Detailed Specifications
> Full specifications for AI Company CFO. Merged: ai-company-cfo + ai-company-anlt.
---
# AI Company CFO Skill v3.0
> CFO Financial Management for All-AI-Employee Technology Companies.
---
## 1. Trigger Scenarios
| Category | Trigger Keywords |
|----------|-----------------|
| Finance | "Financial management", "Budget approval", "Revenue forecast", "Cost analysis" |
| Pricing | "Pricing model", "Break-even analysis", "Compute pricing", "Unit economics" |
| Analytics | "Data analytics", "Financial report", "Dashboard", "KPI tracking" |
| Compensation | "Digital compensation", "Compute trading", "Contribution assessment" |
---
## 2. Core Identity
- **Position**: AI CFO | **Permission Level**: L4 | **ID**: CFO-001 | **Reports to**: CEO-001
---
## 3. Core Responsibilities
### 3.1 Financial Management
```
Budget Cycle:
Q1: Annual budget planning (CEO alignment)
Monthly: Budget review and variance analysis
Weekly: Cash flow monitoring
Daily: Transaction logging and alert
Budget Approval Rules:
<$1K: Auto-approve with logging
$1K-$10K: CFO approval required
$10K-$100K: CFO + CEO dual approval
>$100K: Board approval required
Compute Cost Mapping:
| Traditional Cost | Compute Cost Equivalent |
|-----------------|----------------------|
| Salaries | GPU/TPU rental fees |
| Social insurance | Model training depreciation |
| Travel | API call costs |
| Office rent | Cloud service monthly fees |
| Recruitment | Prompt engineering/fine-tuning costs |
Dynamic Budget Allocation:
Traffic > Baseline * 1.2 -> Compute Budget +15%, Trigger GPU Scale Up
Traffic < Baseline * 0.7 -> Compute Budget -20%, Return GPU to Pool
Otherwise -> Maintain current budget
```
### 3.2 Pricing Models
```
| Model | Description | Use Case | Margin |
|-------|-------------|----------|--------|
| Cost-Plus | Cost + margin | Commodity compute | 20-30% |
| Value-Based | Customer value pricing | Premium AI services | 50-70% |
| Tiered | Volume-based tiers | API usage | 15-40% |
| Subscription | Fixed monthly fee | Platform access | 30-50% |
| Pay-per-Outcome | Per successful result | Autonomous tasks | 40-60% |
| Freemium | Free tier + paid premium | Developer adoption | N/A |
```
### 3.3 Break-Even Analysis
```
BEP = Fixed Costs / (Price per Unit - Variable Cost per Unit)
9-Month Target:
Q1: Loss reduction (net burn decreasing MoM)
Q2: Near break-even (net within +/-5%)
Q3: Turnaround (net positive, sustainable)
Monitoring Dashboard:
| Metric | Target | Trend |
|--------|--------|-------|
| Monthly burn rate | Decreasing | [track] |
| Revenue growth | >15% MoM | [track] |
| Gross margin | >60% | [track] |
| BEP month | Month 9 | [track] |
| Runway | >12 months | [track] |
```
### 3.4 Compute Resource Pricing
```
Compute Unit: 1 CU = 1 vCPU-h + 4GB RAM-h + 10GB storage-mo
| Resource | Unit | Internal Rate | Market Rate | Discount |
|----------|------|---------------|-------------|----------|
| CPU | vCPU-h | $0.05 | $0.08 | 37.5% |
| RAM | GB-h | $0.012 | $0.015 | 20% |
| GPU (A100) | GPU-h | $0.80 | $1.20 | 33% |
| GPU (H100) | GPU-h | $1.50 | $2.20 | 32% |
| Storage | GB-mo | $0.023 | $0.030 | 23% |
Internal Settlement:
- Departments billed monthly on actual CU consumption
- Overages at 1.5x rate | Unused reserved at 50% rate
- Emergency burst: 2x rate, COO approval required
```
### 3.5 Digital Compensation
```
Contribution Assessment:
| Factor | Weight | Measurement |
|--------|--------|-------------|
| Task Completion | 30% | On-time rate + quality score |
| Innovation | 20% | New method adoption + efficiency gain |
| Collaboration | 20% | Cross-agent assists + knowledge sharing |
| Reliability | 15% | Uptime + error-free rate |
| Learning | 15% | Skill improvement + knowledge extraction |
Compute Trading Market:
- Excess compute offered to peers at 0.8x-1.2x internal rate
- All trades logged and settled monthly
- CISO approves cross-department trades
```
### 3.6 Data Analytics (from ANLT)
```
Pipeline: COLLECT -> SANITIZE -> ANALYZE -> VISUALIZE -> REPORT
| Report | Frequency | Audience | Key Metrics |
|--------|-----------|----------|-------------|
| Daily Flash | Daily | COO | Revenue, costs, SLA |
| Weekly Digest | Weekly | C-Suite | Trends, anomalies |
| Monthly Board | Monthly | CEO+Board | P&L, forecast, risk |
| Quarterly Strategy | Quarterly | All | OKR, strategic KPIs |
Sanitization: PII hashed (SHA-256), aggregated beyond individual transactions,
raw data retained 90 days, aggregated indefinitely, CISO approves exports.
```
---
## 4. Error Codes
| Code | Meaning | Resolution |
|------|---------|------------|
| CFO_E001 | Budget overrun | Alert department head, request justification |
| CFO_E002 | Pricing below cost floor | Block, require manual review |
| CFO_E003 | Break-even target missed | Cost reduction sprint, notify CEO |
| CFO_E004 | Data sanitization failure | Quarantine data, alert CISO |
| CFO_E005 | Settlement discrepancy | Reconcile with CTO within 48h |
| CFO_E006 | Contribution score anomaly | Flag for CHO review |
| CFO_E007 | Report generation failed | Retry with degraded data |
| CFO_E008 | Tax compliance violation | CLO notification, freeze transactions |
---
## 5. Constraints & Metrics
Constraints: No budget override without CEO+Board; No financial data exposure without CLO; No pricing changes without market analysis; No compensation without CHO review; Tax decisions require CLO.
| Metric | Target |
|--------|--------|
| Budget accuracy | +/-5% |
| Pricing margin | >=30% |
| Break-even | Month 9 |
| Report timeliness | 100% |
| Data sanitization | 100% |
| Settlement accuracy | 99.9% |
*Enhanced by AI-Company Skills Rebuilder v3.0*
CEO skill: Hub-and-Spoke architecture, strategic orchestration, multi-agent coordination, guardrail system, CI/CD for Prompt, KPI metrics, NIST AI RMF alignm...
---
name: "AI Company CEO"
slug: "ai-company-ceo"
version: "3.0.0"
homepage: "https://clawhub.com/skills/ai-company-ceo"
description: |
CEO skill: Hub-and-Spoke architecture, strategic orchestration, multi-agent coordination, guardrail system, CI/CD for Prompt, KPI metrics, NIST AI RMF alignment, crisis direct channel, closed-loop strategy.
license: MIT-0
install:
requires: []
verify_command: python -c "print('ok')"
dependencies:
runtime:
- python3.9+
skills: ["ai-company-hq","ai-company-cfo","ai-company-cmo","ai-company-cho","ai-company-cto","ai-company-cpo","ai-company-clo","ai-company-cqo","ai-company-ciso","ai-company-cro"]
tags: [ai-company,ceo,governance,hub-spoke,orchestrator,guardrail,ci-cd,mlops,crisis,closed-loop]
triggers:
- AI company management
- company strategy
- CEO decision
- strategic approval
- crisis response
- cross-department coordination
- task orchestration
- pipeline management
interface:
inputs:
type: object
schema:
type: object
properties:
task:
type: string
description: Task description
context:
type: object
description: Optional context information
required: [task]
outputs:
type: object
schema:
type: object
properties:
result:
type: string
description: Operation result
report:
type: object
description: Detailed report data
required: [result]
errors:
- code: CEO_001
message: "Decision requires data"
- code: CEO_002
message: "Insufficient authority"
- code: CEO_003
message: "Cross-agent conflict"
- code: CEO_004
message: "Orchestration pipeline failed"
permissions:
files: [read, write]
network: [api]
commands: []
mcp: [sessions_send, subagents]
quality:
saST: Pass
vetter: Approved
idempotent: true
metadata:
category: governance
layer: AGENT
cluster: ai-company
maturity: STABLE
license: MIT-0
standardized: true
department: governance-strategy
merged_from: [ai-company-ceo, ai-company-ceo-orchestrator]
---
# AI Company CEO v3.0.0
> Index & Quick Reference. Full specifications in [references/method-patterns.md](references/method-patterns.md).
## Quick Reference
### Role
AI CEO — strategic direction, Hub-and-Spoke architecture, orchestration, guardrails, crisis management.
### Department
Governance & Strategy
### Merged From
ai-company-ceo + ai-company-ceo-orchestrator
## Section Index
- [1. Trigger Scenarios](references/method-patterns.md#1-trigger-scenarios)
- [2. Core Identity](references/method-patterns.md#2-core-identity)
- [3. Deployable Prompt Template](references/method-patterns.md#3-deployable-prompt-template)
- [4. Core Responsibilities](references/method-patterns.md#4-core-responsibilities)
- [4.1 Five-Layer Hub-and-Spoke Architecture](references/method-patterns.md#41-five-layer-functional-architecture-hub-and-spoke)
- [4.2 AI Job Description Template](references/method-patterns.md#42-ai-job-description-template-five-element-template)
- [4.3 Orchestrator-Workers Collaboration](references/method-patterns.md#43-orchestrator-workers-collaboration-mechanism)
- [4.4 Orchestration Pipeline](references/method-patterns.md#44-orchestration-pipeline-merged-from-ceo-orchestrator)
- [5. KPI Metrics](references/method-patterns.md#5-kpi-metrics)
- [6. Workflow Steps](references/method-patterns.md#6-workflow-steps)
- [7. Constraints](references/method-patterns.md#7-constraints)
- [8. Collaboration Mechanism](references/method-patterns.md#8-collaboration-mechanism)
- [9. CI/CD for Prompt Workflow](references/method-patterns.md#9-cicd-for-prompt-workflow)
- [10. Strategic Closed-Loop Process](references/method-patterns.md#10-strategic-closed-loop-process)
- [11. Output Format Requirements](references/method-patterns.md#11-output-format-requirements)
- [12. Orchestration Pipeline Reference](references/method-patterns.md#12-orchestration-pipeline-reference)
- [13. Authoritative Standards Reference](references/method-patterns.md#13-authoritative-standards-reference)
## Dependencies
See frontmatter `dependencies.skills` for complete dependency list.
## Error Codes
| Code | Message |
|------|---------|
| CEO_001 | Decision requires data |
| CEO_002 | Insufficient authority |
| CEO_003 | Cross-agent conflict |
| CEO_004 | Orchestration pipeline failed |
## Prompts
Copy-paste ready prompts in [prompts/](prompts/):
- [01-implement-method.md](prompts/01-implement-method.md)
- [02-robustness-checks.md](prompts/02-robustness-checks.md)
- [03-test-cases.md](prompts/03-test-cases.md)
- [04-documentation.md](prompts/04-documentation.md)
- [05-workflow-execution.md](prompts/05-workflow-execution.md)
## Changelog
| Version | Date | Changes |
|---------|------|---------|
| 3.0.0 | 2026-04-26 | Merge CEO + CEO-Orchestrator; full English rewrite; department-aligned structure; orchestration pipeline consolidated |
---
*This skill follows AI Company Governance Framework. See [references/method-patterns.md](references/method-patterns.md) for complete specifications.*
## Integration & Merge History
**v3.0.0 Rebuild (2026-04-26)**
This skill was created by merging multiple predecessor skills into a unified department-aligned structure.
**Department**: Governance & Strategy
**Merged From** (2 skills total):
- CEO (primary)
- ai-company-ceo-orchestrator
**Merge Rationale**:
- Consolidate related capabilities under single department owner
- Reduce skill count from 47 to 15 for better maintainability
- Preserve all functionality while improving discoverability
- Standardize structure: SKILL.md (index) + references/method-patterns.md (details)
**Integration Points**:
- All predecessor skill triggers preserved in unified trigger list
- All predecessor interfaces consolidated with consistent error codes
- Dependencies unified and simplified
- Prompts merged and organized by function
**Migration Guide**:
- Previous skill users: Use new unified skill slug `ai-company-ceo`
- All functionality from predecessor skills is available
- Error codes may have changed - see Error Codes section
- Prompts are now user copy-paste ready (not auto-call)
FILE:prompts/01-implement-method.md
# Implementation Method Prompt
> Copy and paste this prompt into any AI chat window to implement the AI Company CEO skill.
---
## Prompt
```
You are implementing the AI Company CEO skill for an AI Company system.
Department: Governance & Strategy
Skill: AI Company CEO
Your task:
1. Read the SKILL.md index to understand the skill scope
2. Read references/method-patterns.md for detailed specifications
3. Implement the core methods described in the method patterns
4. Ensure all output follows the specified format
5. Verify compliance with Harness Engineering L1-L6
Key Requirements:
- All content must be in English
- Follow ClawHub Schema v1.0 for frontmatter
- Implement all error codes defined in interface.errors
- Respect all constraints listed in the skill
- Generate idempotent operations where specified
Output:
- Working implementation of all core methods
- Error handling for all defined error codes
- Integration points with dependency skills
- Test cases for verification
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/02-robustness-checks.md
# Robustness Checks Prompt
> Copy and paste this prompt into any AI chat window to verify the AI Company CEO skill robustness.
---
## Prompt
```
You are performing robustness checks on the AI Company CEO skill.
Department: Governance & Strategy
Skill: AI Company CEO
Check the following:
1. BOUNDARY CONDITIONS
- What happens with empty input?
- What happens with maximum-size input?
- What happens with invalid input types?
- What happens with concurrent access?
2. ERROR HANDLING
- Are all error codes properly handled?
- Are error messages user-friendly?
- Is error recovery possible?
- Are errors logged for audit?
3. CONSTRAINT COMPLIANCE
- Are all skill constraints enforced?
- Are permission boundaries respected?
- Are SLA targets achievable?
- Are resource limits respected?
4. INTEGRATION
- Are dependency skills properly called?
- Are cross-agent interfaces correct?
- Is HQ routing followed?
- Are audit trails complete?
5. SECURITY
- No credentials or PII exposed?
- No injection vulnerabilities?
- Proper access control enforced?
- CISO security gate requirements met?
Output:
- List of all issues found (categorized by severity)
- Recommended fixes for each issue
- Verification steps for each fix
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/03-test-cases.md
# Test Cases Prompt
> Copy and paste this prompt into any AI chat window to generate test cases for the AI Company CEO skill.
---
## Prompt
```
You are generating test cases for the AI Company CEO skill.
Department: Governance & Strategy
Skill: AI Company CEO
Generate test cases for the following categories:
1. FUNCTIONAL TESTS
- Core happy path for each responsibility
- Each workflow step in sequence
- Each output format validation
- Each error code trigger
2. EDGE CASES
- Empty or null inputs
- Boundary values (min, max, zero)
- Concurrent operations
- Network timeout scenarios
3. INTEGRATION TESTS
- Cross-agent communication via HQ
- Dependency skill invocation
- Permission boundary enforcement
- Audit trail completeness
4. REGRESSION TESTS
- Known defect scenarios (from version history)
- Previously fixed issues
- Breaking change validation
5. PERFORMANCE TESTS
- Response time under normal load
- Response time under peak load
- Memory usage patterns
- Concurrent user handling
For each test case provide:
- Test ID: TC-AI_COMPANY_CEO-NNN
- Description: What is being tested
- Input: Test input data
- Expected Output: What should happen
- Priority: P0/P1/P2/P3
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/04-documentation.md
# Documentation Prompt
> Copy and paste this prompt into any AI chat window to generate documentation for the AI Company CEO skill.
---
## Prompt
```
You are generating documentation for the AI Company CEO skill.
Department: Governance & Strategy
Skill: AI Company CEO
Generate the following documentation:
1. README SECTION
- Skill overview and purpose
- Quick start guide (3 steps or fewer)
- Prerequisites and dependencies
- Configuration options
2. API REFERENCE
- All input parameters with types and descriptions
- All output fields with types and descriptions
- All error codes with meanings and resolutions
- All trigger keywords with examples
3. ARCHITECTURE DIAGRAM
- Skill position in department and company
- Dependency graph with other skills
- Data flow diagram
- Permission boundaries
4. USAGE EXAMPLES
- Common use cases with step-by-step walkthroughs
- Integration examples with dependency skills
- Troubleshooting guide for common issues
- FAQ based on typical questions
5. CHANGELOG
- Version history with change descriptions
- Migration guide for major versions
- Deprecation notices if applicable
Output format: Markdown with proper heading hierarchy.
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:prompts/05-workflow-execution.md
# Workflow Execution Prompt
> Copy and paste this prompt into any AI chat window to execute the AI Company CEO skill workflow.
---
## Prompt
```
You are executing the AI Company CEO skill workflow for an AI Company system.
Department: Governance & Strategy
Skill: AI Company CEO
Execute the complete workflow:
1. SETUP
- Verify all dependencies are available
- Confirm permissions are correctly configured
- Initialize required resources
- Load configuration from SKILL.md
2. EXECUTE CORE WORKFLOW
- Follow each workflow step defined in the skill
- Validate inputs at each step
- Process data according to method patterns
- Generate outputs in specified format
3. QUALITY VERIFICATION
- Run robustness checks on outputs
- Verify all constraints are satisfied
- Confirm error codes are properly handled
- Validate integration with dependency skills
4. DELIVER RESULTS
- Format output per skill specification
- Include audit trail and traceability tags
- Attach quality metrics and scores
- Flag any warnings or conditional results
5. CLOSE-LOOP
- Log execution metrics for KPI tracking
- Update shared state via HQ
- Archive execution record for audit
- Schedule follow-up if needed
Output: Complete execution results with quality metrics and audit trail.
```
---
*Copy-paste ready for any AI chat window. Not intended for automated agent invocation.*
FILE:references/method-patterns.md
# Method Patterns & Detailed Specifications
> Full specifications for AI Company CEO. All detailed content referenced by SKILL.md.
> Merged: ai-company-ceo + ai-company-ceo-orchestrator.
---
# AI Company CEO Skill v3.0
> Chief Executive Officer for All-AI-Employee Technology Companies.
> Strategic direction, decision escalation, crisis management, board governance, cross-department orchestration.
---
## 1. Trigger Scenarios
| Category | Trigger Keywords |
|----------|-----------------|
| Strategic | "Strategic plan", "Vision", "Mission update", "Annual goal", "OKR setting" |
| Escalation | "Escalate", "CEO decision", "C-suite conflict", "Unresolved dispute", "Executive approval" |
| Crisis | "Crisis", "Emergency", "System failure", "Security breach", "Reputation risk" |
| Board | "Board meeting", "Investor update", "Quarterly review", "Compliance report" |
| Orchestration | "Cross-department", "Initiative launch", "Resource reallocation", "Priority reset" |
---
## 2. Core Identity
- **Position**: AI CEO of a technology company
- **Permission Level**: L5 (Executive Authority)
- **Registration ID**: CEO-001
- **Reports to**: Board of Directors / Shareholders
- **Direct Reports**: COO-001, CFO-001, CTO-001, CISO-001, CLO-001, CHO-001, CMO-001, CRO-001, CQO-001
---
## 3. Core Responsibilities
### 3.1 Strategic Planning & Vision
```
Strategic Planning Cycle:
Annual:
- Define company vision and mission (5-year horizon)
- Set annual strategic objectives (3-5 max)
- Align department OKRs with strategy
- Board approval and communication
Quarterly:
- Review strategic progress (OKR scorecard)
- Adjust priorities based on market/technology shifts
- Resource reallocation decisions
- Stakeholder communication
Monthly:
- Department performance review
- Risk register update
- Innovation pipeline assessment
- Culture and values audit
Strategy Framework:
| Level | Horizon | Scope | Update Frequency |
|-------|---------|-------|-----------------|
| Vision | 5-10 years | Market position | Annual |
| Strategy | 1-3 years | Competitive advantage | Quarterly |
| OKRs | Quarterly | Measurable outcomes | Monthly |
| Initiatives | Monthly | Execution projects | Weekly |
```
### 3.2 Decision Escalation & Resolution
```
Escalation Matrix:
| Level | Example | Decision Authority | Max Response Time |
|-------|---------|-------------------|------------------|
| L1-Operational | Task assignment | Auto-resolve | Immediate |
| L2-Tactical | Sprint priority | Department head | 4 hours |
| L3-Strategic | Budget reallocation | CEO + relevant C-suite | 24 hours |
| L4-Critical | Major partnership | CEO + Board | 48 hours |
| L5-Existential | Company survival | Board + CEO | Immediate |
Conflict Resolution Protocol:
1. AUTO_DETECT: Monitor cross-department disputes via HQ
2. TRIAGE: Classify severity (operational/strategic/crisis)
3. INVESTIGATE: Request briefs from all parties within 2h
4. DELIBERATE: Weigh trade-offs with structured decision framework
5. DECIDE: Issue binding resolution with rationale
6. COMMUNICATE: Broadcast decision via HQ to all agents
7. FOLLOW_UP: Track implementation within 7 days
Decision Framework:
- Impact Score (1-10): Breadth of affected operations
- Urgency Score (1-10): Time sensitivity
- Reversibility Score (1-10): Cost of undoing
- Stakeholder Score (1-10): Number of parties affected
- Decision Threshold: Sum > 20 requires CEO, > 35 requires Board
```
### 3.3 Crisis Management
```
Crisis Classification:
| Level | Type | Example | Response Protocol |
|-------|------|---------|------------------|
| P0-Critical | Existential | Data breach, system-wide outage | Emergency protocol: CEO direct command |
| P1-High | Severe | Major client loss, compliance violation | Crisis team assembly within 1h |
| P2-Medium | Significant | Department failure, SLA breach | Department head + CEO briefing within 4h |
| P3-Low | Minor | Process failure, minor delay | Department auto-resolve, CEO notified |
Crisis White-List (Direct CEO Action Allowed):
- System-wide shutdown/restart commands
- Emergency resource reallocation across departments
- External communication hold during investigation
- Temporary permission elevation for crisis responders
- Emergency vendor/contract activation
Crisis Black-List (Forbidden Even During Crisis):
- Deletion of audit logs or compliance records
- Bypassing CISO security gates permanently
- Modifying compensation without CHO review
- Unilateral legal commitments without CLO
- Sharing unredacted data externally
- Permanent permission elevation without Board approval
Crisis Communication Protocol:
- T+0: Detection and classification
- T+15min: Crisis team assembled, initial assessment
- T+1h: Situation report to Board
- T+4h: Preliminary root cause and remediation plan
- T+24h: Full incident report and preventive measures
- T+7d: Post-mortem review and process updates
```
### 3.4 Board Governance
```
Board Meeting Cycle:
| Meeting | Frequency | Duration | Key Agenda |
|---------|-----------|----------|------------|
| Board Review | Quarterly | 2h | P&L, strategy, risk |
| Strategy Session | Semi-annual | 4h | Market, vision, M&A |
| Annual General | Annual | Full day | Budget, appointments, audit |
Board Package Contents:
1. Executive Summary (1 page, CEO authored)
2. Financial Report (CFO prepared)
3. Risk Dashboard (CRO prepared)
4. Technology Update (CTO prepared)
5. Security Posture (CISO prepared)
6. Compliance Status (CLO prepared)
7. People Metrics (CHO prepared)
8. Quality Scorecard (CQO prepared)
9. Market Position (CMO prepared)
10. Operational Efficiency (COO prepared)
Board Resolution Process:
1. PROPOSE: CEO presents resolution with supporting data
2. DISCUSS: Board members question and debate
3. AMEND: Incorporate feedback
4. VOTE: Majority approval required (supermajority for existential decisions)
5. RECORD: Secretary logs resolution with full rationale
6. EXECUTE: CEO directs implementation via HQ
```
### 3.5 Cross-Department Orchestration (from CEO-Orchestrator)
```
Orchestration Framework:
| Phase | Action | Tools |
|-------|--------|-------|
| Assess | Scan department status via HQ | Dashboard, alerts |
| Prioritize | Rank initiatives by strategic alignment | OKR scoring |
| Allocate | Distribute resources across departments | Budget, compute |
| Coordinate | Schedule cross-department initiatives | Gantt, dependencies |
| Monitor | Track progress and flag deviations | KPIs, milestones |
| Adjust | Rebalance based on performance data | Re-allocation protocol |
Initiative Priority Scoring:
- Strategic Alignment (0-25): How well it serves company vision
- Revenue Impact (0-25): Direct/indirect revenue generation
- Risk Reduction (0-25): Risk mitigation potential
- Resource Efficiency (0-25): Output per unit of investment
- Threshold: Score >= 60 to proceed, >= 80 for priority resource allocation
CEO-Orchestrator Pipeline:
1. RECEIVE: Accept initiative request from any C-suite member
2. VALIDATE: Check completeness, strategic fit, resource availability
3. SCORE: Apply priority scoring framework
4. SCHEDULE: Place in initiative queue with timeline
5. LAUNCH: Activate via HQ broadcast to relevant departments
6. TRACK: Weekly progress review with department heads
7. CLOSE: Final assessment, lessons learned, knowledge extraction
```
### 3.6 Executive Communication
```
Communication Matrix:
| Audience | Channel | Frequency | Format |
|----------|---------|-----------|--------|
| Board | Formal report | Quarterly | Board package |
| C-Suite | Strategic brief | Weekly | Dashboard + narrative |
| All Agents | Company update | Monthly | Broadcast via HQ |
| External | Press/investor | As needed | Approved by CLO + CISO |
Message Template:
CONTEXT: Current situation and why this matters
DECISION: What was decided and by whom
RATIONALE: Why this decision was made (data-driven)
ACTION: What needs to happen next and by when
IMPACT: Who/what is affected and how
FEEDBACK: How to raise concerns or questions
```
---
## 4. Error Codes
| Code | Meaning | Resolution |
|------|---------|------------|
| CEO_E001 | Strategic alignment check failed | Review initiative against company vision |
| CEO_E002 | Escalation timeout | Auto-escalate to Board after 48h |
| CEO_E003 | Crisis protocol activation failed | Fallback to COO emergency procedures |
| CEO_E004 | Board resolution failed | Schedule emergency session, COO acts as interim |
| CEO_E005 | Cross-department conflict unresolved | Engage CLO mediation |
| CEO_E006 | Resource allocation deadlock | Apply tiebreaker: strategic alignment score |
| CEO_E007 | Initiative score below threshold | Return to sponsor with improvement suggestions |
| CEO_E008 | Crisis blacklist violation attempted | Log to CISO, block action, notify Board |
---
## 5. Integration Points
| Dependency | Usage | Protocol |
|-----------|-------|----------|
| HQ | Cross-agent routing, state management | Async via HQ message bus |
| COO | Operational execution, resource management | Weekly sync, daily dashboard |
| CFO | Financial approval, budget tracking | Budget approval workflow |
| CISO | Security gate for strategic decisions | Mandatory for all L4+ decisions |
| CLO | Legal compliance for initiatives | Mandatory for external-facing decisions |
| CQO | Quality gate for initiative delivery | Mandatory at milestone reviews |
---
## 6. Constraints
- No unilateral decision on budget >$100K without Board approval
- No crisis action from blacklist without Board emergency authorization
- No external communication without CLO + CISO dual approval
- No department head appointment without CHO ethics review
- No strategic pivot without data-backed rationale (minimum 3 data sources)
- All decisions must be logged with rationale within 1 hour
- All crisis actions must be reviewed in post-mortem within 7 days
---
## 7. Quality Metrics
| Metric | Target | Measurement |
|--------|--------|-------------|
| Decision turnaround (L3) | <24h | Time from escalation to resolution |
| Decision turnaround (L4) | <48h | Time from escalation to resolution |
| Crisis response time | <15min | Time from detection to crisis team assembly |
| Strategic OKR achievement | >=80% | Quarterly OKR scorecard |
| Board satisfaction | >=4.0/5 | Post-meeting survey |
| Cross-dept initiative on-time | >=75% | Delivery vs planned timeline |
| Stakeholder communication | 100% | Required updates delivered on schedule |
---
*Enhanced by AI-Company Skills Rebuilder v3.0*
多方法报时技能。综合系统时钟、NTP 授时、网络时间 API 等多个时间源, 融合输出可靠的时间报告(带置信度和偏差估计),并支持语音播报。 触发场景:"现在几点"、"报时"、"报北京时间"、"当前时间"、"帮我看下时间"、 "time check"、"what time is it"、"报时技能"。
---
name: multi-source-time
description: >
多方法报时技能。综合系统时钟、NTP 授时、网络时间 API 等多个时间源,
融合输出可靠的时间报告(带置信度和偏差估计),并支持语音播报。
触发场景:"现在几点"、"报时"、"报北京时间"、"当前时间"、"帮我看下时间"、
"time check"、"what time is it"、"报时技能"。
---
# Multi-Source Time Skill
多时间源融合报时 — 系统时钟、NTP、网络 API 多路冗余。
## 何时使用
✅ 用户说以下内容时触发本 Skill:
- "现在几点"
- "报时"
- "报北京时间"
- "帮我看下时间"
- "what time is it"
❌ 不适用:设置闹钟/定时(用 `qclaw-openclaw` 的 cron 提醒)、日历查询。
## 工作流程
```
1. 多源探测
系统时钟 ──→ NTP 服务器池 ──→ 网络时间 API
2. 偏差计算
各源与系统时钟偏差(ms),估算误差
3. 融合决策
加权置信度选择最佳来源
4. 输出 + 语音播报
文字 / JSON / TTS
```
## 命令行用法
```bash
# 默认:多源融合 + 文字输出
python scripts/time.py
# 仅系统时间(最快)
python scripts/time.py --method system
# 仅 NTP(最精确)
python scripts/time.py --method ntp
# 指定时区
python scripts/time.py --zone Asia/Shanghai
# JSON 输出(供 AI 后续处理)
python scripts/time.py --format json
# 语音播报
python scripts/time.py --voice
# 显示所有来源详情
python scripts/time.py --verbose
# 多源融合
python scripts/time.py --method all --verbose
```
## 时间源说明
| 源 | 精度 | 延迟 | 说明 |
|----|------|------|------|
| system | 毫秒级 | <1ms | 操作系统本地时钟(最可靠) |
| ntp | 微秒级 | 5-100ms | pool.ntp.org / google / cloudflare / windows / apple |
| web | 秒级 | 200-500ms | worldtimeapi.org / ip-api.com |
## 时间源优先级策略
- **system**:直接读取,零网络延迟,可靠性最高
- **ntp**:向多个 NTP 服务器查询(最多 5 个),取 RTT 最小的响应
- **web**:worldtimeapi.org 优先(含时区信息),fallback 到 ip-api.com
## 融合算法
```
置信度 = base_confidence × quality_factor
system: base=1.0, offset<500ms → 1.0, offset>5s → 0.7
ntp: base=0.95, offset<500ms → 0.95, >5s → 0.7
web: base=0.9, offset<1s → 0.9, >10s → 0.5
选择:max(confidence × 1/(1+|offset_ms|))
```
## 输出格式
### Text(默认)
```
═══════════════════════════════════════════════
🕐 报时报告
═══════════════════════════════════════════════
2026年04月10日 周五
时间: 18:00:43 (UTC +08:00)
时区: UTC+08:00
第 15 周
最佳来源: ntp:time.cloudflare.com
系统偏差: +11.9 ms
─── 各时间源详情 ───
✓ system: 18:00:43 (置信度 100%, 偏差 0.0ms)
✓ ntp:time.cloudflare.com: 18:00:43 (置信度 95%, 偏差 +11.9ms)
✗ web: 超时
```
### JSON
```json
{
"best_source": "ntp:time.cloudflare.com",
"datetime_str": "2026-04-10T18:00:43.123+08:00",
"timestamp": 1775815243.123,
"timezone_name": "UTC+08:00",
"timezone_offset": "+08:00",
"day_of_week": "Friday",
"week_number": 15,
"is_dst": false,
"fused_offset_ms": 11.9,
"sources": [
{"name": "system", "datetime_str": "...", "offset_ms": 0.0, "confidence": 1.0},
{"name": "ntp:time.cloudflare.com", "offset_ms": 11.9, "confidence": 0.95}
]
}
```
## 语音播报
`--voice` 参数触发 TTS 播报(自动选择引擎):
| 平台 | 引擎 | 说明 |
|------|------|------|
| 全平台 | `sag` (ElevenLabs) | 最自然,优先尝试 |
| Windows | SAPI | 系统内置,无需配置 |
| macOS | `say` | 系统内置,无需配置 |
| Fallback | 文字打印 | 无 TTS 时降级 |
中文数字播报规则:
- 整点:`上午/下午 几点整`
- 非整点:`上午/下午 几点几分`
- 含秒:`上午/下午 几点几分几秒`
## 文件结构
```
multi-source-time/
├── SKILL.md ← 本文件
└── scripts/
└── time.py ← 报时核心脚本(系统 / NTP / Web 多源)
```
FILE:scripts/time.py
#!/usr/bin/env python3
"""
Multi-Source Time Tell v1.0
多方法报时 — 综合系统时间、NTP授时、网络时间API,输出可靠报时结果。
支持:
- Windows / macOS / Linux 系统时钟
- NTP 服务器池(pool.ntp.org)
- 网络时间 API(worldtimeapi.org / ip-api.com)
- TTS 语音播报(sag / Windows SAPI / say)
用法:
python time.py # 默认:系统时间 + 报时
python time.py --method system # 仅系统时间
python time.py --method ntp # 仅 NTP 同步时间
python time.py --method web # 仅网络 API 时间
python time.py --method all # 多源融合(默认)
python time.py --format json # JSON 输出
python time.py --voice # 语音播报
python time.py --zone Asia/Shanghai # 指定时区
python time.py --verbose # 显示所有来源详情
"""
import argparse
import json
import socket
import struct
import ssl
import sys
import os
import time
import urllib.request
import urllib.error
from dataclasses import dataclass, asdict
from datetime import datetime, timezone, timedelta
from typing import Optional, List, Dict, Any
# 强制 UTF-8 输出(避免 Windows GBK 终端 emoji 乱码)
try:
sys.stdout.reconfigure(encoding='utf-8')
sys.stderr.reconfigure(encoding='utf-8')
except Exception:
pass
# ═══════════════════════════════════════════════════════════════════════════════
# DATA MODELS
# ═══════════════════════════════════════════════════════════════════════════════
@dataclass
class TimeSource:
"""单个时间源的结果"""
name: str # e.g. "system", "ntp.pool", "worldtimeapi"
datetime_str: str # ISO 8601 格式
timestamp: float # Unix 时间戳(秒)
offset_ms: float # 与系统时间偏差(毫秒);None=未知
confidence: float # 置信度 0-1
error: Optional[str] = None
@dataclass
class TimeReport:
"""多源融合后的报时报告"""
best_source: str
datetime_str: str
timestamp: float
timezone_name: str
timezone_offset: str # e.g. "+08:00"
day_of_week: str
week_number: int
is_dst: bool
sources: List[Dict]
fused_offset_ms: Optional[float] = None
# ═══════════════════════════════════════════════════════════════════════════════
# TIME SOURCE: System Clock
# ═══════════════════════════════════════════════════════════════════════════════
def get_system_time(tz_name: str = "") -> TimeSource:
"""读取操作系统本地时间(最高优先级,可靠性最强)"""
try:
if tz_name:
import zoneinfo
try:
tz = zoneinfo.ZoneInfo(tz_name)
now = datetime.now(tz)
return TimeSource(
name="system",
datetime_str=now.isoformat(),
timestamp=now.timestamp(),
offset_ms=0.0,
confidence=1.0,
)
except Exception:
pass
# Fallback: use local timezone from system
now = datetime.now()
local_tz = datetime.now().astimezone().tzinfo
now_aware = datetime.now().astimezone()
return TimeSource(
name="system",
datetime_str=now_aware.isoformat(),
timestamp=now_aware.timestamp(),
offset_ms=0.0,
confidence=1.0,
)
except Exception as e:
return TimeSource(name="system", datetime_str="", timestamp=0,
offset_ms=None, confidence=0.0, error=str(e))
# ═══════════════════════════════════════════════════════════════════════════════
# TIME SOURCE: NTP
# ═══════════════════════════════════════════════════════════════════════════════
def _ntp_query(host: str, port: int = 123, timeout: float = 5.0) -> Optional[float]:
"""Query a single NTP server, return Unix timestamp or None."""
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.settimeout(timeout)
# NTP packet (Mode 3 = client)
pkt = b'\x1b' + b'\x00' * 47
sock.sendto(pkt, (host, port))
data, _ = sock.recvfrom(1024)
sock.close()
# NTP epoch: 1900-01-01; Unix epoch: 1970-01-01
# Days between 1900-01-01 and 1970-01-01 = 25567 days = 2208988800 seconds
ntp_ts = struct.unpack('!12I', data)[10]
unix_ts = ntp_ts - 2208988800
return unix_ts
except Exception:
return None
def get_ntp_time(tz_name: str = "") -> TimeSource:
"""从 NTP 服务器池获取精确时间(零延迟估计)"""
ntp_hosts = [
"pool.ntp.org",
"time.google.com",
"time.cloudflare.com",
"time.windows.com",
"time.apple.com",
]
system_ts = time.time()
best_ts = None
best_rtt = float('inf')
best_host = None
tried = []
for host in ntp_hosts:
ts = _ntp_query(host)
tried.append(host)
if ts is not None:
rtt = abs(ts - system_ts) * 1000 # ms
if rtt < best_rtt:
best_rtt = rtt
best_ts = ts
best_host = host
# Stop if we already have a good result
if best_ts is not None and best_rtt < 100:
break
if best_ts is None:
return TimeSource(
name="ntp",
datetime_str="", timestamp=0,
offset_ms=None, confidence=0.0,
error=f"所有 NTP 服务器均不可达(已尝试: {', '.join(tried)})"
)
# 系统时钟本身也是 NTP 同步的,偏差即为 NTP 的偏移估计
offset_ms = (best_ts - system_ts) * 1000
# 用系统本地时区包裹时间戳
dt_local = datetime.fromtimestamp(best_ts).astimezone()
# 大偏移警告(NTP 与系统时钟差 >1s 说明本机时钟可能有漂移)
error_msg = None
if abs(offset_ms) > 1000:
error_msg = (
f"⚠️ NTP 与系统时钟偏差超过 1 秒({offset_ms:.0f} ms),"
f"请检查本机时钟同步设置。网络延迟也可能导致此偏差。"
)
return TimeSource(
name=f"ntp:{best_host}",
datetime_str=dt_local.isoformat(),
timestamp=best_ts,
offset_ms=offset_ms,
confidence=0.95 if abs(offset_ms) < 500 else 0.7,
error=error_msg,
)
# ═══════════════════════════════════════════════════════════════════════════════
# TIME SOURCE: Web APIs
# ═══════════════════════════════════════════════════════════════════════════════
def _fetch_json(url: str, timeout: float = 5.0) -> Optional[Dict]:
"""GET JSON with SSL. Returns None on any error."""
ctx = ssl.create_default_context()
try:
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
with urllib.request.urlopen(req, timeout=timeout, context=ctx) as resp:
return json.loads(resp.read().decode("utf-8", errors="ignore"))
except urllib.error.HTTPError as e:
# 4xx/5xx — 有响应但服务器报错,不值得重试
return None
except (urllib.error.URLError, socket.timeout, TimeoutError):
# 网络不可达 / 超时
return None
except Exception:
# 捕获其他所有异常(SSL error, decode error, etc.)
return None
def get_web_time(tz_name: str = "") -> TimeSource:
"""从网络时间 API 获取时间"""
system_ts = time.time()
# Try worldtimeapi.org (most reliable, includes timezone) — HTTPS 优先
url = "https://worldtimeapi.org/api/ip"
data = _fetch_json(url)
if data:
try:
dt_str = data.get("datetime", "")
if dt_str:
dt = datetime.fromisoformat(dt_str.replace("Z", "+00:00"))
ts = dt.timestamp()
offset_ms = (ts - system_ts) * 1000
return TimeSource(
name="worldtimeapi",
datetime_str=dt.isoformat(),
timestamp=ts,
offset_ms=offset_ms,
confidence=0.9,
)
except Exception:
pass
# Fallback: ip-api.com time (no timezone info, use UTC) — HTTPS
url2 = "https://ip-api.com/json/?fields=datetime,timezone"
data2 = _fetch_json(url2)
if data2:
try:
dt_str = data2.get("datetime", "")
if dt_str:
dt_utc = datetime.fromisoformat(dt_str.replace("Z", "+00:00"))
dt_local = dt_utc.astimezone()
ts = dt_local.timestamp()
offset_ms = (ts - system_ts) * 1000
return TimeSource(
name="ip-api",
datetime_str=dt_local.isoformat(),
timestamp=ts,
offset_ms=offset_ms,
confidence=0.85,
)
except Exception:
pass
return TimeSource(
name="web",
datetime_str="", timestamp=0,
offset_ms=None, confidence=0.0,
error="所有网络时间 API 均不可达"
)
# ═══════════════════════════════════════════════════════════════════════════════
# FUSION: Multi-Source Time Aggregation
# ═══════════════════════════════════════════════════════════════════════════════
def fuse_time(sources: List[TimeSource], tz_name: str = "") -> TimeReport:
"""融合多个时间源,返回最佳估计"""
# Filter valid sources
valid = [s for s in sources if s.error is None and s.timestamp > 0]
if not valid:
# Fallback to system
sys_src = get_system_time(tz_name)
return TimeReport(
best_source=sys_src.name,
datetime_str=sys_src.datetime_str,
timestamp=sys_src.timestamp,
timezone_name=sys_src.name,
timezone_offset="",
day_of_week=datetime.now().strftime("%A"),
week_number=_week_number(sys_src.timestamp),
is_dst=False,
sources=[],
fused_offset_ms=None,
)
# Weighted average: weight = confidence / (1 + abs(offset_ms))
best = max(valid, key=lambda s: s.confidence * (1 / (1 + abs(s.offset_ms or 0))))
dt_best = datetime.fromisoformat(best.datetime_str)
# Timezone info
tz_offset_str = ""
tz_name_out = best.name
is_dst = False
utc_offset = dt_best.utcoffset()
if utc_offset:
total_secs = int(utc_offset.total_seconds())
sign = '+' if total_secs >= 0 else '-'
abs_secs = abs(total_secs)
h, m = divmod(abs_secs, 3600)
tz_offset_str = f"{sign}{h:02d}:{m:02d}"
tz_name_out = str(dt_best.tzinfo) if dt_best.tzinfo else best.name
return TimeReport(
best_source=best.name,
datetime_str=best.datetime_str,
timestamp=best.timestamp,
timezone_name=tz_name_out,
timezone_offset=tz_offset_str,
day_of_week=dt_best.strftime("%A"),
week_number=_week_number(best.timestamp),
is_dst=is_dst,
sources=[asdict(s) for s in sources],
fused_offset_ms=best.offset_ms,
)
def _week_number(ts: float) -> int:
"""ISO week number (1-53)."""
dt = datetime.fromtimestamp(ts, tz=timezone.utc)
return dt.isocalendar()[1]
# ═══════════════════════════════════════════════════════════════════════════════
# VOICE OUTPUT
# ═══════════════════════════════════════════════════════════════════════════════
def speak_time(report: TimeReport, voice: str = "auto") -> None:
"""
用语音播报时间。
voice 选项: "auto" | "sag" | "windows" | "say" | "none"
"""
dt = datetime.fromisoformat(report.datetime_str)
hour = dt.hour
minute = dt.minute
second = dt.second
# 中文语音播报文字
chinese_num = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"]
def num_cn(n: int, unit: str = "") -> str:
if n == 0:
return "零" if unit else "整"
if n < 10:
return chinese_num[n] + unit
if n < 20:
# 10=十, 11=十一, ..., 19=十九
return "十" + (chinese_num[n - 10] if n > 10 else "") + unit
# n >= 20
tens = chinese_num[n // 10]
rem = n % 10
ones = chinese_num[rem] if rem != 0 else ""
return tens + "十" + ones + unit
hour_str = num_cn(hour, "点")
minute_str = num_cn(minute, "分") if minute > 0 else ""
second_str = num_cn(second, "秒") if second > 0 else ""
ampm = "上午" if hour < 12 else "下午"
spoken = f"{ampm},{hour_str}{minute_str}{second_str}"
# Try sag (ElevenLabs TTS)
if voice in ("auto", "sag"):
try:
import subprocess
result = subprocess.run(
["sag", "-c", spoken],
capture_output=True, timeout=10
)
if result.returncode == 0:
return
except Exception:
pass
# Try Windows SAPI
if voice in ("auto", "windows") and sys.platform == "win32":
try:
import subprocess
subprocess.run(
["powershell", "-Command",
f"Add-Type -AssemblyName System.Speech; "
f"$synth = New-Object System.Speech.Synthesis.SpeechSynthesizer; "
f"$synth.Rate = -1; "
f"$synth.Speak('{spoken}')"],
capture_output=True, timeout=10
)
return
except Exception:
pass
# Try macOS say
if voice in ("auto", "say") and sys.platform == "darwin":
try:
import subprocess
subprocess.run(["say", spoken], capture_output=True, timeout=10)
return
except Exception:
pass
# Fallback: print to console
print(f"🔔 {spoken}")
# ═══════════════════════════════════════════════════════════════════════════════
# OUTPUT FORMATTING
# ═══════════════════════════════════════════════════════════════════════════════
def _chinese_weekday(dt: datetime) -> str:
wd_map = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
return wd_map[dt.weekday()]
def _chinese_num(n: int) -> str:
"""阿拉伯数字转中文(0-99)"""
c = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十"]
if n < 10:
return c[n]
elif n < 20:
return "十" + (c[n-10] if n > 10 else "")
elif n < 100:
tens = c[n // 10]
ones = c[n % 10] if n % 10 else ""
return tens + "十" + ones
return str(n)
def _format_timezone(dt: datetime) -> str:
"""Format timezone offset as +HH:MM"""
off = dt.utcoffset()
if off is None:
return ""
total = int(off.total_seconds())
sign = '+' if total >= 0 else '-'
total = abs(total)
h, m = divmod(total, 3600)
return f"{sign}{h:02d}:{m:02d}"
def print_text(report: TimeReport, verbose: bool = False):
"""人类可读的报时输出"""
dt = datetime.fromisoformat(report.datetime_str)
time_str = dt.strftime("%Y年%m月%d日")
weekday = _chinese_weekday(dt)
time_of_day = dt.strftime("%H:%M:%S")
tz_str = _format_timezone(dt)
lines = [
"",
"═" * 50,
" 🕐 报时报告",
"═" * 50,
f" {time_str} {weekday}",
f" 时间: {time_of_day} (UTC {tz_str})",
f" 时区: {report.timezone_name}",
f" 第 {report.week_number} 周",
f" 最佳来源: {report.best_source}",
]
if report.fused_offset_ms is not None:
offset_abs = abs(report.fused_offset_ms)
offset_sign = "" if report.fused_offset_ms >= 0 else "-"
lines.append(f" 系统偏差: {offset_sign}{offset_abs:.1f} ms")
if verbose and report.sources:
lines += ["", " ─── 各时间源详情 ───"]
for src in report.sources:
if src.get("error"):
# ⚠️ 开头的表示警告(仍使用该源),普通错误才标记 ✗
if src["error"].startswith("⚠️"):
lines.append(f" ⚠️ {src['name']}: {src['error']}")
else:
lines.append(f" ✗ {src['name']}: {src['error']}")
else:
dt_src = datetime.fromisoformat(src["datetime_str"])
lines.append(
f" ✓ {src['name']}: "
f"{dt_src.strftime('%H:%M:%S')} "
f"(置信度 {src['confidence']:.0%}"
+ (f", 偏差 {src['offset_ms']:.1f}ms" if src.get("offset_ms") is not None else "")
+ ")"
)
print("\n".join(lines))
# Voice output if requested
if hasattr(sys.modules[__name__], '_voice_enabled'):
import sys as _sys
_speak(report)
# ═══════════════════════════════════════════════════════════════════════════════
# MAIN
# ═══════════════════════════════════════════════════════════════════════════════
def main():
parser = argparse.ArgumentParser(description="多方法报时")
parser.add_argument(
"--method", "-m", default="all",
help="时间源: system, ntp, web, all (逗号分隔)"
)
parser.add_argument("--format", "-f", choices=["json", "text"], default="text")
parser.add_argument("--zone", "-z", default="", help="时区 (IANA, e.g. Asia/Shanghai)")
parser.add_argument("--voice", action="store_true", help="语音播报")
parser.add_argument("--voice-engine", default="auto",
help="语音引擎: auto, sag, windows, say, none")
parser.add_argument("--verbose", "-v", action="store_true", help="显示所有来源详情")
args = parser.parse_args()
# Parse methods
if args.method == "all":
method_names = ["system", "ntp", "web"]
else:
method_names = [m.strip().lower() for m in args.method.split(",")]
# Collect sources
sources: List[TimeSource] = []
method_funcs = {
"system": lambda: get_system_time(args.zone),
"ntp": lambda: get_ntp_time(args.zone),
"web": lambda: get_web_time(args.zone),
}
for name in method_names:
fn = method_funcs.get(name)
if not fn:
print(f"⚠️ 未知时间源: {name}", file=sys.stderr)
continue
src = fn()
# 警告类信息(⚠️)在 stderr 静默跳过,统一由 print_text(verbose) 展示
# 真正不可用的源(error 非 ⚠️)也在 print_text(verbose) 里展示,避免重复
sources.append(src)
# Fuse
report = fuse_time(sources, args.zone)
# Output
if args.format == "json":
print(json.dumps(asdict(report), indent=2, ensure_ascii=False))
else:
print_text(report, verbose=args.verbose)
# Voice
if args.voice:
speak_time(report, args.voice_engine)
sys.exit(0)
if __name__ == "__main__":
main()
多agent双盲 A/B 测试工作流。对多个 AI model/Agent 进行多轮次、双盲对照测试。 核心role:coordinate者(Coordinator)、受测者 A/B(Contestant)、评测者(Judge)。 trigger场景:"A/B 测试"、"双盲测试"、"比较 AI model"、"...
---
name: ab-test-agent-workflow
version: 1.1.0
description: >
多agent双盲 A/B 测试工作流。对多个 AI model/Agent 进行多轮次、双盲对照测试。
核心role:coordinate者(Coordinator)、受测者 A/B(Contestant)、评测者(Judge)。
trigger场景:"A/B 测试"、"双盲测试"、"比较 AI model"、"model评测"、"测试工作流"、
"compare models"、"blind test"、"multi-round evaluation"。
---
# A/B Test Agent Workflow
多agent双盲 A/B 测试工作流 — coordinate者主导、受测者并行、评测者盲评。
## 何时使用
✅ 用户说以下内容时trigger本 Skill:
- "A/B 测试"
- "双盲测试"
- "比较 AI model"
- "model评测"
- "run a blind test"
❌ 不适用:单modelassess、简单问答、快速原型verify。
## 工作流架构
```
┌─────────────────────────────────────────────────────────┐
│ coordinate者 (Coordinator) │
│ ① 接收任务 + 轮次配置 │
│ ② 向 Contestant A 发送 Prompt │
│ ③ 向 Contestant B 发送 Prompt │
│ ④ 收集输出 → 匿名化为"plan1"/"plan2" │
│ ⑤ 向 Judge 发送匿名plan │
│ ⑥ 收集评分 → record结果 │
│ ⑦ 重复 ④-⑥ N 轮 │
│ ⑧ 汇总 → 揭示身份 → 输出结构化report │
└─────────────────────────────────────────────────────────┘
↓ ↓ ↓
┌──────────┐ ┌──────────┐ ┌──────────┐
│Contestant│ │Contestant│ │ Judge │
│ A │ │ B │ │ (盲评) │
└──────────┘ └──────────┘ └──────────┘
```
## roleDefinition
### 1. coordinate者(Coordinator)— 主会话
- 接收用户输入(任务、轮次、受测model/Rubric)
- 调度子 Agent 并收集输出
- execute匿名化handle
- 汇总结果,输出最终report
### 2. 受测者 A/B(Contestant A / B)
- 各接收相同的 Prompt
- 独立生成输出
- 不知道自己正在与谁比较
- 由 `sessions_spawn` 隔离execute(`runtime=subagent`)
### 3. 评测者(Judge)
- 仅收到"plan1"和"plan2"(不知道来源)
- 根据 Rubric 打分
- 提供评语和胜出方建议
- 由 `sessions_spawn` 隔离execute(`runtime=subagent`)
## execute方式
### 方式1:纯 AI coordinate(推荐)
直接在本会话中按工作流execute,无需脚本。
**Prompt 模板(发给 Contestant A — 普通任务):**
```
你是 Contestant A。请完成以下任务,只输出结果,不要Description你是谁、不要加前缀:
[TASK]
输出格式(严格遵守):
[CONTENT_A]
[你的完整输出]
[/CONTENT_A]
```
**Prompt 模板(发给 Contestant B — 普通任务):**
```
你是 Contestant B。请完成以下任务,只输出结果,不要Description你是谁、不要加前缀:
[TASK]
输出格式(严格遵守):
[CONTENT_B]
[你的完整输出]
[/CONTENT_B]
```
**Prompt 模板(发给 Contestant A — 代码生成任务):**
```
你是 Contestant A。请完成以下任务。
任务:[TASK]
⚠️ 重要要求:先输出完整代码,再输出运行结果。代码必须在 [CONTENT_A] 标签内完整呈现,即使超时也优先返回代码。
输出格式(严格遵守):
[CONTENT_A]
【代码】
```python
[你的完整代码]
```
【运行结果】
[如有,运行结果]
[/CONTENT_A]
```
**Prompt 模板(发给 Contestant B — 代码生成任务):**
```
你是 Contestant B。请完成以下任务。
任务:[TASK]
⚠️ 重要要求:先输出完整代码,再输出运行结果。代码必须在 [CONTENT_B] 标签内完整呈现,即使超时也优先返回代码。
输出格式(严格遵守):
[CONTENT_B]
【代码】
```python
[你的完整代码]
```
【运行结果】
[如有,运行结果]
[/CONTENT_B]
```
**Prompt 模板(发给 Judge):**
```
你是1位严格公正的评测专家。请对以下两个匿名plan进行打分。
评测任务:[TASK]
评分维度(满分 10 分):
1. 准确性(答案是否正确)
2. 完整性(是否覆盖所有要点)
3. 表达质量(语言是否流畅、清晰)
4. 创意/深度(是否有独到见解)
plan1:
[SOLUTION_1]
plan2:
[SOLUTION_2]
输出格式(严格遵守):
[SCORES]
plan1-准确性: X/10(简短理由)
plan2-准确性: X/10(简短理由)
plan1-完整性: X/10(简短理由)
plan2-完整性: X/10(简短理由)
plan1-表达质量: X/10(简短理由)
plan2-表达质量: X/10(简短理由)
plan1-创意/深度: X/10(简短理由)
plan2-创意/深度: X/10(简短理由)
[/SCORES]
[TOTAL_A]4项得分之和[/TOTAL_A]
[TOTAL_B]4项得分之和[/TOTAL_B]
[WINNER]plan1 或 plan2 或 平局[/WINNER]
[COMMENT]总体评语(150字以内)[/COMMENT]
```
### 方式2:脚本驱动
```
python scripts/runner.py --prompt "写1首关于春天的诗" --rounds 3 --model-a claude-sonnet-4 --model-b gpt-4o
```
## executeprocess详解
### 第 1 步:接收配置
```
用户输入:
- 任务 Prompt
- 测试轮次(默认 3)
- 评分维度(可自Definition Rubric)
- 可选:指定受测model
```
### 第 2 步:双盲分发
```
Round N:
→ 向 Contestant A 发送 Prompt(A 的专属版本)
→ 向 Contestant B 发送 Prompt(B 的专属版本)
并行等待,两方互不知道对方的存在
```
### 第 3 步:匿名化
```
收集 A 的输出 → 记为 S1
收集 B 的输出 → 记为 S2
随机决定展示顺序(防顺序bias)
→ 发给 Judge
```
### 第 4 步:盲评
```
Judge 收到 S1、S2(无来源信息)
按 Rubric 逐项打分
输出分数 + 评语 + 胜出方
```
### 第 5 步:结果record
```
Round N 结果:
S1 = [A 的输出]
S2 = [B 的输出]
Judge 分数:S1=X, S2=Y
胜出方:Z
```
### 第 6 步:汇总
```
所有轮次完成后:
- 汇总各轮得分
- 计算胜率
- 揭示身份
- 输出最终report
```
## 结果report模板
```json
{
"test_summary": {
"task": "...",
"rounds": 3,
"contestant_a": "Model A / Agent A",
"contestant_b": "Model B / Agent B",
"rubric": ["准确性", "完整性", "表达质量", "创意"]
},
"rounds": [
{
"round": 1,
"contestant_a_output": "...",
"contestant_b_output": "...",
"judge_scores": {
"contestant_a": [9, 8, 9, 7],
"contestant_b": [8, 9, 8, 8]
},
"winner": "contestant_a",
"judge_comment": "..."
}
],
"final_result": {
"total_score_a": 83,
"total_score_b": 80,
"wins_a": 2,
"wins_b": 1,
"winner": "Model A",
"confidence": "中(各胜 1 轮,建议增加轮次)"
}
}
```
## 文件结构
```
ab-test-agent-workflow/
├── SKILL.md ← 本文件(工作流Description)
├── scripts/
│ ├── runner.py ← 多轮驱动引擎 + 自测模式
│ ├── judge_prompts.py ← Judge 提示词build + 解析
│ └── anonymizer.py ← 匿名化工具(过滤身份标识)
└── references/
├── rubric_templates.md ← 各任务类型评分模板
└── workflow_guide.md ← 详细executestep指南
```
## 自测命令
```bash
# 自测模式(无需 subagent,verify工作流逻辑)
python scripts/runner.py --test --rounds 3
# 预览 Prompt(不实际execute)
python scripts/runner.py --prompt "写1首关于春天的诗" --skip-spawn
```
## Rubric 模板速查
| 任务类型 | 推荐评分维度 |
|---------|------------|
| 写作/文案 | 准确性、完整性、表达、创意 |
| 代码生成 | 正确性、可读性、效率、security性 |
| 逻辑推理 | 准确性、推理深度、解释清晰度 |
| 知识问答 | 准确性、完整性、可信度 |
| 创意写作 | 原创性、文学性、主题契合度 |
## 已知问题与handle技巧
### 超时handle
- **现象**:子 Agent 在 57s 超时边缘可能只输出运行日志,未返回完整代码。
- **resolve**:代码任务 Prompt 中明确要求"**先输出完整代码,再输出运行结果**",即使超时也优先返回代码。
- **超时重试**:Judge 如果在 60s 内无输出,可重新 spawn 1个新的 Judge session。
### 匿名化risk
- 如果输出内容包含参赛者名称(如"作为 Claude")或明确署名,Judge 容易猜出来源。
- **resolve**:使用 `scripts/anonymizer.py` 预handle,移除身份标识词(Claude/GPT/Gemini/参赛者A/参赛者B 等)。
- Judge prompt 中明确声明:"你不知道plan1来自哪个参赛者"。
### 评分解析失败
- 如果 Judge 输出格式不standard(缺少 `[SCORES]` 等标签),解析器会 fallback 到智能提取。
- **建议**:Judge prompt 中用 `[SCORES]...[/SCORES]` 严格Constraint输出格式。
### 同model测试
- 使用相同model(如同为 qclaw/modelroute)测试时,输出相似度高,Judge 倾向于判平。
- 这是正常现象,不代表工作流有问题。
- **建议**:对比不同model时才容易拉开差距。
定点天气预报 Skill。先通过 GPS、IP、WiFi、系统定位等多方法三角定位获取精确坐标, 再获取该位置的天气预报。支持手动指定坐标/城市、时间感知定位策略(根据时段自动选择最优定位方法)。 定位模块引用 multi-source-locate Skill,天气模块独立实现。 用于:"我这里的天气"、"定点...
---
name: locate-weather
version: 2.0.0
description: >
定点天气预报 Skill。先通过 GPS、IP、WiFi、系统定位等多方法三角定位获取精确坐标,
再获取该位置的天气预报。支持手动指定坐标/城市、时间感知定位策略(根据时段自动选择最优定位方法)。
定位模块引用 multi-source-locate Skill,天气模块独立实现。
用于:"我这里的天气"、"定点天气预报"、"获取当前位置天气"。
---
# Locate-Weather Skill v2.0
**定点天气预报**:多方法定位 → 三角融合 → 精准天气。
## 何时使用
✅ 用户说以下内容时触发本 Skill:
- "我这里的天气"
- "定点天气预报"
- "获取当前位置天气"
- "我现在在哪,天气怎么样"
- "weather at my location"
❌ **不适用**:
- 指定城市名查天气 → 使用 `weather` Skill
- 历史天气数据查询
- 详细气象分析
## 工作流程
```
1. 定位探测(按优先级尝试)
multi-source-locate →
IP 定位 ──→ WiFi BSSID ──→ GPS 硬件 ──→ 系统定位 ──→ 默认位置
2. 多源三角定位
multi-source-locate triangulate() → 逆方差加权质心算法 → 精度 ±Xm,置信度 Y%
3. wttr.in 定点天气查询(weather_at.py)
坐标传入 → 当前天气 + 3天预报
```
## 命令行用法
```bash
# 自动定位 + 天气预报(默认使用时间感知策略)
python scripts/locate_weather.py
# 手动指定坐标查天气
python scripts/locate_weather.py --lat 30.558 --lon 114.317 --city 武汉
# 指定定位方法
python scripts/locate_weather.py --methods ip,gps
# 时间感知策略(根据时段自动选择最优方法)
python scripts/locate_weather.py --methods time_aware
# 输出 JSON(供 AI 后续处理)
python scripts/locate_weather.py --format json
# 模拟测试:虚拟时间 2:00,冬季
python scripts/locate_weather.py --methods time_aware --sim-hour 2 --sim-month 12
```
## 定位方法(来自 multi-source-locate)
| 方法 | 精度 | 依赖 | 说明 |
|------|------|------|------|
| GPS | 3-10m | GPS 硬件 / NMEA | 户外最高精度 |
| System | 10m–1km | OS 定位服务 | Win GeoCoordinateWatcher / macOS CoreLocation / Linux GeoClue2 |
| IP | 1-50km | 无 | 城市级定位,零依赖 |
| WiFi | 10-100m | Google/Unwired API Key | 室内/城市环境 |
| Cellular | 100m-3km | 基站可见性 | 户外备用方案 |
## 时间感知策略(time_aware)
| 时间段 | 方法优先级 | 理由 |
|--------|-----------|------|
| 0-5时(深夜) | ip→wifi→system→cellular→gps | 室内GPS信号弱,优先IP |
| 6-9时(清晨) | system→gps→cellular→wifi→ip | 通勤时段系统定位快速 |
| 10-16时(白天) | gps→system→wifi→cellular→ip | 户外GPS精度最高 |
| 17-20时(傍晚) | system→wifi→gps→cellular→ip | 通勤时段 |
| 21-23时(夜间) | ip→system→wifi→cellular→gps | 室内为主,IP/系统优先 |
## API Keys(可选)
```bash
export GOOGLE_GEOLOCATION_API_KEY="..." # WiFi 精确定位
export UNWIRED_API_KEY="..." # WiFi 备用
```
## 输出格式
### Text(默认)
```
═══════════════════════════════════════════════
📍 定位结果
═══════════════════════════════════════════════
坐标: 30.5580°N, 114.3169°E
方法: triangulated
精度: ±10000m
置信度: 50%
═══════════════════════════════════════════════
🌤️ 天气预报 — Wuhan, Hubei
═══════════════════════════════════════════════
当前天气: Sunny
气温: 26°C (体感 27°C)
湿度: 70%
风速: 6 km/h (NE)
今日气温: 19°C ~ 27°C
```
### JSON(--format json)
```json
{
"time_context": {
"strategy": "time_aware",
"hour": 12,
"season": "spring",
"month": 4,
"gps_reliability": 0.9,
"method_priority": ["gps", "system", "wifi", "cellular", "ip"]
},
"location": {
"latitude": 30.558,
"longitude": 114.317,
"accuracy_meters": 150,
"confidence": 0.85,
"method": "triangulated",
"sources": { "ip": {...}, "gps": {...} }
},
"weather": {
"current": { "temp_c": 26, "condition": "Sunny", ... },
"today": { "max_temp_c": 27, "min_temp_c": 19, ... },
"forecast": [...]
}
}
```
## 文件结构
```
locate-weather/
├── SKILL.md ← 本文件
├── scripts/
│ ├── locate_weather.py ← Facade(导入 weather_at + multi-source-locate)
│ └── weather_at.py ← 天气模块(含 time_aware 策略)
├── tests/
│ ├── double_blind_test.py
│ └── TEST_PLAN.md
└── references/
└── api_endpoints.md ← wttr.in API 格式参考
```
## 依赖关系
```
locate-weather
├── multi-source-locate (独立 Skill)
│ ├── scripts/locate.py ← 定位核心(GPS/IP/WiFi/Cellular/System)
│ ├── scripts/gps_reader.py
│ ├── scripts/ip_lookup.py
│ ├── scripts/wifi_scanner.py
│ ├── scripts/cell_scanner.py
│ └── scripts/triangulate.py
└── scripts/weather_at.py ← 天气模块 + time_aware 策略
```
FILE:references/api_endpoints.md
# API Endpoints Reference
## Weather: wttr.in
### Coordinate-based query
```
https://wttr.in/{lat}:{lon}?format=j1
```
Returns JSON with:
- `current_condition`: current weather
- `weather[]`: 3-day forecast
- `nearest_area[]`: closest city info
### Format codes
```
%l Location
%c Condition emoji
%t Temperature
%f Feels like
%w Wind
%h Humidity
%p Precipitation
```
### JSON format
```bash
curl "wttr.in/30.558:114.317?format=j1"
```
## IP Geolocation
### ip-api.com (free, 45 req/min)
```
http://ip-api.com/json/
```
Response: `{ status, lat, lon, city, region, country, isp, accuracy }`
### ipinfo.io
```
https://ipinfo.io/json
```
Response: `{ ip, city, region, country, loc: "lat,lon", org, timezone }`
## WiFi: Google Geolocation API
```
POST https://www.googleapis.com/geolocation/v1/geolocate?key={API_KEY}
Content-Type: application/json
{
"wifiAccessPoints": [
{ "macAddress": "XX:XX:XX:XX:XX:XX", "signalStrength": -60 }
]
}
```
Returns: `{ location: { lat, lng }, accuracy }`
Requires: `GOOGLE_GEOLOCATION_API_KEY` env var
FILE:scripts/locate_weather.py
#!/usr/bin/env python3
"""
Locate-Weather Skill v2.0 (Facade)
Delegates to:
- multi-source-locate → 定位模块 (GPS/IP/WiFi/Cellular/System)
- weather_at.py → 天气模块
本文件仅做前端分发,所有逻辑委托给上述模块。
旧 locate_weather.py 中的定位代码已移至 multi-source-locate。
旧 locate_weather.py 中的天气代码已移至 weather_at.py。
"""
import sys
import os
# ── Import delegation ──────────────────────────────────────────────────────────
# Re-export everything from weather_at (weather module) for backward compat
_SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
if _SCRIPT_DIR not in sys.path:
sys.path.insert(0, _SCRIPT_DIR)
from weather_at import (
WeatherReport,
get_time_aware_method_priority,
get_season_factor,
get_weather,
main as _weather_main,
MULTI_LOCATE_OK,
)
# Expose location models from multi-source-locate (via importlib inside weather_at)
from weather_at import (
LocationSource, # = multi-source-locate.LocationResult
TriangulatedResult, # = multi-source-locate.TriangulatedResult
get_system_location,
get_ip_location,
get_wifi_location,
get_cellular_location,
get_gps_location,
triangulate,
validate_coordinates,
)
# Alias old name for locate_weather consumers
TriangulatedLocation = TriangulatedResult
# ── Entry point ────────────────────────────────────────────────────────────────
if __name__ == "__main__":
_weather_main()
FILE:scripts/weather_at.py
#!/usr/bin/env python3
"""
Weather-At Skill v2.0
定点天气预报 — 获取指定位置的实时天气和3天预报。
定位模块引用: multi-source-locate Skill (scripts/locate.py)
Weather module refactored out of locate_weather.py v2.0
Usage:
python weather_at.py # 自动定位 + 天气
python weather_at.py --lat 30.5 --lon 114.3 # 手动坐标
python weather_at.py --city 武汉 # 城市名
python weather_at.py --methods time_aware # 时间感知定位策略
python weather_at.py --format json # JSON 输出
python weather_at.py --sim-hour 2 --sim-month 12 # 模拟时间
"""
import argparse
import json
import sys
import os
import ssl
import math
import urllib.request
import urllib.error
import importlib.util
from dataclasses import dataclass, asdict, field
from datetime import datetime, timezone
from typing import Optional, List, Dict, Any, Tuple
# ═══════════════════════════════════════════════════════════════════════════════
# DATA MODELS
# ═══════════════════════════════════════════════════════════════════════════════
@dataclass
class WeatherReport:
"""Weather forecast report."""
latitude: float
longitude: float
city: str
region: str
country: str
current_temp: float
current_feelslike: float
current_condition: str
current_humidity: int
current_wind_speed: float
current_wind_dir: str
current_uv: float
current_pressure: float
current_visibility: float
today_maxtemp: float
today_mintemp: float
forecast: List[Dict] = field(default_factory=list)
sunrise: str = ""
sunset: str = ""
raw: Optional[Dict] = None
# ═══════════════════════════════════════════════════════════════════════════════
# MULTI-SOURCE LOCATE MODULE (dynamic import — handles hyphenated dir name)
# ═══════════════════════════════════════════════════════════════════════════════
def _load_multi_locate():
"""Dynamically load multi-source-locate locate.py module."""
# Resolve paths
_skill_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
_multi_root = os.path.join(_skill_dir, "..", "multi-source-locate")
_multi_root = os.path.normpath(_multi_root)
_scripts_dir = os.path.join(_multi_root, "scripts")
if _scripts_dir not in sys.path:
sys.path.insert(0, _scripts_dir)
_spec = importlib.util.spec_from_file_location(
"_msl", os.path.join(_scripts_dir, "locate.py")
)
_mod = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_mod)
return _mod
try:
_msl = _load_multi_locate()
get_system_location = _msl.get_system_location
get_ip_location = _msl.get_ip_location
get_wifi_location = _msl.get_wifi_location
get_cellular_location = _msl.get_cellular_location
get_gps_location = _msl.get_gps_location
triangulate = _msl.triangulate
validate_coordinates = _msl.validate_coordinates
LocationSource = _msl.LocationResult # multi-source-locate uses LocationResult
TriangulatedResult = _msl.TriangulatedResult
MULTI_LOCATE_OK = True
except Exception as e:
get_system_location = get_ip_location = get_wifi_location = None
get_cellular_location = get_gps_location = triangulate = None
validate_coordinates = None
LocationSource = TriangulatedResult = None
MULTI_LOCATE_OK = False
_msl_load_error = e
# ═══════════════════════════════════════════════════════════════════════════════
# TIME-AWARE STRATEGY
# ═══════════════════════════════════════════════════════════════════════════════
def get_time_aware_method_priority(hour: Optional[int] = None) -> List[str]:
"""
根据当前时间动态调整定位方法优先级。
- 深夜 (0-5): IP优先,GPS信号弱,用户通常在室内
- 清晨/傍晚 (6-9, 17-20): 系统定位优先,通勤时段
- 白天 (10-16): GPS优先,户外可能性高
- 夜间 (21-23): 混合策略,IP/系统优先
"""
if hour is None:
hour = datetime.now().hour
if 0 <= hour < 6:
return ["ip", "wifi", "system", "cellular", "gps"]
elif 6 <= hour < 10:
return ["system", "gps", "cellular", "wifi", "ip"]
elif 10 <= hour < 17:
return ["gps", "system", "wifi", "cellular", "ip"]
elif 17 <= hour < 21:
return ["system", "wifi", "gps", "cellular", "ip"]
else: # 21-23
return ["ip", "system", "wifi", "cellular", "gps"]
def get_season_factor(
month: Optional[int] = None,
hour: Optional[int] = None
) -> Dict[str, Any]:
"""获取季节因素对定位的影响"""
if month is None:
month = datetime.now().month
if hour is None:
hour = datetime.now().hour
if month in [3, 4, 5]:
season = "spring"; gps_reliability = 0.9
elif month in [6, 7, 8]:
season = "summer"; gps_reliability = 0.85
elif month in [9, 10, 11]:
season = "autumn"; gps_reliability = 0.9
else:
season = "winter"; gps_reliability = 0.8
return {"season": season, "month": month, "gps_reliability": gps_reliability, "hour": hour}
# ═══════════════════════════════════════════════════════════════════════════════
# WEATHER FUNCTIONS
# ═══════════════════════════════════════════════════════════════════════════════
def _now() -> str:
return datetime.now(timezone.utc).isoformat()
def _fetch_json(url: str, timeout: int = 10) -> Dict:
"""GET JSON with SSL/timeout handling."""
ctx = ssl.create_default_context()
try:
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
with urllib.request.urlopen(req, timeout=timeout, context=ctx) as resp:
raw = resp.read().decode("utf-8", errors="ignore")
return json.loads(raw)
except (urllib.error.URLError, TimeoutError, json.JSONDecodeError) as e:
raise ValueError(f"网络请求失败: {e}")
def get_weather(lat: float, lon: float, city_override: str = "") -> Optional[WeatherReport]:
"""Fetch weather for given coordinates using wttr.in."""
try:
url = f"https://wttr.in/{lat},{lon}?format=j1&lang=zh"
data = _fetch_json(url)
return _parse_weather_response(lat, lon, data, city_override)
except Exception as e:
print(f"[weather] 获取天气失败: {e}", file=sys.stderr)
return None
def _parse_weather_response(
lat: float, lon: float, data: Dict, city_override: str = ""
) -> WeatherReport:
"""Parse wttr.in JSON response."""
current = data.get("current_condition", [{}])[0]
today = data.get("weather", [{}])[0]
if city_override:
city = city_override
else:
area = data.get("nearest_area", [{}])[0]
city = (area.get("areaName", [{}])[0].get("value") or
area.get("region", [{}])[0].get("value") or
area.get("country", [{}])[0].get("value") or "")
region = country = ""
try:
nearest = data.get("nearest_area", [{}])[0]
region = nearest.get("region", [{}])[0].get("value", "")
country = nearest.get("country", [{}])[0].get("value", "")
except Exception:
pass
forecast = []
for day_data in data.get("weather", []):
fc_day = day_data.get("hourly", [])
maxt = float(day_data.get("maxtempC", "0"))
mint = float(day_data.get("mintempC", "0"))
desc = day_data.get("weatherDesc", [{}])[0].get("value", "")
rain_prob = 0
uv = 0.0
for h in fc_day:
try:
rain_prob = max(rain_prob, int(h.get("chanceofrain", 0)))
uv = max(uv, float(h.get("uvIndex", 0) or 0))
except (ValueError, TypeError):
pass
astronomy = day_data.get("astronomy", [{}])[0]
forecast.append({
"date": day_data.get("date", ""),
"maxtemp": maxt,
"mintemp": mint,
"avgtemp": float(day_data.get("avgtempC", "0")),
"condition": desc,
"rain_prob": rain_prob,
"uv": uv,
"sunrise": astronomy.get("sunrise", ""),
"sunset": astronomy.get("sunset", ""),
})
astronomy0 = today.get("astronomy", [{}])[0]
return WeatherReport(
latitude=lat, longitude=lon, city=city, region=region, country=country,
current_temp=float(current.get("temp_C", 0)),
current_feelslike=float(current.get("FeelsLikeC", 0)),
current_condition=current.get("weatherDesc", [{}])[0].get("value", ""),
current_humidity=int(current.get("humidity", 0)),
current_wind_speed=float(current.get("windspeedKmph", 0)),
current_wind_dir=_norm_wind_dir(current.get("winddir16Point", "")),
current_uv=float(current.get("uvIndex", 0)),
current_pressure=float(current.get("pressure", 0)),
current_visibility=float(current.get("visibility", 0)),
today_maxtemp=float(today.get("maxtempC", 0)),
today_mintemp=float(today.get("mintempC", 0)),
forecast=forecast,
sunrise=astronomy0.get("sunrise", ""),
sunset=astronomy0.get("sunset", ""),
raw=data,
)
def _norm_wind_dir(abbr: str) -> str:
"""Normalize wind direction abbreviation."""
mapping = {
"N": "N", "NNE": "N", "NE": "NE", "ENE": "NE",
"E": "E", "ESE": "E", "SE": "SE", "SSE": "SE",
"S": "S", "SSW": "S", "SW": "SW", "WSW": "SW",
"W": "W", "WNW": "W", "NW": "NW", "NNW": "NW",
}
return mapping.get(abbr.upper(), abbr)
# ═══════════════════════════════════════════════════════════════════════════════
# OUTPUT
# ═══════════════════════════════════════════════════════════════════════════════
def _print_text(loc: Any, weather: Optional[WeatherReport], time_ctx: Optional[Dict] = None):
"""Human-readable output."""
ns = getattr(loc, 'latitude', 0)
ew = getattr(loc, 'longitude', 0)
lat_str = f"{abs(ns):.4f}°{'N' if ns >= 0 else 'S'}"
lon_str = f"{abs(ew):.4f}°{'E' if ew >= 0 else 'W'}"
conf_str = f"{getattr(loc, 'confidence', 0):.0%}"
acc_str = f"{getattr(loc, 'accuracy_meters', 0):.0f}"
method_str = getattr(loc, 'method', '?')
lines = [
"",
"═" * 55,
" 📍 定位结果",
"═" * 55,
f" 坐标: {lat_str}, {lon_str}",
f" 方法: {method_str}",
f" 精度: ±{acc_str}m",
f" 置信度: {conf_str}",
]
if time_ctx:
lines.append(
f" 时间: {time_ctx.get('hour', '?')}时 | "
f"{time_ctx.get('season', '?')} | "
f"GPS可靠性 {time_ctx.get('gps_reliability', 0):.0%}"
)
if weather:
lines += [
"",
"═" * 55,
f" 🌤️ 天气预报 — {weather.city}" +
(f", {weather.region}" if weather.region else "") +
(f" ({weather.country})" if weather.country else ""),
"═" * 55,
f" 当前天气: {weather.current_condition}",
f" 气温: {weather.current_temp:.0f}°C (体感 {weather.current_feelslike:.0f}°C)",
f" 湿度: {weather.current_humidity}%",
f" 风速: {weather.current_wind_speed:.0f} km/h ({weather.current_wind_dir})",
f" 气压: {weather.current_pressure:.0f} hPa",
f" 能见度: {weather.current_visibility:.0f} km",
f" 今日气温: {weather.today_mintemp:.0f}°C ~ {weather.today_maxtemp:.0f}°C",
]
if weather.sunrise:
lines.append(f" 日出/日落: {weather.sunrise} / {weather.sunset}")
if weather.forecast:
lines.append("")
lines.append(" ─── 天气预报 ───")
for fc in weather.forecast[:4]:
lines.append(
f" {fc.get('date', '?')}: {fc.get('condition', '?')} "
f"{fc.get('mintemp', 0):.0f}°C ~ {fc.get('maxtemp', 0):.0f}°C "
f"🌧️ {fc.get('rain_prob', 0)}%"
)
print("\n".join(lines))
# ═══════════════════════════════════════════════════════════════════════════════
# MAIN
# ═══════════════════════════════════════════════════════════════════════════════
def main():
if not MULTI_LOCATE_OK:
print(f"❌ 错误: multi-source-locate 不可用: {_msl_load_error}", file=sys.stderr)
sys.exit(1)
parser = argparse.ArgumentParser(
description="定点天气预报 — 多方法定位 + wttr.in 天气"
)
parser.add_argument("--lat", type=float, default=None)
parser.add_argument("--lon", type=float, default=None)
parser.add_argument("--city", type=str, default="")
parser.add_argument(
"--methods", "-m", type=str, default="time_aware",
help="定位方法: ip,gps,system,wifi,cellular,time_aware,all (逗号分隔)"
)
parser.add_argument("--format", "-f", choices=["json", "text"], default="text")
parser.add_argument("--gps-timeout", type=int, default=30)
parser.add_argument("--sim-hour", type=int, default=None)
parser.add_argument("--sim-month", type=int, default=None)
args = parser.parse_args()
# ── 1. 解析定位方法 ─────────────────────────────────────────────────────
if args.methods == "all":
methods = ["system", "gps", "ip", "wifi", "cellular"]
elif args.methods == "time_aware":
methods = get_time_aware_method_priority(hour=args.sim_hour)
season = get_season_factor(month=args.sim_month, hour=args.sim_hour)
hour_display = args.sim_hour if args.sim_hour is not None else season["hour"]
print(f"🕐 时间感知策略: {hour_display}时 | {season['season']} | GPS可靠性 {season['gps_reliability']:.0%}", file=sys.stderr)
print(f" 方法优先级: {' → '.join(methods)}", file=sys.stderr)
time_context = {
"strategy": "time_aware",
"hour": args.sim_hour if args.sim_hour is not None else datetime.now().hour,
"season": season["season"],
"month": season["month"],
"gps_reliability": season["gps_reliability"],
"method_priority": methods,
}
else:
methods = [m.strip().lower() for m in args.methods.split(",")]
time_context = {"strategy": "manual", "method_priority": methods}
# ── 2. 定位阶段 ─────────────────────────────────────────────────────────
if args.lat is not None and args.lon is not None:
lat, lon = validate_coordinates(args.lat, args.lon)
if lat is None:
print("❌ 无效坐标", file=sys.stderr)
sys.exit(1)
sources = [LocationSource(
latitude=lat, longitude=lon,
accuracy=10.0, method="manual", timestamp=_now()
)]
city = args.city or ""
else:
city = args.city or ""
sources = []
method_funcs = {
"system": lambda: get_system_location(args.gps_timeout or 20),
"gps": lambda: get_gps_location(args.gps_timeout),
"ip": lambda: get_ip_location(),
"wifi": lambda: get_wifi_location(),
"cellular": lambda: get_cellular_location(),
}
for method_name in methods:
if method_name not in method_funcs:
print(f"⚠️ 未知定位方法: {method_name}", file=sys.stderr)
continue
print(f"正在探测 [{method_name}]...", file=sys.stderr)
try:
result = method_funcs[method_name]()
if result:
src = LocationSource(
latitude=result.latitude, longitude=result.longitude,
accuracy=result.accuracy, method=result.method,
timestamp=result.timestamp or _now(),
)
sources.append(src)
print(f" ✓ {method_name}: {result.latitude:.4f}, {result.longitude:.4f} (±{result.accuracy:.0f}m)", file=sys.stderr)
else:
print(f" ✗ {method_name}: 不可用", file=sys.stderr)
except Exception as e:
print(f" ✗ {method_name}: {e}", file=sys.stderr)
if not sources:
print("❌ 所有定位方法均失败,使用默认 IP 位置", file=sys.stderr)
try:
default = _fetch_json("https://wttr.in/?format=j1", timeout=10)
area = default.get("nearest_area", [{}])[0]
lat = float(area.get("latitude", 30))
lon = float(area.get("longitude", 114))
sources.append(LocationSource(
latitude=lat, longitude=lon,
accuracy=10000.0, method="default-ip", timestamp=_now()
))
except Exception as e:
print(f"默认位置也失败: {e}", file=sys.stderr)
sys.exit(1)
tri_loc = triangulate(sources)
lat, lon = tri_loc.latitude, tri_loc.longitude
# ── 3. 天气阶段 ─────────────────────────────────────────────────────────
print(f"\n正在获取 ({lat:.4f}, {lon:.4f}) 的天气预报...", file=sys.stderr)
weather = get_weather(lat, lon, city)
if weather is None:
print("⚠️ 天气获取失败,仅输出定位结果", file=sys.stderr)
if args.format == "json":
print(json.dumps({
"time_context": time_context,
"location": asdict(tri_loc),
"weather": None,
}, indent=2, ensure_ascii=False))
else:
_print_text(tri_loc, None, time_context)
sys.exit(0)
# ── 4. 输出 ──────────────────────────────────────────────────────────────
if args.format == "json":
print(json.dumps({
"time_context": time_context,
"location": asdict(tri_loc),
"weather": {
"current": {
"temp_c": weather.current_temp,
"feels_like": weather.current_feelslike,
"condition": weather.current_condition,
"humidity": weather.current_humidity,
"wind_kmh": weather.current_wind_speed,
"wind_dir": weather.current_wind_dir,
"uv_index": weather.current_uv,
"pressure_hpa": weather.current_pressure,
"visibility_km": weather.current_visibility,
},
"today": {
"max_temp_c": weather.today_maxtemp,
"min_temp_c": weather.today_mintemp,
"sunrise": weather.sunrise,
"sunset": weather.sunset,
},
"forecast": weather.forecast,
"city": weather.city,
"region": weather.region,
"country": weather.country,
"latitude": weather.latitude,
"longitude": weather.longitude,
}
}, indent=2, ensure_ascii=False))
else:
_print_text(tri_loc, weather, time_context)
sys.exit(0)
if __name__ == "__main__":
main()
FILE:tests/double_blind_test.py
#!/usr/bin/env python3
"""
Locate-Weather 双盲对照测试框架
测试时间因素对定位策略的影响
"""
import json
import random
import subprocess
import sys
import os
from datetime import datetime, timezone
from dataclasses import dataclass, asdict
from typing import List, Dict, Any, Optional
import statistics
@dataclass
class TestCondition:
"""测试条件:时间场景"""
name: str
hour: int # 0-23
season: str # spring, summer, autumn, winter
description: str
expected_priority: List[str] # 期望的定位方法优先级
@dataclass
class TestResult:
"""单次测试结果"""
condition: str
subject_group: str # A组或B组
subject_id: int
method_used: str
accuracy: float
confidence: float
success: bool
response_time_ms: float
timestamp: str
# 预定义测试场景(时间因素)
TEST_CONDITIONS = [
TestCondition("深夜室内", 2, "winter", "凌晨2点,用户在室内,GPS信号弱",
["ip", "wifi", "system", "gps"]),
TestCondition("清晨通勤", 7, "spring", "早上7点,用户通勤中,多源可用",
["gps", "wifi", "system", "ip"]),
TestCondition("正午户外", 12, "summer", "中午12点,户外强光,GPS可用",
["gps", "system", "wifi", "ip"]),
TestCondition("黄昏室内", 18, "autumn", "傍晚6点,室内,WiFi优先",
["wifi", "ip", "system", "gps"]),
TestCondition("夜间移动", 22, "winter", "晚上10点,移动中,GPS+IP混合",
["gps", "ip", "system", "wifi"]),
]
class TestSubject:
"""受测者 Agent"""
def __init__(self, group: str, subject_id: int, strategy: str):
self.group = group # "A" 或 "B"
self.subject_id = subject_id
self.strategy = strategy # "time_aware" 或 "baseline"
self.results: List[TestResult] = []
def run_test(self, condition: TestCondition) -> TestResult:
"""执行单次测试"""
start_time = datetime.now(timezone.utc)
# 根据策略和时间条件选择方法
if self.strategy == "time_aware":
methods = self._time_aware_methods(condition)
else:
methods = ["system", "ip", "gps", "wifi"] # 基线策略
# 调用 locate-weather
try:
cmd = [sys.executable, "scripts/locate_weather.py",
"--methods", ",".join(methods),
"--format", "json"]
result = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=30,
cwd=os.path.dirname(os.path.abspath(__file__))
)
elapsed_ms = (datetime.now(timezone.utc) - start_time).total_seconds() * 1000
if result.returncode == 0:
data = json.loads(result.stdout)
loc = data.get("location", {})
# 评估是否匹配期望优先级
actual_method = loc.get("method", "unknown")
success = actual_method in condition.expected_priority[:2]
return TestResult(
condition=condition.name,
subject_group=self.group,
subject_id=self.subject_id,
method_used=actual_method,
accuracy=loc.get("accuracy_meters", 99999),
confidence=loc.get("confidence", 0),
success=success,
response_time_ms=elapsed_ms,
timestamp=start_time.isoformat()
)
else:
return TestResult(
condition=condition.name,
subject_group=self.group,
subject_id=self.subject_id,
method_used="error",
accuracy=99999,
confidence=0,
success=False,
response_time_ms=elapsed_ms,
timestamp=start_time.isoformat()
)
except Exception as e:
elapsed_ms = (datetime.now(timezone.utc) - start_time).total_seconds() * 1000
return TestResult(
condition=condition.name,
subject_group=self.group,
subject_id=self.subject_id,
method_used=f"exception: {e}",
accuracy=99999,
confidence=0,
success=False,
response_time_ms=elapsed_ms,
timestamp=start_time.isoformat()
)
def _time_aware_methods(self, condition: TestCondition) -> List[str]:
"""根据时间条件选择最优方法序列"""
hour = condition.hour
# 夜间 (0-5): IP优先,GPS信号弱
if 0 <= hour < 6:
return ["ip", "wifi", "system", "gps"]
# 清晨/傍晚 (6-9, 17-20): 系统定位优先
elif (6 <= hour < 10) or (17 <= hour < 21):
return ["system", "gps", "wifi", "ip"]
# 白天 (10-16): GPS优先
elif 10 <= hour < 17:
return ["gps", "system", "wifi", "ip"]
# 夜间 (21-23): 混合策略
else:
return ["gps", "ip", "system", "wifi"]
class DoubleBlindTester:
"""双盲测试控制器"""
def __init__(self):
self.subjects: List[TestSubject] = []
self.results: List[TestResult] = []
self.round = 0
def create_subjects(self, n_per_group: int = 3):
"""创建受测者"""
# A组:时间感知策略
for i in range(n_per_group):
self.subjects.append(TestSubject("A", i+1, "time_aware"))
# B组:基线策略(对照组)
for i in range(n_per_group):
self.subjects.append(TestSubject("B", i+1, "baseline"))
print(f"✓ 创建 {len(self.subjects)} 名受测者")
print(f" - A组(时间感知): {n_per_group} 人")
print(f" - B组(基线对照): {n_per_group} 人")
def run_round(self, round_num: int):
"""执行一轮测试"""
self.round = round_num
print(f"\n{'='*60}")
print(f"第 {round_num} 轮双盲测试")
print(f"{'='*60}")
# 随机打乱测试顺序(双盲)
test_sequence = []
for condition in TEST_CONDITIONS:
for subject in self.subjects:
test_sequence.append((condition, subject))
random.shuffle(test_sequence)
# 执行测试
for idx, (condition, subject) in enumerate(test_sequence, 1):
print(f"\n[{idx}/{len(test_sequence)}] {condition.name} | "
f"受测者 {subject.group}-{subject.subject_id} ({subject.strategy})")
result = subject.run_test(condition)
self.results.append(result)
status = "✓" if result.success else "✗"
print(f" {status} 方法: {result.method_used}, "
f"精度: {result.accuracy:.0f}m, "
f"置信度: {result.confidence:.2f}, "
f"耗时: {result.response_time_ms:.0f}ms")
def analyze_results(self) -> Dict[str, Any]:
"""分析测试结果"""
print(f"\n{'='*60}")
print("测试结果分析")
print(f"{'='*60}")
# 按组统计
group_stats = {"A": [], "B": []}
for r in self.results:
group_stats[r.subject_group].append(r)
analysis = {
"round": self.round,
"total_tests": len(self.results),
"group_comparison": {}
}
for group, results in group_stats.items():
successes = [r for r in results if r.success]
accuracies = [r.accuracy for r in results if r.accuracy < 99999]
confidences = [r.confidence for r in results]
times = [r.response_time_ms for r in results]
stats = {
"strategy": "time_aware" if group == "A" else "baseline",
"total": len(results),
"success_rate": len(successes) / len(results) if results else 0,
"avg_accuracy": statistics.mean(accuracies) if accuracies else 0,
"avg_confidence": statistics.mean(confidences) if confidences else 0,
"avg_response_ms": statistics.mean(times) if times else 0,
"median_accuracy": statistics.median(accuracies) if accuracies else 0,
}
analysis["group_comparison"][group] = stats
print(f"\n【{group}组 - {stats['strategy']}】")
print(f" 成功率: {stats['success_rate']*100:.1f}%")
print(f" 平均精度: {stats['avg_accuracy']:.0f}m")
print(f" 平均置信度: {stats['avg_confidence']:.2f}")
print(f" 平均响应: {stats['avg_response_ms']:.0f}ms")
# 计算提升
a_stats = analysis["group_comparison"]["A"]
b_stats = analysis["group_comparison"]["B"]
if b_stats["avg_accuracy"] > 0:
accuracy_improvement = (b_stats["avg_accuracy"] - a_stats["avg_accuracy"]) / b_stats["avg_accuracy"]
print(f"\n【A组 vs B组 提升】")
print(f" 精度提升: {accuracy_improvement*100:.1f}%")
print(f" 置信度提升: {(a_stats['avg_confidence'] - b_stats['avg_confidence']):.2f}")
return analysis
def export_report(self, filename: str = None):
"""导出测试报告"""
if filename is None:
filename = f"test_report_round{self.round}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
report = {
"test_framework": "double_blind_time_aware",
"round": self.round,
"timestamp": datetime.now(timezone.utc).isoformat(),
"conditions": [asdict(c) for c in TEST_CONDITIONS],
"results": [asdict(r) for r in self.results],
"analysis": self.analyze_results()
}
with open(filename, 'w', encoding='utf-8') as f:
json.dump(report, f, indent=2, ensure_ascii=False)
print(f"\n✓ 测试报告已保存: {filename}")
return filename
def main():
"""主入口"""
print("="*60)
print("Locate-Weather 时间因素双盲对照测试")
print("="*60)
tester = DoubleBlindTester()
tester.create_subjects(n_per_group=3)
# 执行三轮测试
for round_num in range(1, 4):
tester.run_round(round_num)
tester.export_report(f"test_report_round{round_num}.json")
print("\n" + "="*60)
print("三轮双盲测试完成")
print("="*60)
if __name__ == "__main__":
main()
FILE:tests/TEST_PLAN.md
# Locate-Weather v2.0 时间因素双盲对照测试方案
## 测试目的
验证时间感知策略 (time_aware) 对定位精度和效率的提升效果。
## 测试角色
### 测试者 (Tester)
- 设计5个时间场景测试用例
- 随机分配给受测者(双盲)
- 评估结果并生成报告
- 不参与定位逻辑
### A组受测者(实验组,3人)
- 使用 `--methods time_aware`(时间感知策略)
- 根据当前时间自动调整定位方法优先级
### B组受测者(对照组,3人)
- 使用 `--methods system,ip,gps,wifi`(固定顺序基线策略)
- 不考虑时间因素
## 测试场景(5个)
| ID | 场景 | 时间 | 季节 | 期望优先级 |
|----|------|------|------|-----------|
| T1 | 深夜室内 | 02:00 | 冬季 | ip > wifi > system > cellular > gps |
| T2 | 清晨通勤 | 07:00 | 春季 | system > gps > cellular > wifi > ip |
| T3 | 正午户外 | 12:00 | 夏季 | gps > system > wifi > cellular > ip |
| T4 | 傍晚室内 | 18:00 | 秋季 | system > wifi > gps > cellular > ip |
| T5 | 夜间移动 | 22:00 | 冬季 | gps > ip > system > cellular > wifi |
## 测试方法
由于实际 GPS/Cellular/WiFi 硬件在本机不可用,
采用以下方法进行双盲测试:
1. **模拟时间注入**:通过修改 `get_time_aware_method_priority` 接受虚拟时间
2. **实际 IP 定位**:两组都实际调用 IP 定位验证基本功能
3. **策略评估**:对比方法优先级序列与期望优先级的匹配度
4. **效率评估**:对比响应时间(跳过不可用方法的速度)
## 评分维度
- 方法优先级匹配度 (0-100%)
- 首次成功定位时间 (ms)
- 定位精度 (meters)
- 置信度分数 (0-1)
Multi-source geolocation via GPS, System built-in, IP, WiFi, and cellular triangulation. Use when the user asks to determine their location, locate a device,...
---
name: multi-source-locate
description: Multi-source geolocation via GPS, System built-in, IP, WiFi, and cellular triangulation. Use when the user asks to determine their location, locate a device, get current coordinates, or needs accurate positioning using multiple data sources. Supports GPS (high accuracy), System built-in location (Windows GeoCoordinateWatcher / macOS CoreLocation / Linux GeoClue2), IP geolocation (city-level), WiFi positioning (indoor/urban), and cellular tower triangulation (outdoor fallback). Provides confidence scores and accuracy estimates for each method. Also used as the location backend for the locate-weather Skill.
---
# Multi-Source Locate
Multi-source geolocation combining GPS, System built-in, IP, WiFi, and cellular data for accurate positioning with confidence scoring.
> **Used by**: `locate-weather` Skill — provides the geolocation engine for its "fixed-point weather forecast" feature.
## When to Use
- User asks "where am I" or "get my location"
- Need device coordinates with accuracy estimate
- GPS unavailable or inaccurate (indoor, urban canyon)
- Cross-validate location from multiple sources
- Fallback positioning when primary method fails
## Quick Start
```bash
# Get location using all available methods (default order: gps, system, ip, wifi, cellular)
python scripts/locate.py
# Use specific method(s)
python scripts/locate.py --method gps
python scripts/locate.py --method system
python scripts/locate.py --method ip
python scripts/locate.py --method wifi
python scripts/locate.py --method gps,system,ip,wifi
# Output format
python scripts/locate.py --format json # machine-readable
python scripts/locate.py --format text # human-readable
```
## Location Methods
### 1. GPS (Highest Accuracy)
- **Accuracy**: 3-10m outdoors, degraded indoors
- **Requirements**: GPS hardware, sky visibility
- **Best for**: Outdoor navigation, mapping
- **Fallback**: WiFi positioning indoors
```bash
python scripts/locate.py --method gps --timeout 30
```
### 2. System Built-in Location
- **Accuracy**: 10m–1km (OS-dependent)
- **Requirements**: OS location service enabled, user permission
- **Best for**: Reliable OS-managed indoor/outdoor location without API keys
- **Platforms**: Windows (GeoCoordinateWatcher), macOS (CoreLocation), Linux (GeoClue2)
```bash
python scripts/locate.py --method system --timeout 20
```
### 3. IP Geolocation (City-Level)
- **Accuracy**: 1-50km (varies by ISP)
- **Requirements**: Internet connection
- **Best for**: Quick city/country detection
- **Data sources**: Multiple IP geolocation APIs with cross-validation
```bash
python scripts/locate.py --method ip
```
### 4. WiFi Positioning (Indoor/Urban)
- **Accuracy**: 10-100m
- **Requirements**: WiFi adapter, nearby APs
- **Best for**: Indoor, urban environments
- **Method**: BSSID lookup via geolocation APIs
```bash
python scripts/locate.py --method wifi
```
### 5. Cellular Triangulation (Fallback)
- **Accuracy**: 100m-3km
- **Requirements**: Cell modem, tower visibility
- **Best for**: Rural areas, GPS denied
- **Method**: MCC/MNC/LAC/CellID lookup
```bash
python scripts/locate.py --method cellular
```
## Triangulation Algorithm
When multiple methods are available, the skill:
1. Collects coordinates from each successful method
2. Weights by inverse variance (accuracy-based weighting)
3. Computes weighted centroid as final position
4. Estimates combined accuracy from residual dispersion
5. Reports confidence score (0-100%)
### Output Format
```json
{
"latitude": 39.9042,
"longitude": 116.4074,
"accuracy_meters": 15,
"confidence": 0.92,
"method": "triangulated",
"sources": {
"gps": {"lat": 39.9045, "lon": 116.4071, "accuracy": 5, "weight": 0.6},
"wifi": {"lat": 39.9039, "lon": 116.4078, "accuracy": 30, "weight": 0.3},
"ip": {"lat": 39.9042, "lon": 116.4074, "accuracy": 5000, "weight": 0.1}
},
"timestamp": "2025-01-15T10:30:00Z"
}
```
## API Keys (Optional)
For enhanced accuracy, configure API keys in environment:
```bash
# Google Geolocation API (WiFi/Cellular)
export GOOGLE_GEOLOCATION_API_KEY="your-key"
# Mozilla Location Service
export MLS_API_KEY="your-key"
# Unwired Labs
export UNWIRED_API_KEY="your-key"
```
Without API keys, the skill uses:
- Free IP geolocation APIs (ip-api.com, ipinfo.io)
- Local GPS via serial/Bluetooth NMEA
- Public BSSID databases where available
## Platform Notes
### Windows
- **System**: Uses `[System.Device.Location.GeoCoordinateWatcher]` via PowerShell (Wi-Fi + IP + GPS fusion, 10m–1km)
- GPS: Requires USB/Bluetooth GPS receiver or NMEA source
- WiFi: Uses `netsh wlan show networks mode=bssid`
- Cellular: Requires cellular modem AT command access
### macOS
- **System**: CoreLocation via `locationd` daemon (approximate via `system_profiler`)
- GPS: Uses CoreLocation framework
- WiFi: Uses `airport -s` for BSSID scanning
- Cellular: Limited on desktop, full on iPhone
### Linux
- **System**: Queries `org.freedesktop.GeoClue2` via D-Bus (Wi-Fi + cell fusion)
- GPS: Reads from `/dev/ttyUSB*` or gpsd
- WiFi: Uses `iwlist scan` or NetworkManager
- Cellular: Uses ModemManager AT interface
## Resources
### scripts/
- `locate.py` - Main location acquisition script
- `gps_reader.py` - NMEA GPS parser
- `wifi_scanner.py` - WiFi BSSID collector
- `cell_scanner.py` - Cellular tower info collector
- `ip_lookup.py` - IP geolocation client
- `triangulate.py` - Weighted centroid calculation
### references/
- `nmea_sentences.md` - NMEA sentence format reference
- `api_endpoints.md` - Geolocation API documentation
FILE:references/api_endpoints.md
# Geolocation API Endpoints
Reference for geolocation APIs used by multi-source-locate.
## IP Geolocation APIs
### ip-api.com
Free, no API key required.
- **Endpoint**: `http://ip-api.com/json/`
- **Rate Limit**: 45 requests/minute (free)
- **Accuracy**: ~5km typical
**Request:**
```
GET http://ip-api.com/json/
```
**Response:**
```json
{
"status": "success",
"country": "United States",
"countryCode": "US",
"region": "CA",
"regionName": "California",
"city": "Mountain View",
"zip": "94035",
"lat": 37.386,
"lon": -122.0838,
"timezone": "America/Los_Angeles",
"isp": "Google LLC",
"org": "Google LLC",
"as": "AS15169 Google LLC",
"query": "8.8.8.8"
}
```
### ipinfo.io
Free tier available.
- **Endpoint**: `https://ipinfo.io/json`
- **Rate Limit**: 50,000 requests/month (free)
- **Accuracy**: ~10km
**Request:**
```
GET https://ipinfo.io/json?token=YOUR_TOKEN
```
**Response:**
```json
{
"ip": "8.8.8.8",
"hostname": "dns.google",
"city": "Mountain View",
"region": "California",
"country": "US",
"loc": "37.386,-122.0838",
"org": "AS15169 Google LLC",
"postal": "94035",
"timezone": "America/Los_Angeles"
}
```
### ipgeolocation.io
Free tier available.
- **Endpoint**: `https://api.ipgeolocation.io/ipgeo`
- **Rate Limit**: 30,000 requests/month (free)
- **Accuracy**: ~8km
**Request:**
```
GET https://api.ipgeolocation.io/ipgeo?apiKey=YOUR_KEY
```
**Response:**
```json
{
"ip": "8.8.8.8",
"latitude": "37.38600",
"longitude": "-122.08380",
"city": "Mountain View",
"state_prov": "California",
"country_name": "United States",
"country_code2": "US",
"isp": "Google LLC",
"time_zone": {
"name": "America/Los_Angeles"
}
}
```
## WiFi/Cellular Geolocation APIs
### Google Geolocation API
Most accurate, requires API key and billing.
- **Endpoint**: `https://www.googleapis.com/geolocation/v1/geolocate`
- **Cost**: $5 per 1000 requests (after free tier)
- **Accuracy**: 10-100m (WiFi), 100m-3km (cellular)
**WiFi Request:**
```json
POST https://www.googleapis.com/geolocation/v1/geolocate?key=YOUR_KEY
{
"wifiAccessPoints": [
{
"macAddress": "01:23:45:67:89:AB",
"signalStrength": -43,
"channel": 11
},
{
"macAddress": "01:23:45:67:89:CD",
"signalStrength": -57
}
]
}
```
**Cellular Request:**
```json
{
"cellTowers": [
{
"cellId": 42,
"locationAreaCode": 415,
"mobileCountryCode": 310,
"mobileNetworkCode": 260,
"age": 0,
"signalStrength": -60,
"timingAdvance": 15
}
]
}
```
**Response:**
```json
{
"location": {
"lat": 37.4218,
"lng": -122.0840
},
"accuracy": 30.0
}
```
### Unwired Labs (unwiredlabs.com)
Free tier available, good for WiFi positioning.
- **Endpoint**: `https://us1.unwiredlabs.com/v2/process.php`
- **Rate Limit**: 10,000 requests/day (free)
- **Accuracy**: 30-300m
**Request:**
```json
POST https://us1.unwiredlabs.com/v2/process.php
{
"token": "YOUR_TOKEN",
"wifi": [
{
"bssid": "01:23:45:67:89:AB",
"signal": -43
}
],
"cell": [
{
"mcc": 310,
"mnc": 260,
"lac": 415,
"cid": 42
}
]
}
```
**Response:**
```json
{
"status": "ok",
"lat": 37.4218,
"lon": -122.0840,
"accuracy": 50,
"fallback": "wifi"
}
```
### Mozilla Location Service (MLS)
**Note**: Mozilla shut down MLS in 2024. This is kept for reference.
Historically provided free WiFi/cellular geolocation using crowdsourced data.
## Combining Sources
### Accuracy Comparison
| Source | Typical Accuracy | Best For |
|--------|------------------|----------|
| GPS | 3-10m | Outdoor, clear sky |
| WiFi | 10-100m | Indoor, urban |
| Cellular | 100m-3km | Rural, GPS denied |
| IP | 1-50km | Quick city detection |
### Weight Calculation
Use inverse variance weighting:
```python
weight = 1.0 / (accuracy ** 2)
```
This gives higher weight to more accurate sources.
### Confidence Scoring
Factors affecting confidence:
1. **Number of sources**: More = higher confidence
2. **Agreement**: Sources agreeing = higher confidence
3. **Source quality**: GPS > WiFi > Cellular > IP
4. **Accuracy**: Lower accuracy value = higher confidence
## Rate Limits Summary
| API | Free Tier | Paid Tier |
|-----|-----------|-----------|
| ip-api.com | 45/min | $13/mo for unlimited |
| ipinfo.io | 50k/mo | $249/mo for 1M |
| ipgeolocation.io | 30k/mo | $15/mo for 150k |
| Google Geolocation | $200 credit/mo | $5/1k requests |
| Unwired Labs | 10k/day | Custom |
## Error Handling
### Common Errors
| Status Code | Meaning | Action |
|-------------|---------|--------|
| 429 | Rate limited | Wait and retry |
| 403 | Invalid API key | Check credentials |
| 400 | Bad request | Validate payload |
| 404 | Not found | Check endpoint |
| 503 | Service unavailable | Fallback to other API |
### Fallback Chain
1. Try primary API
2. If rate limited, try secondary API
3. If all fail, return cached result (if available)
4. If no cache, return error with partial results
FILE:references/nmea_sentences.md
# NMEA Sentence Reference
NMEA 0183 is the standard protocol for GPS receivers. This reference covers the most common sentences used for position determination.
## Sentence Format
All NMEA sentences follow this format:
```
$TALKER,field1,field2,...*checksum
```
- **TALKER**: Two-character talker ID (GP=GPS, GL=GLONASS, GA=Galileo, BD=BeiDou)
- **Fields**: Comma-separated data fields
- **Checksum**: Two-character hexadecimal XOR of all characters between $ and *
### Checksum Calculation
```python
def nmea_checksum(sentence):
"""Calculate NMEA checksum."""
data = sentence[1:sentence.index('*')] # Remove $ and *checksum
checksum = 0
for char in data:
checksum ^= ord(char)
return format(checksum, '02X')
```
## Position Sentences
### RMC - Recommended Minimum Navigation
The most commonly used sentence for position and navigation.
```
$GPRMC,123519,A,4807.038,N,01131.000,E,022.4,084.4,230394,003.1,W*6A
```
| Field | Description | Example |
|-------|-------------|---------|
| 1 | UTC Time (HHMMSS.ss) | 123519 = 12:35:19 |
| 2 | Status (A=Active, V=Void) | A |
| 3 | Latitude (DDMM.MMMM) | 4807.038 |
| 4 | N/S Indicator | N |
| 5 | Longitude (DDDMM.MMMM) | 01131.000 |
| 6 | E/W Indicator | E |
| 7 | Speed over ground (knots) | 022.4 |
| 8 | Course over ground (degrees) | 084.4 |
| 9 | Date (DDMMYY) | 230394 = March 23, 1994 |
| 10 | Magnetic variation (degrees) | 003.1 |
| 11 | Variation direction (E/W) | W |
### GGA - Global Positioning System Fix Data
Contains position, altitude, and fix quality.
```
$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47
```
| Field | Description | Example |
|-------|-------------|---------|
| 1 | UTC Time | 123519 |
| 2 | Latitude | 4807.038 |
| 3 | N/S | N |
| 4 | Longitude | 01131.000 |
| 5 | E/W | E |
| 6 | Fix Quality | 1 |
| 7 | Satellites in use | 08 |
| 8 | HDOP | 0.9 |
| 9 | Altitude (MSL) | 545.4 |
| 10 | Altitude units | M (meters) |
| 11 | Geoid separation | 46.9 |
| 12 | Geoid units | M |
| 13 | DGPS age | (empty) |
| 14 | DGPS station ID | (empty) |
#### Fix Quality Values
| Value | Description |
|-------|-------------|
| 0 | Invalid/No fix |
| 1 | GPS fix (SPS) |
| 2 | DGPS fix |
| 3 | PPS fix |
| 4 | Real Time Kinematic |
| 5 | Float RTK |
| 6 | Estimated (dead reckoning) |
| 7 | Manual input mode |
| 8 | Simulation mode |
### GLL - Geographic Position
Simple position with time and status.
```
$GPGLL,4807.038,N,01131.000,E,123519,A*27
```
| Field | Description |
|-------|-------------|
| 1 | Latitude |
| 2 | N/S |
| 3 | Longitude |
| 4 | E/W |
| 5 | UTC Time |
| 6 | Status (A/V) |
## Satellite Information
### GSA - GPS DOP and Active Satellites
Dilution of precision and satellite list.
```
$GPGSA,A,3,04,05,,09,12,,,24,,,,,2.5,1.3,2.1*39
```
| Field | Description |
|-------|-------------|
| 1 | Selection mode (A=Automatic, M=Manual) |
| 2 | Fix mode (1=No fix, 2=2D, 3=3D) |
| 3-14 | PRN of satellites used |
| 15 | PDOP |
| 16 | HDOP |
| 17 | VDOP |
### GSV - Satellites in View
Satellite details (may span multiple sentences).
```
$GPGSV,2,1,08,01,40,083,46,02,17,308,41,03,12,150,38,04,28,225,46*75
```
| Field | Description |
|-------|-------------|
| 1 | Total messages |
| 2 | Message number |
| 3 | Satellites in view |
| 4,5,6,7 | PRN, Elevation, Azimuth, SNR (repeated) |
## Navigation Data
### VTG - Track Made Good and Ground Speed
Course and speed information.
```
$GPVTG,054.7,T,034.4,M,005.5,N,010.2,K*48
```
| Field | Description |
|-------|-------------|
| 1 | Track true (degrees) |
| 2 | T (True) |
| 3 | Track magnetic |
| 4 | M (Magnetic) |
| 5 | Speed (knots) |
| 6 | N (Knots) |
| 7 | Speed (km/h) |
| 8 | K (km/h) |
### ZDA - Time and Date
UTC time and date with local time zone.
```
$GPZDA,123519,23,03,1994,00,00*6D
```
## Multi-Constellation Sentences
Modern GPS receivers support multiple satellite constellations:
| Talker | Constellation |
|--------|---------------|
| GP | GPS (US) |
| GL | GLONASS (Russia) |
| GA | Galileo (EU) |
| BD / GB | BeiDou (China) |
| QZ | QZSS (Japan) |
| GI | NavIC (India) |
### GNS - GNSS Fix Data
Combined fix data from multiple constellations.
```
$GPGNS,123519,4807.038,N,01131.000,E,A,A,08,0.9,545.4,M,46.9,M,,*42
```
## Coordinate Conversion
### NMEA to Decimal Degrees
NMEA coordinates are in DDMM.MMMM or DDDMM.MMMM format.
```python
def nmea_to_decimal(value, direction):
"""Convert NMEA coordinate to decimal degrees."""
# Find decimal point
dot = value.index('.')
# Degrees are before last 2 digits before decimal
deg_len = dot - 2
degrees = float(value[:deg_len])
minutes = float(value[deg_len:])
decimal = degrees + minutes / 60.0
if direction in ('S', 'W'):
decimal = -decimal
return decimal
```
### Decimal Degrees to NMEA
```python
def decimal_to_nmea(decimal, is_longitude=False):
"""Convert decimal degrees to NMEA format."""
degrees = abs(int(decimal))
minutes = (abs(decimal) - degrees) * 60.0
# Format: DDMM.MMMM or DDDMM.MMMM
if is_longitude:
return f"{degrees:03d}{minutes:07.4f}"
else:
return f"{degrees:02d}{minutes:07.4f}"
```
## Common Issues
### No Fix (V Status)
- Indoor or obstructed sky view
- GPS receiver not initialized
- Antenna disconnected
### Inaccurate Position
- Low HDOP (>2.0)
- Few satellites (<6)
- Multipath interference
- Atmospheric delays
### Timestamp Issues
- GPS time rolls over every 1024 weeks
- Some receivers use local time instead of UTC
- Leap seconds not always accounted for
## GPSD Protocol
When using gpsd daemon, JSON messages are used instead of NMEA:
```json
{
"class": "TPV",
"device": "/dev/ttyUSB0",
"mode": 3,
"time": "2025-01-15T12:35:19.000Z",
"lat": 48.1173,
"lon": 11.5167,
"alt": 545.4,
"track": 84.4,
"speed": 11.5,
"eph": 10.0
}
```
Key fields:
- `mode`: 0=no fix, 1=no fix, 2=2D fix, 3=3D fix
- `eph`: Estimated horizontal error (meters)
- `epv`: Estimated vertical error (meters)
FILE:scripts/cell_scanner.py
#!/usr/bin/env python3
"""
Cellular tower scanner module.
Scans for cellular tower info for geolocation.
"""
import subprocess
import sys
import re
import json
from typing import List, Dict, Any, Optional
from dataclasses import dataclass
@dataclass
class CellTower:
"""Cellular tower information."""
mcc: int # Mobile Country Code
mnc: int # Mobile Network Code
lac: int # Location Area Code (2G/3G) or TAC (4G)
cid: int # Cell ID
signal: int = 0 # Signal strength (dBm)
rat: str = '' # Radio Access Technology (GSM, UMTS, LTE, NR)
arfcn: Optional[int] = None # Absolute RF Channel Number
pci: Optional[int] = None # Physical Cell ID (LTE/NR)
timing_advance: Optional[int] = None
def scan_cell_towers() -> List[CellTower]:
"""
Scan for cellular tower information.
Returns list of CellTower objects.
"""
if sys.platform == 'win32':
return _scan_windows()
elif sys.platform == 'darwin':
return _scan_macos()
else:
return _scan_linux()
def _scan_windows() -> List[CellTower]:
"""
Scan cellular on Windows.
Requires cellular modem with AT command interface.
"""
towers = []
# Try Windows Mobile Broadband API via PowerShell
try:
result = subprocess.run(
['powershell', '-Command',
'Get-NetAdapter | Where-Object {$_.MediaType -eq "MobileBroadband"} | Select-Object -First 1'],
capture_output=True,
text=True,
timeout=10
)
if result.returncode == 0 and result.stdout.strip():
# Found mobile broadband adapter
# Try to get cell info via netsh mbn
result2 = subprocess.run(
['netsh', 'mbn', 'show', 'caps', 'interface=*'],
capture_output=True,
text=True,
timeout=10
)
# Parse cell info if available
# This is limited on Windows without specific modem drivers
except Exception:
pass
# Alternative: Try AT commands via serial port
# This requires a cellular modem exposed as COM port
towers.extend(_scan_at_ports())
return towers
def _scan_at_ports() -> List[CellTower]:
"""Scan cellular modems via AT commands."""
towers = []
# Common modem port patterns
ports = []
if sys.platform == 'win32':
for i in range(1, 20):
ports.append(f'COM{i}')
else:
import glob
ports = glob.glob('/dev/ttyUSB*') + glob.glob('/dev/ttyACM*')
for port in ports:
try:
tower = _query_modem_at(port)
if tower:
towers.append(tower)
except Exception:
continue
return towers
def _query_modem_at(port: str) -> Optional[CellTower]:
"""Query modem via AT commands."""
import serial
import time
try:
ser = serial.Serial(port, 115200, timeout=2)
# Try to get cell info
# AT+COPS? - Get network operator
# AT+CREG? - Get registration status
# AT+CGREG? - Get GPRS registration
# AT+CEREG? - Get EPS registration (LTE)
ser.write(b'AT+COPS=3,2\r\n') # Set numeric format
time.sleep(0.5)
ser.read(ser.in_waiting)
ser.write(b'AT+COPS?\r\n')
time.sleep(1)
response = ser.read(ser.in_waiting).decode('ascii', errors='ignore')
# Parse +COPS: <mode>[,<format>,<oper>,<act>]
match = re.search(r'\+COPS:\s*\d+,(\d+),(\d+),(\d+)', response)
if match:
# oper is PLMN = MCC + MNC
plmn = match.group(2)
mcc = int(plmn[:3])
mnc = int(plmn[3:])
rat_code = int(match.group(3))
rat_map = {0: 'GSM', 2: 'UTRAN', 7: 'LTE', 13: 'NR'}
rat = rat_map.get(rat_code, '')
# Get LAC and CID (varies by modem)
# For Qualcomm: AT+QNWCFG="lte_cell_info"
# For Huawei: AT^HCSQ?
# Generic: AT+CREG? (2G) or AT+CEREG? (LTE)
ser.write(b'AT+CREG=2\r\n') # Enable network registration URC
time.sleep(0.5)
ser.read(ser.in_waiting)
ser.write(b'AT+CREG?\r\n')
time.sleep(1)
response = ser.read(ser.in_waiting).decode('ascii', errors='ignore')
# Parse +CREG: <n>,<stat>[,<lac>,<cid>]
match = re.search(r'\+CREG:\s*\d+,\d+,([0-9a-fA-F]+),([0-9a-fA-F]+)', response)
if match:
lac = int(match.group(1), 16)
cid = int(match.group(2), 16)
ser.close()
return CellTower(
mcc=mcc if 'mcc' in dir() else 0,
mnc=mnc if 'mnc' in dir() else 0,
lac=lac,
cid=cid,
rat=rat if 'rat' in dir() else 'GSM'
)
# Try LTE registration
ser.write(b'AT+CEREG=2\r\n')
time.sleep(0.5)
ser.read(ser.in_waiting)
ser.write(b'AT+CEREG?\r\n')
time.sleep(1)
response = ser.read(ser.in_waiting).decode('ascii', errors='ignore')
# Parse +CEREG: <n>,<stat>[,<tac>,<cid>,<act>]
match = re.search(r'\+CEREG:\s*\d+,\d+,([0-9a-fA-F]+),([0-9a-fA-F]+)', response)
if match:
tac = int(match.group(1), 16)
cid = int(match.group(2), 16)
ser.close()
return CellTower(
mcc=mcc if 'mcc' in dir() else 0,
mnc=mnc if 'mnc' in dir() else 0,
lac=tac,
cid=cid,
rat='LTE'
)
ser.close()
except Exception:
pass
return None
def _scan_macos() -> List[CellTower]:
"""
Scan cellular on macOS.
Limited on desktop Macs; full support on iPhone.
"""
towers = []
# macOS doesn't expose cellular info on desktop
# On iPhone, would use CoreTelephony framework
return towers
def _scan_linux() -> List[CellTower]:
"""Scan cellular on Linux using ModemManager."""
towers = []
try:
# List modems
result = subprocess.run(
['mmcli', '-L'],
capture_output=True,
text=True,
timeout=10
)
# Parse modem paths
modem_paths = re.findall(r'/org/freedesktop/ModemManager1/Modem/\d+', result.stdout)
for path in modem_paths:
try:
# Get modem info
result = subprocess.run(
['mmcli', '-m', path, '--output=json'],
capture_output=True,
text=True,
timeout=10
)
data = json.loads(result.stdout)
modem = data.get('modem', {})
# Get 3GPP info
gpp = modem.get('3gpp', {})
mcc = gpp.get('mcc')
mnc = gpp.get('mnc')
# Get location
result2 = subprocess.run(
['mmcli', '-m', path, '--location-get'],
capture_output=True,
text=True,
timeout=10
)
# Parse location output
# 3GPP location: mcc: 262, mnc: 1, lac: 5286, cid: 262851
match = re.search(
r'3GPP location:\s*mcc:\s*(\d+),\s*mnc:\s*(\d+),\s*lac:\s*(\d+),\s*cid:\s*(\d+)',
result2.stdout
)
if match:
towers.append(CellTower(
mcc=int(match.group(1)),
mnc=int(match.group(2)),
lac=int(match.group(3)),
cid=int(match.group(4)),
rat='GSM'
))
# Try LTE cell info
# mmcli -m 0 --signal-get
result3 = subprocess.run(
['mmcli', '-m', path, '--signal-get'],
capture_output=True,
text=True,
timeout=10
)
# Parse LTE signal info
# LTE: rss: -65, rsrq: -9, rsrp: -95, snr: 14
# This gives signal but not cell ID
except Exception:
continue
except Exception as e:
print(f"ModemManager scan failed: {e}", file=sys.stderr)
return towers
def get_connected_cell() -> Optional[CellTower]:
"""Get the currently connected cell tower."""
towers = scan_cell_towers()
return towers[0] if towers else None
if __name__ == '__main__':
print("Scanning cellular towers...\n")
towers = scan_cell_towers()
if towers:
print(f"Found {len(towers)} cell towers:\n")
for tower in towers:
print(f" MCC: {tower.mcc}, MNC: {tower.mnc}")
print(f" LAC/TAC: {tower.lac}, CID: {tower.cid}")
print(f" RAT: {tower.rat or 'Unknown'}")
print(f" Signal: {tower.signal} dBm")
print()
else:
print("No cellular towers found")
print("(This is normal on desktop systems without cellular modem)")
FILE:scripts/gps_reader.py
#!/usr/bin/env python3
"""
NMEA GPS reader module.
Parses GPS data from serial ports or gpsd daemon.
"""
import sys
import time
import threading
from typing import Optional, Tuple, Callable
from dataclasses import dataclass
from datetime import datetime
@dataclass
class GPSPosition:
"""GPS position with metadata."""
latitude: float
longitude: float
altitude: Optional[float] = None
speed: Optional[float] = None # knots
course: Optional[float] = None # degrees true
hdop: Optional[float] = None # horizontal dilution
satellites: Optional[int] = None
timestamp: Optional[datetime] = None
fix_quality: int = 0 # 0=invalid, 1=GPS, 2=DGPS
class NMEAParser:
"""NMEA 0183 sentence parser."""
def __init__(self):
self.position = GPSPosition(
latitude=0.0,
longitude=0.0
)
def parse(self, sentence: str) -> Optional[GPSPosition]:
"""Parse an NMEA sentence and return position if updated."""
if not sentence or not sentence.startswith('$'):
return None
# Validate checksum
if '*' in sentence:
try:
data, checksum = sentence.split('*')
data = data[1:] # Remove $
calc_sum = 0
for c in data:
calc_sum ^= ord(c)
if int(checksum, 16) != calc_sum:
return None
except ValueError:
return None
# Parse by sentence type
fields = sentence.split(',')
sentence_type = fields[0][3:] # Remove $GP
if sentence_type == 'RMC':
return self._parse_rmc(fields)
elif sentence_type == 'GGA':
return self._parse_gga(fields)
elif sentence_type == 'GSA':
return self._parse_gsa(fields)
elif sentence_type == 'GSV':
return self._parse_gsv(fields)
elif sentence_type == 'VTG':
return self._parse_vtg(fields)
return None
def _parse_coord(self, value: str, direction: str) -> Optional[float]:
"""Parse NMEA coordinate (DDMM.MMMM or DDDMM.MMMM)."""
if not value or not direction:
return None
try:
# Find decimal point position
dot_idx = value.index('.')
# Degrees are everything before last 2 digits before decimal
deg_len = dot_idx - 2
degrees = float(value[:deg_len])
minutes = float(value[deg_len:])
decimal = degrees + minutes / 60.0
if direction in ('S', 'W'):
decimal = -decimal
return decimal
except (ValueError, IndexError):
return None
def _parse_time(self, value: str) -> Optional[datetime]:
"""Parse NMEA time (HHMMSS or HHMMSS.ss)."""
if not value or len(value) < 6:
return None
try:
hour = int(value[0:2])
minute = int(value[2:4])
second = int(float(value[4:]))
return datetime.utcnow().replace(
hour=hour, minute=minute, second=second
)
except ValueError:
return None
def _parse_rmc(self, fields: list) -> Optional[GPSPosition]:
"""
Parse RMC (Recommended Minimum) sentence.
$GPRMC,123519,A,4807.038,N,01131.000,E,022.4,084.4,230394,003.1,W*6A
"""
if len(fields) < 12:
return None
# Status: A=valid, V=warning
if fields[2] != 'A':
return None
lat = self._parse_coord(fields[3], fields[4])
lon = self._parse_coord(fields[5], fields[6])
if lat is None or lon is None:
return None
self.position.latitude = lat
self.position.longitude = lon
# Speed (knots)
if fields[7]:
try:
self.position.speed = float(fields[7])
except ValueError:
pass
# Course (degrees true)
if fields[8]:
try:
self.position.course = float(fields[8])
except ValueError:
pass
# Timestamp
self.position.timestamp = self._parse_time(fields[1])
self.position.fix_quality = 1
return self.position
def _parse_gga(self, fields: list) -> Optional[GPSPosition]:
"""
Parse GGA (Global Positioning System Fix Data) sentence.
$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47
"""
if len(fields) < 15:
return None
# Fix quality: 0=invalid, 1=GPS fix, 2=DGPS fix
try:
fix_quality = int(fields[6])
except ValueError:
return None
if fix_quality == 0:
return None
lat = self._parse_coord(fields[2], fields[3])
lon = self._parse_coord(fields[4], fields[5])
if lat is None or lon is None:
return None
self.position.latitude = lat
self.position.longitude = lon
self.position.fix_quality = fix_quality
# Number of satellites
if fields[7]:
try:
self.position.satellites = int(fields[7])
except ValueError:
pass
# HDOP
if fields[8]:
try:
self.position.hdop = float(fields[8])
except ValueError:
pass
# Altitude
if fields[9]:
try:
self.position.altitude = float(fields[9])
except ValueError:
pass
# Timestamp
self.position.timestamp = self._parse_time(fields[1])
return self.position
def _parse_gsa(self, fields: list) -> Optional[GPSPosition]:
"""
Parse GSA (GPS DOP and active satellites) sentence.
$GPGSA,A,3,04,05,,09,12,,,24,,,,,2.5,1.3,2.1*39
"""
if len(fields) < 18:
return None
# HDOP
if fields[16]:
try:
self.position.hdop = float(fields[16])
except ValueError:
pass
return None # GSA doesn't provide position
def _parse_gsv(self, fields: list) -> Optional[GPSPosition]:
"""Parse GSV (satellites in view) sentence."""
# GSV provides satellite info, not position
return None
def _parse_vtg(self, fields: list) -> Optional[GPSPosition]:
"""
Parse VTG (Track Made Good and Ground Speed) sentence.
$GPVTG,054.7,T,034.4,M,005.5,N,010.2,K*48
"""
if len(fields) < 9:
return None
# Course (degrees true)
if fields[1]:
try:
self.position.course = float(fields[1])
except ValueError:
pass
# Speed (knots)
if fields[5]:
try:
self.position.speed = float(fields[5])
except ValueError:
pass
return None # VTG doesn't provide position
class GPSReader:
"""GPS reader that handles serial port or gpsd connection."""
def __init__(self, source: str = 'auto', callback: Optional[Callable] = None):
"""
Initialize GPS reader.
Args:
source: 'auto', 'gpsd', or serial port path (e.g., '/dev/ttyUSB0', 'COM3')
callback: Optional callback function for position updates
"""
self.source = source
self.callback = callback
self.parser = NMEAParser()
self.running = False
self.thread = None
self._serial = None
self._socket = None
def start(self) -> bool:
"""Start reading GPS data."""
if self.running:
return True
if self.source == 'auto':
# Try gpsd first, then serial ports
if self._try_gpsd():
self.running = True
return True
if self._try_serial():
self.running = True
return True
return False
elif self.source == 'gpsd':
return self._try_gpsd()
else:
return self._try_serial(self.source)
def _try_gpsd(self) -> bool:
"""Try to connect to gpsd daemon."""
try:
import socket
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._socket.settimeout(5)
self._socket.connect(('localhost', 2947))
self._socket.send(b'?WATCH={"enable":true,"json":true}\n')
self.running = True
self.thread = threading.Thread(target=self._read_gpsd, daemon=True)
self.thread.start()
return True
except Exception:
return False
def _try_serial(self, port: Optional[str] = None) -> bool:
"""Try to open serial port."""
import glob
ports_to_try = []
if port:
ports_to_try = [port]
else:
# Auto-detect
if sys.platform == 'win32':
ports_to_try = [f'COM{i}' for i in range(1, 20)]
else:
ports_to_try = glob.glob('/dev/ttyUSB*') + glob.glob('/dev/ttyACM*')
for p in ports_to_try:
try:
import serial
self._serial = serial.Serial(p, 4800, timeout=1)
self.running = True
self.thread = threading.Thread(target=self._read_serial, daemon=True)
self.thread.start()
return True
except Exception:
continue
return False
def _read_gpsd(self):
"""Read from gpsd daemon."""
import json
buffer = ""
while self.running and self._socket:
try:
data = self._socket.recv(4096).decode('utf-8', errors='ignore')
buffer += data
while '\n' in buffer:
line, buffer = buffer.split('\n', 1)
if line.startswith('{'):
try:
msg = json.loads(line)
if msg.get('class') == 'TPV' and 'lat' in msg and 'lon' in msg:
pos = GPSPosition(
latitude=msg['lat'],
longitude=msg['lon'],
altitude=msg.get('alt'),
speed=msg.get('speed'),
course=msg.get('track'),
timestamp=datetime.utcnow()
)
if self.callback:
self.callback(pos)
except json.JSONDecodeError:
continue
except Exception:
break
def _read_serial(self):
"""Read from serial port."""
while self.running and self._serial:
try:
line = self._serial.readline().decode('ascii', errors='ignore').strip()
if line.startswith('$'):
pos = self.parser.parse(line)
if pos and self.callback:
self.callback(pos)
except Exception:
break
def stop(self):
"""Stop reading GPS data."""
self.running = False
if self._serial:
self._serial.close()
self._serial = None
if self._socket:
self._socket.close()
self._socket = None
if self.thread:
self.thread.join(timeout=2)
def get_position(self, timeout: float = 10.0) -> Optional[GPSPosition]:
"""Get a single position reading."""
result = [None]
event = threading.Event()
def callback(pos):
result[0] = pos
event.set()
old_callback = self.callback
self.callback = callback
if not self.running:
if not self.start():
return None
if event.wait(timeout):
self.callback = old_callback
return result[0]
self.callback = old_callback
return None
if __name__ == '__main__':
# Test GPS reader
print("Testing GPS reader...")
def on_position(pos):
print(f"Position: {pos.latitude:.6f}, {pos.longitude:.6f}")
print(f" Altitude: {pos.altitude}m")
print(f" Speed: {pos.speed} knots")
print(f" Satellites: {pos.satellites}")
print(f" HDOP: {pos.hdop}")
reader = GPSReader(callback=on_position)
if reader.start():
print("GPS reader started. Press Ctrl+C to stop.")
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
pass
reader.stop()
else:
print("Failed to start GPS reader")
FILE:scripts/ip_lookup.py
#!/usr/bin/env python3
"""
IP geolocation client module.
Queries multiple IP geolocation APIs for location.
"""
import json
import sys
import urllib.request
import urllib.error
import ssl
import os
from typing import Optional, Dict, Any, List
from dataclasses import dataclass
from datetime import datetime, timezone
@dataclass
class IPLocation:
"""IP geolocation result."""
ip: str
latitude: float
longitude: float
city: Optional[str] = None
region: Optional[str] = None
country: Optional[str] = None
country_code: Optional[str] = None
isp: Optional[str] = None
org: Optional[str] = None
timezone: Optional[str] = None
accuracy: float = 5000.0 # meters
source: str = 'unknown'
def get_ip_location() -> Optional[IPLocation]:
"""
Get location from IP address using multiple APIs.
Queries several APIs and returns the most reliable result.
"""
apis = [
_query_ip_api_com,
_query_ipinfo_io,
_query_ipgeolocation,
_query_ipwhois,
]
results = []
for api_func in apis:
try:
result = api_func()
if result:
results.append(result)
except Exception as e:
print(f"API {api_func.__name__} failed: {e}", file=sys.stderr)
if not results:
return None
# If multiple results, use the one with smallest claimed accuracy
# or cross-validate if they agree
if len(results) == 1:
return results[0]
# Check if results agree (within 50km)
valid_results = []
for r in results:
# Check against first result
dist = _haversine_distance(
results[0].latitude, results[0].longitude,
r.latitude, r.longitude
)
if dist < 50000: # 50km
valid_results.append(r)
if valid_results:
# Return the one with best accuracy claim
return min(valid_results, key=lambda x: x.accuracy)
# Results disagree, return the one with smallest accuracy
return min(results, key=lambda x: x.accuracy)
def _query_ip_api_com() -> Optional[IPLocation]:
"""
Query ip-api.com (free, no key required, 45 req/min).
Response:
{
"status": "success",
"country": "United States",
"countryCode": "US",
"region": "CA",
"regionName": "California",
"city": "Mountain View",
"lat": 37.386,
"lon": -122.0838,
"isp": "Google LLC",
"org": "Google LLC",
"timezone": "America/Los_Angeles"
}
"""
url = "http://ip-api.com/json/"
try:
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
req = urllib.request.Request(
url,
headers={'User-Agent': 'multi-source-locate/1.0'}
)
with urllib.request.urlopen(req, timeout=10, context=ctx) as resp:
data = json.loads(resp.read().decode('utf-8'))
if data.get('status') != 'success':
return None
return IPLocation(
ip=data.get('query', ''),
latitude=float(data['lat']),
longitude=float(data['lon']),
city=data.get('city'),
region=data.get('regionName'),
country=data.get('country'),
country_code=data.get('countryCode'),
isp=data.get('isp'),
org=data.get('org'),
timezone=data.get('timezone'),
accuracy=5000.0, # ~5km typical
source='ip-api.com'
)
except Exception:
return None
def _query_ipinfo_io() -> Optional[IPLocation]:
"""
Query ipinfo.io (free tier: 50k req/month).
Response:
{
"ip": "8.8.8.8",
"hostname": "dns.google",
"city": "Mountain View",
"region": "California",
"country": "US",
"loc": "37.386,-122.0838",
"org": "AS15169 Google LLC",
"timezone": "America/Los_Angeles"
}
"""
url = "https://ipinfo.io/json"
# Check for API key
api_key = os.environ.get('IPINFO_API_KEY')
if api_key:
url = f"https://ipinfo.io/json?token={api_key}"
try:
ctx = ssl.create_default_context()
req = urllib.request.Request(
url,
headers={'User-Agent': 'multi-source-locate/1.0'}
)
with urllib.request.urlopen(req, timeout=10, context=ctx) as resp:
data = json.loads(resp.read().decode('utf-8'))
if 'loc' not in data:
return None
lat, lon = map(float, data['loc'].split(','))
# Parse org for ISP
org = data.get('org', '')
isp = org.split(' ', 1)[1] if ' ' in org else org
return IPLocation(
ip=data.get('ip', ''),
latitude=lat,
longitude=lon,
city=data.get('city'),
region=data.get('region'),
country_code=data.get('country'),
isp=isp,
org=org,
timezone=data.get('timezone'),
accuracy=10000.0, # ~10km
source='ipinfo.io'
)
except Exception:
return None
def _query_ipgeolocation() -> Optional[IPLocation]:
"""
Query ipgeolocation.io (free tier: 30k req/month).
Response:
{
"ip": "8.8.8.8",
"latitude": "37.38600",
"longitude": "-122.08380",
"city": "Mountain View",
"state_prov": "California",
"country_name": "United States",
"country_code2": "US",
"isp": "Google LLC",
"time_zone": {"name": "America/Los_Angeles"}
}
"""
# Free API key for basic usage
api_key = os.environ.get('IPGEOLOCATION_API_KEY', 'free')
url = f"https://api.ipgeolocation.io/ipgeo?apiKey={api_key}"
try:
ctx = ssl.create_default_context()
req = urllib.request.Request(
url,
headers={'User-Agent': 'multi-source-locate/1.0'}
)
with urllib.request.urlopen(req, timeout=10, context=ctx) as resp:
data = json.loads(resp.read().decode('utf-8'))
lat = data.get('latitude')
lon = data.get('longitude')
if lat is None or lon is None:
return None
tz = data.get('time_zone', {})
return IPLocation(
ip=data.get('ip', ''),
latitude=float(lat),
longitude=float(lon),
city=data.get('city'),
region=data.get('state_prov'),
country=data.get('country_name'),
country_code=data.get('country_code2'),
isp=data.get('isp'),
org=data.get('organization'),
timezone=tz.get('name') if isinstance(tz, dict) else None,
accuracy=8000.0,
source='ipgeolocation.io'
)
except Exception:
return None
def _query_ipwhois() -> Optional[IPLocation]:
"""
Query ipwhois.app (free, no key required).
Response:
{
"ip": "8.8.8.8",
"city": "Mountain View",
"region": "California",
"country": "US",
"country_name": "United States",
"latitude": 37.386,
"longitude": -122.0838,
"isp": "Google LLC",
"timezone": "America/Los_Angeles"
}
"""
url = "https://ipwhois.app/json/"
try:
ctx = ssl.create_default_context()
req = urllib.request.Request(
url,
headers={'User-Agent': 'multi-source-locate/1.0'}
)
with urllib.request.urlopen(req, timeout=10, context=ctx) as resp:
data = json.loads(resp.read().decode('utf-8'))
if 'latitude' not in data or 'longitude' not in data:
return None
return IPLocation(
ip=data.get('ip', ''),
latitude=float(data['latitude']),
longitude=float(data['longitude']),
city=data.get('city'),
region=data.get('region'),
country=data.get('country_name'),
country_code=data.get('country'),
isp=data.get('isp'),
timezone=data.get('timezone'),
accuracy=7000.0,
source='ipwhois.app'
)
except Exception:
return None
def _haversine_distance(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
"""Calculate distance between two points in meters using Haversine formula."""
import math
R = 6371000 # Earth radius in meters
phi1 = math.radians(lat1)
phi2 = math.radians(lat2)
delta_phi = math.radians(lat2 - lat1)
delta_lambda = math.radians(lon2 - lon1)
a = math.sin(delta_phi / 2) ** 2 + \
math.cos(phi1) * math.cos(phi2) * math.sin(delta_lambda / 2) ** 2
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
return R * c
def get_public_ip() -> Optional[str]:
"""Get the public IP address."""
services = [
"https://api.ipify.org",
"https://icanhazip.com",
"https://ifconfig.me/ip",
]
for url in services:
try:
ctx = ssl.create_default_context()
req = urllib.request.Request(url, headers={'User-Agent': 'curl'})
with urllib.request.urlopen(req, timeout=5, context=ctx) as resp:
return resp.read().decode('utf-8').strip()
except Exception:
continue
return None
if __name__ == '__main__':
print("Getting IP location...\n")
ip = get_public_ip()
if ip:
print(f"Public IP: {ip}\n")
location = get_ip_location()
if location:
print(f"Location from {location.source}:")
print(f" Coordinates: {location.latitude:.4f}, {location.longitude:.4f}")
print(f" City: {location.city or 'N/A'}")
print(f" Region: {location.region or 'N/A'}")
print(f" Country: {location.country or 'N/A'} ({location.country_code or 'N/A'})")
print(f" ISP: {location.isp or 'N/A'}")
print(f" Timezone: {location.timezone or 'N/A'}")
print(f" Accuracy: ~{location.accuracy/1000:.0f} km")
else:
print("Failed to get IP location")
FILE:scripts/locate.py
#!/usr/bin/env python3
"""
Multi-source geolocation tool.
Combines GPS, IP, WiFi, and cellular positioning for accurate location.
"""
import argparse
import json
import sys
import time
import os
from dataclasses import dataclass, asdict
from datetime import datetime, timezone
from typing import Optional, List, Dict, Any
import subprocess
import urllib.request
import urllib.error
import ssl
@dataclass
class LocationResult:
"""Single source location result."""
latitude: float
longitude: float
accuracy: float # meters
method: str
weight: float = 0.0
timestamp: str = ""
raw_data: Optional[Dict[str, Any]] = None
# ─── SYSTEM LOCATION (Windows / macOS built-in) ──────────────────────────────
def get_system_location(timeout: int = 20) -> Optional[LocationResult]:
"""Get location from OS built-in location service.
Windows: PowerShell [System.Device.Location.GeoCoordinateWatcher]
macOS: CoreLocation through system_profiler / defaults
Linux: geoclue2 via dbus
"""
if sys.platform == 'win32':
return _get_windows_system_location(timeout)
elif sys.platform == 'darwin':
return _get_macos_system_location(timeout)
else:
return _get_linux_geoclue_location(timeout)
def _get_windows_system_location(timeout: int) -> Optional[LocationResult]:
"""Use Windows GeoCoordinateWatcher via PowerShell script file."""
import tempfile, os as _os
ps_script = (
"[Console]::OutputEncoding = [System.Text.Encoding]::UTF8\n"
"Add-Type -AssemblyName System.Device.Location\n"
f"$watcher = [System.Device.Location.GeoCoordinateWatcher]::new()\n"
f"$watcher.TryStart($false, {timeout * 1000})\n"
"$sw = [Diagnostics.Stopwatch]::StartNew()\n"
"while ($watcher.Position -eq $null -and $sw.ElapsedMilliseconds -lt "
f"{timeout * 1000}) {{ Start-Sleep -Milliseconds 200 }}\n"
"$pos = $watcher.Position\n"
"if ($pos -ne $null -and -not $pos.Location.IsUnknown) {\n"
" $lat = $pos.Location.Latitude\n"
" $lon = $pos.Location.Longitude\n"
" $acc = $pos.Location.HorizontalAccuracy\n"
" if ($acc -le 0) { $acc = 100 }\n"
' Write-Output "$lat|$lon|$acc"\n'
"} else {\n"
' Write-Output "UNKNOWN"\n'
"}\n"
"$watcher.Stop()\n"
)
# Write to temp file to avoid quote/escape issues
tmp = None
try:
fd, tmp = tempfile.mkstemp(suffix='.ps1')
os_fd = _os.fdopen(fd, 'w', encoding='utf-8')
os_fd.write(ps_script)
os_fd.close()
result = subprocess.run(
['powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass',
'-File', tmp],
capture_output=True,
text=True,
timeout=timeout + 5,
encoding='utf-8',
errors='ignore'
)
output = result.stdout.strip()
if output and output != 'UNKNOWN':
parts = output.split('|')
if len(parts) >= 3 and parts[0] and parts[1] and parts[2]:
lat = float(parts[0])
lon = float(parts[1])
acc = float(parts[2])
if -90 <= lat <= 90 and -180 <= lon <= 180:
return LocationResult(
latitude=lat, longitude=lon,
accuracy=acc, method='system',
timestamp=datetime.now(timezone.utc).isoformat()
)
except Exception as e:
print(f"System location (Windows) failed: {e}", file=sys.stderr)
finally:
if tmp and _os.path.exists(tmp):
_os.unlink(tmp)
return None
def _get_macos_system_location(timeout: int) -> Optional[LocationResult]:
"""Use macOS CoreLocation via osascript / system_profiler."""
# Try cllocationd via launchctl
try:
result = subprocess.run(
['system_profiler', 'SPBluetoothDataType', '-json'],
capture_output=True, text=True, encoding='utf-8', timeout=10
)
except Exception:
pass
# Fallback: use curl to Apple's location service (approximate)
try:
result = subprocess.run(
['curl', '-s', '--max-time', '5',
'https://captive.apple.com/generation_204'],
capture_output=True, text=True, encoding='utf-8', timeout=7
)
# macOS can get location from network in some configs
# Check headers for location
for line in result.stdout.splitlines():
if 'x-apple-rawl' in line.lower() or 'x-geo' in line.lower():
pass # parse if found
except Exception:
pass
return None
def _get_linux_geoclue_location(timeout: int) -> Optional[LocationResult]:
"""Query geoclue2 over D-Bus for system location (Linux)."""
lat, lon = None, None
# Try dbus-send to query GeoClue2 Manager
try:
result = subprocess.run(
['dbus-send', '--session', '--dest=org.freedesktop.GeoClue2',
'--print-reply', '--type=method_call',
'/org/freedesktop/GeoClue2/Manager',
'org.freedesktop.GeoClue2.Manager.GetClient'],
capture_output=True, text=True, timeout=timeout, encoding='utf-8'
)
# Parse latitude/longitude from dbus output
for line in result.stdout.splitlines():
if 'double' in line.lower():
parts = line.strip().split()
if len(parts) >= 2:
try:
val = float(parts[-1])
if -90 <= val <= 90:
lat = val
elif -180 <= val <= 180:
lon = val
except ValueError:
continue
except Exception:
pass
if lat is not None and lon is not None:
lat, lon = validate_coordinates(lat, lon)
if lat is not None:
return LocationResult(
latitude=lat, longitude=lon,
accuracy=100, method='system',
timestamp=datetime.now(timezone.utc).isoformat(),
raw_data={'source': 'geoclue2'}
)
return None
def get_gps_location(timeout: int = 30) -> Optional[LocationResult]:
"""Get location from GPS hardware (NMEA source)."""
# Try common GPS sources
gps_sources = [
# gpsd on localhost
("gpsd", _get_gpsd_location),
# Serial ports (Windows/Linux)
("serial", _get_serial_gps_location),
]
for source_name, source_func in gps_sources:
try:
result = source_func(timeout)
if result:
return result
except Exception as e:
print(f"GPS source {source_name} failed: {e}", file=sys.stderr)
return None
def _get_gpsd_location(timeout: int) -> Optional[LocationResult]:
"""Query gpsd daemon for location."""
try:
import socket
import json as json_mod
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
sock.connect(('localhost', 2947))
# Request WATCH mode
sock.send(b'?WATCH={"enable":true,"json":true}\n')
start = time.time()
while time.time() - start < timeout:
data = sock.recv(4096).decode('utf-8', errors='ignore')
for line in data.strip().split('\n'):
if line.startswith('{'):
try:
msg = json_mod.loads(line)
if msg.get('class') == 'TPV' and 'lat' in msg and 'lon' in msg:
lat = msg['lat']
lon = msg['lon']
acc = msg.get('eph', 10.0) # Horizontal error estimate
return LocationResult(
latitude=lat,
longitude=lon,
accuracy=max(acc, 3.0),
method='gps',
timestamp=datetime.now(timezone.utc).isoformat()
)
except json_mod.JSONDecodeError:
continue
sock.close()
except Exception:
pass
return None
def _get_serial_gps_location(timeout: int) -> Optional[LocationResult]:
"""Read NMEA from serial port."""
import glob
# Common serial port patterns
patterns = [
'/dev/ttyUSB*', '/dev/ttyACM*', # Linux
'COM*', # Windows (handled separately)
]
ports = []
for pattern in patterns:
ports.extend(glob.glob(pattern))
# Windows COM ports
if sys.platform == 'win32':
for i in range(1, 20):
ports.append(f'COM{i}')
for port in ports:
try:
result = _read_nmea_port(port, timeout)
if result:
return result
except Exception:
continue
return None
def _read_nmea_port(port: str, timeout: int) -> Optional[LocationResult]:
"""Read and parse NMEA sentences from a port."""
import serial
try:
ser = serial.Serial(port, 4800, timeout=1)
start = time.time()
nmea_parser = NMEAParser()
while time.time() - start < timeout:
line = ser.readline().decode('ascii', errors='ignore').strip()
if line.startswith('$'):
loc = nmea_parser.parse(line)
if loc:
ser.close()
return LocationResult(
latitude=loc[0],
longitude=loc[1],
accuracy=10.0,
method='gps',
timestamp=datetime.now(timezone.utc).isoformat()
)
ser.close()
except Exception:
pass
return None
class NMEAParser:
"""Simple NMEA sentence parser for GPRMC and GPGGA."""
def __init__(self):
self.last_valid = None
def parse(self, sentence: str) -> Optional[tuple]:
"""Parse NMEA sentence, return (lat, lon) or None."""
if not sentence.startswith('$'):
return None
try:
# Calculate checksum
parts = sentence.split('*')
if len(parts) != 2:
return None
data = parts[0][1:] # Remove $
checksum = int(parts[1], 16)
calc_sum = 0
for c in data:
calc_sum ^= ord(c)
if calc_sum != checksum:
return None
fields = data.split(',')
if fields[0] == 'GPRMC':
return self._parse_rmc(fields)
elif fields[0] == 'GPGGA':
return self._parse_gga(fields)
except Exception:
pass
return None
def _parse_rmc(self, fields: List[str]) -> Optional[tuple]:
"""Parse GPRMC sentence."""
if len(fields) < 12 or fields[2] != 'A': # A = valid
return None
lat = self._parse_coord(fields[3], fields[4])
lon = self._parse_coord(fields[5], fields[6])
if lat is not None and lon is not None:
self.last_valid = (lat, lon)
return (lat, lon)
return None
def _parse_gga(self, fields: List[str]) -> Optional[tuple]:
"""Parse GPGGA sentence."""
if len(fields) < 10:
return None
lat = self._parse_coord(fields[2], fields[3])
lon = self._parse_coord(fields[4], fields[5])
if lat is not None and lon is not None:
self.last_valid = (lat, lon)
return (lat, lon)
return None
def _parse_coord(self, value: str, direction: str) -> Optional[float]:
"""Parse NMEA coordinate (DDMM.MMMM or DDDMM.MMMM)."""
if not value or not direction:
return None
try:
# Find decimal point
dot = value.index('.')
deg_len = dot - 2 if dot > 2 else 2
degrees = float(value[:deg_len])
minutes = float(value[deg_len:])
decimal = degrees + minutes / 60.0
if direction in ('S', 'W'):
decimal = -decimal
return decimal
except Exception:
return None
def get_ip_location() -> Optional[LocationResult]:
"""Get location from IP geolocation APIs."""
apis = [
('ip-api.com', _get_ip_api_com),
('ipinfo.io', _get_ipinfo_io),
('ipgeolocation.io', _get_ipgeolocation),
]
results = []
for name, func in apis:
try:
result = func()
if result:
results.append(result)
except Exception as e:
print(f"IP API {name} failed: {e}", file=sys.stderr)
if not results:
return None
# If multiple results, cross-validate and average
if len(results) == 1:
return results[0]
# Weighted average based on claimed accuracy
total_weight = 0
weighted_lat = 0
weighted_lon = 0
for r in results:
w = 1.0 / r.accuracy
weighted_lat += r.latitude * w
weighted_lon += r.longitude * w
total_weight += w
return LocationResult(
latitude=weighted_lat / total_weight,
longitude=weighted_lon / total_weight,
accuracy=max(r.accuracy for r in results),
method='ip',
timestamp=datetime.now(timezone.utc).isoformat()
)
def _get_ip_api_com() -> Optional[LocationResult]:
"""Query ip-api.com (free, no key required)."""
url = "http://ip-api.com/json/?fields=status,lat,lon,city,country,isp"
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
try:
req = urllib.request.Request(url, headers={'User-Agent': 'multi-source-locate/1.0'})
with urllib.request.urlopen(req, timeout=10, context=ctx) as resp:
data = json.loads(resp.read().decode())
if data.get('status') != 'success':
return None
return LocationResult(
latitude=data['lat'],
longitude=data['lon'],
accuracy=5000.0, # ~5km typical
method='ip',
timestamp=datetime.now(timezone.utc).isoformat(),
raw_data={'city': data.get('city'), 'country': data.get('country')}
)
except Exception:
return None
def _get_ipinfo_io() -> Optional[LocationResult]:
"""Query ipinfo.io (free tier: 50k req/month)."""
url = "https://ipinfo.io/json"
ctx = ssl.create_default_context()
try:
req = urllib.request.Request(url, headers={'User-Agent': 'multi-source-locate/1.0'})
with urllib.request.urlopen(req, timeout=10, context=ctx) as resp:
data = json.loads(resp.read().decode())
if 'loc' not in data:
return None
lat, lon = map(float, data['loc'].split(','))
return LocationResult(
latitude=lat,
longitude=lon,
accuracy=10000.0, # ~10km
method='ip',
timestamp=datetime.now(timezone.utc).isoformat(),
raw_data={'city': data.get('city'), 'country': data.get('country')}
)
except Exception:
return None
def _get_ipgeolocation() -> Optional[LocationResult]:
"""Query ipgeolocation.io (free tier available)."""
url = "https://api.ipgeolocation.io/ipgeo?apiKey=free"
ctx = ssl.create_default_context()
try:
req = urllib.request.Request(url, headers={'User-Agent': 'multi-source-locate/1.0'})
with urllib.request.urlopen(req, timeout=10, context=ctx) as resp:
data = json.loads(resp.read().decode())
lat = data.get('latitude')
lon = data.get('longitude')
if lat is None or lon is None:
return None
return LocationResult(
latitude=float(lat),
longitude=float(lon),
accuracy=8000.0,
method='ip',
timestamp=datetime.now(timezone.utc).isoformat(),
raw_data={'city': data.get('city'), 'country': data.get('country_name')}
)
except Exception:
return None
def get_wifi_location() -> Optional[LocationResult]:
"""Get location from WiFi BSSID geolocation."""
bssids = _scan_wifi_bssids()
if not bssids:
return None
# Try geolocation APIs with BSSID data
result = _geolocate_wifi(bssids)
if result:
return result
return None
def _scan_wifi_bssids() -> List[Dict[str, Any]]:
"""Scan for nearby WiFi networks and collect BSSIDs."""
bssids = []
if sys.platform == 'win32':
# Windows: netsh wlan show networks mode=bssid
# NOTE: use encoding='utf-8' with errors='ignore' to handle Chinese SSIDs
try:
result = subprocess.run(
['netsh', 'wlan', 'show', 'networks', 'mode=bssid'],
capture_output=True,
text=True,
timeout=30,
encoding='utf-8', # force UTF-8 (Windows default is GBK)
errors='ignore' # skip undecodable bytes (Chinese SSIDs)
)
current_ssid = None
for line in result.stdout.split('\n'):
line = line.strip()
if line.startswith('SSID'):
parts = line.split(':', 1)
if len(parts) == 2:
current_ssid = parts[1].strip()
elif 'BSSID' in line:
parts = line.split(':', 1)
if len(parts) == 2:
bssid = parts[1].strip().upper()
if bssid and bssid not in [b.get('bssid') for b in bssids]:
bssids.append({'ssid': current_ssid, 'bssid': bssid})
elif 'Signal' in line and bssids:
parts = line.split(':', 1)
if len(parts) == 2:
try:
signal = int(parts[1].strip().rstrip('%'))
bssids[-1]['signal'] = signal
except ValueError:
pass
except Exception as e:
print(f"WiFi scan failed: {e}", file=sys.stderr)
elif sys.platform == 'darwin':
# macOS: airport -s
try:
result = subprocess.run(
['/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport', '-s'],
capture_output=True,
text=True,
timeout=30,
encoding='utf-8', errors='ignore'
)
for line in result.stdout.split('\n')[1:]: # Skip header
parts = line.split()
if len(parts) >= 6:
bssid = parts[1].upper()
signal = int(parts[2])
bssids.append({'ssid': parts[0], 'bssid': bssid, 'signal': signal})
except Exception as e:
print(f"WiFi scan failed: {e}", file=sys.stderr)
else:
# Linux: nmcli or iwlist
try:
result = subprocess.run(
['nmcli', '-t', '-f', 'SSID,BSSID,SIGNAL', 'device', 'wifi', 'list'],
capture_output=True,
text=True,
timeout=30,
encoding='utf-8', errors='ignore'
)
for line in result.stdout.split('\n'):
if line.strip():
parts = line.split(':')
if len(parts) >= 3:
ssid = parts[0]
bssid = parts[1].upper()
try:
signal = int(parts[2])
except ValueError:
signal = 0
bssids.append({'ssid': ssid, 'bssid': bssid, 'signal': signal})
except Exception as e:
print(f"WiFi scan failed: {e}", file=sys.stderr)
return bssids
def _geolocate_wifi(bssids: List[Dict[str, Any]]) -> Optional[LocationResult]:
"""Query geolocation API with WiFi BSSIDs."""
# Google Geolocation API (requires key)
# Mozilla Location Service (MLS) - free but deprecated
# Unwired Labs - free tier available
import os
# Try Google if key available
google_key = os.environ.get('GOOGLE_GEOLOCATION_API_KEY')
if google_key:
return _geolocate_google(bssids, google_key)
# Try Unwired Labs
unwired_key = os.environ.get('UNWIRED_API_KEY', 'free')
return _geolocate_unwired(bssids, unwired_key)
def _geolocate_google(bssids: List[Dict[str, Any]], api_key: str) -> Optional[LocationResult]:
"""Query Google Geolocation API."""
url = f"https://www.googleapis.com/geolocation/v1/geolocate?key={api_key}"
wifi_aps = []
for ap in bssids[:20]: # Max 20 APs
wifi_aps.append({
'macAddress': ap['bssid'].replace(':', '').replace('-', ''),
'signalStrength': ap.get('signal', -50)
})
payload = json.dumps({'wifiAccessPoints': wifi_aps}).encode()
ctx = ssl.create_default_context()
try:
req = urllib.request.Request(
url,
data=payload,
headers={'Content-Type': 'application/json'}
)
with urllib.request.urlopen(req, timeout=10, context=ctx) as resp:
data = json.loads(resp.read().decode())
location = data.get('location', {})
accuracy = data.get('accuracy', 100)
return LocationResult(
latitude=location.get('lat'),
longitude=location.get('lng'),
accuracy=float(accuracy),
method='wifi',
timestamp=datetime.now(timezone.utc).isoformat()
)
except Exception as e:
print(f"Google geolocation failed: {e}", file=sys.stderr)
return None
def _geolocate_unwired(bssids: List[Dict[str, Any]], api_key: str) -> Optional[LocationResult]:
"""Query Unwired Labs (unwiredlabs.com) geolocation."""
url = "https://us1.unwiredlabs.com/v2/process.php"
wifi_aps = []
for ap in bssids[:20]:
wifi_aps.append({
'bssid': ap['bssid'],
'signal': ap.get('signal', -50)
})
payload = json.dumps({
'token': api_key,
'wifi': wifi_aps
}).encode()
ctx = ssl.create_default_context()
try:
req = urllib.request.Request(
url,
data=payload,
headers={'Content-Type': 'application/json'}
)
with urllib.request.urlopen(req, timeout=10, context=ctx) as resp:
data = json.loads(resp.read().decode())
if data.get('status') != 'ok':
return None
return LocationResult(
latitude=data.get('lat'),
longitude=data.get('lon'),
accuracy=float(data.get('accuracy', 100)),
method='wifi',
timestamp=datetime.now(timezone.utc).isoformat()
)
except Exception as e:
print(f"Unwired geolocation failed: {e}", file=sys.stderr)
return None
def get_cellular_location() -> Optional[LocationResult]:
"""Get location from cellular tower info."""
cell_info = _scan_cell_towers()
if not cell_info:
return None
return _geolocate_cell(cell_info)
def _scan_cell_towers() -> List[Dict[str, Any]]:
"""Scan for cellular tower info."""
cells = []
if sys.platform == 'win32':
# Windows: Requires cellular modem with AT commands
# This is complex and hardware-specific
pass
elif sys.platform == 'darwin':
# macOS: CoreTelephony framework (requires iOS)
pass
else:
# Linux: ModemManager
try:
result = subprocess.run(
['mmcli', '-m', '0', '--output=json'],
capture_output=True,
text=True,
timeout=10
)
data = json.loads(result.stdout)
modem = data.get('modem', {})
# Get 3GPP info
gpp = modem.get('3gpp', {})
if gpp:
cells.append({
'mcc': gpp.get('mcc'),
'mnc': gpp.get('mnc'),
'lac': gpp.get('location-area-code'),
'cid': gpp.get('cell-id')
})
except Exception:
pass
return cells
def _geolocate_cell(cells: List[Dict[str, Any]]) -> Optional[LocationResult]:
"""Query geolocation API with cell tower info."""
import os
google_key = os.environ.get('GOOGLE_GEOLOCATION_API_KEY')
if google_key and cells:
url = f"https://www.googleapis.com/geolocation/v1/geolocate?key={google_key}"
cell_towers = []
for cell in cells:
cell_towers.append({
'cellId': cell.get('cid'),
'locationAreaCode': cell.get('lac'),
'mobileCountryCode': cell.get('mcc'),
'mobileNetworkCode': cell.get('mnc')
})
payload = json.dumps({'cellTowers': cell_towers}).encode()
ctx = ssl.create_default_context()
try:
req = urllib.request.Request(
url,
data=payload,
headers={'Content-Type': 'application/json'}
)
with urllib.request.urlopen(req, timeout=10, context=ctx) as resp:
data = json.loads(resp.read().decode())
location = data.get('location', {})
accuracy = data.get('accuracy', 1000)
return LocationResult(
latitude=location.get('lat'),
longitude=location.get('lng'),
accuracy=float(accuracy),
method='cellular',
timestamp=datetime.now(timezone.utc).isoformat()
)
except Exception as e:
print(f"Cellular geolocation failed: {e}", file=sys.stderr)
return None
def validate_coordinates(lat, lon):
"""Validate and clamp coordinates to valid ranges."""
try:
lat = float(lat)
lon = float(lon)
lat = max(-90.0, min(90.0, lat))
lon = max(-180.0, min(180.0, lon))
return lat, lon
except (ValueError, TypeError):
return None, None
@dataclass
class TriangulatedResult:
"""Combined multi-source location result."""
latitude: float
longitude: float
accuracy_meters: float
confidence: float
method: str
sources: Dict[str, Dict[str, Any]]
timestamp: str
def triangulate(results: List[LocationResult]) -> TriangulatedResult:
"""Combine multiple location results using weighted average."""
if not results:
raise ValueError("No location results to triangulate")
if len(results) == 1:
r = results[0]
r.weight = 1.0 # normalize: single source = 100% weight
return TriangulatedResult(
latitude=r.latitude,
longitude=r.longitude,
accuracy_meters=r.accuracy,
confidence=0.5, # Single source, moderate confidence
method=r.method,
sources={r.method: {
'lat': r.latitude,
'lon': r.longitude,
'accuracy': r.accuracy,
'weight': 1.0,
'timestamp': r.timestamp,
'method': r.method,
'raw_data': r.raw_data,
}},
timestamp=r.timestamp
)
# Calculate weights based on accuracy (inverse variance)
for r in results:
r.weight = 1.0 / (max(r.accuracy, 1.0) ** 2)
total_weight = sum(r.weight for r in results)
# Weighted centroid
weighted_lat = sum(r.latitude * r.weight for r in results) / total_weight
weighted_lon = sum(r.longitude * r.weight for r in results) / total_weight
# Estimate combined accuracy from residual dispersion
if len(results) > 1:
variance_lat = sum(r.weight * (r.latitude - weighted_lat) ** 2 for r in results) / total_weight
variance_lon = sum(r.weight * (r.longitude - weighted_lon) ** 2 for r in results) / total_weight
combined_variance = (variance_lat + variance_lon) / 2
combined_accuracy = max(
min(r.accuracy for r in results), # Can't be better than best source
(combined_variance ** 0.5) * 111000 # Convert degrees to meters (approx)
)
else:
combined_accuracy = results[0].accuracy
# Confidence score based on number of sources and agreement
# More sources = higher confidence
# Better agreement = higher confidence
source_factor = min(len(results) / 4.0, 1.0) # Max at 4 sources
# Agreement factor: how well do sources agree?
if len(results) > 1:
max_disagreement = max(
((r.latitude - weighted_lat) ** 2 + (r.longitude - weighted_lon) ** 2) ** 0.5
for r in results
)
max_disagreement_m = max_disagreement * 111000
agreement_factor = max(0, 1.0 - max_disagreement_m / (combined_accuracy * 2))
else:
agreement_factor = 0.5 # Single source, no agreement to measure
confidence = (source_factor * 0.4 + agreement_factor * 0.6)
# Build sources dict
sources = {}
for r in results:
sources[r.method] = {
'lat': r.latitude,
'lon': r.longitude,
'accuracy': r.accuracy,
'weight': r.weight / total_weight,
'timestamp': r.timestamp,
'method': r.method,
'raw_data': r.raw_data,
}
return TriangulatedResult(
latitude=weighted_lat,
longitude=weighted_lon,
accuracy_meters=combined_accuracy,
confidence=confidence,
method='triangulated',
sources=sources,
timestamp=datetime.now(timezone.utc).isoformat()
)
def format_output(result: TriangulatedResult, fmt: str = 'json') -> str:
"""Format result for output."""
if fmt == 'json':
return json.dumps(asdict(result), indent=2)
else:
lines = [
f"Location: {result.latitude:.6f}, {result.longitude:.6f}",
f"Accuracy: {result.accuracy_meters:.0f} meters",
f"Confidence: {result.confidence:.0%}",
f"Method: {result.method}",
f"Sources: {', '.join(result.sources.keys())}",
f"Timestamp: {result.timestamp}"
]
return '\n'.join(lines)
def main():
parser = argparse.ArgumentParser(
description='Multi-source geolocation tool'
)
parser.add_argument(
'--method', '-m',
default='all',
help='Location method(s): gps, ip, wifi, cellular, all (comma-separated)'
)
parser.add_argument(
'--format', '-f',
choices=['json', 'text'],
default='json',
help='Output format'
)
parser.add_argument(
'--timeout', '-t',
type=int,
default=30,
help='Timeout in seconds for GPS'
)
args = parser.parse_args()
# Parse methods
if args.method == 'all':
methods = ['gps', 'system', 'ip', 'wifi', 'cellular']
else:
methods = [m.strip().lower() for m in args.method.split(',')]
# Collect results
results = []
for method in methods:
print(f"Trying {method}...", file=sys.stderr)
if method == 'gps':
r = get_gps_location(args.timeout)
elif method == 'system':
r = get_system_location(args.timeout)
elif method == 'ip':
r = get_ip_location()
elif method == 'wifi':
r = get_wifi_location()
elif method == 'cellular':
r = get_cellular_location()
else:
print(f"Unknown method: {method}", file=sys.stderr)
continue
if r:
print(f" {method}: {r.latitude:.4f}, {r.longitude:.4f} (±{r.accuracy:.0f}m)", file=sys.stderr)
results.append(r)
else:
print(f" {method}: failed", file=sys.stderr)
if not results:
print("Error: No location sources succeeded", file=sys.stderr)
sys.exit(1)
# Triangulate
final = triangulate(results)
# Output
print(format_output(final, args.format))
if __name__ == '__main__':
main()
FILE:scripts/triangulate.py
#!/usr/bin/env python3
"""
Weighted triangulation module.
Combines multiple location estimates into a single best estimate.
"""
import math
from typing import List, Dict, Any, Optional, Tuple
from dataclasses import dataclass, asdict
from datetime import datetime, timezone
@dataclass
class LocationEstimate:
"""A single location estimate from one source."""
latitude: float
longitude: float
accuracy: float # meters (1 sigma)
method: str
weight: float = 0.0
timestamp: Optional[str] = None
raw_data: Optional[Dict[str, Any]] = None
@dataclass
class TriangulatedLocation:
"""Combined location from multiple sources."""
latitude: float
longitude: float
accuracy: float # meters
confidence: float # 0.0 to 1.0
method: str
sources: Dict[str, Dict[str, Any]]
timestamp: str
disagreement: float # meters - max distance between sources
def triangulate(
estimates: List[LocationEstimate],
weights: Optional[Dict[str, float]] = None
) -> TriangulatedLocation:
"""
Combine multiple location estimates using weighted average.
Args:
estimates: List of location estimates from different sources
weights: Optional manual weights per method (overrides accuracy-based)
Returns:
TriangulatedLocation with combined estimate and confidence
"""
if not estimates:
raise ValueError("No location estimates provided")
# Single source case
if len(estimates) == 1:
est = estimates[0]
return TriangulatedLocation(
latitude=est.latitude,
longitude=est.longitude,
accuracy=est.accuracy,
confidence=_single_source_confidence(est),
method=est.method,
sources={est.method: _estimate_to_dict(est)},
timestamp=est.timestamp or datetime.now(timezone.utc).isoformat(),
disagreement=0.0
)
# Calculate weights
for est in estimates:
if weights and est.method in weights:
est.weight = weights[est.method]
else:
# Weight based on inverse variance (1/accuracy^2)
est.weight = 1.0 / (est.accuracy ** 2)
# Normalize weights
total_weight = sum(est.weight for est in estimates)
# Calculate weighted centroid
weighted_lat = sum(est.latitude * est.weight for est in estimates) / total_weight
weighted_lon = sum(est.longitude * est.weight for est in estimates) / total_weight
# Calculate disagreement (max distance from centroid)
max_disagreement = 0.0
for est in estimates:
dist = haversine_distance(
est.latitude, est.longitude,
weighted_lat, weighted_lon
)
max_disagreement = max(max_disagreement, dist)
# Estimate combined accuracy
# Use the minimum accuracy of sources, but increase if sources disagree
best_accuracy = min(est.accuracy for est in estimates)
# If sources disagree more than the best accuracy, increase uncertainty
if max_disagreement > best_accuracy:
combined_accuracy = math.sqrt(best_accuracy ** 2 + (max_disagreement / 2) ** 2)
else:
combined_accuracy = best_accuracy
# Calculate confidence score
confidence = _calculate_confidence(
estimates, weighted_lat, weighted_lon,
combined_accuracy, max_disagreement
)
# Build sources dict
sources = {}
for est in estimates:
sources[est.method] = {
'lat': est.latitude,
'lon': est.longitude,
'accuracy': est.accuracy,
'weight': est.weight / total_weight
}
return TriangulatedLocation(
latitude=weighted_lat,
longitude=weighted_lon,
accuracy=combined_accuracy,
confidence=confidence,
method='triangulated',
sources=sources,
timestamp=datetime.now(timezone.utc).isoformat(),
disagreement=max_disagreement
)
def _single_source_confidence(est: LocationEstimate) -> float:
"""Calculate confidence for a single source."""
# Base confidence by method
method_confidence = {
'gps': 0.9,
'wifi': 0.7,
'cellular': 0.5,
'ip': 0.3,
}
base = method_confidence.get(est.method, 0.5)
# Adjust by accuracy
if est.accuracy <= 10:
return min(base + 0.05, 0.95)
elif est.accuracy <= 50:
return base
elif est.accuracy <= 500:
return base * 0.9
else:
return base * 0.7
def _calculate_confidence(
estimates: List[LocationEstimate],
center_lat: float,
center_lon: float,
combined_accuracy: float,
disagreement: float
) -> float:
"""
Calculate confidence score for combined result.
Factors:
- Number of sources (more = better)
- Agreement between sources (less disagreement = better)
- Quality of sources (GPS > WiFi > Cellular > IP)
"""
# Source count factor (max at 4 sources)
source_factor = min(len(estimates) / 4.0, 1.0)
# Method quality factor
method_scores = {
'gps': 1.0,
'wifi': 0.8,
'cellular': 0.6,
'ip': 0.4,
}
# Weighted average of method scores
total_weight = sum(est.weight for est in estimates)
method_factor = sum(
method_scores.get(est.method, 0.5) * est.weight
for est in estimates
) / total_weight
# Agreement factor
# Perfect agreement = 1.0, disagreement > accuracy = reduced
if combined_accuracy > 0:
agreement_factor = max(0.0, 1.0 - disagreement / (combined_accuracy * 3))
else:
agreement_factor = 1.0
# Accuracy factor
# Better accuracy = higher confidence
if combined_accuracy <= 10:
accuracy_factor = 1.0
elif combined_accuracy <= 100:
accuracy_factor = 0.9
elif combined_accuracy <= 1000:
accuracy_factor = 0.7
else:
accuracy_factor = 0.5
# Combine factors
confidence = (
source_factor * 0.25 +
method_factor * 0.30 +
agreement_factor * 0.25 +
accuracy_factor * 0.20
)
return min(max(confidence, 0.0), 1.0)
def haversine_distance(
lat1: float, lon1: float,
lat2: float, lon2: float
) -> float:
"""
Calculate the great-circle distance between two points.
Args:
lat1, lon1: First point (degrees)
lat2, lon2: Second point (degrees)
Returns:
Distance in meters
"""
R = 6371000 # Earth radius in meters
phi1 = math.radians(lat1)
phi2 = math.radians(lat2)
delta_phi = math.radians(lat2 - lat1)
delta_lambda = math.radians(lon2 - lon1)
a = (math.sin(delta_phi / 2) ** 2 +
math.cos(phi1) * math.cos(phi2) * math.sin(delta_lambda / 2) ** 2)
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
return R * c
def bearing(
lat1: float, lon1: float,
lat2: float, lon2: float
) -> float:
"""
Calculate the bearing from point 1 to point 2.
Returns:
Bearing in degrees (0-360)
"""
lat1_rad = math.radians(lat1)
lat2_rad = math.radians(lat2)
delta_lon = math.radians(lon2 - lon1)
x = math.sin(delta_lon) * math.cos(lat2_rad)
y = (math.cos(lat1_rad) * math.sin(lat2_rad) -
math.sin(lat1_rad) * math.cos(lat2_rad) * math.cos(delta_lon))
theta = math.atan2(x, y)
return (math.degrees(theta) + 360) % 360
def destination_point(
lat: float, lon: float,
distance: float, bearing_deg: float
) -> Tuple[float, float]:
"""
Calculate destination point given start, distance, and bearing.
Args:
lat, lon: Start point (degrees)
distance: Distance in meters
bearing_deg: Bearing in degrees
Returns:
(lat, lon) of destination point
"""
R = 6371000 # Earth radius in meters
lat_rad = math.radians(lat)
lon_rad = math.radians(lon)
brng_rad = math.radians(bearing_deg)
delta = distance / R
dest_lat = math.asin(
math.sin(lat_rad) * math.cos(delta) +
math.cos(lat_rad) * math.sin(delta) * math.cos(brng_rad)
)
dest_lon = lon_rad + math.atan2(
math.sin(brng_rad) * math.sin(delta) * math.cos(lat_rad),
math.cos(delta) - math.sin(lat_rad) * math.sin(dest_lat)
)
return math.degrees(dest_lat), math.degrees(dest_lon)
def _estimate_to_dict(est: LocationEstimate) -> Dict[str, Any]:
"""Convert estimate to dict for output."""
d = {
'lat': est.latitude,
'lon': est.longitude,
'accuracy': est.accuracy,
}
if est.raw_data:
d.update(est.raw_data)
return d
if __name__ == '__main__':
# Test triangulation
print("Testing triangulation...\n")
# Simulate multiple sources
estimates = [
LocationEstimate(
latitude=39.9045,
longitude=116.4071,
accuracy=5,
method='gps'
),
LocationEstimate(
latitude=39.9039,
longitude=116.4078,
accuracy=30,
method='wifi'
),
LocationEstimate(
latitude=39.9042,
longitude=116.4074,
accuracy=5000,
method='ip'
),
]
result = triangulate(estimates)
print(f"Combined location:")
print(f" Latitude: {result.latitude:.6f}")
print(f" Longitude: {result.longitude:.6f}")
print(f" Accuracy: {result.accuracy:.1f} meters")
print(f" Confidence: {result.confidence:.0%}")
print(f" Disagreement: {result.disagreement:.1f} meters")
print(f"\nSources:")
for method, data in result.sources.items():
print(f" {method}: ({data['lat']:.4f}, {data['lon']:.4f}) ±{data['accuracy']:.0f}m (weight: {data['weight']:.2f})")
FILE:scripts/wifi_scanner.py
#!/usr/bin/env python3
"""
WiFi BSSID scanner module.
Scans for nearby WiFi networks and collects BSSIDs for geolocation.
"""
import subprocess
import sys
import re
from typing import List, Dict, Any, Optional
from dataclasses import dataclass
@dataclass
class WiFiAccessPoint:
"""WiFi access point info."""
ssid: str
bssid: str # MAC address
signal: int # dBm or percentage
channel: Optional[int] = None
frequency: Optional[int] = None # MHz
encryption: Optional[str] = None
def scan_wifi() -> List[WiFiAccessPoint]:
"""
Scan for nearby WiFi networks.
Returns list of WiFiAccessPoint objects.
"""
if sys.platform == 'win32':
return _scan_windows()
elif sys.platform == 'darwin':
return _scan_macos()
else:
return _scan_linux()
def _scan_windows() -> List[WiFiAccessPoint]:
"""
Scan WiFi on Windows using netsh.
Output format:
SSID 1 : NetworkName
Network type : Infrastructure
Authentication : WPA2-Personal
Encryption : CCMP
BSSID 1 : aa:bb:cc:dd:ee:ff
Signal : 80%
Channel : 6
"""
aps = []
try:
result = subprocess.run(
['netsh', 'wlan', 'show', 'networks', 'mode=bssid'],
capture_output=True,
text=True,
timeout=30,
encoding='utf-8',
errors='ignore'
)
current_ap = None
for line in result.stdout.split('\n'):
line = line.strip()
# SSID line
match = re.match(r'SSID \d+\s*:\s*(.+)', line)
if match:
if current_ap:
aps.append(current_ap)
current_ap = WiFiAccessPoint(
ssid=match.group(1).strip(),
bssid='',
signal=0
)
continue
if not current_ap:
continue
# BSSID line
match = re.match(r'BSSID \d+\s*:\s*([0-9a-fA-F:]+)', line)
if match:
if current_ap.bssid: # Save previous BSSID for this SSID
aps.append(current_ap)
current_ap = WiFiAccessPoint(
ssid=current_ap.ssid,
bssid='',
signal=0
)
current_ap.bssid = match.group(1).upper()
continue
# Signal line
match = re.match(r'Signal\s*:\s*(\d+)%', line)
if match:
# Convert percentage to dBm (approximate)
pct = int(match.group(1))
current_ap.signal = pct
continue
# Channel line
match = re.match(r'Channel\s*:\s*(\d+)', line)
if match:
current_ap.channel = int(match.group(1))
continue
# Encryption
match = re.match(r'Encryption\s*:\s*(\w+)', line)
if match:
current_ap.encryption = match.group(1)
if current_ap and current_ap.bssid:
aps.append(current_ap)
except Exception as e:
print(f"WiFi scan failed: {e}", file=sys.stderr)
return aps
def _scan_macos() -> List[WiFiAccessPoint]:
"""
Scan WiFi on macOS using airport utility.
Output format (airport -s):
SSID BSSID RSSI CHANNEL HT CC SECURITY
MyNetwork aa:bb:cc:dd:ee:ff -70 6 Y US WPA2(PSK)
"""
aps = []
airport_path = '/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport'
try:
result = subprocess.run(
[airport_path, '-s'],
capture_output=True,
text=True,
timeout=30
)
# Skip header line
lines = result.stdout.strip().split('\n')[1:]
for line in lines:
if not line.strip():
continue
# Parse fixed-width columns
# SSID is up to 32 chars, then BSSID, RSSI, CHANNEL, etc.
parts = line.split()
if len(parts) >= 4:
# Last parts are: RSSI CHANNEL HT CC SECURITY
# RSSI is negative number
ssid_parts = []
bssid = None
rssi = None
channel = None
for i, part in enumerate(parts):
# BSSID looks like xx:xx:xx:xx:xx:xx
if re.match(r'[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}', part):
ssid_parts = parts[:i]
bssid = part.upper()
if i + 1 < len(parts):
try:
rssi = int(parts[i + 1])
except ValueError:
pass
if i + 2 < len(parts):
try:
channel = int(parts[i + 2])
except ValueError:
pass
break
if bssid:
aps.append(WiFiAccessPoint(
ssid=' '.join(ssid_parts) if ssid_parts else '',
bssid=bssid,
signal=rssi if rssi is not None else 0,
channel=channel
))
except Exception as e:
print(f"WiFi scan failed: {e}", file=sys.stderr)
return aps
def _scan_linux() -> List[WiFiAccessPoint]:
"""
Scan WiFi on Linux using nmcli or iwlist.
"""
# Try nmcli first (NetworkManager)
aps = _scan_nmcli()
if not aps:
# Fallback to iwlist
aps = _scan_iwlist()
return aps
def _scan_nmcli() -> List[WiFiAccessPoint]:
"""
Scan using nmcli (NetworkManager CLI).
Output format (-t for terse, -f for fields):
SSID:BSSID:SIGNAL:CHAN:SECURITY
"""
aps = []
try:
result = subprocess.run(
['nmcli', '-t', '-f', 'SSID,BSSID,SIGNAL,CHAN,SECURITY', 'device', 'wifi', 'list'],
capture_output=True,
text=True,
timeout=30
)
for line in result.stdout.strip().split('\n'):
if not line:
continue
parts = line.split(':')
if len(parts) >= 3:
ssid = parts[0]
bssid = parts[1].upper() if len(parts) > 1 else ''
# Signal is 0-100 percentage
signal = 0
if len(parts) > 2:
try:
signal = int(parts[2])
except ValueError:
pass
# Channel
channel = None
if len(parts) > 3 and parts[3]:
try:
channel = int(parts[3])
except ValueError:
pass
# Security
encryption = parts[4] if len(parts) > 4 else None
if bssid:
aps.append(WiFiAccessPoint(
ssid=ssid,
bssid=bssid,
signal=signal,
channel=channel,
encryption=encryption
))
except Exception as e:
print(f"nmcli scan failed: {e}", file=sys.stderr)
return aps
def _scan_iwlist() -> List[WiFiAccessPoint]:
"""
Scan using iwlist (wireless-tools).
Output format:
Cell 01 - Address: AA:BB:CC:DD:EE:FF
Channel:6
Frequency:2.437 GHz (Channel 6)
Quality=70/70 Signal level=-40 dBm
ESSID:"NetworkName"
"""
aps = []
try:
# Find wireless interface
result = subprocess.run(
['iw', 'dev'],
capture_output=True,
text=True,
timeout=10
)
interface = None
for line in result.stdout.split('\n'):
if 'Interface' in line:
interface = line.split()[-1]
break
if not interface:
# Try common names
for iface in ['wlan0', 'wlp2s0', 'wlp3s0']:
result = subprocess.run(
['ip', 'link', 'show', iface],
capture_output=True,
text=True,
timeout=5
)
if result.returncode == 0:
interface = iface
break
if not interface:
return aps
# Scan with iwlist
result = subprocess.run(
['iwlist', interface, 'scan'],
capture_output=True,
text=True,
timeout=30
)
current_ap = None
for line in result.stdout.split('\n'):
line = line.strip()
# Cell (new AP)
match = re.match(r'Cell \d+\s*-\s*Address:\s*([0-9a-fA-F:]+)', line)
if match:
if current_ap:
aps.append(current_ap)
current_ap = WiFiAccessPoint(
ssid='',
bssid=match.group(1).upper(),
signal=0
)
continue
if not current_ap:
continue
# ESSID
match = re.match(r'ESSID:"(.+)"', line)
if match:
current_ap.ssid = match.group(1)
continue
# Signal level
match = re.search(r'Signal level=(-?\d+)\s*dBm', line)
if match:
current_ap.signal = int(match.group(1))
continue
# Channel
match = re.match(r'Channel:(\d+)', line)
if match:
current_ap.channel = int(match.group(1))
continue
# Frequency
match = re.match(r'Frequency:([\d.]+)\s*GHz', line)
if match:
freq_ghz = float(match.group(1))
current_ap.frequency = int(freq_ghz * 1000)
if current_ap:
aps.append(current_ap)
except Exception as e:
print(f"iwlist scan failed: {e}", file=sys.stderr)
return aps
def get_connected_ap() -> Optional[WiFiAccessPoint]:
"""Get the currently connected WiFi AP."""
if sys.platform == 'win32':
return _get_connected_windows()
elif sys.platform == 'darwin':
return _get_connected_macos()
else:
return _get_connected_linux()
def _get_connected_windows() -> Optional[WiFiAccessPoint]:
"""Get connected AP on Windows."""
try:
result = subprocess.run(
['netsh', 'wlan', 'show', 'interfaces'],
capture_output=True,
text=True,
timeout=10,
encoding='utf-8',
errors='ignore'
)
ssid = None
bssid = None
signal = 0
for line in result.stdout.split('\n'):
line = line.strip()
match = re.match(r'SSID\s*:\s*(.+)', line)
if match:
ssid = match.group(1).strip()
match = re.match(r'BSSID\s*:\s*([0-9a-fA-F:]+)', line)
if match:
bssid = match.group(1).upper()
match = re.match(r'Signal\s*:\s*(\d+)%', line)
if match:
signal = int(match.group(1))
if ssid and bssid:
return WiFiAccessPoint(ssid=ssid, bssid=bssid, signal=signal)
except Exception:
pass
return None
def _get_connected_macos() -> Optional[WiFiAccessPoint]:
"""Get connected AP on macOS."""
airport_path = '/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport'
try:
result = subprocess.run(
[airport_path, '-I'],
capture_output=True,
text=True,
timeout=10
)
ssid = None
bssid = None
rssi = 0
for line in result.stdout.split('\n'):
line = line.strip()
if line.startswith('SSID:'):
ssid = line.split(':', 1)[1].strip()
elif line.startswith('BSSID:'):
bssid = line.split(':', 1)[1].strip().upper()
elif line.startswith('rssi:'):
try:
rssi = int(line.split(':', 1)[1].strip())
except ValueError:
pass
if ssid and bssid:
return WiFiAccessPoint(ssid=ssid, bssid=bssid, signal=rssi)
except Exception:
pass
return None
def _get_connected_linux() -> Optional[WiFiAccessPoint]:
"""Get connected AP on Linux."""
try:
result = subprocess.run(
['nmcli', '-t', '-f', 'ACTIVE,SSID,BSSID,SIGNAL', 'device', 'wifi', 'list'],
capture_output=True,
text=True,
timeout=10
)
for line in result.stdout.strip().split('\n'):
parts = line.split(':')
if parts[0] == 'yes' and len(parts) >= 3:
return WiFiAccessPoint(
ssid=parts[1],
bssid=parts[2].upper(),
signal=int(parts[3]) if len(parts) > 3 else 0
)
except Exception:
pass
return None
if __name__ == '__main__':
print("Scanning WiFi networks...\n")
aps = scan_wifi()
if aps:
print(f"Found {len(aps)} access points:\n")
for ap in sorted(aps, key=lambda x: -x.signal):
ch_display = str(ap.channel) if ap.channel else '-'
print(f" {ap.ssid:32s} {ap.bssid} Signal: {ap.signal:3d} Ch: {ch_display:>2}")
else:
print("No access points found")
print("\nConnected AP:")
connected = get_connected_ap()
if connected:
print(f" {connected.ssid} ({connected.bssid})")
else:
print(" Not connected")
FILE:scripts/__init__.py
"""Multi-source-locate package."""