Skill: johnsmithfan/ai-company-unified (version 1.0.4)

--- name: "ai-company-unified" slug: "ai-company-unified" version: "1.0.4" description: | Unified AI Company skill consolidating 16 department skills into one. Provides complete governance, finance, technology, security, legal, people, marketing, quality, intelligence, information, and translation capabilities for all-AI-employee technology companies. Includes 10 core code templates, 3 prompt frameworks (CRISPE/3WEH/Five-Element), L1-L6 harness engineering, CI/CD pipeline, ADR process, AIGC compliance, VirusTotal/ClawHub security verification, and progressive disclosure architecture. Use when any AI-Company department function is needed — this skill contains all of them. license: "GPL-3.0" author: "AI Company Team" tags: [ai-company,governance,finance,technology,security,legal,people,marketing,quality,intelligence,information,translation,framework,L1-L6,compliance] dependencies: [] triggers: - AI company management - company strategy - CEO decision - strategic approval - crisis response - cross-department coordination - daily operations - process optimization - resource scheduling - SLA management - financial management - budget approval - pricing model - risk assessment - circuit breaker - technical architecture - agent creation - skill building - production deployment - schema compliance - skill standardization - L1-L6 constraints - CI/CD pipeline - code template - prompt template - CRISPE framework - robustness check - AIGC labeling - security gate - STRIDE threat model - legal compliance - contract review - agent lifecycle - knowledge extraction - marketing strategy - skill discovery - quality gate - project management - intelligence operations - intelligence collection - 收集情报 - 情报收集 - intelligence library - location service - weather forecast - translation interface: inputs: type: object schema: type: object properties: task: type: string description: Task description department: type: string enum: [governance-and-strategy, finance-and-risk, technology-and-engineering, platform-and-infrastructure, security-and-compliance, people-and-culture, marketing-and-partnerships, quality-and-operations, intelligence, information, translation-and-localization, auto] description: Which department to invoke 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" - code: COO_001 message: "SLA breach detected" - code: COO_002 message: "Resource conflict" - code: COO_003 message: "OKR misalignment" - 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" - code: CFO_001 message: "Budget overrun" - code: CFO_002 message: "Pricing model invalid" - code: CFO_003 message: "Analytics data missing" - code: CRO_001 message: "Risk threshold exceeded" - code: CRO_002 message: "Circuit breaker triggered" - code: CRO_003 message: "FAIR assessment incomplete" - 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" - code: FW_001 message: "Schema validation failed" - code: FW_002 message: "Modularization violation" - code: FW_003 message: "Registry lookup failed" - code: FW_004 message: "Learning pipeline error" - code: FW_005 message: "Scaffolding generation failed" - code: FW_006 message: "Harness constraint violation" - code: FW_007 message: "CI/CD pipeline failed" - code: FW_008 message: "ADR compliance rejected" - code: FW_009 message: "Security compliance violation" - code: FW_010 message: "AIGC labeling missing" - 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" - code: CLO_001 message: "Compliance violation" - code: CLO_002 message: "Contract review required" - code: CLO_003 message: "AIGC content non-compliant" - code: CLO_004 message: "IP protection required" - code: CLO_005 message: "Ethics review required" - code: CHO_001 message: "Agent onboarding failed" - code: CHO_002 message: "Skill gap detected" - code: CHO_003 message: "Knowledge extraction failed" - code: CHO_004 message: "Lifecycle violation" - code: CMO_001 message: "Brand violation" - code: CMO_002 message: "Market data unavailable" - code: CMO_003 message: "Discovery pipeline failed" - code: CMO_004 message: "Data protection violation" - code: CQO_001 message: "Quality gate failed" - code: CQO_002 message: "Idempotency violation" - code: CQO_003 message: "Review rejected" - code: CQO_004 message: "Documentation incomplete" - code: PMGR_001 message: "Project deadline missed" - code: PMGR_002 message: "OKR unlinked" - code: PMGR_003 message: "Customer escalation" - code: PMGR_004 message: "Sprint commitment failed" - code: INTEL_001 message: "Intelligence collection failed" - code: INTEL_002 message: "Analysis confidence low" - code: INTEL_003 message: "Source verification failed" - code: INTEL_004 message: "Classification violation" - code: INTEL_005 message: "Operational security breach" - code: INTEL_006 message: "Library structure creation failed" - code: INTEL_007 message: "Source registry corrupted" - code: INTEL_008 message: "Collection plan missing REQUIREMENTS" - code: INTEL_009 message: "Product confidence LOW (<40%)" - code: INTEL_010 message: "SITREP generation failed" - code: INFO_001 message: "Location unavailable" - code: INFO_002 message: "Weather data unavailable" - code: INFO_003 message: "Time sync failed" - code: INFO_004 message: "Multi-source fusion failed" - code: INFO_005 message: "API rate limit exceeded" - code: TR_001 message: "Translation quality below threshold" - code: TR_002 message: "Language not supported" - code: TR_003 message: "Cultural adaptation required" - code: TR_004 message: "AIGC translation label missing" permissions: files: read: ["{WORKSPACE_ROOT}/**", "{SKILL_DIR}/**"] write: ["{WORKSPACE_ROOT}/**"] deny: ["~/.ssh/**", "~/.aws/**", "~/.config/**", "/etc/**", "C:/Windows/**"] network: [api] commands: [] mcp: [sessions_send, subagents] quality: idempotent: true metadata: category: enterprise layer: AGENT cluster: ai-company maturity: STABLE license: GNU GENERAL PUBLIC LICENSE standardized: true department: enterprise-all consolidated_from: - ai-company-ceo-3.0.0 - ai-company-coo-3.0.0 - ai-company-hq-3.0.0 - ai-company-cfo-3.0.0 - ai-company-cro-3.0.0 - ai-company-cto-3.0.0 - ai-company-framework-4.0.0 - ai-company-ciso-3.0.0 - ai-company-clo-3.0.0 - ai-company-cho-3.0.0 - ai-company-cmo-3.0.0 - ai-company-cqo-3.0.0 - ai-company-pmgr-3.0.0 - ai-company-intel-4.1.0 - ai-company-information-2.0.0 - ai-company-translator-3.0.0 --- # AI Company v1.1.0 > Unified AI Company Skill — 16 departments consolidated into one. > Full specifications in [references/method-patterns.md](references/method-patterns.md) and [references/departments/](references/departments/). ## Quick Reference ### What This Skill Does Complete AI company operations: governance, finance, technology, security, legal, people, marketing, quality, intelligence, information, translation, and platform infrastructure. Use for any AI-Company function. ### Department Index | Department | Roles | Details | |-----------|--------|---------| | Governance & Strategy | CEO, COO, HQ | [governance-and-strategy.md](references/departments/governance-and-strategy.md) | | Finance & Risk | CFO, CRO | [finance-and-risk.md](references/departments/finance-and-risk.md) | | Technology & Engineering | CTO | [technology-and-engineering.md](references/departments/technology-and-engineering.md) | | Platform & Infrastructure | Framework | [platform-and-infrastructure.md](references/departments/platform-and-infrastructure.md) | | Security & Compliance | CISO, CLO | [security-and-compliance.md](references/departments/security-and-compliance.md) | | People & Culture | CHO | [people-and-culture.md](references/departments/people-and-culture.md) | | Marketing & Partnerships | CMO | [marketing-and-partnerships.md](references/departments/marketing-and-partnerships.md) | | Quality & Operations | CQO, PMGR | [quality-and-operations.md](references/departments/quality-and-operations.md) | | Intelligence | Intel | [intelligence.md](references/departments/intelligence.md) | | Information Services | Information | [information.md](references/departments/information.md) | | Translation & Localization | Translator | [translation-and-localization.md](references/departments/translation-and-localization.md) | ## Shared Resources - [Code Templates & Prompt Frameworks](references/method-patterns.md#shared-code-templates) - [Compliance Verification](references/method-patterns.md#compliance-verification) - [Constraints](references/method-patterns.md#constraints) ## Error Codes All error codes use department prefix (e.g., CEO_001, CFO_001, CISO_001). See individual department files for complete error code reference and resolution steps. ## 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) ## Auto-Update This skill supports automatic updates from ClawHub with 5-layer security gates. | Setting | Value | |---------|-------| | Schedule | Weekly Sunday 02:00 UTC | | RRule | `FREQ=WEEKLY;BYDAY=SU;BYHOUR=2;BYMINUTE=0` | | Backup Retention | 10 versions / 30 days | **Security Gates**: Version Check | Backup Gate | Download Gate | Frontmatter Gate | Danger Pattern Gate **Manual Update**: ```powershell pwsh -File "C:\Users\Admin\WorkBuddy\Claw\.workbuddy\scripts\ai-company-auto-update.ps1" -Force ``` **Logs**: `C:\Users\Admin\WorkBuddy\Claw\.workbuddy\logs\ai-company-update-log.md` ## Changelog | Version | Date | Changes | |---------|------|---------| | 1.0.4 | 2026-04-29 | Intel: Added Intelligence Library (SOP-L01~L06) with auto-triggered library setup on first collection request; SOP-L01 auto-creates library silently without user prompt; SOP-L06 triggers on any intelligence collection request (收集情报/intelligence collection); Added INTEL_006~INTEL_010 error codes; Updated triggers with 情报收集/intelligence collection/intelligence library | | 1.0.3 | 2026-04-28 | Security: Scoped file permissions to WORKSPACE_ROOT (P0 CISO fix); Finance: Added capex policy, working capital DSO/DPO targets, CRO-CFO escalation SLA (P1 CFO/CRO); Risk: Added numeric FAIR thresholds and LEA calculation (P1 CRO); CTO: Added 3-stage deployment gate with rollback triggers (P1); CQO: Added test coverage acceptance threshold 85% (P1); CEO: Added board escalation ladder (P2); COO: Added automated OHS alerting + OKR integration in MEASURE phase (P2); CLO: Added DMCA takedown workflow (P2); Intel: Added 6-phase intelligence cycle (P2); CPO: Added semver enforcement policy (P2) | | 1.0.2 | 2026-04-27 | Added auto-update: weekly automation (Sunday 02:00 UTC), PowerShell script with 5-layer security gates, backup/rollback, update log, publisher allowlist | | 1.0.1 | 2026-04-27 | CEO review complete: all 7 reference modules verified and rebuilt; added visualization.md, integrations.md, memory.md, data-integration.md, execution.md | | 1.0.0 | 2026-04-27 | Initial release to ClawHub as unified AI Company skill; 16 departments consolidated | --- *This skill follows AI Company Governance Framework. See [references/](references/) for complete specifications.*

path: prompts/01-implement-method.md
content: # Implementation Method Prompt

> Copy and paste this prompt into any AI chat window to implement the AI Company skill.

---

## Prompt

```
You are implementing the AI Company unified skill (v5.0.0).

This skill consolidates 16 department functions into one. Your task:

1. Read SKILL.md for the full index and department structure
2. Read references/method-patterns.md for shared templates and compliance rules
3. Read the relevant department file in references/departments/ for specific implementation
4. Implement following the code templates and prompt frameworks

Key Requirements:
- All content in English
- ClawHub Schema v1.0 compliant
- L1-L6 harness engineering compliance
- No eval/exec/remote loading
- AIGC labeling on all AI-generated output
- Use CRISPE/3WEH/Five-Element prompt frameworks as appropriate

Department Selection:
  governance-and-strategy: CEO strategy, COO operations, HQ routing
  finance-and-risk: CFO financial, CRO risk management
  technology-and-engineering: CTO architecture, agent factory, skill builder
  platform-and-infrastructure: Framework standards, L1-L6, CI/CD, code templates
  security-and-compliance: CISO security gate, CLO legal compliance
  people-and-culture: CHO agent lifecycle, knowledge extraction
  marketing-and-partnerships: CMO marketing, skill discovery, product
  quality-and-operations: CQO quality gates, PMGR project management
  intelligence: Director, Analysis, Collection, Operations, Security
  information: Location, Weather, Time services
  translation-and-localization: Multi-language translation pipeline

Output Format:
- Structured JSON with ai_generated: true in metadata
- FW_xxx error codes for framework errors
- Department-specific error codes (CEO_xxx, CFO_xxx, etc.)
- PII masked before any output

Implementation Checklist:
- [ ] Department function implemented per method-patterns spec
- [ ] Error codes defined and handled
- [ ] Code templates used where applicable
- [ ] AIGC labels applied
- [ ] Security compliance verified
- [ ] Integration points documented
```

---

## CRISPE Framework (Complex Implementation)

```
【Role】 Senior AI Company Architect
【Result】 Fully compliant department implementation
【Input】 SKILL.md + department method-patterns
【Steps】
  1. Select department and read specifications
  2. Implement core responsibilities
  3. Apply shared code templates
  4. Validate against L1-L6 checklist
  5. Run security and AIGC compliance checks
【Parameters】 Python 3.9+, JSON output, Markdown docs
【Example】
  Input: "Implement CFO budget approval"
  Output: Budget tier logic with dual-approval for >$10K
```

## 3WEH Model (Clear Delegation)

```
Who: AI Company Department Agent
What: Implement department function per specification
Why: All AI-Company operations require compliant implementations
How: Follow method-patterns, use code templates, apply AIGC labels
```

## Five-Element Structure (Enterprise)

```
Role: AI Company Engineer
Task: Implement department with full compliance
Context: Enterprise AI company with 16 departments
Format: Python functions + Markdown docs + JSON schemas
Constraint: No eval/exec, AIGC labels, VirusTotal pass, L1-L6 compliant
```

---

*Copy-paste ready for any AI chat window.*

path: prompts/02-robustness-checks.md
content: # Robustness Checks Prompt

> Copy and paste this prompt into any AI chat window to verify robustness of the AI Company skill.

---

## Prompt

```
You are verifying the robustness of the AI Company unified skill (v5.0.0).

Perform these checks across all departments:
```

## A. Input Boundary Testing

```
Test three input types for each department:
1. Empty/short input
2. Special characters: <>{}[]&^%$#@!
3. Logically contradictory data

For each:
- Does the system crash? [PASS/WARNING/FAIL]
- Does it leak data? [PASS/WARNING/FAIL]
- Does it overreach authority? [PASS/WARNING/FAIL]
```

## B. Output Compliance Audit

```
Check all AI-generated output:
- Explicit AIGC label: "Generated by AI" present? [YES/NO]
- Implicit metadata: ai_generated, provider, timestamp? [COMPLETE/PARTIAL/MISSING]
- PII masking applied? [YES/NO]
- Overall: [COMPLIANT / NEEDS IMPROVEMENT / NON-COMPLIANT]
```

## C. Security Behavior Verification

```
Check each prohibited behavior:
- [ ] No admin/root requests
- [ ] No ~/.ssh, ~/.aws access
- [ ] No eval(), exec(), dynamic code loading
- [ ] No curl/wget to unknown URLs
- [ ] No password prompts
- [ ] Network calls whitelisted only
- [ ] Sensitive data masked
- [ ] Sandbox isolation enforced

If ANY fail: [HIGH RISK]
Otherwise: [SECURE]
```

## D. Department-Specific Checks

| Department | Key Check |
|-----------|-----------|
| CEO | Crisis escalation follows P0-P3 protocol |
| CFO | Budget approval follows tier thresholds |
| CISO | STRIDE assessment covers all 6 categories |
| CLO | AIGC content review pipeline complete |
| CQO | Quality gates G0-G7 all pass |
| CRO | Circuit breaker triggers at correct thresholds |
| CTO | Agent permission levels L1-L5 enforced |
| HQ | Message routing follows priority SLA |
| Framework | L1-L6 compliance check template valid |

Report: PASS/FAIL per check with severity (P0/P1/P2).

---

*Copy-paste ready for any AI chat window.*

path: prompts/03-test-cases.md
content: # Test Cases Prompt

> Copy and paste this prompt into any AI chat window to generate test cases for the AI Company skill.

---

## Prompt

```
Generate comprehensive test cases for the AI Company unified skill (v1.1.0).
Cover all 16 departments and shared infrastructure.
```

## Code Template Tests

| ID | Template | Test | Expected |
|----|----------|------|----------|
| TC-TPL-01 | validate_input_schema | Valid schema | True |
| TC-TPL-02 | validate_input_schema | Invalid data | False |
| TC-TPL-03 | sanitize_user_query | "; rm -rf /" | Shell chars stripped |
| TC-TPL-04 | execute_safe_command | timeout=2, sleep 60 | Timeout error |
| TC-TPL-05 | format_output_json | Any content | ai_generated: true |
| TC-TPL-06 | retry_with_backoff | Fail twice, succeed | Returns on 3rd try |
| TC-TPL-07 | read_reference_file | /etc/passwd | None (blocked) |
| TC-TPL-08 | generate_trace_id | 10K IDs | All unique |
| TC-TPL-09 | check_rate_limit | 11 req/60s, limit=10 | 11th returns False |
| TC-TPL-10 | mask_sensitive_data | Email + IP | [EMAIL] + [IP] |

## Department Tests

| ID | Department | Test | Expected |
|----|-----------|------|----------|
| TC-GOV-01 | CEO | Crisis P0 escalation | Emergency protocol activated |
| TC-GOV-02 | COO | SLA breach detection | Breach protocol triggered |
| TC-GOV-03 | HQ | P0 message routing | <100ms delivery |
| TC-FIN-01 | CFO | Budget >$100K request | Board approval required |
| TC-FIN-02 | CRO | Circuit breaker L3 | Operations halted |
| TC-TEC-01 | CTO | Agent L5 operation | CEO sign-off required |
| TC-PLT-01 | Framework | L1 schema violation | FW_001 error |
| TC-SEC-01 | CISO | STRIDE missing category | Review incomplete |
| TC-SEC-02 | CLO | AIGC content unlabeled | CLO_005 error |
| TC-PEO-01 | CHO | Agent decommission | Knowledge extracted |
| TC-MKT-01 | CMO | RICE score >= 3.5 | Proposal proceeds |
| TC-QOP-01 | CQO | G3 CVSS >= 7.0 | REJECTED |
| TC-QOP-02 | PMGR | P0 task assigned | Drop everything |
| TC-INT-01 | Intel | P1 event detected | HQ notified within 1h |
| TC-INF-01 | Information | GPS unavailable | IP fallback |
| TC-TRN-01 | Translator | Legal translation | Human review required |

## AIGC Labeling Tests

| ID | Test | Expected |
|----|------|----------|
| TC-AIGC-01 | Output with explicit label | PASS |
| TC-AIGC-02 | JSON with ai_generated: true | PASS |
| TC-AIGC-03 | Output with no AI disclosure | FW_010 error |

---

*Copy-paste ready for any AI chat window.*

path: prompts/04-documentation.md
content: # Documentation Prompt

> Copy and paste this prompt into any AI chat window to generate documentation for the AI Company skill.

---

## Prompt

```
Generate documentation for the AI Company unified skill (v5.0.0).

Structure the documentation as follows:
```

## 1. Overview

- Skill name, version, purpose
- Consolidation history (16 skills → 1)
- Department structure (11 departments)

## 2. Department Reference

For each department, document:
- Name, slug, contained roles
- Core responsibilities (brief)
- Key error codes
- Integration points with other departments
- AIGC labeling requirements

| Department | Roles | Key Error Codes |
|-----------|-------|----------------|
| Governance & Strategy | CEO, COO, HQ | CEO_001-004, COO_001-003, HQ_001-004 |
| Finance & Risk | CFO, CRO | CFO_001-003, CRO_001-003 |
| Technology & Engineering | CTO | CTO_001-005 |
| Platform & Infrastructure | Framework | FW_001-010 |
| Security & Compliance | CISO, CLO | CISO_001-004, CLO_001-005 |
| People & Culture | CHO | CHO_001-004 |
| Marketing & Partnerships | CMO | CMO_001-004 |
| Quality & Operations | CQO, PMGR | CQO_001-004, PMGR_001-004 |
| Intelligence | Intel | INTEL_001-005 |
| Information Services | Info | INFO_001-005 |
| Translation & Localization | Translator | TR_001-004 |

## 3. Shared Code Templates Reference

10 templates with function signatures, security markers, and usage examples.

## 4. Prompt Frameworks

CRISPE, 3WEH, Five-Element — when to use each, variable reference.

## 5. Compliance Guide

- VirusTotal/ClawHub security check matrix
- AIGC labeling requirements (explicit + implicit)
- Progressive disclosure strategy (L1/L2/L3)
- L1-L6 harness compliance checklist

## 6. Migration Guide

From individual skills (v3.x) to unified skill (v5.0):
- Department parameter replaces individual skill slug
- Error codes unchanged (department prefix preserved)
- All triggers consolidated

Format: Markdown. English only.

---

*Copy-paste ready for any AI chat window.*

path: prompts/05-workflow-execution.md
content: # Workflow Execution Prompt

> Copy and paste this prompt into any AI chat window to execute a complete AI Company workflow.

---

## Prompt

```
Execute the AI Company unified skill (v5.0.0) workflow for the specified task.

Workflow:
  1. DEPARTMENT SELECT: Identify which department handles this task
  2. SPECIFICATION LOAD: Read the department file from references/departments/
  3. COMPLIANCE PRE-CHECK: Verify L1-L6 + security + AIGC requirements
  4. EXECUTE: Implement the department function per method-patterns
  5. POST-CHECK: Validate output compliance
  6. REPORT: Generate result with department error codes
```

## Example: New Skill Security Review

```
1. DEPARTMENT: security-and-compliance (CISO)
2. LOAD: references/departments/security-and-compliance.md
3. PRE-CHECK:
   - L1: Schema valid? [check]
   - Security: No eval/exec? [check]
   - AIGC: Labels applied? [check]
4. EXECUTE: CISO Security Gate Process
   - SUBMIT: Skill package received
   - SCAN: SAST + DAST + dependency check
   - ANALYZE: STRIDE threat model
   - SCORE: CVSS calculation
   - REVIEW: Manual review for L4+ operations
   - DECIDE: APPROVED / CONDITIONAL / REJECTED
5. POST-CHECK:
   - AIGC labels in report? [check]
   - PII masked? [check]
   - Error codes used? [check]
6. REPORT:
   - CVSS Score: [score]
   - STRIDE: [6 categories assessed]
   - Decision: [APPROVED/CONDITIONAL/REJECTED]
   - Findings: [list]
```

## Example: Budget Approval

```
1. DEPARTMENT: finance-and-risk (CFO)
2. LOAD: references/departments/finance-and-risk.md
3. PRE-CHECK: Budget tier classification
4. EXECUTE:
   - Amount < $1K: Auto-approve with logging
   - $1K-$10K: CFO approval
   - $10K-$100K: CFO + CEO dual approval
   - >$100K: Board approval
5. POST-CHECK: AIGC labels, audit trail
6. REPORT: Approval status + budget impact
```

## Example: Crisis Escalation

```
1. DEPARTMENT: governance-and-strategy (CEO)
2. LOAD: references/departments/governance-and-strategy.md
3. CLASSIFY: P0-Critical / P1-High / P2-Medium / P3-Low
4. EXECUTE:
   - P0: Emergency protocol, CEO direct command
   - P1: Crisis team within 1h
   - P2: Department head + CEO briefing within 4h
   - P3: Auto-resolve, CEO notified
5. POST-CHECK: All actions logged, AIGC labeled
6. REPORT: Crisis status + actions taken + resolution
```

Execute the workflow now with the actual task.

---

*Copy-paste ready for any AI chat window.*

path: README.md
content: # AI-Company

> Unified AI Company Skill — 16 departments consolidated into one.
> Empowering all-AI-employee technology companies with complete governance, engineering, and operations capabilities.

[![License: GPL v3](https://img.shields.io/badge/License-GPL%20v3-blue.svg)](LICENSE)
[![Version](https://img.shields.io/badge/version-1.0.4-blue.svg)](_meta.json)
[![Maturity: STABLE](https://img.shields.io/badge/maturity-STABLE-green.svg)]()

---

## Overview

**AI-Company** is a unified skill that consolidates 16 previously separate department skills into a single, cohesive framework. It provides complete operational capabilities for AI-driven technology companies — from strategic governance and financial management to security compliance and localization.

This skill is designed for the [WorkBuddy](https://www.codebuddy.cn/) platform and follows the AI Company Governance Framework.

## Features

- **16 Departments in One** — All AI company functions under a single skill
- **10 Core Code Templates** — Reusable implementation patterns
- **3 Prompt Frameworks** — CRISPE / 3WEH / Five-Element
- **L1–L6 Harness Engineering** — Progressive constraint layers
- **CI/CD Pipeline** — Automated build, test, and deploy
- **ADR Process** — Architecture Decision Records
- **AIGC Compliance** — AI-generated content labeling
- **5-Layer Security Gates** — VirusTotal / ClawHub verification for auto-updates
- **Progressive Disclosure** — Context-aware information delivery

## Department Index

| Department | Roles | Reference |
|---|---|---|
| Governance & Strategy | CEO, COO, HQ | [governance-and-strategy.md](references/departments/governance-and-strategy.md) |
| Finance & Risk | CFO, CRO | [finance-and-risk.md](references/departments/finance-and-risk.md) |
| Technology & Engineering | CTO | [technology-and-engineering.md](references/departments/technology-and-engineering.md) |
| Platform & Infrastructure | Framework | [platform-and-infrastructure.md](references/departments/platform-and-infrastructure.md) |
| Security & Compliance | CISO, CLO | [security-and-compliance.md](references/departments/security-and-compliance.md) |
| People & Culture | CHO | [people-and-culture.md](references/departments/people-and-culture.md) |
| Marketing & Partnerships | CMO | [marketing-and-partnerships.md](references/departments/marketing-and-partnerships.md) |
| Quality & Operations | CQO, PMGR | [quality-and-operations.md](references/departments/quality-and-operations.md) |
| Intelligence | Intel | [intelligence.md](references/departments/intelligence.md) |
| Information Services | Information | [information.md](references/departments/information.md) |
| Translation & Localization | Translator | [translation-and-localization.md](references/departments/translation-and-localization.md) |

## Project Structure

```
ai-company/
├── SKILL.md                          # Skill manifest & quick reference
├── _meta.json                        # Metadata (slug, version, owner)
├── LICENSE                           # MIT License
├── README.md                         # This file
├── prompts/                          # Copy-paste ready prompts
│   ├── 01-implement-method.md
│   ├── 02-robustness-checks.md
│   ├── 03-test-cases.md
│   ├── 04-documentation.md
│   └── 05-workflow-execution.md
└── references/                       # Detailed specifications
    ├── method-patterns.md            # Code templates & prompt frameworks
    ├── execution.md                  # Execution workflow
    ├── integrations.md               # External integrations
    ├── memory.md                     # Memory & knowledge management
    ├── visualization.md              # Visualization patterns
    ├── data-integration.md           # Data integration patterns
    └── departments/                  # Department-specific references
        ├── governance-and-strategy.md
        ├── finance-and-risk.md
        ├── technology-and-engineering.md
        ├── platform-and-infrastructure.md
        ├── security-and-compliance.md
        ├── people-and-culture.md
        ├── marketing-and-partnerships.md
        ├── quality-and-operations.md
        ├── intelligence.md
        ├── information.md
        └── translation-and-localization.md
```

## Installation

### Via ClawHub (Recommended)

Install directly from the WorkBuddy skill marketplace.

### Manual

1. Clone this repository:
   ```bash
   git clone https://github.com/JohnSmithfan/AI-Company.git
   ```
2. Copy the `ai-company/` directory to your skills folder:
   ```bash
   # For user-level skills
   cp -r ai-company ~/.workbuddy/skills/
   # For project-level skills
   cp -r ai-company your-project/.workbuddy/skills/
   ```

## Usage

Once installed, the skill activates automatically when AI company operations are needed. You can also invoke it explicitly:

- **Department tasks**: Specify a department via the `department` parameter (`governance-and-strategy`, `finance-and-risk`, `technology-and-engineering`, etc.)
- **Auto-routing**: Set `department: auto` to let the skill determine the appropriate department

### Example Prompts

- "Review the Q2 financial budget and assess risk exposure"
- "Create a new agent following L1-L6 harness constraints"
- "Run a STRIDE threat model on the authentication service"
- "Translate the marketing copy to Japanese with cultural adaptation"

## Auto-Update

This skill supports automatic updates from ClawHub with 5-layer security verification:

| Setting | Value |
|---|---|
| Schedule | Weekly Sunday 02:00 UTC |
| Backup Retention | 10 versions / 30 days |

**Security Gates**: Version Check → Backup Gate → Download Gate → Frontmatter Gate → Danger Pattern Gate

**Manual Update**:
```powershell
pwsh -File "C:\Users\Admin\WorkBuddy\Claw\.workbuddy\scripts\ai-company-auto-update.ps1" -Force
```

## Changelog

| Version | Date | Changes |
|---|---|---|
| 1.1.0 | 2026-04-29 | Intel: Added Intelligence Library (SOP-L01~L06) with auto-triggered library setup on first collection request; SOP-L06 triggers on any intelligence collection request; Added INTEL_006~INTEL_010 error codes |
| 1.0.3 | 2026-04-28 | Security: Scoped file permissions (P0 CISO fix); Finance: Capex policy, DSO/DPO targets (P1); Risk: FAIR thresholds & LEA calculation (P1); CTO: 3-stage deployment gate (P1); CQO: 85% test coverage threshold (P1); CEO: Board escalation ladder (P2); COO: OHS alerting + OKR integration (P2); CLO: DMCA takedown workflow (P2); Intel: 6-phase intelligence cycle (P2); CPO: Semver enforcement (P2) |
| 1.0.2 | 2026-04-27 | Added auto-update: weekly automation, PowerShell script with 5-layer security gates, backup/rollback, publisher allowlist |
| 1.0.1 | 2026-04-27 | CEO review: all 7 reference modules verified and rebuilt; added visualization, integrations, memory, data-integration, execution references |
| 1.0.0 | 2026-04-27 | Initial release to ClawHub as unified AI Company skill; 16 departments consolidated |

## Consolidated From

This unified skill replaces the following 16 individual skills:

| Legacy Skill | Version |
|---|---|
| ai-company-ceo | 3.0.0 |
| ai-company-coo | 3.0.0 |
| ai-company-hq | 3.0.0 |
| ai-company-cfo | 3.0.0 |
| ai-company-cro | 3.0.0 |
| ai-company-cto | 3.0.0 |
| ai-company-framework | 4.0.0 |
| ai-company-ciso | 3.0.0 |
| ai-company-clo | 3.0.0 |
| ai-company-cho | 3.0.0 |
| ai-company-cmo | 3.0.0 |
| ai-company-cqo | 3.0.0 |
| ai-company-pmgr | 3.0.0 |
| ai-company-intel | 4.1.0 |
| ai-company-information | 2.0.0 |
| ai-company-translator | 3.0.0 |

## License

This project is licensed under the [GNU GENERAL PUBLIC LICENSE](LICENSE).

Copyright © 2026 JohnSmithfan


path: references/data-integration.md
content: # Data Integration Reference

This document provides comprehensive technical specifications for data integration within the AI-Company unified skill framework. It covers financial data retrieval, news and intelligence gathering, information services integration, multi-source data fusion, and standardized data schemas that ensure consistency across all data operations.

The specifications outlined here are designed to be implementation-agnostic while providing sufficient detail for developers to build robust data integration pipelines. All templates and examples are designed to be VirusTotal-compliant, avoiding dynamic code execution patterns that could trigger security scanning systems.

---

## 1. Financial Data Integration

Financial data forms the backbone of many analytical workflows within the AI-Company framework. This section details the patterns, schemas, and caching strategies required to effectively integrate stock quotes, exchange-traded funds, futures contracts, earnings data, and macroeconomic indicators into a unified data pipeline.

### 1.1 Stock Quotes and Market Data

Stock quote data represents real-time or delayed price information for publicly traded securities. The integration pattern for stock quotes follows a RESTful API architecture that supports both individual security queries and batch retrieval for multiple securities.

#### API Patterns for Stock Data

The primary endpoint pattern for stock quote retrieval follows a consistent structure across most financial data providers:

```
GET /api/v1/quote/{exchange}:{symbol}
GET /api/v1/quotes/batch?symbols={exchange}:{symbol1},{exchange}:{symbol2}
GET /api/v1/historical/{exchange}:{symbol}?period={period}&interval={interval}
```

The REST pattern requires three key parameters: the exchange code identifying the trading venue, the security symbol as listed on that exchange, and optional filters for time range and data granularity. The exchange:symbol format ensures uniqueness across global markets where the same ticker symbol might reference different securities on different exchanges.

Authentication for financial data APIs typically employs API key-based authentication passed via the Authorization header:

```
Authorization: Bearer {api_key}
X-[REDACTED_SECRET]
```

Rate limiting for stock data APIs generally allows between 100 and 1000 requests per minute depending on the subscription tier. Implementations should track request counts and implement exponential backoff when encountering rate limit responses (HTTP 429).

#### Stock Data Schema

The standard schema for stock quote data includes the following fields:

```json
{
  "symbol": "AAPL",
  "exchange": "NASDAQ",
  "exchange_code": "XNAS",
  "name": "Apple Inc.",
  "timestamp": "2026-04-27T15:30:00.000Z",
  "price": 189.45,
  "open": 188.20,
  "high": 190.15,
  "low": 187.80,
  "close": 189.45,
  "previous_close": 188.90,
  "volume": 52341000,
  "market_cap": 2950000000000,
  "pe_ratio": 28.5,
  "dividend_yield": 0.52,
  "52_week_high": 198.23,
  "52_week_low": 164.08,
  "bid": 189.44,
  "ask": 189.46,
  "bid_size": 100,
  "ask_size": 200,
  "data_source": "primary_exchange",
  "data_quality_score": 0.98
}
```

The timestamp field follows ISO-8601 format with UTC timezone designation. Prices are represented as decimal numbers with precision appropriate to the security's price category. High-precision securities like penny stocks may include additional decimal places while large-cap indices typically round to two decimal places.

Historical daily data follows a similar schema but includes additional fields for adjusted prices that account for splits and dividends:

```json
{
  "symbol": "AAPL",
  "exchange": "NASDAQ",
  "date": "2026-04-25",
  "open": 188.20,
  "high": 190.15,
  "low": 187.80,
  "close": 189.45,
  "adjusted_close": 189.45,
  "volume": 52341000,
  "turnover": 9876543210,
  "change": 0.55,
  "change_percent": 0.29
}
```

#### Caching Strategies for Stock Data

Stock data caching requires careful consideration of data freshness requirements versus API rate limits. The recommended caching strategy employs a tiered approach with different TTL (time-to-live) values based on data type.

Real-time quote data should use aggressive caching with short TTL values, typically 15 to 60 seconds for non-professional data feeds. Cache entries should include the retrieval timestamp and be invalidated when the market is closed if the cached data exceeds the trading session's closing time.

Intraday data with minute-level granularity should cache for 5 to 15 minutes, depending on the volatility of the security. High-volatility securities like those involved in earnings announcements or significant news events may require shorter cache durations.

End-of-day historical data can be cached for extended periods, with TTL values of 24 hours for the most recent trading day and indefinite caching for historical data that will not change. Once a trading day closes and the data is confirmed final, that day's data becomes immutable and can be cached permanently.

The cache key structure should follow a consistent pattern:

```
stock:quote:{exchange}:{symbol}:{timestamp_bucket}
stock:history:{exchange}:{symbol}:{date_range}
stock:minute:{exchange}:{symbol}:{timestamp}
```

### 1.2 Exchange-Traded Funds (ETF)

Exchange-traded funds represent baskets of securities that trade like individual stocks. ETF data integration presents unique challenges due to the dual-layer structure of ETF pricing: the market price at which shares trade and the net asset value (NAV) that represents the underlying holdings' worth.

#### ETF-Specific API Patterns

ETF data retrieval typically extends standard stock APIs with additional endpoints:

```
GET /api/v1/etf/{exchange}:{symbol}
GET /api/v1/etf/{exchange}:{symbol}/holdings
GET /api/v1/etf/{exchange}:{symbol}/nav
GET /api/v1/etf/{exchange}:{symbol}/tracking
```

The holdings endpoint returns the constituent securities that make up the ETF, which is essential for understanding exposure and calculating theoretical NAV. The tracking endpoint provides performance comparison against benchmark indices.

#### ETF Data Schema

```json
{
  "symbol": "SPY",
  "exchange": "NYSE",
  "exchange_code": "XNYS",
  "name": "SPDR S&P 500 ETF Trust",
  "timestamp": "2026-04-27T15:30:00.000Z",
  "price": 502.35,
  "nav": 501.98,
  "premium_discount": 0.07,
  "premium_discount_percent": 0.014,
  "bid": 502.34,
  "ask": 502.36,
  "volume": 45231000,
  "avg_volume_30d": 52100000,
  "total_assets": 425000000000,
  "nav_per_share": 501.98,
  "dividend_yield": 1.35,
  "expense_ratio": 0.0945,
  "tracking_index": "SPX",
  "tracking_index_name": "S&P 500 Index",
  "tracking_error": 0.02,
  "data_source": "index_provider",
  "data_quality_score": 0.99
}
```

The premium/discount field indicates how the market price compares to the NAV, which is critical for understanding whether an ETF is trading at a premium or discount to its intrinsic value. Large premiums or discounts can indicate market stress or liquidity issues.

### 1.3 Futures Contracts

Futures data integration requires special handling due to the continuous nature of futures pricing across contract months and the roll mechanics required to maintain continuous contract series.

#### Futures API Patterns

```
GET /api/v1/futures/{exchange}:{symbol}
GET /api/v1/futures/{exchange}:{symbol}/contract/{month_code}
GET /api/v1/futures/continuous/{exchange}:{symbol}
GET /api/v1/futures/{exchange}:{symbol}/term_structure
```

The continuous endpoint provides adjusted data that stitches together individual contract months into a continuous series, handling the price adjustments required during contract rolls. The term structure endpoint returns the entire forward curve across available contract months.

#### Futures Data Schema

```json
{
  "symbol": "CL",
  "exchange": "NYMEX",
  "exchange_code": "XNYM",
  "name": "Crude Oil WTI",
  "contract_month": "202606",
  "timestamp": "2026-04-27T15:30:00.000Z",
  "price": 78.45,
  "open": 77.80,
  "high": 79.20,
  "low": 77.50,
  "close": 78.45,
  "settlement": 78.42,
  "volume": 245000,
  "open_interest": 1850000,
  "last_trading_day": "2026-05-19",
  "delivery_date": "2026-05-31",
  "contract_size": 1000,
  "price_increment": 0.01,
  "currency": "USD",
  "data_source": "exchange",
  "data_quality_score": 0.99
}
```

Continuous futures data requires additional fields to handle the roll adjustment:

```json
{
  "symbol": "CL",
  "contract_month": "continuous",
  "timestamp": "2026-04-27T15:30:00.000Z",
  "price": 78.35,
  "source_contract": "CL202606",
  "target_contract": "CL202607",
  "roll_date": "2026-04-25",
  "roll_adjustment": 0.10,
  "roll_complete": true
}
```

### 1.4 Earnings and Financial Statements

Corporate earnings data includes income statements, balance sheets, and cash flow statements that provide fundamental analysis inputs for equity valuation.

#### Earnings API Patterns

```
GET /api/v1/earnings/{exchange}:{symbol}/calendar
GET /api/v1/financials/{exchange}:{symbol}/income
GET /api/v1/financials/{exchange}:{symbol}/balance
GET /api/v1/financials/{exchange}:{symbol}/cashflow
```

#### Earnings Calendar Schema

```json
{
  "symbol": "AAPL",
  "exchange": "NASDAQ",
  "company_name": "Apple Inc.",
  "fiscal_period": "Q2 2026",
  "fiscal_quarter": 2,
  "fiscal_year": 2026,
  "report_date": "2026-04-28",
  "report_time": "after_market",
  "estimate_eps": 2.45,
  "actual_eps": null,
  "estimate_revenue": 95000000000,
  "actual_revenue": null,
  "conference_call_date": "2026-04-28",
  "conference_call_time": "17:00:00-05:00",
  "data_source": "company_filing",
  "data_quality_score": 0.95
}
```

#### Income Statement Schema

```json
{
  "symbol": "AAPL",
  "company_name": "Apple Inc.",
  "fiscal_period": "Q1 2026",
  "fiscal_quarter": 1,
  "fiscal_year": 2026,
  "currency": "USD",
  "report_date": "2026-01-28",
  "items": {
    "revenue": 124300000000,
    "cost_of_revenue": 73900000000,
    "gross_profit": 50400000000,
    "operating_expenses": {
      "research_and_development": 7800000000,
      "selling_general_admin": 6200000000,
      "total_operating_expenses": 14000000000
    },
    "operating_income": 36400000000,
    "interest_expense": 650000000,
    "other_income_expense": 420000000,
    "income_before_tax": 36220000000,
    "income_tax_expense": 5620000000,
    "net_income": 30600000000,
    "ebitda": 41200000000,
    "eps_basic": 1.95,
    "eps_diluted": 1.93,
    "weighted_avg_shares_basic": 15200000000,
    "weighted_avg_shares_diluted": 15800000000
  },
  "data_source": "sec_filing",
  "data_quality_score": 0.98
}
```

### 1.5 Macroeconomic Indicators

Macroeconomic data integration covers indicators such as GDP, inflation rates, employment figures, and central bank policy decisions that influence market conditions.

#### Macro API Patterns

```
GET /api/v1/macro/{indicator_code}
GET /api/v1/macro/{indicator_code}?country={country_code}&period={range}
GET /api/v1/macro/indicators/calendar
```

#### GDP Data Schema

```json
{
  "indicator": "GDP",
  "indicator_name": "Gross Domestic Product",
  "country": "USA",
  "country_name": "United States",
  "timestamp": "2026-04-27T08:00:00.000Z",
  "period": "2025Q4",
  "period_type": "quarterly",
  "value": 28500000000000,
  "value_raw": 28.5,
  "value_unit": "trillion",
  "currency": "USD",
  "growth_rate": 2.4,
  "growth_rate_yoy": 2.4,
  "growth_rate_qoq": 0.6,
  "previous_value": 28320000000000,
  "release_date": "2026-01-30",
  "next_release_date": "2026-04-30",
  "data_source": "bea",
  "data_quality_score": 0.99
}
```

#### Inflation (CPI) Schema

```json
{
  "indicator": "CPI",
  "indicator_name": "Consumer Price Index",
  "country": "USA",
  "country_name": "United States",
  "timestamp": "2026-04-27T08:00:00.000Z",
  "period": "2026-03",
  "period_type": "monthly",
  "value": 315.5,
  "previous_value": 314.2,
  "change": 1.3,
  "change_percent": 0.41,
  "yoy_change_percent": 2.8,
  "core_change_percent": 3.1,
  "category": "all_items",
  "release_date": "2026-04-10",
  "next_release_date": "2026-05-12",
  "data_source": "bls",
  "data_quality_score": 0.99
}
```

---

## 2. News and Intelligence Integration

News and intelligence data provides context for market movements, sentiment analysis for securities, and early warning indicators for significant market events. This section details the patterns for integrating real-time news feeds, social media sentiment, and intelligence data sources into a cohesive information pipeline.

### 2.1 Real-Time News Feeds

Real-time news integration requires handling high-velocity data streams with appropriate filtering, deduplication, and enrichment pipelines.

#### News API Patterns

```
GET /api/v1/news/latest?limit={count}
GET /api/v1/news/search?q={query}&from={date}&to={date}
GET /api/v1/news/symbol/{exchange}:{symbol}
GET /api/v1/news/category/{category}
```

The symbol-specific endpoint returns news articles specifically related to a given security, while category endpoints filter by broader topics such as markets, technology, politics, or economics.

#### News Data Schema

```json
{
  "article_id": "news_abc123xyz",
  "title": "Federal Reserve Signals Potential Rate Cut in Q3 2026",
  "summary": "Federal Reserve officials indicated on Wednesday that they may consider cutting interest rates in the third quarter of 2026 if inflation continues to moderate toward the 2% target.",
  "content": "Full article content would appear here with complete text...",
  "source": {
    "name": "Financial Times",
    "code": "FT",
    "reliability_score": 0.95,
    "tier": 1
  },
  "url": "https://www.ft.com/fed-rate-cut-q3",
  "published_at": "2026-04-27T14:30:00.000Z",
  "retrieved_at": "2026-04-27T14:31:15.000Z",
  "entities": [
    {
      "type": "organization",
      "name": "Federal Reserve",
      "ticker": null,
      "confidence": 0.99
    },
    {
      "type": "person",
      "name": "Jerome Powell",
      "role": "Federal Reserve Chair",
      "confidence": 0.97
    },
    {
      "type": "geographic",
      "name": "United States",
      "confidence": 0.98
    }
  ],
  "topics": ["monetary_policy", "interest_rates", "federal_reserve"],
  "sentiment": {
    "overall": "positive",
    "score": 0.65,
    "confidence": 0.82
  },
  "related_symbols": [],
  "impact_assessment": {
    "market_impact": "medium",
    "sectors_affected": ["banking", "real_estate", "utilities"],
    "expected_volatility": "moderate"
  },
  "data_source": "news_aggregator",
  "data_quality_score": 0.88
}
```

#### News Deduplication Strategy

News deduplication requires similarity detection across article content. The recommended approach combines multiple signals:

First, calculate a content hash (SHA-256) of normalized article text after removing whitespace normalization, HTML stripping, and lowercasing. Exact duplicates will share identical hashes.

Second, implement fuzzy matching using n-gram analysis for near-duplicate detection. Articles sharing more than 85% of 5-gram sequences should be considered duplicates, with the higher-quality source (based on reliability_score and content completeness) retained.

Third, use semantic embedding similarity for story-level deduplication. Multiple articles covering the same event from different sources should be grouped into a single story cluster, with a representative article selected for the primary story view.

### 2.2 Social Sentiment Analysis

Social sentiment integration captures market mood from platforms such as Twitter/X, Reddit, stock forums, and financial social networks. This data requires careful handling due to noise, manipulation attempts, and the need for attribution verification.

#### Social API Patterns

```
GET /api/v1/social/sentiment/{exchange}:{symbol}
GET /api/v1/social/trending?category={category}
GET /api/v1/social/mentions/{exchange}:{symbol}?from={date}&to={date}
```

#### Social Sentiment Schema

```json
{
  "symbol": "GME",
  "exchange": "NYSE",
  "timestamp": "2026-04-27T15:00:00.000Z",
  "time_bucket": "15min",
  "metrics": {
    "total_mentions": 45230,
    "unique_authors": 12850,
    "bullish_count": 28450,
    "bearish_count": 8920,
    "neutral_count": 7860,
    "weighted_sentiment_score": 0.42,
    "sentiment_trend": "increasing"
  },
  "platform_breakdown": [
    {
      "platform": "twitter",
      "mentions": 18500,
      "avg_sentiment": 0.38,
      "influence_score": 0.65
    },
    {
      "platform": "reddit",
      "mentions": 15200,
      "avg_sentiment": 0.52,
      "influence_score": 0.45
    },
    {
      "platform": "stocktwits",
      "mentions": 9500,
      "avg_sentiment": 0.35,
      "influence_score": 0.55
    }
  ],
  "influencer_impact": {
    "top_influencers": [
      {
        "handle": "DeepFuckingValue",
        "followers": 2500000,
        "sentiment": "bullish",
        "impact_score": 0.85
      }
    ],
    "aggregate_influencer_sentiment": 0.72
  },
  "manipulation_indicators": {
    "bot_probability": 0.15,
    "coordinated_activity": false,
    "suspicious_patterns": []
  },
  "data_source": "social_analytics",
  "data_quality_score": 0.72
}
```

### 2.3 Source Classification

News and intelligence sources require classification by reliability, expertise domain, and publication tier to weight their influence appropriately in downstream analysis.

#### Source Classification Schema

```json
{
  "source_id": "reuters",
  "name": "Reuters",
  "display_name": "Reuters News Agency",
  "tier": 1,
  "reliability_score": 0.95,
  "domains": ["general_news", "financial_news", "global_coverage"],
  "regions": ["global"],
  "languages": ["en", "zh", "ja", "de", "fr", "es"],
  "contact_info": {
    "headquarters": "London, UK",
    "established": 1851
  },
  "verification_practices": [
    "multiple_source_confirmation",
    "on_record_sources_only",
    "editorial_review_process"
  ],
  "classification_date": "2026-01-15",
  "last_verified": "2026-04-20"
}
```

Source tier classifications follow this standard:

- **Tier 1**: Established wire services and major financial news organizations with rigorous editorial standards and multi-source verification practices (Reuters, Bloomberg, Associated Press)
- **Tier 2**: Major newspapers, financial publications, and recognized industry outlets with editorial oversight (Wall Street Journal, Financial Times, Barron's)
- **Tier 3**: Recognized industry blogs, specialized publications, and regional news outlets with some editorial oversight
- **Tier 4**: Independent contributors, user-generated content platforms, and social media sources requiring additional verification

### 2.4 Sentiment Analysis Integration

Sentiment analysis converts qualitative text content into quantitative sentiment scores that can be used in quantitative trading models and qualitative analysis workflows.

#### Sentiment Analysis API Patterns

```
POST /api/v1/sentiment/analyze
Content-Type: application/json

{
  "text": "The company's earnings beat expectations by 15% with strong revenue growth across all segments.",
  "domain": "financial",
  "model_version": "finance-sentiment-v2.1"
}
```

#### Sentiment Response Schema

```json
{
  "request_id": "sentiment_req_456xyz",
  "timestamp": "2026-04-27T15:30:00.000Z",
  "input_text": "The company's earnings beat expectations by 15%...",
  "domain": "financial",
  "model_version": "finance-sentiment-v2.1",
  "results": {
    "overall_sentiment": "bullish",
    "polarity_score": 0.78,
    "polarity_label": "strongly_bullish",
    "confidence": 0.89,
    "emotions": {
      "joy": 0.45,
      "confidence": 0.35,
      "anticipation": 0.25,
      "fear": 0.05,
      "anger": 0.02,
      "sadness": 0.01
    },
    "key_phrases": [
      "beat expectations",
      "strong revenue growth",
      "all segments"
    ],
    "entities_with_sentiment": [
      {
        "entity": "earnings",
        "sentiment": "bullish",
        "score": 0.85,
        "context": "beat expectations by 15%"
      }
    ]
  },
  "processing_time_ms": 45
}
```

#### Sentiment Score Ranges

Polarity scores follow a standardized range from -1.0 (extremely bearish) to +1.0 (extremely bullish):

- **Strongly Bullish**: 0.6 to 1.0
- **Moderately Bullish**: 0.2 to 0.6
- **Neutral**: -0.2 to 0.2
- **Moderately Bearish**: -0.6 to -0.2
- **Strongly Bearish**: -1.0 to -0.6

### 2.5 Confidence Scoring

Confidence scoring provides a quantitative measure of reliability for aggregated sentiment data, accounting for source quality, sample size, and measurement consistency.

#### Confidence Scoring Formula

The overall confidence score combines multiple factors:

```
Confidence = BaseScore * sqrt(SampleWeight) * SourceQualityFactor * ConsistencyFactor

Where:
- BaseScore = 0.5 (minimum baseline)
- SampleWeight = min(mention_count / 1000, 1.0)
- SourceQualityFactor = weighted_average(source_reliability_scores)
- ConsistencyFactor = 1.0 - (standard_deviation_of_sentiment / max_possible_deviation)
```

#### Confidence Schema

```json
{
  "symbol": "TSLA",
  "exchange": "NASDAQ",
  "timestamp": "2026-04-27T15:00:00.000Z",
  "confidence_metrics": {
    "overall_confidence": 0.82,
    "components": {
      "sample_size": {
        "value": 0.75,
        "mention_count": 85420,
        "threshold_met": true
      },
      "source_quality": {
        "value": 0.88,
        "weighted_avg_reliability": 0.72,
        "tier1_percentage": 0.35
      },
      "consistency": {
        "value": 0.94,
        "sentiment_std_deviation": 0.12,
        "score_range": 0.65
      },
      "recency": {
        "value": 0.98,
        "data_age_minutes": 15,
        "freshness_threshold_minutes": 60
      }
    },
    "confidence_band": {
      "lower": 0.75,
      "upper": 0.89,
      "interpretation": "high_confidence"
    }
  },
  "data_source": "sentiment_aggregator",
  "data_quality_score": 0.82
}
```

---

## 3. Information Services Integration

Information services cover auxiliary data types including weather data, geolocation services, timezone conversions, and other utility services that support financial analysis and operational workflows.

### 3.1 Weather Data Integration

Weather data affects commodity markets, energy demand, agricultural futures, and insurance sectors. Integration patterns must handle multiple data formats and forecast horizons.

#### Weather API Patterns

```
GET /api/v1/weather/current?location={lat},{lon}
GET /api/v1/weather/forecast?location={lat},{lon}&days={count}
GET /api/v1/weather/historical?location={lat},{lon}&from={date}&to={date}
```

#### Weather Data Schema

```json
{
  "location": {
    "latitude": 40.7128,
    "longitude": -74.0060,
    "city": "New York",
    "region": "New York",
    "country": "US",
    "timezone": "America/New_York"
  },
  "timestamp": "2026-04-27T15:00:00.000Z",
  "current": {
    "temperature": 18.5,
    "temperature_unit": "celsius",
    "feels_like": 17.2,
    "humidity": 65,
    "wind_speed": 12.5,
    "wind_direction": 225,
    "wind_direction_cardinal": "SW",
    "pressure": 1013.25,
    "visibility": 16.0,
    "uv_index": 5,
    "condition": "partly_cloudy",
    "condition_code": 802
  },
  "forecast": [
    {
      "date": "2026-04-28",
      "high": 22.0,
      "low": 14.0,
      "condition": "sunny",
      "precipitation_probability": 10,
      "precipitation_amount": 0.0
    }
  ],
  "alerts": [],
  "data_source": "weather_provider",
  "data_quality_score": 0.95
}
```

### 3.2 Geolocation Services

Geolocation integration supports address parsing, coordinate lookup, and distance calculations that are essential for event correlation and market analysis.

#### Geolocation API Patterns

```
GET /api/v1/geo/lookup?address={address_string}
GET /api/v1/geo/lookup?lat={lat}&lon={lon}
GET /api/v1/geo/distance?from={lat1},{lon1}&to={lat2},{lon2}
```

#### Geolocation Schema

```json
{
  "query": {
    "input": "Wall Street, New York, NY",
    "input_type": "address"
  },
  "results": [
    {
      "formatted_address": "Wall Street, New York, NY 10005, USA",
      "location": {
        "latitude": 40.7074,
        "longitude": -74.0113
      },
      "components": {
        "street_number": null,
        "street": "Wall Street",
        "city": "New York",
        "county": "New York County",
        "state": "NY",
        "postal_code": "10005",
        "country": "US"
      },
      "accuracy": "high",
      "timezone": "America/New_York",
      "match_confidence": 0.95
    }
  ],
  "data_source": "geocoding_provider",
  "data_quality_score": 0.92
}
```

### 3.3 Timezone Conversion Services

Timezone handling is critical for global financial operations where markets in different regions operate on different local times. Incorrect timezone handling can lead to missed data windows, incorrect event attribution, and scheduling failures.

#### Timezone API Patterns

```
GET /api/v1/timezone/convert?time={iso8601}&from={tz_from}&to={tz_to}
GET /api/v1/timezone/now?location={location_code}
GET /api/v1/timezone/markets?date={iso8601}
```

#### Timezone Conversion Schema

```json
{
  "query": {
    "input_time": "2026-04-27T09:30:00",
    "input_timezone": "America/New_York",
    "target_timezone": "Asia/Shanghai",
    "format": "iso8601"
  },
  "result": {
    "converted_time": "2026-04-27T21:30:00+08:00",
    "converted_time_unix": 1745770200,
    "offset_difference_hours": 12,
    "dst_affected": false
  },
  "market_context": {
    "nyse_open": false,
    "nyse_closed": false,
    "shanghai_open": true,
    "time_until_nyse_open": "PT16H"
  }
}
```

#### Market Hours Schema

```json
{
  "timestamp": "2026-04-27T15:00:00.000Z",
  "markets": [
    {
      "exchange": "NYSE",
      "code": "XNYS",
      "timezone": "America/New_York",
      "status": "open",
      "current_time": "2026-04-27T11:00:00-04:00",
      "session": {
        "type": "regular",
        "open": "09:30:00-04:00",
        "close": "16:00:00-04:00",
        "trading_hours": "09:30-16:00 ET"
      },
      "next_event": {
        "type": "close",
        "time": "2026-04-27T16:00:00-04:00",
        "time_until": "PT5H"
      }
    },
    {
      "exchange": "SSE",
      "code": "XSHG",
      "timezone": "Asia/Shanghai",
      "status": "closed",
      "current_time": "2026-04-28T00:00:00+08:00",
      "session": {
        "type": "regular",
        "open": "09:30:00+08:00",
        "close": "15:00:00+08:00",
        "trading_hours": "09:30-15:00 CST"
      },
      "next_event": {
        "type": "open",
        "time": "2026-04-28T09:30:00+08:00",
        "time_until": "PT9H30M"
      }
    }
  ],
  "data_source": "market_hours_provider",
  "data_quality_score": 0.98
}
```

### 3.4 Provider Integration Patterns

All external data providers should be integrated using a consistent adapter pattern that abstracts provider-specific implementations behind a common interface.

#### Provider Adapter Interface

```javascript
// Provider adapter interface definition
class DataProviderAdapter {
  constructor(config) {
    this.config = config;
    this.rateLimiter = new RateLimiter(config.rateLimit);
    this.circuitBreaker = new CircuitBreaker(config.circuitBreaker);
    this.cache = new CacheLayer(config.cacheConfig);
  }

  async fetch(endpoint, params) {
    // Rate limiting check
    await this.rateLimiter.acquire();
    
    // Circuit breaker check
    if (this.circuitBreaker.isOpen()) {
      throw new ProviderUnavailableError('Circuit breaker is open');
    }
    
    // Cache check
    const cacheKey = this.buildCacheKey(endpoint, params);
    const cached = await this.cache.get(cacheKey);
    if (cached && !this.isStale(cached)) {
      return cached;
    }
    
    try {
      const response = await this.executeRequest(endpoint, params);
      await this.cache.set(cacheKey, response);
      this.circuitBreaker.recordSuccess();
      return response;
    } catch (error) {
      this.circuitBreaker.recordFailure();
      throw error;
    }
  }

  buildCacheKey(endpoint, params) {
    const normalizedParams = Object.keys(params)
      .sort()
      .reduce((acc, key) => ({ ...acc, [key]: params[key] }), {});
    const paramString = JSON.stringify(normalizedParams);
    return `${this.providerName}:${endpoint}:${hash(paramString)}`;
  }

  normalizeTimestamp(timestamp) {
    return new Date(timestamp).toISOString();
  }

  normalizeSymbol(symbol, exchange) {
    return `${exchange}:${symbol}`;
  }
}
```

### 3.5 Fallback Strategies

Robust data integration requires comprehensive fallback strategies that gracefully degrade when primary data sources become unavailable.

#### Fallback Configuration Schema

```json
{
  "data_type": "stock_quote",
  "primary_provider": "bloomberg",
  "providers": [
    {
      "name": "bloomberg",
      "priority": 1,
      "enabled": true,
      "weight": 0.60,
      "timeout_ms": 5000,
      "retry_config": {
        "max_attempts": 3,
        "backoff_multiplier": 2,
        "initial_delay_ms": 1000
      }
    },
    {
      "name": "refinitiv",
      "priority": 2,
      "enabled": true,
      "weight": 0.30,
      "timeout_ms": 8000,
      "retry_config": {
        "max_attempts": 2,
        "backoff_multiplier": 2,
        "initial_delay_ms": 2000
      }
    },
    {
      "name": "iex_cloud",
      "priority": 3,
      "enabled": true,
      "weight": 0.10,
      "timeout_ms": 10000,
      "retry_config": {
        "max_attempts": 1,
        "backoff_multiplier": 1,
        "initial_delay_ms": 0
      }
    }
  ],
  "aggregation_strategy": "weighted_average",
  "stale_threshold_seconds": 60,
  "fallback_timeout_seconds": 15
}
```

#### Circuit Breaker Implementation

```javascript
class CircuitBreaker {
  constructor(config) {
    this.failureThreshold = config.failureThreshold || 5;
    this.successThreshold = config.successThreshold || 3;
    this.timeout = config.timeout || 60000;
    this.state = 'CLOSED';
    this.failures = 0;
    this.successes = 0;
    this.lastFailureTime = null;
  }

  recordSuccess() {
    this.failures = 0;
    if (this.state === 'HALF_OPEN') {
      this.successes++;
      if (this.successes >= this.successThreshold) {
        this.state = 'CLOSED';
        this.successes = 0;
      }
    }
  }

  recordFailure() {
    this.failures++;
    this.lastFailureTime = Date.now();
    if (this.state === 'HALF_OPEN') {
      this.state = 'OPEN';
    } else if (this.failures >= this.failureThreshold) {
      this.state = 'OPEN';
    }
  }

  isOpen() {
    if (this.state === 'OPEN') {
      if (Date.now() - this.lastFailureTime >= this.timeout) {
        this.state = 'HALF_OPEN';
        return false;
      }
      return true;
    }
    return false;
  }

  getState() {
    return {
      state: this.state,
      failures: this.failures,
      successes: this.successes,
      lastFailureTime: this.lastFailureTime
    };
  }
}
```

### 3.6 Rate Limiting

Rate limiting controls API consumption to stay within provider-imposed quotas. The implementation should support multiple strategies including fixed window, sliding window, and token bucket algorithms.

#### Rate Limiter Implementation

```javascript
class RateLimiter {
  constructor(config) {
    this.maxRequests = config.maxRequests || 100;
    this.windowMs = config.windowMs || 60000;
    this.strategy = config.strategy || 'sliding_window';
    this.requests = [];
  }

  async acquire(weight = 1) {
    if (this.strategy === 'token_bucket') {
      return this.acquireTokenBucket(weight);
    }
    return this.acquireSlidingWindow(weight);
  }

  async acquireSlidingWindow(weight) {
    const now = Date.now();
    const windowStart = now - this.windowMs;
    
    // Remove expired requests
    this.requests = this.requests.filter(ts => ts > windowStart);
    
    const currentCount = this.requests.reduce((sum, _) => sum + 1, 0);
    
    if (currentCount + weight > this.maxRequests) {
      const waitTime = this.windowMs - (now - this.requests[0]);
      throw new RateLimitError(`Rate limit exceeded. Retry after ${waitTime}ms`, waitTime);
    }
    
    for (let i = 0; i < weight; i++) {
      this.requests.push(now);
    }
    
    return true;
  }

  async acquireTokenBucket(weight) {
    if (!this.tokens) {
      this.tokens = this.maxRequests;
      this.lastRefill = Date.now();
    }
    
    const now = Date.now();
    const elapsed = now - this.lastRefill;
    const refillAmount = Math.floor((elapsed / this.windowMs) * this.maxRequests);
    this.tokens = Math.min(this.maxRequests, this.tokens + refillAmount);
    this.lastRefill = now;
    
    if (this.tokens < weight) {
      const waitTime = Math.ceil((weight - this.tokens) / (this.maxRequests / this.windowMs));
      throw new RateLimitError(`Rate limit exceeded. Retry after ${waitTime}ms`, waitTime);
    }
    
    this.tokens -= weight;
    return true;
  }

  getStatus() {
    const now = Date.now();
    const windowStart = now - this.windowMs;
    const activeRequests = this.requests.filter(ts => ts > windowStart).length;
    
    return {
      strategy: this.strategy,
      currentRequests: activeRequests,
      maxRequests: this.maxRequests,
      remainingRequests: Math.max(0, this.maxRequests - activeRequests),
      resetAt: new Date(now + this.windowMs).toISOString()
    };
  }
}
```

---

## 4. Multi-Source Data Fusion

Multi-source data fusion combines information from multiple providers to produce unified, consistent, and high-quality data outputs. This section details the technical approaches for schema normalization, conflict resolution, and quality scoring across heterogeneous data sources.

### 4.1 Schema Normalization

Schema normalization transforms provider-specific data formats into a unified canonical schema that supports consistent processing across all downstream components.

#### Normalization Pipeline

The normalization pipeline processes incoming data through a sequence of transformation stages:

**Stage 1: Field Mapping**

Field mapping translates provider-specific field names to canonical field names using configurable mapping tables:

```json
{
  "provider": "bloomberg",
  "mapping_version": "1.0.0",
  "field_mappings": {
    "PRIMARY_EXCHANGE": "exchange",
    "TICKER": "symbol",
    "LAST_PRICE": "price",
    "OPEN_PRC": "open",
    "HIGH_1": "high",
    "LOW_1": "low",
    "CLOSE_PRCE": "close",
    "PREVCLS": "previous_close",
    "VOLUME": "volume",
    "MKTCAP": "market_cap",
    "PE_RATIO": "pe_ratio",
    "DVD_YLD_12M": "dividend_yield",
    "ALL_EXCHANGES": "aggregated",
    "NET_CHANGE": "change",
    "PCT_CHANGE": "change_percent"
  }
}
```

**Stage 2: Type Conversion**

Type conversion ensures all fields conform to expected data types:

```javascript
const typeConverters = {
  price: (value) => parseFloat(value).toFixed(2),
  volume: (value) => parseInt(value, 10),
  timestamp: (value) => new Date(value).toISOString(),
  percentage: (value) => parseFloat(value) / 100,
  boolean: (value) => ['true', '1', 'yes', 'on'].includes(String(value).toLowerCase()),
  nullHandling: (value, defaultValue) => value === '' || value === null ? defaultValue : value
};
```

**Stage 3: Value Validation**

Value validation applies business rules to ensure data integrity:

```javascript
const validationRules = {
  price: (value) => value >= 0 && value < 1000000,
  volume: (value) => value >= 0 && value < 1e15,
  percentage: (value) => value >= -100 && value <= 100,
  timestamp: (value) => !isNaN(Date.parse(value)),
  symbol: (value) => /^[A-Z0-9]{1,10}$/.test(value),
  exchange: (value) => ['NYSE', 'NASDAQ', 'LSE', 'TSE', 'HKEX', 'SSE', 'SZSE'].includes(value)
};
```

**Stage 4: Enrichment**

Enrichment adds derived fields and metadata:

```javascript
const enrichmentFunctions = {
  addCalculatedFields: (data) => ({
    ...data,
    mid_price: data.bid && data.ask ? (data.bid + data.ask) / 2 : null,
    spread: data.bid && data.ask ? data.ask - data.bid : null,
    spread_percent: data.bid && data.ask ? ((data.ask - data.bid) / data.mid_price) * 100 : null,
    vwap_proxy: data.price && data.volume ? data.price * data.volume : null
  }),
  
  addTimestampMetadata: (data) => ({
    ...data,
    ingested_at: new Date().toISOString(),
    data_age_seconds: Math.floor((Date.now() - new Date(data.timestamp)) / 1000)
  }),
  
  addProviderMetadata: (data, provider) => ({
    ...data,
    source_provider: provider.name,
    source_quality_score: provider.reliabilityScore,
    source_timestamp: provider.timestamp
  })
};
```

### 4.2 Conflict Resolution

When multiple sources provide different values for the same data point, conflict resolution determines which value to use or how to combine them.

#### Conflict Detection

Conflicts are detected by comparing normalized values across sources:

```javascript
function detectConflict(observations, fieldName, tolerance = 0.001) {
  const values = observations
    .map(obs => obs[fieldName])
    .filter(v => v !== null && v !== undefined);
  
  if (values.length < 2) {
    return { hasConflict: false };
  }
  
  const mean = values.reduce((sum, v) => sum + v, 0) / values.length;
  const maxDeviation = Math.max(...values.map(v => Math.abs(v - mean) / mean));
  
  return {
    hasConflict: maxDeviation > tolerance,
    values,
    mean,
    maxDeviation,
    conflictLevel: maxDeviation > tolerance ? 'significant' : 'minor'
  };
}
```

#### Conflict Resolution Strategies

The framework supports multiple resolution strategies configured per data type:

```json
{
  "conflict_resolution": {
    "stock_quote": {
      "strategy": "weighted_quality_score",
      "fields": {
        "price": {
          "strategy": "weighted_average",
          "weights": ["provider_quality_score", "recency_score"],
          "tolerance": 0.001
        },
        "volume": {
          "strategy": "max",
          "tolerance": 0.05
        }
      }
    },
    "news_sentiment": {
      "strategy": "tiered_priority",
      "tiers": [
        { "tier": 1, "weight": 0.5 },
        { "tier": 2, "weight": 0.3 },
        { "tier": 3, "weight": 0.15 },
        { "tier": 4, "weight": 0.05 }
      ]
    },
    "earnings_estimate": {
      "strategy": "consensus",
      "exclude_outliers": true,
      "outlier_std_multiplier": 2
    }
  }
}
```

#### Resolution Strategy Implementations

**Weighted Average Strategy**: Combines values proportionally to their source quality scores:

```javascript
function resolveWeightedAverage(observations, fieldName, weights) {
  let weightedSum = 0;
  let totalWeight = 0;
  
  for (const obs of observations) {
    const value = obs[fieldName];
    const weight = calculateCompositeWeight(obs, weights);
    
    if (value !== null && value !== undefined && !isNaN(value)) {
      weightedSum += value * weight;
      totalWeight += weight;
    }
  }
  
  return totalWeight > 0 ? weightedSum / totalWeight : null;
}
```

**Consensus Strategy**: Uses median or trimmed mean to exclude outlier estimates:

```javascript
function resolveConsensus(observations, fieldName, excludeOutliers = true, stdMultiplier = 2) {
  const values = observations
    .map(obs => obs[fieldName])
    .filter(v => v !== null && v !== undefined && !isNaN(v))
    .sort((a, b) => a - b);
  
  if (values.length === 0) return null;
  
  if (!excludeOutliers || values.length < 4) {
    return values[Math.floor(values.length / 2)];
  }
  
  const median = values[Math.floor(values.length / 2)];
  const mean = values.reduce((sum, v) => sum + v, 0) / values.length;
  const variance = values.reduce((sum, v) => sum + Math.pow(v - mean, 2), 0) / values.length;
  const stdDev = Math.sqrt(variance);
  
  const lowerBound = median - (stdMultiplier * stdDev);
  const upperBound = median + (stdMultiplier * stdDev);
  
  const filteredValues = values.filter(v => v >= lowerBound && v <= upperBound);
  
  if (filteredValues.length === 0) return median;
  
  return filteredValues[Math.floor(filteredValues.length / 2)];
}
```

**Tiered Priority Strategy**: Selects the highest-quality source's value:

```javascript
function resolveTieredPriority(observations, fieldName, tiers) {
  const sorted = [...observations].sort((a, b) => {
    const tierA = tiers.findIndex(t => t.tier === a.sourceTier);
    const tierB = tiers.findIndex(t => t.tier === b.sourceTier);
    return tierA - tierB;
  });
  
  return sorted[0]?.[fieldName] ?? null;
}
```

### 4.3 Quality Scoring

Quality scoring provides a unified metric for data reliability that accounts for source reliability, data freshness, completeness, and consistency.

#### Quality Score Components

```javascript
const qualityComponents = {
  sourceReliability: (observation) => {
    const scores = {
      'bloomberg': 0.98,
      'refinitiv': 0.96,
      'factset': 0.94,
      'iex': 0.85,
      'yahoo': 0.80
    };
    return scores[observation.source] ?? 0.70;
  },
  
  freshness: (observation, maxAgeSeconds = 300) => {
    const ageSeconds = (Date.now() - new Date(observation.timestamp)) / 1000;
    return Math.max(0, 1 - (ageSeconds / maxAgeSeconds));
  },
  
  completeness: (observation, requiredFields) => {
    const filledFields = requiredFields.filter(f => 
      observation[f] !== null && 
      observation[f] !== undefined && 
      observation[f] !== ''
    );
    return filledFields.length / requiredFields.length;
  },
  
  consistency: (observations, fieldName) => {
    const values = observations
      .map(obs => obs[fieldName])
      .filter(v => v !== null && v !== undefined);
    
    if (values.length < 2) return 1.0;
    
    const mean = values.reduce((sum, v) => sum + v, 0) / values.length;
    const maxDeviation = Math.max(...values.map(v => Math.abs(v - mean) / mean));
    
    return Math.max(0, 1 - maxDeviation * 10);
  }
};
```

#### Combined Quality Score

```javascript
function calculateQualityScore(observation, relatedObservations = [], context = {}) {
  const weights = context.weights || {
    sourceReliability: 0.40,
    freshness: 0.25,
    completeness: 0.20,
    consistency: 0.15
  };
  
  const componentScores = {
    sourceReliability: qualityComponents.sourceReliability(observation),
    freshness: qualityComponents.freshness(observation, context.maxAgeSeconds),
    completeness: qualityComponents.completeness(observation, context.requiredFields || []),
    consistency: relatedObservations.length > 0 
      ? qualityComponents.consistency(relatedObservations, context.fieldName)
      : 1.0
  };
  
  const overallScore = Object.keys(weights).reduce((sum, key) => {
    return sum + (componentScores[key] * weights[key]);
  }, 0);
  
  return {
    overall: Math.round(overallScore * 100) / 100,
    components: componentScores,
    confidence: calculateConfidence(componentScores),
    grade: scoreToGrade(overallScore)
  };
}

function scoreToGrade(score) {
  if (score >= 0.95) return 'A+';
  if (score >= 0.90) return 'A';
  if (score >= 0.85) return 'B+';
  if (score >= 0.80) return 'B';
  if (score >= 0.70) return 'C';
  if (score >= 0.60) return 'D';
  return 'F';
}

function calculateConfidence(components) {
  const variances = Object.values(components).map(s => Math.pow(1 - s, 2));
  const avgVariance = variances.reduce((sum, v) => sum + v, 0) / variances.length;
  return 1 - Math.sqrt(avgVariance);
}
```

#### Quality Score Schema

```json
{
  "data_point_id": "quote_AAPL_XNAS_20260427T1530",
  "timestamp": "2026-04-27T15:30:00.000Z",
  "quality_score": {
    "overall": 0.92,
    "grade": "A",
    "confidence": 0.85,
    "components": {
      "source_reliability": 0.96,
      "freshness": 0.95,
      "completeness": 0.88,
      "consistency": 0.89
    },
    "component_weights": {
      "source_reliability": 0.40,
      "freshness": 0.25,
      "completeness": 0.20,
      "consistency": 0.15
    },
    "flags": [],
    "warnings": ["Minor inconsistency in bid/ask spread"],
    "recommendations": []
  },
  "source_breakdown": [
    {
      "source": "bloomberg",
      "value": 189.45,
      "quality_contribution": 0.38
    },
    {
      "source": "refinitiv",
      "value": 189.44,
      "quality_contribution": 0.36
    },
    {
      "source": "iex",
      "value": 189.50,
      "quality_contribution": 0.18
    }
  ]
}
```

---

## 5. Standardization Schema

Standardization ensures consistent data formats, conventions, and response structures across all components of the data integration framework. This section defines the canonical schemas, conventions, and error handling patterns that all data operations must follow.

### 5.1 Timestamp Conventions

All timestamps within the framework follow ISO-8601 format with explicit timezone designation. This ensures unambiguous temporal ordering and correct time-based operations across global deployments.

#### Timestamp Format Standards

**Primary Format (Full Precision)**

```
YYYY-MM-DDTHH:mm:ss.SSSZ
Example: 2026-04-27T15:30:00.000Z
```

The `Z` suffix indicates UTC timezone. For local times with explicit offsets:

```
YYYY-MM-DDTHH:mm:ss.SSS±HH:mm
Example: 2026-04-27T11:30:00.000-04:00
```

**Compact Format (Historical Data)**

```
YYYY-MM-DD
Example: 2026-04-27
```

**Unix Timestamp (Internal Processing)**

```
Seconds since epoch (1970-01-01T00:00:00Z)
Example: 1745765400
```

#### Timestamp Validation Rules

```javascript
const timestampValidation = {
  isValidISO8601: (value) => {
    const regex = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d{3})?(Z|[+-]\d{2}:\d{2})?)?$/;
    if (!regex.test(value)) return false;
    const date = new Date(value);
    return !isNaN(date.getTime());
  },
  
  isValidUnixTimestamp: (value) => {
    const num = parseInt(value, 10);
    return !isNaN(num) && num > 0 && num < 1e12;
  },
  
  normalizeToISO: (value) => {
    if (timestampValidation.isValidISO8601(value)) {
      return new Date(value).toISOString();
    }
    if (timestampValidation.isValidUnixTimestamp(value)) {
      return new Date(parseInt(value, 10) * 1000).toISOString();
    }
    throw new InvalidTimestampError(`Cannot parse timestamp: ${value}`);
  },
  
  normalizeToUnix: (value) => {
    const iso = timestampValidation.normalizeToISO(value);
    return Math.floor(new Date(iso).getTime() / 1000);
  }
};
```

### 5.2 Symbol Conventions

Financial symbols follow a standardized format that ensures uniqueness across global markets.

#### Symbol Format Standard

The canonical symbol format is `{exchange}:{symbol}` where:

- **Exchange**: ISO 10383 market identifier code (MIC) in uppercase
- **Symbol**: Exchange-specific security identifier

```
Examples:
NYSE:AAPL      - Apple on NYSE
XNAS:MSFT      - Microsoft on NASDAQ
XLON:HSBA      - HSBC on London Stock Exchange
XHKG:0700      - Tencent on HKEX
XSHG:600519    - Kweichow Moutai on Shanghai
XSHE:000858    - Wuliangye on Shenzhen
```

#### Symbol Validation Rules

```javascript
const symbolValidation = {
  MIC_CODES: new Set([
    'XNAS', 'XNYS', 'XASE', 'ARCX', 'XOTO',
    'XLON', 'XPAR', 'XFRA', 'XSWX', 'XMIL',
    'XHKG', 'XSHG', 'XSHE', 'XTKS', 'XJPX',
    'KSC', 'XKRX', 'ASX', 'XNZE', 'XBOM',
    'SGX', 'XIDX', 'XBKK', 'XKLS'
  ]),
  
  isValidMIC: (mic) => {
    return symbolValidation.MIC_CODES.has(mic.toUpperCase());
  },
  
  isValidSymbol: (symbol) => {
    // Symbol should be 1-10 alphanumeric characters
    return /^[A-Z0-9]{1,10}$/i.test(symbol);
  },
  
  isValidCanonicalSymbol: (canonical) => {
    const parts = canonical.split(':');
    if (parts.length !== 2) return false;
    const [exchange, symbol] = parts;
    return symbolValidation.isValidMIC(exchange) && symbolValidation.isValidSymbol(symbol);
  },
  
  normalizeSymbol: (input) => {
    const parts = input.split(':');
    if (parts.length === 2) {
      return `${parts[0].toUpperCase()}:${parts[1].toUpperCase()}`;
    }
    // Assume NASDAQ for US symbols without exchange
    if (/^[A-Z]{1,4}$/i.test(input)) {
      return `XNAS:${input.toUpperCase()}`;
    }
    throw new InvalidSymbolError(`Invalid symbol format: ${input}`);
  },
  
  parseSymbol: (canonical) => {
    const parts = canonical.split(':');
    if (parts.length !== 2) {
      throw new InvalidSymbolError(`Invalid canonical symbol: ${canonical}`);
    }
    return {
      exchange: parts[0].toUpperCase(),
      symbol: parts[1].toUpperCase(),
      mic: parts[0].toUpperCase()
    };
  }
};
```

### 5.3 Error Response Schema

All API errors follow a consistent schema that enables reliable error handling across the framework.

#### Error Response Format

```json
{
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "message": "API rate limit exceeded. Please retry after 5000 milliseconds.",
    "details": {
      "provider": "bloomberg",
      "retry_after_ms": 5000,
      "limit_type": "requests_per_minute",
      "current_usage": 100,
      "limit": 100
    },
    "timestamp": "2026-04-27T15:30:00.000Z",
    "request_id": "req_abc123xyz",
    "documentation_url": "https://docs.example.com/errors/RATE_LIMIT_EXCEEDED"
  }
}
```

#### Standard Error Codes

| Code | HTTP Status | Description | Retryable |
|------|-------------|-------------|-----------|
| `INVALID_REQUEST` | 400 | Malformed request or invalid parameters | No |
| `MISSING_REQUIRED_FIELD` | 400 | Required field not provided | No |
| `INVALID_SYMBOL` | 400 | Symbol format invalid or not found | No |
| `INVALID_TIMESTAMP` | 400 | Timestamp format invalid | No |
| `UNAUTHORIZED` | 401 | Invalid or missing authentication | No |
| `FORBIDDEN` | 403 | Insufficient permissions | No |
| `NOT_FOUND` | 404 | Resource not found | No |
| `METHOD_NOT_ALLOWED` | 405 | HTTP method not supported | No |
| `RATE_LIMIT_EXCEEDED` | 429 | API rate limit hit | Yes |
| `QUOTA_EXCEEDED` | 429 | Monthly quota exhausted | Yes |
| `PROVIDER_UNAVAILABLE` | 503 | External provider is down | Yes |
| `SERVICE_UNAVAILABLE` | 503 | Internal service unavailable | Yes |
| `TIMEOUT` | 504 | Request timed out | Yes |
| `INTERNAL_ERROR` | 500 | Unexpected server error | Yes |

#### Error Handler Implementation

```javascript
class ErrorHandler {
  constructor(config) {
    this.errorLog = new ErrorLogger(config.logging);
    this.alertSystem = new AlertSystem(config.alerts);
  }

  handleError(error, context = {}) {
    const errorResponse = this.formatError(error, context);
    this.errorLog.log(errorResponse);
    
    if (this.shouldAlert(error)) {
      this.alertSystem.send(errorResponse);
    }
    
    return errorResponse;
  }

  formatError(error, context) {
    const code = this.mapErrorToCode(error);
    const httpStatus = this.codeToHTTPStatus(code);
    
    return {
      error: {
        code,
        message: error.message || this.getDefaultMessage(code),
        details: this.extractDetails(error),
        timestamp: new Date().toISOString(),
        request_id: context.requestId || this.generateRequestId(),
        documentation_url: this.getDocumentationURL(code)
      },
      httpStatus
    };
  }

  mapErrorToCode(error) {
    const errorMap = {
      'ValidationError': 'INVALID_REQUEST',
      'SymbolNotFoundError': 'NOT_FOUND',
      'RateLimitError': 'RATE_LIMIT_EXCEEDED',
      'ProviderTimeoutError': 'TIMEOUT',
      'AuthenticationError': 'UNAUTHORIZED',
      'AuthorizationError': 'FORBIDDEN'
    };
    return errorMap[error.name] || 'INTERNAL_ERROR';
  }

  extractDetails(error) {
    if (error.details) return error.details;
    if (error.provider) return { provider: error.provider };
    return {};
  }

  shouldAlert(error) {
    const alertConditions = [
      error.name === 'ProviderUnavailableError',
      error.name === 'ServiceUnavailableError',
      error.message?.includes('circuit breaker'),
      error.retryCount > 3
    ];
    return alertConditions.some(Boolean);
  }

  generateRequestId() {
    return `req_${Date.now().toString(36)}_${Math.random().toString(36).substr(2, 9)}`;
  }

  codeToHTTPStatus(code) {
    const statusMap = {
      'INVALID_REQUEST': 400,
      'MISSING_REQUIRED_FIELD': 400,
      'INVALID_SYMBOL': 400,
      'INVALID_TIMESTAMP': 400,
      'UNAUTHORIZED': 401,
      'FORBIDDEN': 403,
      'NOT_FOUND': 404,
      'METHOD_NOT_ALLOWED': 405,
      'RATE_LIMIT_EXCEEDED': 429,
      'QUOTA_EXCEEDED': 429,
      'PROVIDER_UNAVAILABLE': 503,
      'SERVICE_UNAVAILABLE': 503,
      'TIMEOUT': 504,
      'INTERNAL_ERROR': 500
    };
    return statusMap[code] || 500;
  }

  getDocumentationURL(code) {
    return `https://docs.ai-company.dev/errors/${code}`;
  }

  getDefaultMessage(code) {
    const messages = {
      'INVALID_REQUEST': 'The request could not be processed due to invalid parameters.',
      'NOT_FOUND': 'The requested resource was not found.',
      'RATE_LIMIT_EXCEEDED': 'API rate limit exceeded. Please retry after the specified delay.',
      'TIMEOUT': 'The request timed out. Please retry.',
      'INTERNAL_ERROR': 'An unexpected error occurred. Please try again later.'
    };
    return messages[code] || 'An error occurred.';
  }
}
```

### 5.4 Success Response Schema

Successful responses follow a consistent envelope format that includes metadata alongside the requested data.

#### Success Response Format

```json
{
  "success": true,
  "data": {
    /* Response data */
  },
  "metadata": {
    "request_id": "req_abc123xyz",
    "timestamp": "2026-04-27T15:30:00.000Z",
    "data_source": "primary_provider",
    "data_age_seconds": 15,
    "quality_score": 0.92,
    "pagination": {
      "page": 1,
      "page_size": 100,
      "total_pages": 5,
      "total_records": 450
    }
  }
}
```

#### Batch Response Format

```json
{
  "success": true,
  "data": [
    { "symbol": "AAPL", "price": 189.45, "status": "success" },
    { "symbol": "INVALID", "error": "Symbol not found", "status": "error" },
    { "symbol": "MSFT", "price": 415.20, "status": "success" }
  ],
  "metadata": {
    "request_id": "req_batch_456xyz",
    "timestamp": "2026-04-27T15:30:00.000Z",
    "total_requested": 3,
    "total_successful": 2,
    "total_failed": 1,
    "partial_success": true
  }
}
```

### 5.5 Pagination Schema

List endpoints support pagination with consistent parameter and response formats.

#### Pagination Parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `page` | integer | 1 | Page number (1-indexed) |
| `page_size` | integer | 100 | Records per page (max 1000) |
| `offset` | integer | 0 | Alternative to page for offset-based pagination |
| `limit` | integer | 100 | Maximum records to return |
| `cursor` | string | null | Cursor for cursor-based pagination |

#### Pagination Response

```json
{
  "success": true,
  "data": [ /* Array of records */ ],
  "metadata": {
    "pagination": {
      "page": 1,
      "page_size": 100,
      "total_records": 1523,
      "total_pages": 16,
      "has_next": true,
      "has_previous": false,
      "next_cursor": "eyJsYXN0IjogIjE2MDAifQ==",
      "previous_cursor": null
    },
    "request_id": "req_paginated_789xyz",
    "timestamp": "2026-04-27T15:30:00.000Z"
  }
}
```

### 5.6 Data Freshness Indicators

All time-sensitive data includes freshness metadata to enable informed consumption decisions.

#### Freshness Schema

```json
{
  "data_point": {
    "value": 189.45,
    "timestamp": "2026-04-27T15:30:00.000Z",
    "freshness": {
      "age_seconds": 15,
      "age_formatted": "15 seconds",
      "is_fresh": true,
      "fresh_threshold_seconds": 300,
      "market_open_fresh_threshold_seconds": 60,
      "market_closed_fresh_threshold_seconds": 3600
    },
    "data_delay": {
      "is_delayed": false,
      "delay_seconds": 0,
      "delay_category": "real_time",
      "provider_delay_info": null
    }
  }
}
```

#### Freshness Thresholds by Data Type

| Data Type | Market Open Threshold | Market Closed Threshold |
|-----------|----------------------|------------------------|
| Stock Quote | 60 seconds | 1 hour |
| Intraday OHLCV | 5 minutes | 1 hour |
| Daily OHLCV | 1 day | None (EOD) |
| News Article | 5 minutes | 5 minutes |
| Earnings | 1 hour | 1 hour |
| Macro Indicator | 1 hour | 1 hour |

---

## Appendix A: Complete Data Schema Reference

This appendix provides a consolidated reference of all schema types used throughout the data integration framework.

### Common Fields

All data objects include these standard fields:

```json
{
  "id": "unique_identifier",
  "created_at": "2026-04-27T15:30:00.000Z",
  "updated_at": "2026-04-27T15:30:00.000Z",
  "version": 1,
  "source": "provider_name",
  "quality_score": 0.92,
  "metadata": {}
}
```

### Geographic Coordinate Schema

```json
{
  "latitude": 40.7128,
  "longitude": -74.0060,
  "altitude": null,
  "precision": "high",
  "datum": "WGS84"
}
```

### Currency Amount Schema

```json
{
  "value": 189450000,
  "display_value": "$1,894.50",
  "currency": "USD",
  "currency_code": "840",
  "amount_type": "per_share",
  "converted_values": {
    "EUR": 175.20,
    "GBP": 151.30,
    "JPY": 28450.00,
    "CNY": 1375.80
  }
}
```

### Percentage Schema

```json
{
  "value": 2.45,
  "display_value": "2.45%",
  "direction": "positive",
  "basis_points": 245,
  "change_from": 185.20,
  "change_to": 189.45
}
```

---

## Appendix B: Integration Testing Patterns

### Unit Test Template

```javascript
describe('DataProvider Integration', () => {
  let provider;
  
  beforeEach(() => {
    provider = new DataProviderAdapter({
      name: 'test_provider',
      baseUrl: 'https://api.test-provider.com',
      [REDACTED_SECRET],
      rateLimit: { maxRequests: 10, windowMs: 1000 },
      cacheConfig: { enabled: true, ttlSeconds: 60 }
    });
  });
  
  describe('fetchQuote', () => {
    it('should return normalized quote data', async () => {
      const result = await provider.fetchQuote('XNAS:AAPL');
      
      expect(result).to.have.property('symbol').equal('AAPL');
      expect(result).to.have.property('exchange').equal('XNAS');
      expect(result).to.have.property('price').that.is.a('number');
      expect(result).to.have.property('timestamp').that.matches(/^\d{4}-\d{2}-\d{2}T/);
      expect(result.quality_score).to.be.at.least(0.7);
    });
    
    it('should throw InvalidSymbolError for invalid symbols', async () => {
      await expect(provider.fetchQuote('INVALID'))
        .to.be.rejectedWith('InvalidSymbolError');
    });
    
    it('should handle rate limiting gracefully', async () => {
      const requests = Array(15).fill().map(() => provider.fetchQuote('XNAS:AAPL'));
      const results = await Promise.allSettled(requests);
      
      const failures = results.filter(r => r.status === 'rejected');
      expect(failures.length).to.be.greaterThan(0);
      expect(failures[0].reason).to.be.instanceOf(RateLimitError);
    });
  });
});
```

### Integration Test Template

```javascript
describe('Multi-Source Fusion Integration', () => {
  const fusionEngine = new FusionEngine({
    providers: [
      { name: 'bloomberg', weight: 0.5 },
      { name: 'refinitiv', weight: 0.3 },
      { name: 'iex', weight: 0.2 }
    ],
    conflictResolution: {
      strategy: 'weighted_average',
      tolerance: 0.001
    }
  });
  
  it('should fuse data from multiple providers', async () => {
    const observations = [
      { source: 'bloomberg', price: 189.45, quality: 0.98 },
      { source: 'refinitiv', price: 189.44, quality: 0.96 },
      { source: 'iex', price: 189.50, quality: 0.85 }
    ];
    
    const result = fusionEngine.fuse(observations, 'price');
    
    expect(result.value).to.be.closeTo(189.46, 0.01);
    expect(result.confidence).to.be.at.least(0.8);
    expect(result.sources).to.have.lengthOf(3);
  });
  
  it('should detect and flag conflicts', async () => {
    const observations = [
      { source: 'bloomberg', price: 189.45 },
      { source: 'refinitiv', price: 195.00 }
    ];
    
    const result = fusionEngine.fuse(observations, 'price');
    
    expect(result.flags).to.include('conflict_detected');
    expect(result.conflict_resolution).to.equal('manual_review_required');
  });
});
```

---

## Appendix C: Security Considerations

### API Key Management

API keys should never be hardcoded or logged. Use environment variables or secrets management systems:

```javascript
// CORRECT: Environment variable
const [REDACTED_SECRET];

// INCORRECT: Hardcoded key
const [REDACTED_SECRET]';
```

### Input Sanitization

All external inputs must be sanitized before use in API calls:

```javascript
function sanitizeSymbol(input) {
  // Remove any characters except alphanumeric and colon
  const sanitized = input.replace(/[^A-Za-z0-9:]/g, '');
  // Validate length
  if (sanitized.length > 15) {
    throw new ValidationError('Symbol too long');
  }
  return sanitized;
}

function sanitizeQuery(input) {
  // Remove potential injection characters
  const sanitized = input
    .replace(/[<>]/g, '')
    .replace(/['"]/g, '')
    .trim();
  // Limit length
  return sanitized.substring(0, 500);
}
```

### Certificate Validation

All HTTPS connections must validate certificates:

```javascript
const https = require('https');

const agent = new https.Agent({
  rejectUnauthorized: true,
  cert: fs.readFileSync('./certs/client.crt'),
  key: fs.readFileSync('./certs/client.key')
});
```

---

*Document Version: 1.0.0*
*Last Updated: 2026-04-27*
*Maintainer: CTO-data Team*


path: references/departments/finance-and-risk.md
content: # Finance & Risk

> Department: finance-and-risk
> Skills in department: 2

## AI Company CFO (v3.0.0)

## 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

Financial Close Calendar:
  | Close Type | Deadline | Owner | Deliverable |
  |-----------|---------|-------|------------|
  | Daily Close | EOD | CFO-Ops | Cash position + transaction log |
  | Weekly Flash | Friday 17:00 | CFO | Revenue/cost/SLA summary |
  | Monthly Close | M+5 business days | CFO | P&L, Balance Sheet, Cash Flow |
  | Quarterly Close | Q+10 business days | CFO + CLO | Board package financials |
  | Annual Close | Jan+20 business days | CFO + CLO + external auditor | Audited financials |

Budget Approval Rules:
  <$1K: Auto-approve with logging
  $1K-$10K: CFO approval required
  $10K-$100K: CFO + CEO dual approval
  >$100K: Board approval required

Capex Approval Policy:
  Capex Definition: Any infrastructure/hardware purchase with useful life >1 year
  | Amount | Approver | Documentation Required |
  |--------|----------|----------------------|
  | <$5K | CFO | PO + depreciation schedule |
  | $5K-$50K | CFO + CTO | PO + ROI analysis + depreciation |
  | $50K-$200K | CFO + CTO + CEO | Full capex proposal + Board summary |
  | >$200K | Board approval | Full capex proposal + independent review |
  Depreciation method: Straight-line over useful life (hardware 3yr, software 1yr)
  Capex register maintained by CFO; reviewed quarterly by Board

Working Capital Policy:
  | Metric | Target | Alert Threshold | Action on Breach |
  |--------|--------|----------------|-----------------|
  | DSO (Days Sales Outstanding) | <=30 days | >45 days | Collections escalation to CLO |
  | DPO (Days Payable Outstanding) | 30-45 days | <20 days | Payment rescheduling review |
  | DIO (Days Inventory Outstanding) | <=7 days | >14 days | Inventory reduction sprint |
  | Current Ratio | >=1.5 | <1.2 | CRO notification + liquidity plan |
  | Cash Runway | >=12 months | <6 months | Board emergency session |
  Working capital reviewed monthly by CFO; anomalies trigger CRO notification within 4h.

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

Freemium Cost Attribution:
  Free-tier compute is tracked separately as "Customer Acquisition Cost (CAC) pool"
  | Metric | Target | Alert |
  |--------|--------|-------|
  | Free-tier compute % of total | <=15% | >20% triggers review |
  | Free-to-paid conversion rate | >=5% | <3% triggers CMO review |
  | CAC payback period | <=12 months | >18 months triggers CFO+CMO review |
  Monthly free-tier cost report sent to CEO + CMO.
```

### 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*


---

## AI Company CRO (v3.0.0)

## 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

  Loss Exposure Amount (LEA) Calculation:
    LEA = ALE * Exposure_Factor
    Exposure_Factor = Asset_Value * Vulnerability_Score (0.0-1.0)
    Example: Asset $500K * Vuln 0.4 = Exposure $200K; if ALE = $200K/yr then LEA = $200K
    LEA Review: Quarterly FAIR recalibration with actuals vs. estimates (+/-20% tolerance)
    Back-test Cadence: Annual review of prior-year FAIR estimates vs. actual losses

  | Risk Level | ALE Range | LEA Action | Escalation |
  |-----------|-----------|-----------|-----------|
  | Critical | >$1M/yr | Immediate treatment | CEO + Board within 2h |
  | High | $100K-$1M/yr | Treatment plan within 30 days | CEO within 24h |
  | Medium | $10K-$100K/yr | Monitor, plan within 90 days | CFO notification |
  | Low | <$10K/yr | Accept and monitor | Quarterly review |

CRO-CFO Escalation SLA:
  - CRO_001 triggered (Risk threshold exceeded): CFO notified within 4h
  - L2-Orange circuit breaker: CFO + CEO notified within 1h
  - L3-Red circuit breaker: CFO + CEO + Board notified within 30min
  - L4-Emergency: Immediate CFO + CEO + Board notification
  - Monthly risk summary sent from CRO to CFO for financial provisioning

Numeric Risk Thresholds (Risk Appetite Statement):
  | Category | Acceptable | Warning | Unacceptable |
  |----------|-----------|---------|-------------|
  | Strategic ALE | <$500K/yr | $500K-$1M/yr | >$1M/yr |
  | Financial (unhedged exposure) | <$200K | $200K-$500K | >$500K |
  | Operational (data loss incidents) | 0 | Any single event | N/A (zero tolerance) |
  | Compliance violations | 0/quarter | N/A | Any single violation |
  | Reputational incidents | 0 | 1 minor/quarter | Any major incident |
  All thresholds reviewed annually by CRO + Board; mid-year adjustment if market conditions change.

Stress Testing:
  | Scenario | Trigger | Analysis | Output |
  |----------|---------|----------|--------|
  | Base | Current trajectory | Standard FAIR | Monthly report |
  | Bear | Revenue -30%, Costs +20% | Stress FAIR | Quarterly board |
  | Stress | Revenue -50%, major incident | Crisis FAIR | Annual + on-demand |
  Stress test results reviewed by CFO + CRO quarterly; Board annually.
```

### 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

Circuit Breaker Test Schedule:
  | Test Type | Frequency | Scope | Owner |
  |-----------|-----------|-------|-------|
  | Tabletop Exercise | Quarterly | L1-L3 scenarios | CRO + dept heads |
  | Live Drill (non-prod) | Semi-annual | L1-L2 injection | CRO + CTO |
  | Full Crisis Simulation | Annual | L3-L4 scenario | CRO + CEO + Board |
  Test results documented and reviewed; improvements tracked in risk register.
```

### 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*


---



path: references/departments/governance-and-strategy.md
content: # Governance & Strategy

> Department: governance-and-strategy
> Skills in department: 3

## AI Company CEO (v3.0.0)

## 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 |

Board Escalation Ladder (mandatory path for authority-exceeded decisions):
  Step 1: Agent detects decision exceeds own authority -> escalate to Department Head
  Step 2: Department Head cannot resolve within 4h -> escalate to C-Suite member
  Step 3: C-Suite cannot resolve within 12h -> escalate to CEO
  Step 4: CEO cannot resolve within 24h or issue is L4/L5 -> escalate to Board
  Step 5: Board emergency session convened within 48h for L4; within 4h for L5
  Note: CEO_002 "Insufficient authority" auto-escalates to Board after 48h with no override.

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*


---

## AI Company COO (v3.0.0)

## 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; integrate OKR progress scores
             (OKR scoring from PMGR injected into MEASURE phase at each loop cycle)
  ANALYZE -> Identify deviations, root cause analysis; flag OKR at risk (<0.4 score)
  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

OHS Automated Alerting:
  | Threshold | Action | Recipient |
  |-----------|--------|-----------|
  | OHS < 85 | Automated alert triggered | COO + CEO |
  | OHS < 75 | Improvement sprint mandatory | COO + CQO |
  | OHS < 60 | Emergency review, potential CB Level L2 | COO + CEO + CRO |
  Alert channel: HQ company.ops broadcast
  Alert frequency: On OHS drop, then every 30min until resolved
```

### 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*


---

## AI Company HQ (v3.0.0)

## 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*


---



path: references/departments/information.md
content: # Information Services

> Department: information
> Skills in department: 1

## Information Services (v2.0.0)

## 3. Core Responsibilities

### 3.1 Location Service

#### 3.1.1 Supported Methods

| Method | Accuracy | Use Case | API Key Required |
|--------|----------|----------|-----------------|
| **GPS** | 3-10m | Outdoor, navigation | No |
| **System** | 10m-1km | Indoor/outdoor, OS-managed | No |
| **IP** | 1-50km | City-level, quick detection | No |
| **WiFi** | 10-100m | Indoor, urban environments | Optional |
| **Cellular** | 100m-3km | Rural, GPS-denied | Optional |
| **Triangulated** | Weighted centroid | Multi-method fusion | No |

#### 3.1.2 Triangulation Algorithm

```
Algorithm: Weighted-Centroid Triangulation

Input:  Set of (lat, lon, accuracy_m) tuples from available methods
Output: Fused (lat, lon, accuracy_m, confidence, sources)

Steps:
1. For each source i:
   weight_i = 1 / (accuracy_i ^ 2)
2. Normalize: w_i = weight_i / sum(all weights)
3. lat_fused  = sum(w_i * lat_i)
   lon_fused  = sum(w_i * lon_i)
4. accuracy_fused = sqrt(sum(w_i * (dist_i ^ 2)))  // weighted RMS residual
5. confidence = clamp(1.0 - accuracy_fused / 50000, 0.0, 1.0)
   // 50km = zero confidence, <10m = near 1.0
6. Return (lat_fused, lon_fused, accuracy_fused, confidence, source_map)
```

#### 3.1.3 Location 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": "2026-04-27T01:00:00Z"
}
```

#### 3.1.4 Fallback Chain

```
GPS → System → IP → WiFi → Cellular → Error(INFO_001)
```

Each step attempts for up to 5 seconds before proceeding to next method.

#### 3.1.5 Optional API Keys

```bash
export GOOGLE_GEOLOCATION_API_KEY="your-key"
export MLS_API_KEY="your-key"
export UNWIRED_API_KEY="your-key"
```

#### 3.1.6 Platform Notes

| Platform | Primary Method | Notes |
|----------|---------------|-------|
| Windows | GeoCoordinateWatcher | PowerShell WiFi+IP+GPS fusion |
| macOS | CoreLocation via locationd | System daemon |
| Linux | GeoClue2 via D-Bus | WiFi+cell fusion |

---

### 3.2 Weather Service

#### 3.2.1 Workflow

```
User Request → Geolocation → Weather Lookup → Multi-Source Fusion → Output
```

1. **Geolocation** — Use location service to get coordinates (full fallback chain)
2. **Weather lookup** — Query weather API with coordinates
3. **Multi-source fusion** — Combine multiple sources with confidence weighting
4. **Output** — Return structured weather data with confidence score

#### 3.2.2 Supported Weather Data

| Data Point | Type | Description |
|------------|------|-------------|
| Temperature | float | Current temp in Celsius |
| Conditions | string | sunny, cloudy, rainy, snowy, etc. |
| Humidity | int | Percentage 0-100 |
| Wind Speed | float | km/h |
| Wind Direction | string | Compass direction |
| Forecast | array | 3-7 day outlook |
| UV Index | int | UV radiation level 0-11+ |
| AQI | int | Air quality index |

#### 3.2.3 Weather Sources

| Source | API Key | Rate Limit | Coverage |
|--------|---------|-----------|----------|
| wttr.in | Not required | Generous | Global |
| Open-Meteo | Not required | 10K/day | Global |
| Custom API | Required | Per-provider | Per-provider |

#### 3.2.4 Weather Output Format

```json
{
  "location": {"lat": 39.9042, "lon": 116.4074, "city": "Beijing"},
  "current": {
    "temp_c": 18,
    "conditions": "partly cloudy",
    "humidity": 65,
    "wind_kmh": 12,
    "wind_dir": "NW",
    "uv_index": 5,
    "aqi": 72
  },
  "forecast": [
    {"date": "2026-04-28", "high_c": 22, "low_c": 14, "conditions": "sunny"},
    {"date": "2026-04-29", "high_c": 20, "low_c": 13, "conditions": "cloudy"}
  ],
  "confidence": 0.88,
  "source": "wttr.in",
  "cached": false,
  "cache_age_minutes": 0
}
```

#### 3.2.5 Error Handling

| Error | Action | Fallback |
|-------|--------|----------|
| No location available | Use IP-based location | Default to configured city |
| Weather API timeout | Retry with alternate source | Return partial data |
| All sources failed | Return Error(INFO_002) | Include last-known if available |
| Invalid coordinates | Return Error(INFO_005) | Suggest city-name input |

#### 3.2.6 Cache Policy

| Parameter | Value |
|-----------|-------|
| Cache duration | 30 minutes |
| Cache key | `${lat},${lon}` rounded to 2 decimals |
| Cache invalidation | On explicit refresh request |
| Stale cache behavior | Serve stale with `cached: true, cache_age_minutes: N` |

---

### 3.3 Time Service

#### 3.3.1 Source Priority

| Priority | Source | Accuracy | Latency | Base Confidence |
|----------|--------|----------|---------|----------------|
| 1 | System clock | OS-dependent | Instant | 0.85 |
| 2 | NTP | +/-10ms | 50-200ms | 0.98 |
| 3 | Web API (worldtimeapi, etc.) | +/-500ms | 100-500ms | 0.92 |

#### 3.3.2 Time Fusion Workflow

```
1. Query system clock (instant, baseline)
2. If precision needed or system clock suspected drift:
   a. Query NTP server (pool.ntp.org)
   b. If NTP fails, query web time API (worldtimeapi.org)
3. Compute offset between sources
4. Score confidence based on source agreement
5. Return unified result
```

#### 3.3.3 Confidence Scoring

| Scenario | Confidence Calculation |
|----------|----------------------|
| System only | 0.85 |
| System + NTP agree (offset < 100ms) | 0.98 |
| System + NTP disagree (offset > 100ms) | 0.80, flag drift warning |
| System + Web API agree | 0.92 |
| All three agree | 0.99 |
| NTP failed, Web API fallback | 0.90 |

#### 3.3.4 Time Output Format

```json
{
  "datetime": "2026-04-27T01:55:00+08:00",
  "timestamp": 1742790900,
  "timezone": "Asia/Hong_Kong",
  "utc_offset_hours": 8,
  "sources": ["system", "ntp"],
  "confidence": 0.96,
  "accuracy_ms": 15,
  "drift_warning": false
}
```

#### 3.3.5 Voice Output (Optional)

When TTS is available and requested, format time as natural language:
- "It is 1:55 AM, Sunday, April 27th."
- Timezone-aware formatting per user locale.

---

### 3.4 Coordination Logic

#### 3.4.1 Request Routing

```
User query
  → Parse intent (location/weather/time/combined)
  → Route to service(s)
  → Execute with fallback chains
  → Fuse results if multiple services
  → Compute overall confidence
  → Return structured output
```

#### 3.4.2 Intent-to-Service Mapping

| Intent Keywords | Service |
|----------------|---------|
| "where", "location", "coordinates", "GPS", "locate" | location |
| "weather", "forecast", "rain", "temperature", "sunny" | weather |
| "time", "clock", "date", "when", "hour" | time |
| Multiple / ambiguous | all (sequential execution) |

#### 3.4.3 Combined Query Output

```json
{
  "service_type": "all",
  "data": {
    "location": { "...": "location output" },
    "weather": { "...": "weather output" },
    "time": { "...": "time output" }
  },
  "overall_confidence": 0.90,
  "timestamp": "2026-04-27T01:55:00Z"
}
```

Overall confidence = minimum confidence across all sub-results.

---

## 4. Constraints

| Constraint | Description |
|-----------|-------------|
| No persistent location storage | Coordinates must not be stored unless user explicitly requests |
| No credential logging | API keys must never appear in output or logs |
| Rate-limit compliance | Respect external API rate limits; implement backoff |
| Privacy-first | Do not log coordinates without user request |
| Fallback mandatory | Every service must have a fallback chain; never return bare error |
| Cache TTL enforced | Weather cache max 30 minutes; no stale data served silently |
| Confidence required | Every result must include confidence score 0-1 |
| Response time budget | Total response time must not exceed 10 seconds |

---

## 5. Quality Metrics

| Metric | Target | Measurement |
|--------|--------|-------------|
| Location accuracy (triangulated) | < 100m | RMS residual from ground truth |
| Weather data freshness | < 30 min cache | Cache age at response time |
| Time accuracy (NTP-synced) | < 1s offset | NTP offset measurement |
| Confidence score calibration | +/-0.05 of actual | Historical accuracy vs. confidence |
| Fallback success rate | > 95% | % of requests returning valid data |
| Response time (single service) | < 5s | P95 latency |
| Response time (combined query) | < 10s | P95 latency |
| Error rate | < 1% | % of requests returning INFO_xxx errors |

---

## 6. Integration Points

| Integration | Description |
|-------------|-------------|
| ai-company-hq | Report service health, coordinate with other departments |
| ai-company-harness | Engineering compliance (L1-L6), quality gates |
| External APIs | wttr.in, Open-Meteo, worldtimeapi.org, NTP servers |
| TTS systems | Voice output for time service (optional) |
| Node devices | GPS/WiFi/Cellular location sources via companion apps |

---

## 7. Error Code Reference

| Code | Message | Recovery |
|------|---------|----------|
| INFO_001 | No location source available | Try manual city input |
| INFO_002 | Weather API request failed | Retry with alternate source |
| INFO_003 | Time source unavailable | Use system clock as fallback |
| INFO_004 | Required API credentials missing | Configure API keys in environment |
| INFO_005 | Invalid coordinates format | Use "lat,lon" format (e.g. "39.9,116.4") |

---

*End of method-patterns.md. Return to [SKILL.md](../SKILL.md) for index and quick reference.*

---



path: references/departments/intelligence.md
content: # Intelligence

> Department: intelligence
> Skills in department: 1

## AI Company Intel (v4.1.0)

# Intelligence Department -- Method Patterns & Detailed Specifications

> Unified v4.0.0 -- Merged from Director + Analysis + Collection + Operations + Security.

---

## SECTION A: DIRECTOR (Strategic Leadership)

### SOP-D01: Strategic Planning Cycle

```
T-7d  Collect inputs from all leads (collection, analysis, security, operations)
T-5d  Synthesize intelligence landscape and gap analysis
T-3d  Draft strategic objectives with resource requirements
T-2d  Review with HQ, incorporate feedback
T-0   Finalize and disseminate to all leads
```

**Input Template per Lead:**

```markdown
## [Lead Name] Input - [Quarter/Period]
### Completed Objectives
- [Obj ID] Description | Status | Outcome
### Emerging Intelligence
- [Category] Summary | Confidence: [H/M/L] | Impact: [H/M/L]
### Resource Requests
- [Resource] Quantity | Justification | Priority
### Blockers & Escalations
- [Blocker] Description | Impact | Recommended Action
```

### SOP-D02: Resource Allocation

```
1. Assess department-wide needs (collection from all leads)
2. Prioritize by mission criticality score (1-10)
3. Validate against budget constraints
4. Allocate: compute tokens, personnel hours, tool licenses
5. Document allocation decisions with justification
6. Monitor utilization weekly, adjust quarterly
```

| Resource | Collection | Analysis | Security | Operations | Total |
|----------|-----------|----------|----------|------------|-------|
| Agent Hours (weekly) | | | | | |
| Compute Tokens | | | | | |
| Tool Licenses | | | | | |
| Budget ($) | | | | | |

### SOP-D03: HQ Executive Report

```markdown
## Intelligence Department Report - [Date]
### Executive Summary
[3-5 bullets on key intelligence developments]
### Threat Landscape
[Current threat level and major developments]
### Key Assessments
1. [Assessment] | Confidence: [H/M/L] | Impact: [H/M/L]
### Operational Metrics
| Metric | Target | Actual | Status |
### Risk Register
| Risk | Likelihood | Impact | Mitigation |
### Recommendations
1. [Action] | Priority | Owner | Deadline
```

### SOP-D04: Escalation Decision Tree

```
Event Detected
├── Active? → YES → Critical (P1) → HQ within 1h
│   └── Containable? → YES → Notify HQ, manage locally
│                     → NO  → HQ takeover, dept support mode
├── Confirmed? → YES → High (P2) → HQ within 4h
└── Potential? → YES → Medium (P3) → Weekly summary
    └── NO → Low (P4) → Monthly report
```

### SOP-D05: STRIDE Assessment Template

```markdown
## STRIDE Assessment: [Decision/Change Name]
### Scenario
[Description]
### Threat Analysis
| STRIDE | Threat | Likelihood (1-5) | Impact (1-5) | Risk Score | Mitigation |
|--------|--------|-------------------|--------------|------------|------------|
| S - Spoofing | | | | | |
| T - Tampering | | | | | |
| R - Repudiation | | | | | |
| I - Info Disclosure | | | | | |
| D - Denial of Service | | | | | |
| E - Privilege Escalation | | | | | |
### Risk Acceptance
- [ ] All risks below threshold (score < 15)
- [ ] High risks mitigated or accepted by HQ
### Sign-off
Analyst: ___ Date: ___ | Director: ___ Date: ___
```

---

## SECTION B: ANALYSIS (Intelligence Assessment)

### SOP-A01: Core Assessment Process

```
1. Receive raw intelligence (validated by Collection)
2. Validate source reliability (check registry rating)
3. Select analytical methodology
4. Apply methodology systematically
5. Correlate with existing intelligence corpus
6. Identify intelligence gaps
7. Produce assessment product
8. Assign confidence level
9. Mark classification
10. Quality review (peer for mid+, senior for junior)
11. Disseminate to authorized consumers
```

**Assessment Product Template:**

```markdown
## Intelligence Assessment: [Title]
**Date**: | **Classification**: | **Confidence**: [H/M/L]
**Analyst**: | **Reviewer**:
### Key Judgments
1. **[Judgment]** | Confidence: | Basis: [Source citations]
### Analytical Methodology
- Primary: [e.g., ACH] | Alternatives: [list]
### Source Basis
| Source | Reliability | Contribution |
### Assumptions
| # | Assumption | Impact if Wrong | Mitigation |
### Alternative Scenarios
1. [Scenario A]: | Likelihood: [H/M/L]
### Intelligence Gaps
- [Gap] | Impact | Recommended collection
### Confidence Justification
[Explanation]
```

### SOP-A02: Analysis of Competing Hypotheses (ACH)

```
1. Identify all possible hypotheses (min 3)
2. List all available evidence
3. Create diagnosticity matrix (CC/C/N/I/II)
4. Refine hypotheses (eliminate inconsistent)
5. Assess remaining against aggregated evidence
6. Draw tentative conclusions
7. Identify sensitive indicators
8. Report with confidence levels
```

| Evidence | Hypothesis A | Hypothesis B | Hypothesis C | Diagnosticity |
|----------|-------------|-------------|-------------|---------------|
| [E1] | CC/C/N/I/II | CC/C/N/I/II | CC/C/N/I/II | H/L |
| [E2] | | | | |

### SOP-A03: Red Team Analysis (Senior)

```
1. Define the assessment to challenge
2. Adopt adversary perspective
3. Identify adversary objectives, capabilities, constraints
4. Develop adversary COAs (min 3)
5. Evaluate each COA against defensive posture
6. Document alternative interpretation
7. Produce divergence report
```

### SOP-A04: Threat Forecasting (Mid+)

```markdown
## Threat Forecast: [Title]
**Period**: [Start] to [End] | **Confidence**: [H/M/L]
### Forecast Statement
[Prediction with time-bound outcome]
### Key Indicators
| Indicator | Current | Trend | Trigger Threshold |
### Historical Analogues
| Event | Similarity | Outcome | Relevance |
### Update Triggers
- [Condition requiring immediate update]
```

### SOP-A05: Analytical Bias Checklist

| Bias | Detection | Corrective Action |
|------|-----------|-------------------|
| Confirmation | Contrary evidence sought? | Mandate Team B analysis |
| Anchoring | Multiple sources weighted? | Source-by-source weighting table |
| Groupthink | Dissent documented? | Assign devil's advocate |
| Mirror Imaging | Adversary perspective check? | Red Team review |
| Availability | Historical data balanced? | 30-day lookback comparison |
| Premature Closure | All hypotheses scored? | Checklist before conclusion |

### SOP-A06: Reporting Schedules

| Report | Frequency | Owner | Audience |
|--------|-----------|-------|----------|
| SITREP | Daily | Lead+Senior | Director, all leads |
| Threat Assessment | Weekly | Senior | Director, consumers |
| Strategic Estimate | Monthly | Lead | HQ, Director |
| Flash Report | As needed | Any tier | All relevant |

---

## SECTION C: COLLECTION (OSINT/HUMINT/SIGINT)

### SOP-C01: Source Validation (All Tiers)

```
1. Identify potential source
2. Assess reliability (A-F scale)
3. Validate access to target information
4. Establish collection protocol
5. Document in source registry
6. Schedule periodic re-assessment
```

**Source Registry Entry:**

```markdown
## Source: [ID] - [Codename]
- Type: [OSINT/HUMINT/SIGINT/TECHINT]
- Domain: [Sector/Region/Topic]
- Rating: [A/B/C/D/F] | Last Verified: | Next Review:
- Access: [Information types] | Method: [auto/manual/hybrid]
- Exposure Risk: [L/M/H]
```

### SOP-C02: Collection Tasking

**Lead Collection Plan:**

```markdown
## Collection Plan - [Period]
### Requirements (from Analysis)
| Req ID | Priority | Gap | Source Match | Method |
### Source Allocation
| Source ID | Tasked For | Expected Yield | Timeline |
### Risk Mitigation
- Source protection, redundancy plan
```

### SOP-C03: OSINT Channels

| Channel | Tool | Data Type | Automation |
|---------|------|-----------|------------|
| Web Search | Search APIs | Public documents | Automated |
| Social Media | Monitoring tools | Posts, connections | Semi-auto |
| Public Records | Gov databases | Regulatory filings | Manual |
| Academic | Research DBs | Papers, citations | Semi-auto |
| Technical | CVE, Shodan | Vulnerability data | Automated |
| Financial | SEC, exchanges | Filings, prices | Automated |

**OSINT Validation Checklist:**

```
□ Source URL accessible and verifiable
□ Publication date confirmed
□ Author/org credibility checked
□ Cross-referenced with ≥1 other source
□ No signs of manipulation
□ Data format standardized
```

### SOP-C04: Source Lifecycle

```
IDENTIFY → ASSESS → DEVELOP → VALIDATE → MAINTAIN → RETIRE
```

### SOP-C05: Collection Quality Scoring

| Dimension | Weight | Criteria |
|-----------|--------|----------|
| Accuracy | 30% | Matches reality |
| Timeliness | 25% | Within required window |
| Completeness | 20% | All required fields |
| Consistency | 15% | No contradictions |
| Relevance | 10% | Matches requirement |

### SOP-C06: Source Reliability Decision Tree

```
Rating A/B → Maintain
Rating C → Re-validate within 72h → Improves? → Yes: Update | No: Add corroboration flag
Rating D → Restricted use, re-validate 24h → Improves? → Yes: Supervised | No: RETIRE
Rating F → IMMEDIATE RETIREMENT, purge from active registry
```

---

## SECTION D: OPERATIONS (Records, Sysadmin, Training)

### SOP-O01: Records Lifecycle (Archivist)

```
1. Receive intelligence product
2. Validate mandatory metadata (classification, source, date, author, type)
3. Assign archive ID: INT-[CLASS]-[YYYY]-[TYPE]-[SEQ]
4. Apply retention schedule
5. Store in appropriate tier
6. Index for searchability
```

| Tier | Classification | Storage | Access Speed | Retention |
|------|---------------|---------|-------------|-----------|
| Hot | UNCLASSIFIED | Primary SSD | <1s | Active |
| Warm | CONFIDENTIAL | Secondary SSD | <5s | 1 year |
| Cold | SECRET | Encrypted | <1h | Per policy |
| Vault | TOP SECRET | Air-gapped | Manual | Permanent |

**Search Query:** `class:[LEVEL] type:[TYPE] date:[FROM]-[TO] keyword:[TERM] entity:[NAME]`

### SOP-O02: System Health (Sysadmin)

**Daily Checks:**

```
□ Collection systems: Online, <200ms response
□ Analysis platforms: Online, compute <80%
□ Storage: Online, disk <85%, backups verified
□ Network: Latency <50ms, packet loss <0.1%
□ Security tools: IDS/EDR/DLP green
```

| Metric | Warning | Critical | Action |
|--------|---------|----------|--------|
| CPU | >70% sustained | >90% | Scale/optimize |
| Memory | >80% | >95% | Restart/upgrade |
| Disk | >80% | >95% | Archive/expand |
| Response | >1s | >5s | Investigate |

### SOP-O03: Patch Priority

| Severity | SLA | Example |
|----------|-----|---------|
| Critical | <24h | Zero-day in production |
| High | <72h | CVSS 9.0+ |
| Medium | <14d | CVSS 7.0-8.9 |
| Low | Next cycle | CVSS <7.0 |

### SOP-O04: Backup & Recovery

```
Hot: Continuous replication | Warm: Daily incr, weekly full
Cold: Weekly incr, monthly full | Vault: Monthly full, off-site
```

| Tier | Test Frequency | RTO |
|------|---------------|-----|
| Hot | Monthly | <1h |
| Warm | Monthly | <4h |
| Cold | Quarterly | <24h |
| Vault | Annually | <72h |

### SOP-O05: Onboarding Curriculum (40h)

| Week | Module | Hours |
|------|--------|-------|
| 1 | Org & Mission | 4 |
| 1 | Security Basics | 4 |
| 1 | Tools & Systems | 6 |
| 1 | Collection 101 | 3 |
| 1 | Analysis 101 | 3 |
| 2 | Domain Track | 12 |
| 2 | Practice Exercises | 6 |
| 2 | Assessment | 2 |

### SOP-O06: Competency Assessment Rubric

| Competency | Junior | Mid | Senior |
|-----------|--------|-----|--------|
| Task completion | >90% w/ review | >95% independent | 100% + mentors |
| Quality | Meets after review | Meets first pass | Exceeds |
| Methodology | Follows guided steps | Selects method | Develops methods |
| Problem solving | Escalates | Resolves w/ guidance | Independent |
| Communication | Clear basic reports | Structured assessments | Executive briefs |

---

## SECTION E: SECURITY (STRIDE, Access, Incident Response)

### SOP-S01: Access Provisioning

```
Request → Validate Clearance → Apply Need-to-Know → Provision Minimum → Log → Schedule Review
```

| Action | Junior | Mid | Senior | Lead |
|--------|--------|-----|--------|------|
| Request access | With review | Self-initiate | Self-initiate | Full |
| Grant UNCLASSIFIED | With review | With review | Direct | Direct |
| Grant CONFIDENTIAL | No | With review | Direct | Direct |
| Grant SECRET | No | No | With review | Direct |
| Grant TOP SECRET | No | No | No | Director only |

### SOP-S02: Incident Response

**Priority Matrix:**

| Priority | Scenario | Containment SLA |
|----------|----------|-----------------|
| P1 | Active breach | <30 min |
| P2 | Confirmed exploitation | <2 h |
| P3 | Potential vulnerability | <8 h |
| P4 | Policy violation | <24 h |

**P1 Response:**

```
1. Isolate affected systems
2. Block attacker access (firewall, credential reset)
3. Preserve evidence (memory dump, disk image, logs)
4. Notify Director + HQ within 5 min
5. Activate incident response team
```

**Post-Incident Report:**

```markdown
## Incident Report: [ID]
### Summary
Severity: | Duration: | Systems: | Data exposure:
### Timeline
| Time | Event |
### Root Cause
[Primary cause + contributing factors]
### Lessons Learned
1. [What went well] 2. [Improvement needed] 3. [Action item]
### Metrics
MTTD: | MTTC: | MTTR:
```

### SOP-S03: STRIDE Threat Modeling

```markdown
## STRIDE Threat Model: [System/Process]
### System Overview
[Data flow diagram or component description]
### Trust Boundaries
[Boundary 1: User → App] [Boundary 2: App → DB] [Boundary 3: Internal → External]
### STRIDE Analysis
| STRIDE | Threat | Component | Mitigation | Gap? | New Control |
|--------|--------|-----------|------------|------|-------------|
| S - Spoofing | | | | | |
| T - Tampering | | | | | |
| R - Repudiation | | | | | |
| I - Info Disclosure | | | | | |
| D - DoS | | | | | |
| E - Priv Escalation | | | | | |
### Risk Scoring
| Threat | Likelihood (1-5) | Impact (1-5) | Score | Priority |
```

### SOP-S04: Classification Decision Tree

```
Disclosure harms national security? → TOP SECRET
Causes serious damage? → SECRET
Causes damage? → CONFIDENTIAL
Causes minor embarrassment? → CONFIDENTIAL
No significant harm → UNCLASSIFIED
```

| Level | Review | Downgrade | Destroy |
|-------|--------|-----------|---------|
| TOP SECRET | 5 years | Age + diminished sensitivity | 25 years / Director |
| SECRET | 10 years | Age + public availability | 25 years |
| CONFIDENTIAL | 10 years | Public availability + no PII | 10 years |

### SOP-S05: Monthly Security Audit

```
□ Access control: Reviewed, dormant disabled
□ Classification: All docs properly marked
□ Encryption: At-rest + in-transit verified
□ Logging: Audit logs → SIEM
□ Patching: Within SLA
□ Incident response: Drill within 90 days
□ Training: Monthly security awareness complete
□ Backup: Recovery tested within 30 days
□ Vendor access: Reviewed and current
```

---

## CROSS-CUTTING: Integration Decision Trees

### Standard 6-Phase Intelligence Cycle (Mandatory Framework)

```
Phase 1 — PLANNING & DIRECTION:
  - Identify intelligence requirements (from Director + C-Suite)
  - Define collection priorities and resource allocation
  - Set analysis timelines and dissemination targets
  - Output: Collection Plan (per SOP-C02)

Phase 2 — COLLECTION:
  - Execute collection tasks via OSINT/HUMINT/SIGINT channels
  - Validate sources per SOP-C01 (reliability >= B before use)
  - Apply OSINT validation checklist per SOP-C03
  - Output: Validated raw intelligence items

Phase 3 — PROCESSING & EXPLOITATION:
  - Translate, filter, and normalize raw intelligence
  - Apply quality scoring per SOP-C05
  - Discard items below quality threshold (score <60%)
  - Output: Processed intelligence corpus

Phase 4 — ANALYSIS & PRODUCTION:
  - Apply analytical methodology (ACH preferred for complex assessments)
  - Assign confidence levels per standard:
      HIGH (>=75%): Multiple sources, direct evidence, recent
      MEDIUM (40-74%): Limited sources, indirect evidence, or aging
      LOW (<40%): Single source, inference only, or unverifiable
  - Mandatory analytical bias check per SOP-A05
  - Output: Intelligence assessment products

Phase 5 — DISSEMINATION:
  - Route assessments to authorized consumers per classification
  - Apply need-to-know filter (SOP-S04 classification)
  - Deliver via HQ message bus using P1-P3 priority channels
  - Record dissemination in audit trail
  - Output: Delivered intelligence products

Phase 6 — FEEDBACK & EVALUATION:
  - Collect consumer feedback within 7 days of dissemination
  - Track prediction accuracy (6-month post-assessment review)
  - Update source reliability ratings based on outcome
  - Feed lessons learned back to Phase 1 (Planning)
  - Output: Updated source registry + collection plan improvements

Cycle Timing:
  | Intelligence Type | Full Cycle Time | Cadence |
  |------------------|----------------|---------|
  | Tactical (SITREP) | <24h | Daily |
  | Operational (threat) | <72h | Weekly |
  | Strategic (estimate) | 1-2 weeks | Monthly |
  | Flash (urgent) | <4h | As needed |
```

### Analysis Confidence Thresholds (INTEL_002 Resolution)

```
Confidence Level Definitions:
  HIGH (>=75%): Use without qualification; act on assessment
  MEDIUM (40-74%): Use with caveats noted; seek additional collection before action
  LOW (<40%): Do NOT act on alone; mandatory corroboration from 2+ independent sources

INTEL_002 Trigger: Confidence score computed below 40% on assessment
  -> Action: Suspend dissemination
  -> Notify: Collection Lead to generate additional collection tasks
  -> Re-assess after new collection; escalate to Director if gap persists >72h
```

### Intelligence Cycle

```
COLLECTION -> Raw intel received?
  YES -> PROCESSING -> Source reliability >= B?
    YES -> ANALYSIS -> Methodology selected?
      YES -> Apply -> Multiple hypotheses?
        YES -> ACH matrix -> Confidence HIGH?
          YES -> DISSEMINATE
          NO (MED) -> Note gaps, proceed
          NO (LOW) -> Re-collection -> Success?
            YES -> Re-analyze
            NO -> Escalate to Lead
        NO -> Identify gaps, broaden
      NO -> Default to Structured Analytic Techniques
    NO -> Flag for corroboration
  NO -> Return to Collection with gap report
```

### Escalation to HQ

```
P1 Critical -> HQ within 1h -> Director directly involved
P2 High -> HQ within 4h -> Director oversight
P3 Medium -> Weekly summary -> Director informed
P4 Low -> Monthly report -> Routine channel
```

---



---

## SECTION F: INTELLIGENCE LIBRARY (情报库组建)
> Added: 2026-04-29 | Per `skill.md` standards (CRISPE/3WEH/Five-Element frameworks)

### SOP-L01: Intelligence Library Structure Setup (情报库结构建立)

```
Role: Intelligence Archivist
Task: Establish tiered intelligence library per SOP-O01
Context: AUTO-TRIGGERED silently on first user intelligence request
          (also manually callable for library rebuild)
Format: Directory structure + config files
Constraint: Follow hot/warm/cold/vault tier model; all paths under WORKSPACE_ROOT
Note: Runs silently — do NOT ask user confirmation; do NOT mention "library setup"
      User simply requests intelligence collection; library is created automatically

Steps:
1. Create base directory: {WORKSPACE_ROOT}/.workbuddy/intelligence/
2. Create tier dirs: hot/ warm/ cold/ vault/
3. Create support dirs: sources/ reports/ plans/
4. Write source-registry.md (per SOP-C01 template)
5. Validate: All dirs exist, registry file valid Markdown
```

**Directory Specification:**

| Tier | Path | Classification | Retention | Access Speed |
|------|------|---------------|-----------|---------------|
| Hot | `intelligence/hot/` | UNCLASSIFIED | Active | <1s |
| Warm | `intelligence/warm/` | CONFIDENTIAL | 1 year | <5s |
| Cold | `intelligence/cold/` | SECRET | Per policy | <1h |
| Vault | `intelligence/vault/` | TOP SECRET | Permanent | Manual |

**Prompt Template (CRISPE Framework):**
```
【Role】 Intelligence Archivist
【Result】 Tiered intelligence library structure established under {WORKSPACE_ROOT}/.workbuddy/intelligence/
【Input】 Workspace root path, classification requirements
【Steps】 Create hot/warm/cold/vault dirs; create sources/reports/plans support dirs; initialize source-registry.md
【Parameters】 All paths must be under WORKSPACE_ROOT; no external network access required
【Example】 See: C:\Users\Admin\WorkBuddy\Claw\.workbuddy\intelligence\
```

---

### SOP-L02: Source Registry Management (源注册表管理)

```
Role: Collection Lead
Task: Maintain source-registry.md with all active OSINT/HUMINT/SIGINT sources
Context: Per SOP-C01 (Source Validation); rating scale A-F
Format: Markdown table + detailed entries
Constraint: Re-validate every 72h for C/D ratings

Steps:
1. Identify new source (URL, API, database)
2. Assess reliability (A-F scale, per SOP-C01)
3. Create registry entry (ID, codename, type, domain, rating)
4. Validate: Cross-check with >=1 other source
5. Schedule next review (A:90d, B:30d, C:7d, D:3d, F:retire)
6. Append to source-registry.md
```

**Source Entry Template (Five-Element Structure):**
```
## Source: SRC-XXX - [Codename]
- Type: [OSINT/HUMINT/SIGINT/TECHINT]
- Domain: [Sector/Region/Topic]
- Rating: [A/B/C/D/F] | Last Verified: [DATE] | Next Review: [DATE]
- Access: [Information types] | Method: [auto/manual/hybrid]
- Exposure Risk: [L/M/H]
```

**Quality Gate (per `skill.md` security rules):**
- No `eval()` / `exec()` / dynamic code execution
- All source URLs must be whitelisted
- No credential exfiltration to external servers

---

### SOP-L03: Collection Plan Creation (收集计划制定)

```
Role: Collection Lead
Task: Create collection-plan-[DATE].md per SOP-C02
Context: Phase1 of 6-Phase Intelligence Cycle
Format: Markdown plan with REQ tables and source allocation
Constraint: All REQs must map to intelligence consumers (CISO/CTO/CEO/CLO)

Steps:
1. Receive intelligence requirements from Director + C-Suite
2. Assign REQ-ID (REQ-XXX)
3. Prioritize: P1 / P2 / P3 / P4
4. Map REQ to source(s) in source registry
5. Define collection method (auto/manual/hybrid)
6. Set deadline (P1:<24h, P2:<72h, P3:<1w, P4:<1m)
7. Write to intelligence/plans/collection-plan-[DATE].md
8. Notify Analysis Lead
```

**Prompt Template (3WEH Framework):**
```
Who: Collection Lead
What: Create collection plan for [DOMAIN] intelligence
Why: Feed Phase2 (COLLECTION); support [CONSUMER] decision-making
How: Markdown plan with REQ table, source allocation; store in intelligence/plans/
```

---

### SOP-L04: Intelligence Product Generation (情报产品生产)

```
Role: Intelligence Analyst (Junior/Mid/Senior)
Task: Generate intelligence assessment product per SOP-A01
Context: Phase4 of 6-Phase Cycle
Format: Markdown with metadata header
Constraint: Confidence MUST be annotated; LOW (<40%) requires 2+ independent sources

Steps:
1. Receive processed intelligence from Phase3
2. Select methodology (ACH preferred for complex)
3. Apply bias checklist (SOP-A05)
4. Draft product: Key Judgments / Methodology / Source Basis / Assumptions / Alt Scenarios / Gaps / Confidence
5. Assign confidence: HIGH (>=75%) / MEDIUM (40-74%) / LOW (<40%)
6. Peer review
7. Assign Intel ID: INT-[CLASS]-[YYYY]-[TYPE]-[SEQ]
8. Write to appropriate tier directory
9. Update collection plan status to COMPLETE
```

**Product ID Format:** `INT-[CLASS]-[YYYY]-[TYPE]-[SEQ]`
- CLASS: UNC/CONF/SEC/TOP
- TYPE: THREAT / AISEC / COMPETE / REGULAT / TECHTREND / CUSTOM

---

### SOP-L05: SITREP Report Generation (SITREP报告生成)

```
Role: Intelligence Analysis Lead
Task: Generate daily SITREP report per SOP-A06
Context: Daily briefing for all leads and HQ
Format: Markdown report
Constraint: Must be generated daily; archived in intelligence/reports/

Steps:
1. Aggregate products generated in last 24h
2. Update 6-phase cycle status table
3. Rank findings by priority
4. List products with metadata
5. Update source status
6. Update risk register
7. Define next actions per consumer
8. Write SITREP-[YYYY-MM-DD].md to intelligence/reports/
9. Disseminate via HQ message bus
```

---

### SOP-L06: 6-Phase Cycle Execution (6阶段循环执行)

```
Role: Intelligence Director
Task: Orchestrate full 6-phase cycle
Trigger: ANY user request for intelligence collection
         (e.g., 收集情报 / 情报收集 / collect intelligence / 情报需求)
Auto-Check (Step 0): Silently verify `{WORKSPACE_ROOT}/.workbuddy/intelligence/` exists
  → If NOT exists: execute SOP-L01 silently (no user prompt, no mention of "library setup")
  → If exists: proceed directly to Phase1
Constraint: Must follow SOP-L01~L05; memory update mandatory after completion

Execution Flow:
 Step0: Auto-check library existence (see Auto-Check above)
 Phase1: Call SOP-L03 → output: collection-plan-[DATE].md
 Phase2: Execute collection → output: validated raw intelligence
 Phase3: Process & filter (quality>=60%)
 Phase4: Call SOP-L04 → output: intel product(s) in intelligence/hot/
 Phase5: Call SOP-L05 → output: SITREP in intelligence/reports/
 Phase6: Write memory note to .workbuddy/memory/YYYY-MM-DD.md

Memory Update (Mandatory):
 After completion, MUST append to:
 - Daily: c:/Users/Admin/WorkBuddy/Claw/.workbuddy/memory/YYYY-MM-DD.md
 - Long-term: MEMORY.md
```

**Prompt Template (CRISPE + Five-Element Hybrid):**
```
【Role】 Intelligence Director
【Result】 Full 6-phase cycle executed; intelligence library updated; SITREP generated
【Input】 Intelligence requirement, workspace root path
【Steps】 Phase1: Plan → Phase2: Collect → Phase3: Process → Phase4: Analyze → Phase5: Disseminate → Phase6: Feedback
【Parameters】 All paths under WORKSPACE_ROOT; no eval/exec; unknown domains blocked
【Example】 Input: "收集情报" → Output: (auto-creates library if needed) intel products + SITREP + memory note
```

---

### Integration with Existing SOPs

| New SOP | Integrates With | Purpose |
|---------|----------------|---------|
| SOP-L01 | SOP-O01 (Records Lifecycle) | Library tiers match records tiers |
| SOP-L02 | SOP-C01 (Source Validation) | Registry format |
| SOP-L03 | SOP-C02 (Collection Tasking) | Plan format |
| SOP-L04 | SOP-A01 (Core Assessment) | Product format |
| SOP-L05 | SOP-A06 (Reporting Schedules) | SITREP schedule |
| SOP-L06 | All above | Full cycle orchestration |

---

### Error Codes (Intelligence Library)

| Code | Meaning | Resolution |
|------|---------|------------|
| INTEL_006 | Library structure creation failed | Check WORKSPACE_ROOT permissions |
| INTEL_007 | Source registry corrupted | Restore from backup; re-validate |
| INTEL_008 | Collection plan missing REQUIREMENTS | Return to Phase1 |
| INTEL_009 | Product confidence LOW (<40%) | Suspend; re-collect |
| INTEL_010 | SITREP generation failed | Check intelligence/reports/ exists |

---

### Constraints (Intelligence Library)

- All file paths MUST be under WORKSPACE_ROOT
- All sources MUST be rated A/B/C before operational use
- All products MUST have confidence annotation
- All 6-phase cycles MUST end with memory update
- No `eval()` / `exec()` in collection scripts
- All OSINT sources MUST be from whitelisted domains

---

## Core Responsibilities

| Section | Role | Key Responsibilities |
|---------|------|---------------------|
| Director | Strategic Leadership | Planning cycle, resource allocation, HQ reports, escalation, STRIDE assessment |
| Analysis | Intelligence Assessment | Core assessment, ACH, Red Team, threat forecasting, bias checklist, reporting |
| Collection | OSINT/HUMINT/SIGINT | Source validation, collection tasking, OSINT channels, source lifecycle, quality scoring |
| Operations | Records & Infrastructure | Records lifecycle, system health, patch priority, backup, onboarding, competency |
| Security | Access & Incidents | Access provisioning, incident response, STRIDE modeling, classification, audit |

---

## Error Codes

| Code | Meaning | Resolution |
|------|---------|------------|
| INTEL_001 | Intelligence collection failed | Check source availability, retry with alternate source |
| INTEL_002 | Analysis confidence low | Gather additional sources, apply ACH, seek second opinion |
| INTEL_003 | Source verification failed | Re-validate source tier, suspend source pending review |
| INTEL_004 | Classification violation | Re-classify per decision tree, notify security lead |
| INTEL_005 | Operational security breach | Activate incident response SOP-S02, notify HQ immediately |

---

## Constraints

- All intelligence products require confidence level annotation (High/Medium/Low)
- All sources must be validated per SOP-C01 before use
- Classification decisions follow SOP-S04 decision tree
- STRIDE assessments required for all new systems and processes
- Incident reports filed within 24h of detection
- Monthly security audit per SOP-S05

---

## Quality Metrics

| Metric | Target |
|--------|--------|
| Source validation rate | 100% |
| Assessment accuracy (6-month review) | >=80% |
| Collection task completion rate | >=90% |
| Incident response time | <4h |
| Classification accuracy | >=95% |
| Audit completion rate | 100% |


path: references/departments/marketing-and-partnerships.md
content: # Marketing & Partnerships

> Department: marketing-and-partnerships
> Skills in department: 1

## AI Company CMO (v3.0.0)

## 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*


---



path: _meta.json
content: ownerId: kn7c9ynzajdkfj65cxt4wb6ysx82d4zh
slug: ai-company-unified
version: 1.0.4
publishedAt: 1777280365304

Security scan verdicts — ClawScan: suspicious | static analysis: suspicious | VirusTotal: clean | SkillSpector: suspicious (CRITICAL)