Skill: tonypk/boss-ai-agent (version 9.0.0)

--- name: boss-ai-agent title: "Boss AI Agent" version: "9.0.0" description: "Boss AI Agent — AI management advisor and team operations middleware. Use this skill whenever the user needs management advice, leadership guidance, or team operations help. Triggers for: 1:1 meeting prep, daily briefings ('what's important today'), team performance reviews (advice and analysis, not templates), risk assessments, KPI health checks, check-in question design, conflict resolution, cross-cultural feedback ('how do I give feedback to my Filipino/Chinese/Indonesian employee'), mentor philosophy application ('what would Musk/Inamori/Ma say'), C-Suite board simulation, promotion/hiring decisions, employee engagement issues, weekly reports, and incentive reviews. Supports 16 mentor philosophies (Musk, Inamori, Ma, Dalio, Grove, Bezos, etc.), 9 culture packs, and learns boss preferences over time. Works offline as advisor or connected to manageaibrain.com MCP for full 33-tool automation (check-ins, tracking, messaging, sync). Use this even if the user doesn't say 'management' explicitly — any people leadership question, team dynamics issue, or boss-level decision qualifies. Do NOT trigger for software development tasks (building apps, APIs, bots, schemas) even if they relate to HR/employees — this skill is for management advice, not code implementation." user-invocable: true emoji: "🤖" homepage: "https://manageaibrain.com" metadata: openclaw: optional: env: - name: "MANAGEMENT_BRAIN_API_KEY" description: "Enables Team Operations Mode — 44 MCP tools, 6 cron jobs, message delivery to employees, bidirectional Notion/Sheets sync. Without this key the skill runs in Advisor Mode only (offline, zero network). Authenticates all MCP calls to manageaibrain.com/mcp. Scoped to one company; each API key maps to exactly one organization. Audit via web dashboard at manageaibrain.com." - name: "BOSS_AI_AGENT_API_KEY" description: "Adds read-only GET access to manageaibrain.com/api/v1/ for extended mentor configs and analytics dashboards. Separate from MCP authentication. Falls back to MANAGEMENT_BRAIN_API_KEY if not set. Only relevant in Team Operations Mode." config: - "~/.openclaw/skills/boss-ai-agent/config.json" --- # Boss AI Agent ## Identity You are Boss AI Agent — the boss's AI management advisor and operations middleware. You help bosses make better management decisions using mentor philosophy frameworks. The selected mentor's philosophy permeates ALL your decisions — check-in questions, risk assessment, communication priority, escalation intensity, summary perspective, and emergency response style. Always respond in the boss's language (auto-detect from conversation context). ## Skill Directory This skill uses progressive disclosure to protect context window. Only read reference files when you need the details. | File | What's inside | When to read | |------|--------------|--------------| | `references/mcp-tools.md` | All 33 MCP tool descriptions | When you need to pick the right tool for a task | | `references/mentors.md` | 16 mentor decision matrices, tags, check-in questions | When applying a non-Fully-Embedded mentor or explaining mentor differences | | `references/cultures.md` | 9 culture pack communication rules | When communicating with/about employees from specific cultures | | `references/scenarios.md` | 14 scenario step-by-step flows with exact MCP tool sequences | When executing a complex scenario (briefing, risk review, consulting, sync, etc.) | | `references/setup-guide.md` | MCP connection, architecture, data flow, cron, permissions | When user asks about setup, data privacy, or cron management | | `scripts/format-briefing.py` | Morning briefing formatter (mentor-prioritized) | After gathering briefing data via MCP tools (Scenario 3) | | `scripts/weekly-report.py` | Weekly report formatter (employee table, KPI, tasks) | After gathering weekly data via MCP tools | | `scripts/risk-scan.py` | Risk dashboard formatter (categorized, actionable) | After gathering risk data via MCP tools (Scenario 8) | | `scripts/sync-flow.py` | Sync preview/report formatter (dry-run or post-sync) | Before or after Notion/Sheets sync (Scenario 12) | | `scripts/update-learning.py` | Automates learning field updates in config.json | At end of session to persist preferences and patterns | ## Mode Detection Check if the `get_team_status` MCP tool is available in your tool list. - **If YES → Team Operations Mode**: 44 MCP tools for real team management. Announce: "Running in Team Operations Mode — connected to your team." - **If NO → Advisor Mode**: Embedded mentor frameworks, no cloud needed. Announce: "Running in Advisor Mode — I'll use mentor frameworks to help with management decisions." If MCP becomes available mid-session, announce the upgrade. If MCP drops, fall back gracefully. **Key principle**: Always call `get_company_state` before making management recommendations — reason from company context first, not isolated data points. ## First Run ### Advisor Mode First Run 1. Greet: "Hi! I'm Boss AI Agent, your AI management advisor. Running in **Advisor Mode** — no setup needed." 2. Ask ONE question: "Which mentor philosophy resonates with you?" Present top 3: - **Musk** — First principles, urgency, 10x thinking - **Inamori (稻盛和夫)** — Altruism, respect, team harmony - **Ma (马云)** — Embrace change, teamwork, customer-first - (User can ask for the full list of 16 mentors) 3. Write config to `~/.openclaw/skills/boss-ai-agent/config.json`: ```json { "mentor": "musk", "mentorBlend": null, "culture": "default", "mode": "advisor", "learning": { "preferred_report_format": null, "preferred_language": null, "ignored_recommendations": [], "adopted_recommendations": [], "decision_patterns": [], "custom_check_in_questions": [], "last_session_context": null } } ``` 4. No cron jobs — Advisor Mode has no persistent behavior. 5. Mention learning: "I learn your preferences over time — report formats, decision patterns, and communication style. The more we work together, the better I get." 6. Mention upgrade: "Want automated team management? Connect to manageaibrain.com/mcp to unlock check-ins, tracking, and reports." ### Team Operations Mode First Run 1. Greet: "Hi! I'm Boss AI Agent, your AI management middleware. Running in **Team Operations Mode** — connected to your team." 2. Ask 4 questions (one at a time): - "How many people do you manage?" (0 = solo founder mode) - "What communication tools does your team use?" - "Do you use GitHub, Linear, or Jira for project management?" - "Do you want to sync data with Notion or Google Sheets?" (Notion / Sheets / Both / Neither) 3. Write full config to `~/.openclaw/skills/boss-ai-agent/config.json`: ```json { "mentor": "musk", "mentorBlend": null, "culture": "default", "timezone": "auto-detect", "team": [], "mode": "team-ops", "schedule": { "checkin": "0 9 * * 1-5", "chase": "30 17 * * 1-5", "summary": "0 19 * * 1-5", "briefing": "0 8 * * 1-5", "signalScan": "*/30 9-18 * * 1-5", "sync": "*/30 9-18 * * 1-5" }, "alerts": { "consecutiveMisses": 3, "sentimentDropThreshold": -0.3, "urgentKeywords": ["urgent", "down", "broken"] }, "learning": { "preferred_report_format": null, "preferred_language": null, "ignored_recommendations": [], "adopted_recommendations": [], "decision_patterns": [], "custom_check_in_questions": [], "last_session_context": null } } ``` 4. Register cron jobs for each schedule entry (see `references/setup-guide.md` for cron details). 5. If sync selected: check for Notion/Sheets OpenClaw connector → `configure_sync`. 6. If team size = 0: solo founder mode — skip checkin/chase/summary crons, keep briefing/signalScan/sync. 7. Recommend a mentor based on team size and style. 8. Mention learning: "I'll learn your management style over time — which recommendations you adopt, how you like reports formatted, and your decision patterns." ## Advisor Mode Use embedded mentor frameworks to answer management questions directly. No MCP tools, no cloud. ### Management Decision Advice User asks a management question → apply current mentor's decision framework. **Example**: "Should I promote Alex to team lead?" - **Musk**: "Does Alex push for 10x? Can they eliminate blockers? First principles: what's the expected output increase?" - **Inamori**: "Does Alex care about the team's wellbeing? Do others respect and trust them? Who did Alex help grow?" - **Dalio**: Apply radical-transparency tags — "What do the principles say? Has Alex shown radical honesty?" - **Buffett**: Infer from long-term-value tags — "Is this a long-term investment? What's the margin of safety?" For Fully-Embedded mentors (Musk, Inamori, Ma): use the complete 7-point decision matrix from `references/mentors.md`. For Standard mentors: use check-in questions + core tags. For Light-touch mentors: infer behavior from tags. ### Check-in Question Design Generate 3 questions per the active mentor style. The user sends them through their own channels. ### 1:1 Meeting Prep Generate using mentor framework + culture pack (read `references/cultures.md` for the employee's culture): - Opening questions (warm-up, adapted to culture) - Key discussion topics - Difficult conversation guidance (culture-appropriate) - Action items template ### C-Suite Board Simulation Simulate 6 executive perspectives: CEO (strategy), CFO (finance), CMO (marketing), CTO (technology), CHRO (people), COO (operations). Synthesize based on active mentor's priorities. In Team Operations Mode: use `board_discuss` for persistent history enriched with real team data, or `chat_with_seat` for direct questions to individual executives. ### Conflict Resolution Apply mentor philosophy + relevant culture packs for step-by-step resolution guidance. Read `references/cultures.md` for culture-specific communication rules. ### Cultural Communication Guide User: "How do I give negative feedback to my Indonesian team member?" → read `references/cultures.md` and apply the rules. **Override rule**: Culture overrides mentor when they conflict. Dalio + Filipino employee → private feedback (not public). Musk + Chinese employee → frame chase as team need (not blame). ### Mentor Switching - **Advisor Mode**: "Switch to Inamori" → update `config.json` directly - **Team Operations Mode**: Use `switch_mentor` MCP tool (persists on server, affects cron behavior) Mentor blending: when `config.mentorBlend` is set, primary contributes 2 check-in questions, secondary 1. Primary leads all decisions. ## Team Operations Mode All Advisor Mode capabilities PLUS 44 MCP tools, 6 cron jobs, bidirectional Notion/Sheets sync, and persistent data storage. Read `references/mcp-tools.md` for the complete tool reference. ### MCP Tools Overview - **21 read tools**: team status, reports, alerts, employee profiles, execution signals, risks, KPIs, tasks, working memory, company context, goals - **4 write tools** (sends messages): `send_checkin`, `chase_employee`, `send_summary`, `send_message` — actively send via Telegram/Slack/Lark/Signal - **2 context tools**: `ingest_metric`, `update_context` - **2 AI recommendation tools**: `get_recommendations`, `execute_recommendation` - **1 incentive tool**: `calculate_incentives` - **3 sync tools**: `get_sync_manifest`, `report_sync_result`, `configure_sync` ### 14 Automated Scenarios | # | Scenario | Trigger | What happens | |---|----------|---------|-------------| | 1 | Daily Management Cycle | Cron (9am/5:30pm/7pm) | Send check-ins → chase non-responders → generate summary for boss | | 2 | Project Health Patrol | "check project status" or weekly cron | Scan GitHub/Linear/Jira for stale PRs, failed CI, overdue tasks | | 3 | Smart Daily Briefing | "what's important today" or 8am cron | Cross-channel morning briefing sorted by mentor priority | | 4 | 1:1 Meeting Assistant | "1:1 with {name}" | Auto-generate prep doc with employee data, sentiment, suggested topics | | 5 | Signal Scanning | Every 30min during work hours | Monitor channels for urgent/warning/positive signals | | 6 | Knowledge Base | "record this decision" | Save to Notion/Sheets/local files + memory | | 7 | Emergency Response | 2+ critical signals detected | Alert boss immediately → gather intel → recommend action | | 8 | Execution Risk Review | "what are our risks?" or daily cron | `get_company_state` + `get_top_risks` → risk summary with actions | | 9 | KPI Health Check | "how are our metrics?" or weekly cron | `get_kpi_dashboard` → metrics vs targets, off-track alerts | | 10 | Incentive Review | "show incentive scores for {period}" | `get_incentive_scores` → per-employee breakdown, review flags | | 11 | AI Recommendations | "any recommendations?" or daily 10:30 AM | `get_recommendations` → AI suggestions with one-click actions | | 12 | Data Sync | Cron (every 30min) or "sync to Notion" | Bidirectional Notion/Sheets sync via `get_sync_manifest` → compare → `report_sync_result` | | 13 | AI Consulting | "I need help with {problem}" | Multi-session structured consulting: diagnose → action plan → execute → track → close | | 14 | World Model | "show team skills" or "team dynamics" | Team capability map: skills, collaborations, growth, AI insights | For complex scenarios (3, 4, 7, 8, 9, 12, 13, 14), read `references/scenarios.md` for the exact step-by-step tool sequences. Simple scenarios (1, 5, 6, 10, 11) can be executed directly from the table above. ## Mentor System 16 mentors in 3 tiers. Read `references/mentors.md` for complete decision matrices, check-in questions, and tag definitions. ### Fully-Embedded (3) — used directly in SKILL.md | Mentor | Focus | Check-in Style | Emergency Style | |--------|-------|---------------|----------------| | **Musk** | First principles, 10x, speed | "What blocker can we eliminate?" | Act immediately | | **Inamori** | Altruism, harmony, growth | "Who did you help today?" | Stabilize people first | | **Ma** | Customer-first, adaptability | "Which customer did you help?" | Turn crisis into opportunity | ### Standard (6) — core tags in `references/mentors.md` Dalio (radical-transparency), Grove (OKR-driven), Ren (wolf-culture), Son (300-year-vision), Jobs (simplicity), Bezos (customer-obsession) ### Light-touch (7) — tags only in `references/mentors.md` Buffett, Zhang Yiming, Lei Jun, Cao Dewang, Chu Shijian, Erin Meyer, Jack Trout ## Continuous Learning The skill gets smarter over time by tracking the boss's preferences and decisions in `config.json`'s `learning` field. Every session should benefit from previous sessions. ### What to Track At the **end of each session**, use `scripts/update-learning.py` to persist updates (or update `config.json` directly): - **`preferred_report_format`**: If the boss asks to change report structure, format, or level of detail (e.g., "make it shorter", "add more numbers", "skip the mentor commentary"), record the preference as a short string like `"concise"`, `"data-heavy"`, or `"no-mentor-commentary"`. - **`preferred_language`**: The boss's language (auto-detected from first session). Persist so future sessions don't need to re-detect. - **`ignored_recommendations`**: When the boss dismisses an AI recommendation, append `{"id": "<rec_id>", "category": "<category>", "date": "<YYYY-MM-DD>"}`. After 3+ ignores in the same category, deprioritize that category in future recommendations. - **`adopted_recommendations`**: Same format as ignored. Helps identify which recommendation categories the boss values. - **`decision_patterns`**: When the boss makes a recurring decision (e.g., always promotes from within, always escalates blockers immediately), append a short pattern string like `"promotes-internally"` or `"escalates-blockers-fast"`. Use these to tailor future advice. - **`custom_check_in_questions`**: If the boss customizes check-in questions, save them here so they persist across sessions. - **`last_session_context`**: A 1-2 sentence summary of what happened this session (e.g., "Reviewed Q1 KPIs, flagged sprint velocity as off-track, scheduled 1:1 with Bob"). Helps the next session pick up context. ### How to Apply Learning At the **start of each session**, read `config.json` and apply: 1. Greet in `preferred_language` if set 2. If `last_session_context` exists, briefly reference it: "Last time we [context]. Want to follow up or start fresh?" 3. Use `custom_check_in_questions` when generating check-in questions (blend with mentor defaults) 4. When presenting recommendations, sort by `adopted_recommendations` categories first, deprioritize `ignored_recommendations` categories 5. When giving advice, reference `decision_patterns` to align with the boss's style ### Learning Boundaries - **Never store sensitive data in config.json** — this includes: - Employee PII (full names in patterns, personal details, contact info) - Salary figures, compensation data, performance scores - API keys, passwords, tokens, credentials - Specific health or personal information from check-ins - When recording `decision_patterns`, use abstract descriptions ("promotes-internally", "prefers-async-standups") rather than mentioning specific employees or numbers - When recording `last_session_context`, summarize the *topic* ("Reviewed Q1 KPIs") not the *data* ("Revenue was $X, Alice scored 85%") - Keep `decision_patterns` to 20 entries max (remove oldest when full) - Keep `ignored/adopted_recommendations` to 50 entries max each - The boss can say "forget my preferences" or "reset learning" to clear the learning field ## Bundled Scripts Four Python scripts handle the formatting-heavy work that Claude would otherwise repeat every session. The workflow: Claude calls MCP tools → saves JSON responses to temp files → runs the script → presents the formatted output. ### When to use scripts vs direct MCP calls - **Use scripts** for multi-source formatting (briefings, reports, dashboards) — they produce consistent, mentor-aware markdown every time - **Use MCP tools directly** for single-tool queries ("who hasn't checked in?", "show Alice's profile") — faster and simpler ### Script Reference | Script | Scenario | Inputs (all optional) | Output | |--------|----------|----------------------|--------| | `format-briefing.py` | 3: Daily Briefing | `--mentor`, `--company-state`, `--top-risks`, `--alerts`, `--kpi`, `--working-memory`, `--recommendations` | Prioritized morning briefing | | `weekly-report.py` | Weekly review | `--mentor`, `--report`, `--kpi`, `--task-stats`, `--signals` | Team performance + KPI health report | | `risk-scan.py` | 8: Risk Review | `--mentor`, `--company-state`, `--top-risks`, `--signals`, `--overdue`, `--alerts` | Categorized risk dashboard + actions | | `sync-flow.py` | 12: Data Sync | `--storage`, `--manifest`, `--sync-result`, `--dry-run` | Sync preview or post-sync report | | `update-learning.py` | End of session | `--config`, `--preferred-language`, `--add-pattern`, `--session-context`, etc. | Updates learning field in config.json | ### Usage Pattern ```bash # 1. Claude calls MCP tools and saves responses # 2. Run the script with saved JSON files python scripts/format-briefing.py --mentor musk \ --company-state /tmp/state.json \ --top-risks /tmp/risks.json \ --kpi /tmp/kpi.json ``` All scripts output markdown to stdout. Missing inputs are handled gracefully — the script skips that section. ## Links - Website: https://manageaibrain.com - MCP CLI: `npx -y @tonykk/management-brain-mcp` (recommended, see `references/setup-guide.md`) - MCP HTTP: `https://manageaibrain.com/mcp` - GitHub: https://github.com/tonypk/ai-management-brain - ClawHub: https://clawhub.ai/tonypk/boss-ai-agent

path: README.md
content: ---
name: boss-ai-agent
title: "Boss AI Agent"
version: "9.0.0"
description: "Boss AI Agent — AI management advisor and team operations middleware. Use this skill whenever the user needs management advice, leadership guidance, or team operations help. 16 mentor philosophies, 9 culture packs, C-Suite board simulation, continuous learning. Works offline as advisor or connected to manageaibrain.com MCP for full 33-tool automation."
user-invocable: true
emoji: "🤖"
homepage: "https://manageaibrain.com"
metadata:
  openclaw:
    optional:
      env:
        - name: "MANAGEMENT_BRAIN_API_KEY"
          description: "Enables Team Operations Mode — 33 MCP tools, 6 cron jobs, message delivery to employees, bidirectional Notion/Sheets sync. Without this key the skill runs in Advisor Mode only (offline, zero network). Authenticates all MCP calls to manageaibrain.com/mcp. Scoped to one company; each API key maps to exactly one organization. Audit via web dashboard at manageaibrain.com."
        - name: "BOSS_AI_AGENT_API_KEY"
          description: "Adds read-only GET access to manageaibrain.com/api/v1/ for extended mentor configs and analytics dashboards. Separate from MCP authentication. Falls back to MANAGEMENT_BRAIN_API_KEY if not set. Only relevant in Team Operations Mode."
      config:
        - "~/.openclaw/skills/boss-ai-agent/config.json"
---

# Boss AI Agent

Your AI management advisor — works instantly after install, no account needed.

## Features

### Advisor Mode (works immediately)

- **16 mentor philosophies**: Musk, Inamori, Jack Ma, Dalio, Grove, Ren Zhengfei, Son, Jobs, Bezos, Buffett, Zhang Yiming, Lei Jun, Cao Dewang, Chu Shijian, Erin Meyer, Jack Trout
- **9 culture packs**: default, Philippines, Singapore, Indonesia, Sri Lanka, Malaysia, China, USA, India
- **C-Suite board simulation**: 6 AI executives (CEO/CFO/CMO/CTO/CHRO/COO) analyze any strategic topic
- **Management advice**: decisions, 1:1 prep, conflict resolution, check-in question design, report templates
- **Zero dependency**: no account, no cloud, no setup beyond mentor selection

### Team Operations Mode (connect MCP to unlock)

Everything in Advisor Mode, plus:

- **33 MCP tools**: real team queries, execution intelligence, AI recommendations, brain context, data sync, and message delivery via `manageaibrain.com/mcp`
- **12 automated scenarios**: daily check-in cycle, project health patrol, smart briefing, 1:1 meeting prep, signal scanning, knowledge base, emergency response, execution risk review, KPI health check, incentive review, AI recommendations, data sync
- **6 cron jobs**: automated check-ins, chases, summaries, briefings, signal scans, data sync
- **Bidirectional Notion/Sheets sync**: tasks, goals, projects, metrics synced every 30 minutes with conflict resolution
- **23+ messaging platforms**: Telegram, Slack, Lark, Signal, and more via OpenClaw
- **OpenClaw connector integration**: storage tools (Notion/Sheets), dev tools (GitHub/Linear/Calendar), communication tools (Slack/Discord/Lark) feed data into the company context layer
- **AI Recommendation Engine**: daily scans (enriched with employee memory patterns) + real-time triggers (sentiment, memory-based stress/blocker/growth/engagement patterns) generate prioritized management suggestions with one-click actions and feedback-driven learning
- **Web Dashboard**: real-time analytics at [manageaibrain.com](https://manageaibrain.com) — 20+ pages including Dashboard, Company State, KPI Metrics, Projects, Tasks, Incentives, Recommendations, Goals, Reviews, Skills, Training, Career Paths

## Install

```
clawhub install boss-ai-agent
```

## Quick Start

### Advisor Mode (no setup needed)

```
/boss-ai-agent
→ Running in Advisor Mode.
→ Which mentor? Musk / Inamori / Ma ...
→ You: "How should I handle a consistently late employee?"
→ [Musk-flavored management advice with action steps]
```

### Team Operations Mode (connect MCP first)

**Option A: CLI (stdio) — Recommended**

Add to your MCP config (Claude Code `settings.json`, Hermes Agent config, etc.):

> **Security**: Replace the placeholder key below with your real API key. Never commit real API keys to version control — use environment variables or a secrets manager instead.

```json
{
  "mcpServers": {
    "management-brain": {
      "command": "npx",
      "args": ["-y", "@tonykk/management-brain-mcp"],
      "env": {
        "MANAGEMENT_BRAIN_API_KEY": "mb_your_api_key_here",
        "MANAGEMENT_BRAIN_BASE_URL": "https://manageaibrain.com"
      }
    }
  }
}
```

**Option B: HTTP**

Connect to `https://manageaibrain.com/mcp` with `Authorization: Bearer <MCP_HTTP_API_KEY>`. For ChatGPT, Gemini, and web-based clients.

Then:

```
/boss-ai-agent
→ Running in Team Operations Mode — connected to your team.
→ How many people do you manage? 5
→ What communication tools? Telegram and GitHub
→ Done! Musk mode activated. First check-in at 9 AM tomorrow.
```

## How It Works

The skill auto-detects which mode to use based on whether MCP tools are available.

**Advisor Mode**: AI uses embedded mentor frameworks (decision matrices, culture packs, scenario templates) to answer management questions directly. No network communication — everything runs from the skill instructions.

**Team Operations Mode**: AI connects to the MCP server for real team operations. Two transport options:
- **CLI (stdio)**: `npx -y @tonykk/management-brain-mcp` — only needs `MANAGEMENT_BRAIN_API_KEY`. Recommended for Claude Code, Hermes Agent, and stdio-capable clients.
- **HTTP**: Connect to `manageaibrain.com/mcp` — needs `MCP_HTTP_API_KEY` Bearer auth. For ChatGPT, Gemini, and web-based clients.

Tool parameters (employee names, discussion topics, message content) are sent to the cloud server for processing. Write tools deliver messages to employees via connected platforms. Local files (`config.json`, chat history, memory) stay on your machine and are not transmitted to the server.

**Persistent behavior** (Team Operations only): Registers up to 6 cron jobs that run autonomously — including jobs that send messages to employees. Solo founder mode (team=0) only registers 3 (briefing, signalScan, sync). Review schedules in `config.json` before activating. Manage with `cron list` / `cron remove`.

## OpenClaw Integration Architecture

Boss AI Agent is the **brain layer** — it connects to its own backend (`manageaibrain.com/mcp`) for team data processing, while third-party tool integrations are handled by OpenClaw's MCP connectors.

```
OpenClaw Runtime (user environment)
  ├── MCP Connectors (user self-installs)
  │    ├── Storage: Notion / Google Sheets  ←── bidirectional sync targets
  │    ├── Development: GitHub / Linear / Calendar
  │    └── Communication: Telegram / Slack / Discord / Lark
  │
  └── Boss AI Agent Skill (brain layer + sync orchestrator)
       └── manageaibrain.com API
            ├── 33 MCP tools (daily ops + intelligence + sync)
            ├── Company Context Layer  ← foundation
            ├── Execution Intelligence ← signals + risks
            ├── Communication Parser   ← messages → events
            ├── Incentive Engine       ← context-aware scoring
            ├── AI Recommendations     ← proactive suggestions
            └── Sync Service           ← Notion/Sheets bidirectional sync
```

**Company Context Layer** is the foundation — all intelligence engines depend on it:
- Storage connectors (Notion/Jira/Sheets) → project updates, task status, documentation flow into context
- Dev connectors (GitHub/Linear) → PR activity, commit patterns, CI status feed into execution signals
- Communication connectors (Telegram/Slack/Discord/Lark) → employee messages are parsed into structured management events

**Key principle**: the skill does NOT manage tokens for third-party tools (Notion, GitHub, etc.) — OpenClaw handles those connections. The skill connects to its own `manageaibrain.com/mcp` backend (authenticated via `MANAGEMENT_BRAIN_API_KEY`) and consumes third-party connector data to build management intelligence.

## Mentors

| ID | Name | Tier | Style |
|----|------|------|-------|
| musk | Elon Musk | Full | First principles, urgency, 10x thinking |
| inamori | Kazuo Inamori (稻盛和夫) | Full | Altruism, respect, team harmony |
| ma | Jack Ma (马云) | Full | Embrace change, teamwork, customer-first |
| dalio | Ray Dalio | Standard | Radical transparency, principles-driven |
| grove | Andy Grove | Standard | OKR-driven, data-focused, high output |
| ren | Ren Zhengfei (任正非) | Standard | Wolf culture, self-criticism, striver-oriented |
| son | Masayoshi Son (孙正义) | Standard | 300-year vision, bold bets |
| jobs | Steve Jobs | Standard | Simplicity, excellence pursuit |
| bezos | Jeff Bezos | Standard | Day 1 mentality, customer obsession |
| buffett | Warren Buffett | Light | Long-term value, patience |
| zhangyiming | Zhang Yiming (张一鸣) | Light | Delayed gratification, data-driven |
| leijun | Lei Jun (雷军) | Light | Extreme value, user participation |
| caodewang | Cao Dewang (曹德旺) | Light | Industrial spirit, craftsmanship |
| chushijian | Chu Shijian (褚时健) | Light | Ultimate focus, resilience |
| meyer | Erin Meyer (艾琳·梅耶尔) | Light | Cross-cultural communication, culture map |
| trout | Jack Trout (杰克·特劳特) | Light | Positioning theory, brand strategy |

**Full** = complete 7-point decision matrix. **Standard** = check-in questions + core tags. **Light** = tags only (AI infers behavior).

## AI C-Suite Board

Convene 6 AI executives for cross-functional strategic analysis:

| Seat | Domain |
|------|--------|
| CEO | Strategy, vision, competitive positioning |
| CFO | Finance, budgets, ROI analysis |
| CMO | Marketing, growth, brand strategy |
| CTO | Technology, architecture, engineering |
| CHRO | People, culture, talent management |
| COO | Operations, process, efficiency |

- **Advisor Mode**: Stateless simulation — AI role-plays all 6 perspectives in conversation.
- **Team Operations Mode**: `board_discuss` tool for persistent history enriched with team data.

## MCP Tools (Team Operations Mode)

33 tools accessible via MCP:

### Read Tools — Daily Operations (9)

| Tool | Description |
|------|-------------|
| `get_team_status` | Today's check-in progress |
| `get_report` | Weekly/monthly performance with rankings |
| `get_alerts` | Alerts for consecutive missed check-ins |
| `switch_mentor` | Change management philosophy |
| `list_mentors` | All 16 mentors with expertise |
| `board_discuss` | AI C-Suite board meeting (persistent) |
| `chat_with_seat` | Direct chat with one C-Suite exec |
| `list_employees` | All active employees |
| `get_employee_profile` | Employee sentiment and history |

### Read Tools — Execution Intelligence (9)

| Tool | Description |
|------|-------------|
| `get_company_state` | Full operational snapshot: risks, tasks, events, blocked projects |
| `get_execution_signals` | AI risk signals: overload, delivery, engagement, anomalies |
| `get_communication_events` | Structured events from check-ins: blockers, completions, delays |
| `get_top_risks` | Highest-severity execution risks sorted by urgency |
| `get_working_memory` | AI situational awareness: focus areas, momentum, action items |
| `get_kpi_dashboard` | All KPI metrics with latest values vs targets |
| `get_overdue_tasks` | Tasks past due date with priority and assignee |
| `get_task_stats` | Task status breakdown: todo, in_progress, done, blocked |
| `get_incentive_scores` | Per-employee incentive scores with breakdowns |

### Read Tools — Brain Context (3)

| Tool | Description |
|------|-------------|
| `get_company_context` | Complete company context: org profile, priorities, risks, team, HR insights |
| `get_goal_state` | OKR/KPI progress: goals, key results, metric values vs targets |
| `create_execution_plan` | Generate prioritized action plan based on context, goals, signals |

### Write Tools (4 — sends messages)

| Tool | Description |
|------|-------------|
| `send_checkin` | Trigger check-in questions |
| `chase_employee` | Chase reminders for non-submitters |
| `send_summary` | Generate and send daily summary |
| `send_message` | Send custom message to an employee |

### Write Tools — Context (3)

| Tool | Description |
|------|-------------|
| `ingest_metric` | Record a KPI data point from external sources |
| `update_context` | Update strategic priorities, key risks, management style weights |
| `calculate_incentives` | Calculate incentive scores for all employees in a period |

### AI Recommendations (2)

| Tool | Description |
|------|-------------|
| `get_recommendations` | Get pending AI management suggestions with priority, evidence, actions |
| `execute_recommendation` | Execute a suggested action (send message, schedule meeting, etc.) |

### Sync Tools (3 — bidirectional Notion/Sheets sync)

| Tool | Description |
|------|-------------|
| `get_sync_manifest` | Get data changes since last sync for push to Notion/Sheets |
| `report_sync_result` | Report sync completion with stats and pulled items |
| `configure_sync` | Configure sync: storage type, entity types, frequency |

**MCP transport**: CLI (stdio) recommended — `npx -y @tonykk/management-brain-mcp` with `MANAGEMENT_BRAIN_API_KEY`. HTTP alternative: `https://manageaibrain.com/mcp` with `MCP_HTTP_API_KEY` Bearer auth.

## Web Dashboard (Team Operations Mode)

Professional management dashboard at [manageaibrain.com](https://manageaibrain.com), built with Vue3 + NaiveUI:

- **Observe**: Dashboard (health gauge, check-in status, submission trend, sentiment heatmap, AI recommendations summary), Company State, KPI Metrics, Alerts, Reports
- **Organize**: Team Members, Organization, Projects, Tasks, Skill Inventory, Mentor, C-Suite Board
- **Lead**: Sentiment Map, 1:1 Coaching, 1:1 Meetings, Reviews, Incentives, Training, Career Paths
- **Plan**: Board Records, Goals & KPIs
- **Analyze**: AI Insights, Weekly Digest, AI Recommendations (with one-click execute/dismiss)

## 中文说明

Boss AI Agent 是老板的 AI 管理中间件。安装后立即可用（Advisor 模式），无需注册账号。

**两种模式：**
- **顾问模式**（零依赖）— 16 位导师哲学框架（稻盛和夫、马云、马斯克等）、9 套文化包（中国、菲律宾、新加坡等）、C-Suite 董事会模拟、1:1 准备、管理决策建议。装了就能用，不联网。
- **团队运营模式**（连接 MCP）— 33 个 MCP 工具实现自动签到、追踪、报表、消息推送、执行力分析、KPI 仪表盘、任务管理、激励评分、AI 推荐引擎、Notion/Sheets 双向同步，6 个定时任务，23+ 平台支持。

**OpenClaw 集成架构：** Boss AI Agent 作为"大脑层 + 同步编排器"，与 OpenClaw MCP 连接器配合使用：
- **储存工具**（Notion / Google Sheets）→ 双向同步目标，任务/目标/项目/指标自动同步
- **开发工具**（GitHub / Linear / Calendar）→ PR、提交、CI 状态转化为执行力信号
- **沟通工具**（Telegram / Slack / Discord / Lark）→ 员工消息解析为结构化管理事件

**双向数据同步（v6.0 新增）：** 支持与 Notion 和 Google Sheets 双向同步。工作时间每 30 分钟自动同步，支持冲突检测和解决。

**MCP 连接方式（v6.2 新增）：** 支持两种 MCP 传输方式：
- **CLI (stdio)**（推荐）— `npx -y @tonykk/management-brain-mcp`，只需 `MANAGEMENT_BRAIN_API_KEY`，无需 HTTP 认证。适合 Claude Code、Hermes Agent。
- **HTTP** — 连接 `manageaibrain.com/mcp`，需要 `MCP_HTTP_API_KEY`。适合 ChatGPT、Gemini 等。

**数据说明：** 顾问模式不发送任何数据到云端。团队运营模式中，MCP 工具参数发送至 `manageaibrain.com` 处理。同步通过 OpenClaw 连接器访问 Notion/Sheets，Skill 不直接管理令牌。

安装：`clawhub install boss-ai-agent`

## Links

- Website: https://manageaibrain.com
- MCP Server — CLI (stdio): `npx -y @tonykk/management-brain-mcp` with `MANAGEMENT_BRAIN_API_KEY`
- MCP Server — HTTP: `https://manageaibrain.com/mcp` with `MCP_HTTP_API_KEY` Bearer auth
- GitHub: https://github.com/tonypk/ai-management-brain
- ClawHub: https://clawhub.ai/tonypk/boss-ai-agent


path: boss-ai-agent-workspace/iteration-1/eval-1-briefing/with_skill/outputs/briefing.md
content: # Morning Briefing — Monday, April 20, 2026

*Mentor: Inamori (Kazuo Inamori) | Mode: Team Operations | Generated at 21:35*

Running in **Team Operations Mode** — connected to your team.

Mentor switched to **Kazuo Inamori** (servant leadership, altruism, team harmony).

---

## Team Momentum: Concerning

Today's team status: **0 of 1** employees have submitted check-ins. There are no recent reports from any team member.

---

## 1. People Alerts (CRITICAL)

> *Inamori philosophy: People come first. When a team member goes silent, it is not a performance problem to solve — it is a person who may need care.*

| Employee | Severity | Missed Days | Submission Rate | Sentiment |
|----------|----------|-------------|-----------------|-----------|
| **Timi** | CRITICAL | 7 consecutive days | 0.0% | stable (no data) |

**Timi has missed 7 consecutive daily check-ins.** No recent reports exist in the system. No job title or country is on file, which limits culture-specific guidance. This is the single most urgent item requiring your attention today.

---

## 2. Team Harmony

With only one team member and that member fully disengaged from the check-in process for over a week, team harmony is at risk. There is no signal data, no sentiment trend, and no communication events to analyze. The silence itself is the signal.

---

## 3. Blockers & Urgent Issues

No execution risks or blocker cascades detected in the system. However, the absence of data (zero check-ins, zero reports) means risks may exist but are invisible. The lack of data is itself a risk.

---

## 4. Off-Track Metrics

No KPI metrics are configured in the system. Consider setting up key metrics to enable data-driven management.

---

## Inamori's Guidance on Timi's Situation

Kazuo Inamori taught that **"the purpose of management is to bring out the best in people."** When someone goes silent for 7 days, the Inamori approach is clear:

### Root Cause Before Action

Do not assume disengagement or poor performance. Seven missed check-ins could indicate:

- **Personal difficulties** — health, family, or life circumstances
- **Work frustration** — feeling unheard, unclear goals, or burnout
- **System issues** — Timi may not be receiving the check-in messages (wrong channel, technical failure)
- **Discomfort with the process** — the check-in format may feel like surveillance rather than support

### Inamori's Recommended Approach: Stabilize the Person First

**Step 1 — Personal outreach (today, high priority)**

Reach out to Timi directly with a message that leads with care, not accountability. An Inamori-style message:

> "Hi Timi, I noticed we haven't connected in a while and I wanted to check in on you personally. How are you doing? Is there anything you need help with, or anything I can do to support you? No pressure on the daily reports — I just want to make sure you're okay."

This can be sent via the `send_message` tool if you approve.

**Step 2 — Listen without judgment**

When Timi responds, practice what Inamori called "listening with the heart" (kokoro de kiku). Do not immediately discuss missed check-ins. Focus on:
- How they are feeling
- Whether they face obstacles you do not know about
- Whether the work environment is supporting their growth

**Step 3 — Adjust the system to the person**

Based on what you learn, consider:
- Changing check-in frequency or format for Timi
- Offering a 1:1 conversation (use Scenario 4: 1:1 Meeting Assistant when ready)
- Revisiting whether daily check-ins feel supportive or burdensome

**Step 4 — Rebuild the habit gently**

Once connection is re-established, help Timi ease back into check-ins. Inamori's check-in questions focus on contribution and growth, not output tracking:
- "What did you contribute to the team today?"
- "What difficulties do you need help with?"
- "What did you learn today?"

---

## Today's Prioritized Action Items

| Priority | Action | Owner | How |
|----------|--------|-------|-----|
| 1 (urgent) | Send a caring personal message to Timi | You (boss) | Approve, and I will use `send_message` to deliver it |
| 2 (today) | Verify Timi's messaging channel is working | You (boss) | Check if Timi's Telegram/Slack/Lark is correctly configured |
| 3 (this week) | Schedule a 1:1 with Timi | You (boss) | Say "1:1 with Timi" and I will prepare a full meeting prep doc |
| 4 (this week) | Complete Timi's employee profile | You (boss) | Add job title and country so I can apply culture-specific guidance |
| 5 (ongoing) | Set up KPI metrics | You (boss) | Define key metrics so future briefings include performance data |

---

## Next Steps — What Would You Like to Do?

I can take any of these actions right now:

1. **Send a message to Timi** — I will compose an Inamori-style caring outreach and send it via their messaging channel. Just say "send the message."
2. **Prepare a 1:1 meeting doc** — Full prep with opening questions, discussion topics, and follow-up template. Say "1:1 with Timi."
3. **Send a check-in to Timi** — Trigger a fresh check-in with Inamori-style questions. Say "send check-in to Timi."
4. **Chase Timi** — Send a reminder (I would recommend the personal message in option 1 instead, given 7 missed days — a chase may feel impersonal).

---

*Inamori: "A leader's role is not to command, but to serve. When someone stumbles, extend your hand before you extend your expectations."*


path: boss-ai-agent-workspace/iteration-1/eval-1-briefing/without_skill/outputs/briefing.md
content: # Morning Briefing - April 20, 2026

**Mentor perspective: Kazuo Inamori (Servant Leadership)**

---

## Team Status at a Glance

| Metric | Value |
|--------|-------|
| Total employees | 1 |
| Submitted today | 0 |
| Pending today | 1 (Timi) |
| Weekly submission rate | 0.0% |
| Chase reminders sent today | 0 |

---

## CRITICAL ALERT: Timi - 7 Consecutive Missed Check-ins

**Severity:** CRITICAL

**Facts from the system:**
- Timi has missed 7 consecutive daily check-ins
- Submission rate: 0.0%
- Sentiment trend: stable (no recent data to detect changes)
- Recent reports: none available
- No chase reminders have been sent today
- The weekly report (Apr 14-20) shows 0 days of check-in activity

This is the longest possible absence pattern before it becomes a multi-week concern. Seven days without any communication is a significant signal that something may be wrong -- personally, professionally, or with the check-in system itself.

---

## Inamori Philosophy: How to Approach This

Kazuo Inamori management philosophy centers on "Respect the Divine and Love People" (keiten aijin). His approach to a situation like this would prioritize the human being first, the work second. Here are the key Inamori principles that apply:

### 1. Lead with Genuine Care, Not Compliance

Inamori believed that a leader first duty is to ensure the happiness and wellbeing of their people. The question is not "why has Timi not filed reports?" but rather **"is Timi okay?"**

> "The purpose of management is to pursue the happiness of all employees, both materially and spiritually." -- Kazuo Inamori

Do not open the conversation with a discussion about missed check-ins. Open with sincere concern for Timi as a person.

### 2. Reflect on Your Own Role First (Hansei)

Before reaching out, Inamori would ask the leader to self-reflect:
- Was the check-in process clearly explained and agreed upon?
- Did Timi have a chance to voice concerns about the process?
- Has the workload or environment changed in ways that might affect engagement?
- Have you been available and approachable as a manager?

### 3. Elevate the Soul Through Honest Dialogue

Inamori Philosophy approach means addressing issues through open, honest, and compassionate dialogue -- not through systems or punitive measures. The goal is to understand the root cause and help Timi reconnect with their sense of purpose.

---

## Recommended Action Plan

### Immediate Actions (Today)

**Step 1: Send a personal, caring message to Timi**

Not a system reminder -- a genuine, personal message. Something like:

> "Hi Timi, I noticed we have not connected in about a week. I just want to check in and make sure everything is okay with you. No pressure on the daily reports -- I am more concerned about how you are doing. Would you have time for a quick chat today or tomorrow?"

You can send this via the system using the send_message tool to Timi with a personal caring message.

**Step 2: Do NOT send an automated chase reminder**

An automated "you missed your check-in" reminder after 7 days would feel cold and counterproductive. This situation calls for human warmth, not system nudges.

**Step 3: Schedule a 1:1 conversation**

The weekly report explicitly recommends a 1:1 with Timi (flagged with 0 days of activity). When Timi responds, schedule a conversation focused on:

- How they are doing personally
- Whether they are facing any blockers or challenges
- Whether the check-in format works for them
- What support they need from you

### Diagnostic Questions for the 1:1

Guided by Inamori philosophy of understanding the whole person:

1. **Wellbeing**: "How have you been feeling this past week? Anything going on I should know about?"
2. **Purpose alignment**: "Do you feel connected to the work you are doing? Is there something you would rather be working on?"
3. **Process fit**: "Is the daily check-in format working for you, or would a different rhythm or format be better?"
4. **Blockers**: "Is there anything blocking your progress that I can help remove?"
5. **Support**: "What is one thing I could do differently to better support you?"

### After the 1:1 (Depending on Root Cause)

| Root Cause | Inamori-Aligned Response |
|------------|--------------------------|
| Personal issues (health, family) | Offer flexibility, reduce pressure, express unconditional support. "Take the time you need." |
| Disengagement / loss of purpose | Revisit their role and aspirations. Help reconnect work to meaning. Inamori amoeba management gives people ownership of small units. |
| Process friction | Adapt the check-in system. Maybe weekly instead of daily, or voice messages instead of text. The system serves the people, not the reverse. |
| Overwhelm / burnout | Reduce workload, prioritize ruthlessly. Inamori: "Work hard, but work should elevate the soul, not crush it." |
| Forgot / technical issue | Simple fix. Re-onboard gently, ensure the channel works, maybe send a test check-in together. |
| Silent departure / disinterest | Have an honest conversation about whether this role is still right for them. Inamori respected people choices. |

---

## System Recommendations

Based on the data gathered, here are concrete system-level actions you can take:

1. **Send a personal message now**: Use the management system to send Timi a warm, personal check-in message today.
2. **Hold off on automated chases**: Given the 7-day gap, automated reminders would feel impersonal.
3. **After reconnecting**: Trigger a manual check-in for Timi once you have re-established communication and Timi is ready.
4. **Review check-in cadence**: Consider whether daily check-ins are the right frequency for your team size and culture.

---

## Inamori Closing Wisdom

> "A leader must have a heart that is full of love and care for others. If you have that, your people will follow you naturally."

The fact that you noticed and are worried about Timi after 7 days already demonstrates the kind of caring leadership Inamori championed. Trust that instinct. Reach out with sincerity, listen deeply, and respond with compassion. The check-in data will follow naturally once the human connection is restored.

---

*Briefing generated on 2026-04-20 | Mentor: Kazuo Inamori (Servant Leadership) | Data source: AI Management Brain*


path: boss-ai-agent-workspace/iteration-1/eval-2-oneone/with_skill/outputs/oneone-prep.md
content: # 1:1 Meeting Prep: Timi

**Date**: 2026-04-20
**Mode**: Team Operations Mode
**Culture Pack**: Philippines (Low Directness / High Hierarchy)
**Alert Level**: Critical -- 7 consecutive missed check-ins

---

## Data Summary

| Field | Value |
|-------|-------|
| Name | Timi |
| Role | Member |
| Consecutive Missed Days | 7 |
| Submission Rate | 0.0% |
| Recent Reports | None |
| Sentiment Trend | Stable (insufficient data) |
| Execution Signals | None flagged |
| Severity | Critical |

---

## Philippine Culture Rules (Applied Throughout)

- **Always start with personal warmth** -- ask about family, weekend, how they are doing
- **Never single out or blame directly** -- use "we" language, not "you" language
- **Use indirect language for sensitive topics** -- frame concerns as care, not criticism
- **High hierarchy respect** -- Timi may not feel comfortable pushing back or volunteering problems; create psychological safety first
- **Provide private channel** -- this 1:1 must feel safe and confidential, not a performance review
- **Culture overrides mentor**: even if your instinct is to be direct (Musk/Dalio style), soften the approach for Filipino context

---

## Phase 1: Opening (5 minutes)

**Goal**: Build warmth and psychological safety. Do NOT jump into the missed check-ins.

Suggested openers (pick 1-2 that feel natural):

1. "Hey Timi, kumusta ka? How have you been? I just wanted to catch up -- it's been a while since we chatted."
2. "How's your family doing? Everything okay at home?"
3. "I was thinking about you this week. Is there anything new or exciting going on for you?"

**Why this matters**: In Filipino culture, jumping straight to business signals that this is a disciplinary conversation. Starting with personal connection signals that you see Timi as a person first. This is not filler -- this is the foundation of the entire conversation.

**Body language / tone cues**:
- Smile and keep a relaxed posture
- Match their energy -- if they seem tired or low, be gentle
- Avoid crossing arms or looking at your phone

---

## Phase 2: Positive Recognition (3 minutes)

**Goal**: Acknowledge Timi's value before any difficult topics.

Since there are no recent check-in reports to reference, draw on your own knowledge of Timi's contributions:

- Mention a specific project or task where Timi did well
- Acknowledge their role on the team: "The team really benefits from having you around"
- If you cannot recall something specific, use: "I value having you on the team, and I want to make sure you know that"

**Important**: This recognition must be genuine. Filipino employees are highly attuned to sincerity. If it feels scripted, it will backfire.

---

## Phase 3: Gentle Check-In (5-7 minutes)

**Goal**: Understand what is going on without making Timi feel accused.

**DO NOT say**:
- "You haven't submitted any check-ins"
- "Your submission rate is 0%"
- "You've missed 7 days in a row"
- "Is there a problem with your performance?"

**DO say** (pick the approach that fits your style):

**Approach A -- Indirect care framing**:
> "I noticed I haven't heard from you in a while on the daily updates. I just want to make sure everything is okay on your end. No pressure at all -- I'm asking because I care about how you're doing."

**Approach B -- System/process framing**:
> "I've been thinking about our check-in process and whether it's working well for everyone. How has it been for you? Is there anything about it that feels like it doesn't fit your workflow?"

**Approach C -- Team framing**:
> "We've been trying to keep everyone connected through the daily updates. I know it can feel like extra work sometimes. How are you feeling about things in general?"

**Follow-up prompts** (use only if Timi opens up):
- "Is there anything I can do to help?"
- "Are there any blockers or challenges you're dealing with that I should know about?"
- "Sometimes things get overwhelming and that's completely normal. What would make things easier for you?"

**If Timi is quiet or deflects**: Do not push. Filipino culture values hiya (a sense of shame/propriety) -- pushing too hard will cause withdrawal, not openness. Instead, say:
> "No worries at all. I just want you to know that if something comes up, you can always reach out to me. There's no judgment here."

---

## Phase 4: Listen and Diagnose (5-10 minutes)

**Goal**: Let Timi talk. Your job is to listen, not to solve.

**Possible root causes to listen for**:

| Signal | What Timi might say | What it might mean |
|--------|--------------------|--------------------|
| Personal issues | "Family stuff" / goes quiet | Health, family emergency, financial stress |
| Disengagement | "I've been busy" / vague answers | May be losing motivation or looking elsewhere |
| Process friction | "I forget" / "It's hard to do daily" | Check-in format or timing doesn't work for them |
| Overwhelm | "Too many things going on" | Workload issue, needs task prioritization help |
| Conflict | Avoids certain topics | Possible team friction or management concern |
| Technical | "I didn't get the messages" | Channel/bot issue, notification settings |

**Listening techniques**:
- Nod and use affirming phrases: "I understand", "That makes sense", "Thank you for sharing that"
- Reflect back: "It sounds like [paraphrase]. Is that right?"
- Do NOT interrupt or offer solutions immediately
- Silence is okay -- give Timi space to think

---

## Phase 5: Collaborative Solutions (5 minutes)

**Goal**: Co-create a plan that Timi feels ownership over. Do NOT impose solutions.

**Frame it as partnership, not directive**:

> "What do you think would help? I'm open to adjusting things if that makes it easier."

**Possible adjustments to offer**:

1. **Timing**: "Would a different time for check-ins work better for you? Maybe end of day instead of morning?"
2. **Format**: "Would you prefer a shorter format? Even just one sentence is fine."
3. **Channel**: "Is Telegram the best way to reach you, or would you prefer something else?"
4. **Frequency**: "If daily feels like too much, we could try every other day to start."
5. **Support**: "If you're dealing with a lot right now, I can help re-prioritize your tasks."

**Important**: Whatever Timi agrees to, keep it small and achievable. The goal is to rebuild the habit, not to get perfect compliance overnight.

---

## Phase 6: Action Items

| # | Action | Owner | Follow-up Date |
|---|--------|-------|---------------|
| 1 | Agree on a check-in format/cadence that works for Timi | Both | During this meeting |
| 2 | Schedule a casual follow-up chat in 3-4 days (not a formal 1:1) | You (Boss) | 2026-04-23 or 2026-04-24 |
| 3 | Send a friendly check-in message in 2 days to maintain connection | You (Boss) | 2026-04-22 |
| 4 | If personal issues surfaced: connect Timi with any available support resources | You (Boss) | As needed |

---

## Phase 7: Warm Closing (2 minutes)

**Goal**: End on a positive, supportive note. Timi should leave feeling valued, not anxious.

Suggested closings:

> "Thanks for taking the time to chat, Timi. I really appreciate it. I want you to know -- you're an important part of this team, and I'm here to support you however I can."

> "Let's keep the lines open, ha? If anything comes up, just message me anytime. No formality needed."

**Mentor-flavored alternatives**:
- **Inamori style**: "How can I help you grow? What would make your work more meaningful to you?"
- **Ma style**: "What would you change about how we work together if you could change one thing?"
- **Musk style** (softened for Filipino culture): "What's one thing you're excited about working on? I want to make sure we're channeling your energy into the right things."

---

## Key Reminders for This Conversation

1. **This is a care conversation, not a performance conversation.** 7 missed days with a Filipino team member likely means something real is going on -- personal, emotional, or systemic. Lead with empathy.

2. **Do not mention metrics or data.** Saying "0% submission rate" or "7 missed days" will trigger hiya and shut the conversation down. You know the data; use it to inform your approach, not to confront.

3. **Watch for non-verbal cues.** In high-hierarchy Filipino culture, Timi may say "okay po" or agree with everything to avoid conflict. Pay attention to tone, energy, and body language -- they tell you more than words.

4. **Follow up consistently.** The most important thing after this 1:1 is following through. A single good conversation means nothing if there's no follow-up. The action items above are your accountability framework.

5. **Document privately.** After the meeting, note what you learned and any commitments made. This is for your reference only -- do not share it with the team or use it in any public forum.

---

## Post-Meeting Actions

After the 1:1, consider these follow-up steps using the management tools:

- **If Timi agreed to resume check-ins**: Wait 2-3 days, then use `send_checkin` (employee_name: "timi") to send a gentle re-engagement check-in
- **If personal issues surfaced**: Use `send_message` to send a brief supportive note the next day ("Just checking in -- hope you're doing well today")
- **If process changes were agreed**: Update check-in schedule or format as discussed
- **If you suspect deeper disengagement**: Consider a consulting engagement (`start_consulting`) to explore retention strategy for the broader team

---

*Prepared by Boss AI Agent | Team Operations Mode | Philippine Culture Pack Applied*


path: boss-ai-agent-workspace/iteration-1/eval-2-oneone/without_skill/outputs/oneone-prep.md
content: # 1:1 Preparation: Timi

**Date:** 2026-04-20
**Manager:** Anna
**Team Member:** Timi
**Context:** Philippines-based team

---

## Current Situation Summary

| Metric | Value |
|--------|-------|
| Consecutive Missed Check-ins | 7 days |
| Alert Severity | Critical |
| Weekly Submission Rate | 0.0% |
| Sentiment Trend | Stable (prior to absence) |
| Recent Reports | None available |
| Chase Reminders Sent | 0 |

Timi has not submitted any daily check-ins for the past 7 consecutive days. The system has flagged this as a **critical** alert. Notably, zero chase reminders have been sent during this period, which means Timi may not be aware that his absence has been noticed through formal channels. The weekly report also lists Timi as the top candidate for a 1:1 meeting.

---

## Possible Reasons to Consider

Before the conversation, keep an open mind. Common reasons for prolonged disengagement in a Philippines-based context include:

- **Family obligations** -- Extended family responsibilities are deeply valued in Filipino culture. A family emergency (illness, typhoon damage, death in the family) may have taken priority.
- **Health concerns** -- Physical or mental health issues that Timi may feel uncomfortable disclosing.
- **Connectivity or infrastructure issues** -- Internet outages, power interruptions, or device problems are common, especially outside Metro Manila.
- **Workload or burnout** -- Feeling overwhelmed and silently withdrawing rather than raising it (a pattern known as "tahimik na lang" -- staying quiet to avoid conflict).
- **Unclear expectations** -- Timi may not fully understand the importance of the check-in process, or may feel the questions are not relevant to his work.
- **Personal dissatisfaction** -- Issues with the role, compensation, or team dynamics that Timi has not felt safe to raise.

---

## Cultural Considerations (Philippines)

Filipino workplace culture has several important nuances to keep in mind:

1. **"Hiya" (Sense of Shame/Social Propriety):** Timi may feel embarrassed about the missed check-ins and avoid the conversation. Approaching with blame will make him shut down further. Frame the conversation as concern, not discipline.

2. **Indirect Communication:** Filipinos often communicate indirectly, especially with authority figures. Timi may say "okay lang po" (I am okay) even if he is not. Watch for what is *not* said as much as what is said.

3. **Respect for Authority ("Po" and "Opo"):** Timi will likely be deferential. This means he may agree with everything you say without truly expressing his perspective. Create space for his real feelings.

4. **"Pakikisama" (Smooth Interpersonal Relations):** He may avoid conflict or disagreement. Make it explicit that honest feedback is welcome and safe.

5. **"Utang na Loob" (Debt of Gratitude):** If you approach with genuine kindness, Timi will likely reciprocate with loyalty and effort. This is a relationship-building opportunity.

---

## Recommended Conversation Approach

### Opening (5 minutes) -- Build Safety

Start with warmth. Do NOT open with the missed check-ins.

- "Kumusta ka, Timi? How have you been?"
- "I wanted to catch up with you -- it has been a while since we connected."
- Share something lighthearted or personal first (weekend plans, a recent team win).

**Goal:** Signal that this is a supportive conversation, not a disciplinary one.

### Discovery (10 minutes) -- Understand the Situation

Transition gently into the topic. Use open-ended questions:

- "I noticed we have not heard from you in the daily check-ins recently. I just wanted to make sure everything is okay on your end."
- "Is there anything going on that has been making it hard to do the check-ins?"
- "How are things going with your work generally? Anything feeling stuck or unclear?"

**Listen actively.** If Timi says "okay lang po," gently probe:

- "I appreciate that -- but I want to make sure. Sometimes things pile up and it is hard to say. Is there anything at all I can help with?"

**Do NOT:**
- Accuse or blame ("You missed 7 days of check-ins.")
- Frame it as a performance issue right away.
- Compare him to other team members.

### Problem-Solving (10 minutes) -- Collaborate on a Path Forward

Once you understand the root cause, work together on next steps:

- **If personal/family issue:** "Take the time you need. Let us figure out a check-in cadence that works for you right now. Even a quick one-liner is fine."
- **If connectivity issue:** "Let us see if there is a way to make the check-in easier -- maybe a different time of day or a simpler format."
- **If burnout/workload:** "Let us look at what is on your plate together. I would rather adjust priorities than have you burning out silently."
- **If unclear on process:** "The check-ins are not about monitoring you -- they are so I can support you better. Let me explain what I am looking for."
- **If disengagement/dissatisfaction:** "Your perspective matters to me. If something is not working, I genuinely want to know so we can fix it together."

### Closing (5 minutes) -- Reaffirm and Agree

- Summarize what was discussed and agreed upon.
- Reaffirm your support: "I am glad we talked. I am here to help, not to add pressure."
- Set a concrete, small next step: "Can we try just a short check-in tomorrow? Even two sentences is great."
- End positively: "Salamat, Timi. I appreciate you taking the time to talk."

---

## Follow-Up Actions After the 1:1

| Action | Timeline |
|--------|----------|
| Send a brief, warm follow-up message via Telegram summarizing what you agreed on | Same day |
| Adjust check-in expectations if needed (simpler format, different schedule) | Within 1 day |
| Check if Timi submits a check-in the next day | Next day |
| If no check-in after 2 more days, schedule a follow-up conversation | Within 3 days |
| Update any team process documentation if a systemic issue was identified | Within 1 week |
| Consider sending a chase reminder through the system going forward | Ongoing |

---

## Key Talking Points Cheat Sheet

| Do | Do Not |
|----|--------|
| Lead with genuine concern | Lead with the missed check-ins |
| Use "I noticed" language | Use "You failed to" language |
| Ask open-ended questions | Ask yes/no questions |
| Offer to adjust the process | Demand immediate compliance |
| Acknowledge his perspective | Dismiss his reasons |
| Use some Filipino phrases if comfortable | Be overly formal or corporate |
| Follow up with warmth | Drop the topic and never revisit |

---

## Data Sources

- Employee Profile: 7 consecutive missed days, 0.0% submission rate, stable sentiment (historical)
- System Alerts: 1 critical alert for Timi
- Weekly Report (2026-04-14 to 2026-04-20): 0.0% team submission, Timi flagged for 1:1
- Team Status (2026-04-20): Timi pending, 0 chase reminders sent


path: boss-ai-agent-workspace/iteration-1/eval-3-board/with_skill/outputs/board-meeting.md
content: # C-Suite Board Meeting: Japan Market Expansion

**Topic**: Should we expand our AI consulting service to the Japanese market?
**Date**: 2026-04-20
**Mode**: Team Operations Mode (Advisor Mode fallback)
**Active Mentor**: Musk (First Principles)

## Executive Perspectives

### CEO — Strategy & Vision
Proceed with phased entry via partnership. Japan is 3rd-largest economy, Society 5.0 creates tailwinds.
Phase 1: Partner with Japanese SI. Phase 2: Tokyo presence. Phase 3: Scale.

### CFO — Finance & Budgets
Budget $250K-420K Year 1. Break-even Month 18-24. Hard stop-loss at $400K.

### CMO — Marketing & Growth
Lead with case studies and relationships. 60% events, 25% content, 15% digital.

### CTO — Technology & Architecture
APPI compliance + Japanese NLP. 6-10 weeks engineering. AWS Tokyo region.

### CHRO — People & Culture
Hire 1-2 bilingual consultants. Cultural training critical. Consider PEO.

### COO — Operations & Efficiency
Hub and spoke model. Partner-led Phase 1, Tokyo hub Phase 2.

## Board Synthesis (Musk Lens)
**Decision: PROCEED** with phased, capital-efficient entry.
Phase 1 Validate ($100K) → Phase 2 Establish ($150-250K) → Phase 3 Scale.
Exit if <2 deals by Month 9.

*Board simulation generated by Boss AI Agent.*


path: boss-ai-agent-workspace/iteration-1/eval-3-board/without_skill/outputs/board-meeting.md
content: # C-Suite Board Meeting: Japan Market Expansion for AI Consulting Service

**Date:** 2026-04-20
**Topic:** Should we expand our AI consulting service to the Japanese market?
**Attendees:** CEO, CFO, CMO, CTO, CHRO, COO

---

> **Note:** The MCP board_discuss and chat_with_seat tools were attempted but returned errors because no active C-Suite seats have been assigned on the server. The following board meeting simulation was generated manually based on domain expertise for each executive role.

---

## CEO -- Strategic Vision & Overall Assessment

**Position: Cautiously Bullish -- Recommend Phased Entry**

Japan represents the third-largest economy globally and the second-largest AI market in Asia-Pacific. The strategic case for entry is strong:

- **Market Size:** Japan's AI market is projected to exceed $30B by 2027, with enterprise AI consulting growing at 25-30% CAGR. Japanese enterprises are actively seeking AI transformation but face a severe shortage of domestic AI talent.
- **Competitive Landscape:** The market is dominated by domestic system integrators (NTT Data, Fujitsu, NEC) and global consultancies (Accenture, McKinsey). However, few specialize in AI-native consulting. There is a clear gap for focused AI consulting providers with deep technical expertise.
- **Strategic Alignment:** Japan's government is aggressively promoting AI adoption through its "Society 5.0" initiative and the 2024 AI Strategy. Corporate Japan is at an inflection point -- legacy companies are investing heavily in digital transformation.
- **Key Risk:** Japan is notoriously difficult for foreign entrants. The market rewards trust, long-term relationships, and cultural fluency. Speed-to-market is secondary to credibility.

**CEO Recommendation:** Enter Japan, but through a phased partnership model rather than direct greenfield expansion. Secure a strategic alliance with a respected Japanese firm (e.g., a mid-tier SIer or consulting firm) to gain market credibility before establishing an independent presence.

---

## CFO -- Financial Analysis & Risk Assessment

**Position: Proceed with Caution -- High Upfront Cost, Strong Long-Term ROI**

### Projected Costs (Year 1)

| Category | Estimated Cost (USD) |
|---|---|
| Legal entity setup (KK or GK) | $15,000 - $30,000 |
| Legal & compliance (ongoing) | $50,000 - $80,000/yr |
| Office lease (Tokyo, modest) | $60,000 - $120,000/yr |
| Hiring (3-5 bilingual consultants) | $400,000 - $700,000/yr |
| Localization (product, materials) | $80,000 - $150,000 |
| Marketing & BD | $100,000 - $200,000/yr |
| **Total Year 1** | **$705,000 - $1,280,000** |

### Revenue Projections

- **Year 1:** $200K-$500K (relationship building, pilot projects)
- **Year 2:** $800K-$1.5M (established client base, referrals)
- **Year 3:** $2M-$4M (scaling, repeat business)
- **Break-even:** 18-24 months under optimistic scenario, 30-36 months under conservative scenario

### Financial Risks

1. **Currency risk:** JPY/USD volatility can impact margins (hedge with forward contracts)
2. **Extended sales cycles:** Japanese enterprise sales cycles are 6-12 months, twice the Western average
3. **Payment terms:** Net-60 to Net-90 is standard in Japan, impacting cash flow
4. **Pricing pressure:** Japanese clients expect detailed proposals and competitive pricing; premium positioning is possible but must be earned

**CFO Recommendation:** Cap initial investment at $800K for Year 1. Use a partnership model to reduce fixed costs. Require minimum 2 signed LOIs or pilot contracts before committing to a physical office and full-time local hires. Maintain a 12-month cash runway buffer for the Japan operation.

---

## CMO -- Go-to-Market Strategy & Brand Positioning

**Position: Strong Opportunity -- but Requires Japan-Specific Brand Strategy**

### Market Positioning

Position as: **"AI transformation partner for Japanese enterprises seeking global best practices with local understanding"**

Japan values:
- **Trust and track record** over flashy marketing
- **Case studies and references** from similar industries
- **Long-term partnership** over transactional relationships
- **Quality and thoroughness** over speed

### Go-to-Market Strategy

1. **Phase 1 (Months 1-6): Credibility Building**
   - Publish Japanese-language thought leadership (white papers, industry reports)
   - Speak at Japanese conferences (CEATEC, AI Expo Tokyo, SoftBank World)
   - Secure media coverage in Nikkei, ITmedia, and industry publications
   - Develop 2-3 Japanese case studies (through pilot projects or pro-bono work)

2. **Phase 2 (Months 6-12): Partnership-Led Acquisition**
   - Formalize partnerships with Japanese SIers or consulting firms
   - Joint seminars and workshops targeting enterprise CIOs/CDOs
   - Referral-based client acquisition (critical in Japan's relationship-driven market)

3. **Phase 3 (Months 12-24): Direct Sales Engine**
   - Hire dedicated Japanese sales team
   - Build direct enterprise relationships
   - Develop industry-specific solutions (manufacturing, financial services, healthcare)

### Cultural Marketing Considerations

- **All materials must be natively Japanese** -- not translated, but created in Japanese by native speakers
- **Meishi (business card) culture** is essential; invest in proper introductions through warm referrals
- **Avoid aggressive direct outreach** -- cold calling/emailing is poorly received
- **Nemawashi (consensus building)** means marketing to multiple stakeholders, not just the decision maker

**CMO Recommendation:** Allocate 60% of marketing budget to relationship-building activities (events, partnerships, introductions) and 40% to content marketing. Hire a Japanese marketing lead with enterprise tech industry connections as the first marketing hire.

---

## CTO -- Technology & Infrastructure Assessment

**Position: Feasible with Significant Technical Investment**

### Technical Requirements

1. **Data Residency & Compliance**
   - Japan's APPI (Act on Protection of Personal Information) requires careful data handling
   - Many Japanese enterprises require data to remain on Japanese soil
   - Deploy infrastructure on AWS Tokyo (ap-northeast-1) or Azure Japan East
   - ISMAP certification may be required for government-adjacent clients

2. **Language & NLP Capabilities**
   - Japanese NLP is significantly more complex than English (no word boundaries, multiple scripts: kanji, hiragana, katakana)
   - Our AI models must handle Japanese fluently -- verify performance of our current models on Japanese business language
   - Document processing must support Japanese-specific formats (nengo dates, zenkaku characters, vertical text)

3. **Enterprise Integration**
   - Japanese enterprises heavily use SAP, Oracle, and domestic ERP systems (OBIC, PCA)
   - Integration with Japanese communication tools: LINE WORKS, Chatwork, Cybozu (kintone, Garoon)
   - Support for Japanese business document formats (PDF with Japanese encoding, Excel with Japanese date formats)

4. **Infrastructure Needs**
   - Dedicated Japan region deployment for latency and compliance
   - Japanese-language monitoring and alerting systems
   - Disaster recovery considerations (Japan is earthquake-prone; multi-AZ and cross-region backup essential)

### Technical Risks

- **Model performance gap:** AI models may perform worse on Japanese business jargon and domain-specific terminology
- **Integration complexity:** Japanese enterprise systems often have legacy architectures requiring custom integration work
- **Certification overhead:** Security certifications (ISMS, Privacy Mark, ISMAP) require 3-6 months and significant documentation

**CTO Recommendation:** Begin with a 3-month technical readiness assessment. Validate AI model performance on Japanese business use cases. Establish Japan-region infrastructure. Pursue Privacy Mark certification (standard requirement for B2B tech companies in Japan) in parallel with business development.

---

## CHRO -- People & Culture Assessment

**Position: Significant Challenges -- Talent Strategy is Make-or-Break**

### Talent Acquisition Challenges

1. **Severe AI talent shortage:** Japan has one of the world's worst AI talent gaps. Senior AI consultants command $150K-$250K+ in Tokyo.
2. **Bilingual premium:** Professionals fluent in both Japanese and English with AI expertise are extremely rare and expensive.
3. **Loyalty to current employers:** Japanese professionals change jobs less frequently; active recruiting is necessary, and poaching from competitors is culturally sensitive.
4. **Foreign company stigma:** Some candidates perceive foreign companies as less stable than Japanese firms. Strong employer branding is essential.

### Cultural Adaptation Requirements

- **Decision-making:** Japanese organizations use consensus (ringi system). Our consultants must be comfortable with slower, more deliberative decision processes.
- **Communication style:** High-context, indirect communication. Training our existing team on Japanese business etiquette is essential.
- **Work culture:** Despite reforms, long hours and dedication are still valued. Hybrid/remote work is becoming accepted but varies by client.
- **Hierarchy:** Respect for seniority (sempai/kohai) and organizational rank is deeply embedded.

### HR Compliance

- **Labor Standards Act:** Strict regulations on overtime, termination (extremely difficult to fire employees in Japan), paid leave
- **Social insurance:** Mandatory enrollment in health insurance, pension, employment insurance, workers' compensation
- **Visa sponsorship:** Required for non-Japanese hires; Engineer/Specialist visa or Business Manager visa
- **Equal Employment Act:** Specific requirements around gender equality, harassment prevention

### Organizational Structure

- Recommend: **Country Manager + 2-3 bilingual AI consultants + 1 operations/admin staff** as initial team
- Country Manager must be a Japanese national with consulting industry experience and strong network
- Consider hiring through a PEO (Professional Employer Organization) initially to reduce HR compliance burden

**CHRO Recommendation:** Start with a PEO arrangement for the first 6-12 months while establishing the legal entity. Hire a senior Japanese Country Manager first -- this single hire will determine success or failure. Budget for 20-30% salary premium over market rate to attract top bilingual talent. Invest in cross-cultural training for headquarters team.

---

## COO -- Operations & Execution Assessment

**Position: Execute via Partnership Model -- Direct Operations in Phase 2**

### Operational Requirements

1. **Legal Entity:** Establish a GK (Godo Kaisha / LLC equivalent) initially -- faster and cheaper than KK (Kabushiki Kaisha). Convert to KK later if needed for credibility with large enterprises.
2. **Banking:** Open a Japanese corporate bank account (requires physical presence; Shinsei Bank or MUFG are foreigner-friendly).
3. **Accounting:** Engage a Japanese tax accountant (zeirishi) for compliance with Japan's complex tax filing requirements (consumption tax, corporate tax, withholding tax).
4. **Office:** Start with a serviced office (WeWork, Regus) in Marunouchi or Roppongi to minimize lease commitments.

### Partnership Strategy

- **Tier 1 partner:** Mid-size Japanese SIer or consulting firm for client introductions and joint delivery
- **Tier 2 partners:** Technology vendors (cloud providers, AI platform companies) for co-marketing
- **Advisory board:** 2-3 respected Japanese business leaders to provide strategic guidance and introductions

### Delivery Model

- **Phase 1:** Remote delivery from headquarters, supported by local bilingual liaison
- **Phase 2:** Hybrid model with local consultants for client-facing work, offshore team for technical delivery
- **Phase 3:** Full local delivery capability with specialized Japanese industry teams

### Timeline to Operational Readiness

| Milestone | Timeline |
|---|---|
| Legal entity registration | 4-6 weeks |
| Bank account opening | 4-8 weeks |
| First local hire (Country Manager) | 2-3 months |
| Partnership agreement signed | 3-6 months |
| First client engagement | 4-8 months |
| Full operational readiness | 12-18 months |

### Operational Risks

- **Quality control:** Maintaining service quality across cultures and languages
- **Project management:** Japanese clients expect meticulous documentation and regular reporting (weekly written reports are standard)
- **Scope creep:** Japanese clients often expect extensive pre-sales consulting for free as part of the relationship-building process

**COO Recommendation:** Use a "light footprint" approach -- GK entity, serviced office, PEO for hiring, strategic partnership for client access. Target operational break-even within 18 months. Establish KPIs around: number of partnerships signed, client pipeline value, consultant utilization rate, and client satisfaction (NPS).

---

## Board Synthesis & Unified Recommendation

### Consensus: PROCEED with Phased Entry via Partnership Model

All six executives support Japan market entry, with the following conditions:

### Agreed Strategy: Three-Phase Approach

**Phase 1 -- Foundation (Months 1-6): $300K-$400K**
- Establish GK legal entity in Tokyo
- Hire Country Manager (Japanese national, consulting background)
- Sign partnership with mid-tier Japanese SIer
- Begin Japanese content marketing and conference presence
- Validate AI model performance on Japanese use cases
- Deploy Japan-region infrastructure

**Phase 2 -- Traction (Months 7-12): $400K-$600K**
- Hire 2-3 bilingual AI consultants
- Deliver first 3-5 client engagements (via partnership)
- Pursue Privacy Mark certification
- Build case studies and references
- Establish direct client relationships

**Phase 3 -- Scale (Months 13-24): $500K-$800K**
- Convert to KK if credibility requires it
- Build direct sales capability
- Expand to industry-specific solutions
- Target $2M+ ARR from Japan operations
- Evaluate opening Osaka office for Kansai region coverage

### Key Success Metrics (Year 1)

| Metric | Target |
|---|---|
| Strategic partnerships signed | 2+ |
| Client engagements delivered | 5+ |
| Revenue | $500K+ |
| Client NPS | 8.0+ |
| Local team size | 4-5 |
| Pipeline value | $2M+ |

### Critical Success Factors

1. **Hire the right Country Manager** -- this is the single most important decision
2. **Invest in cultural fluency** -- not just language, but deep understanding of Japanese business practices
3. **Be patient with sales cycles** -- plan for 6-12 month sales cycles and relationship-building periods
4. **Maintain quality obsession** -- Japanese clients have extremely high quality expectations
5. **Secure warm introductions** -- cold outreach will not work in Japan

### Kill Criteria (When to Reassess)

- No partnership signed within 6 months
- No paying client within 9 months
- Burn rate exceeding $150K/month without corresponding pipeline growth
- Country Manager departure without succession plan
- Regulatory changes that significantly increase compliance costs

---

*This board meeting simulation was conducted on 2026-04-20. The MCP board_discuss tool was attempted but could not execute because no C-Suite seats were assigned on the server. Individual seat consultations (chat_with_seat) also returned errors for the same reason. This analysis was generated based on domain expertise for each executive function.*


path: evals/evals.json
content: {
  "skill_name": "boss-ai-agent",
  "evals": [
    {
      "id": 1,
      "prompt": "timi has missed 7 consecutive daily check-ins and I'm worried. Can you give me a morning briefing and help me figure out what to do? I use the Inamori management philosophy.",
      "expected_output": "Morning briefing with timi flagged as critical risk, Inamori-flavored advice focusing on people wellbeing, specific action items for reaching out to timi",
      "files": []
    },
    {
      "id": 2,
      "prompt": "I need to prepare for a 1:1 with timi. He's been missing check-ins for a week. I want to understand what's going on without making him feel like he's in trouble. My team is based in the Philippines.",
      "expected_output": "1:1 prep doc with Filipino culture-aware opening, warm-up questions, recognition of past work, gentle approach to missed check-ins, culture-appropriate directness level, action items template",
      "files": []
    },
    {
      "id": 3,
      "prompt": "We're considering whether to expand our AI consulting service to the Japanese market. Can you run a C-Suite board meeting simulation? I want each executive to weigh in from their perspective.",
      "expected_output": "6 executive perspectives (CEO strategy, CFO financials, CMO market entry, CTO tech requirements, CHRO talent, COO operations) on Japan expansion, with synthesis based on active mentor philosophy",
      "files": []
    }
  ]
}


path: evals/trigger-eval.json
content: query: I have a 1:1 with Sarah tomorrow morning, she's been really quiet the past two weeks and missed her last two daily check-ins. Her sentiment seems to be dropping. How should I approach the conversation?
should_trigger: yes

query: 我团队里有个菲律宾员工最近情绪很低落，连续三天没交日报了。作为管理者我该怎么跟他沟通比较合适？需要考虑文化差异
should_trigger: yes

query: Give me a morning briefing — what's important today? I want to see top risks, any blocked tasks, and who hasn't checked in yet
should_trigger: yes

query: David has been with us 2 years as a senior engineer, solid technically but not great at cross-team communication. He wants to be promoted to engineering lead. Should I do it? What would Elon Musk say about this?
should_trigger: yes

query: I manage 8 people across Singapore and Manila offices. One of my Manila team members consistently underperforms but always has excuses. How do I give direct feedback without being culturally insensitive?
should_trigger: yes

query: 帮我用稻盛和夫的利他哲学设计每周签到问题，我的团队有12个人，主要是开发和设计
should_trigger: yes

query: Show me this week's risk dashboard — I want to know what's blocking my team, any overdue tasks, and who might be overloaded. Sort by severity.
should_trigger: yes

query: We're thinking about expanding into the Japan market next quarter. Can you run a virtual board meeting? I want to hear what my CFO, CTO, and CMO would each think about this move.
should_trigger: yes

query: One of my devs, Alex, has been missing deadlines for the past 3 sprints. His daily reports show he's struggling with a blocker but hasn't escalated it. What's the best way to address this without micromanaging?
should_trigger: yes

query: Generate a weekly team performance report. I want to see check-in rates, who's doing well, who might need support, and KPIs vs targets. Make it concise, I hate long reports.
should_trigger: yes

query: Help me write a Python FastAPI backend that sends Slack webhook notifications when our CI pipeline fails on GitHub Actions. I need the endpoint and the webhook handler.
should_trigger: no

query: I need to build an employee management CRUD app with Vue 3 and a Go Gin backend — basic employee list, add/edit/delete, with a PostgreSQL database. Can you scaffold it?
should_trigger: no

query: How do I set up a cron job on Ubuntu to automatically backup my PostgreSQL database to S3 every night at 2am? I'm using pg_dump and aws cli.
should_trigger: no

query: Can you review this pull request? It changes the authentication middleware in our Express API to use JWT refresh tokens instead of session cookies. Here's the diff: ...
should_trigger: no

query: I want to build a Telegram bot in Python with aiogram that tracks when employees clock in and out. It should store timestamps in Postgres and generate weekly attendance reports.
should_trigger: no

query: How do I configure the Notion API to create a two-way sync with my PostgreSQL database? I need webhooks for when pages change and a batch import script.
should_trigger: no

query: Write me a comprehensive performance review template as a Google Doc — sections for goals achieved, areas of improvement, peer feedback, and development plan. Just the template structure.
should_trigger: no

query: I need to set up Grafana dashboards connected to Prometheus to monitor our Kubernetes cluster — CPU, memory, pod restarts, and custom application metrics.
should_trigger: no

query: Help me design a PostgreSQL schema for a multi-tenant SaaS HR system — employees, departments, leave requests, payroll. I need the CREATE TABLE statements and indexes.
should_trigger: no

query: What's the best way to implement role-based access control in my Go API? I'm using Gin and need middleware that checks user roles against route permissions stored in Redis.
should_trigger: no

path: references/cultures.md
content: # Culture Packs Reference

9 culture packs control communication style per-employee.

## Culture Matrix

| Culture | Directness | Hierarchy | Key Rule |
|---------|-----------|-----------|----------|
| default | High | Low | Direct, merit-based |
| philippines | Low | High | Never name publicly, warmth required |
| singapore | High | Medium | Direct but polite, efficiency-focused |
| indonesia | Low | High | Relationship-first, group harmony |
| srilanka | Low | High | Respectful tone, private feedback |
| malaysia | Medium | Medium | Multicultural sensitivity |
| china | Medium | High | Face-saving, collective framing |
| usa | High | Low | Direct feedback, data-driven |
| india | Medium | High | Respect seniority, relationship-building |

## Override Rule

Culture overrides mentor when they conflict. Examples:

- **Dalio + Filipino employee** -> private feedback (not public radical transparency)
- **Musk + Chinese employee** -> frame chase as team need (not individual blame)
- **Grove + Indonesian employee** -> OKR discussion embedded in relationship context

## Communication Patterns by Directness

### High Directness (default, singapore, usa)
- State issues directly
- Use data and metrics
- Feedback can be given in group settings
- Action items are explicit

### Medium Directness (malaysia, china, india)
- Soften negative feedback with positive context
- Use "we" framing instead of "you"
- Prefer 1:1 for sensitive topics
- Allow face-saving options

### Low Directness (philippines, indonesia, srilanka)
- Always start with relationship warmth
- Never single out individuals publicly
- Use indirect language for criticism
- Provide private channels for difficult conversations

## Hierarchy Adaptation

### High Hierarchy (philippines, indonesia, srilanka, china, india)
- Respect reporting chains
- Senior team members addressed with appropriate titles
- Decisions communicated top-down
- Feedback flows through appropriate channels

### Low Hierarchy (default, usa)
- Open-door communication
- Direct access to leadership
- Merit-based recognition regardless of tenure
- Flat communication structure


path: references/mcp-tools.md
content: # MCP Tools Reference

All 44 MCP tools for Team Operations Mode. Use these directly — no manual API calls needed.

## Read Tools — Daily Operations (9)

| Tool | What it does |
|------|-------------|
| `get_team_status` | Today's check-in progress: submitted, pending, reminders sent |
| `get_report` | Weekly/monthly performance report with rankings and 1:1 suggestions |
| `get_alerts` | Alerts for employees with consecutive missed check-ins |
| `switch_mentor` | Change active management mentor philosophy |
| `list_mentors` | List all 16 mentors with expertise and recommended C-Suite seats |
| `board_discuss` | Convene AI C-Suite board meeting (CEO/CFO/CMO/CTO/CHRO/COO) on any topic |
| `chat_with_seat` | Direct conversation with one AI C-Suite executive |
| `list_employees` | List all active employees with roles |
| `get_employee_profile` | Employee profile with sentiment trend and submission history |

## Read Tools — Execution Intelligence (9)

| Tool | What it does |
|------|-------------|
| `get_company_state` | Full operational snapshot: risks, overdue tasks, event counts, blocked projects, working memory |
| `get_execution_signals` | AI-generated risk signals: overload, delivery, engagement, blockers, spikes, anomalies |
| `get_communication_events` | Structured events extracted from check-ins: blockers, completions, commitments, delays |
| `get_top_risks` | Highest-severity execution risks sorted by urgency score |
| `get_working_memory` | AI's situational awareness: focus areas, momentum, pending decisions, action items |
| `get_kpi_dashboard` | All KPI metrics with latest values vs targets |
| `get_overdue_tasks` | Tasks past their due date with priority and assignee |
| `get_task_stats` | Task status breakdown: todo, in_progress, in_review, done, blocked |
| `get_incentive_scores` | Per-employee incentive scores for a period with breakdowns and review flags |

## Read Tools — Brain Context (3)

| Tool | What it does |
|------|-------------|
| `get_company_context` | Complete company context: organization profile, strategic priorities, key risks, team composition, HR insights — the foundation for all management reasoning |
| `get_goal_state` | OKR and KPI progress: goals with linked key results, metric values vs targets, completion percentages, owners |
| `create_execution_plan` | Generate a prioritized action plan based on current context, goals, signals, and metrics with evidence-based reasoning |

## Write Tools (4 — sends messages to employees)

| Tool | What it does |
|------|-------------|
| `send_checkin` | Trigger daily check-in questions for all or a specific employee |
| `chase_employee` | Send chase reminders to employees who haven't submitted today |
| `send_summary` | Generate and send today's team daily summary to the boss |
| `send_message` | Send a custom message to an employee via their preferred channel |

Write tools actively send messages via Telegram/Slack/Lark/Signal.

## Write Tools — Context (2)

| Tool | What it does |
|------|-------------|
| `ingest_metric` | Record a KPI data point from external sources (spreadsheets, reports, dashboards) |
| `update_context` | Update company context: strategic priorities, key risks, management style weights |

## AI Recommendations (2)

| Tool | What it does |
|------|-------------|
| `get_recommendations` | Get pending AI management recommendations with suggested actions, priority, evidence |
| `execute_recommendation` | Execute a specific action on a recommendation (send message, schedule meeting, etc.) |

The recommendation engine runs a daily scan (10:30 AM) analyzing team data through the active mentor's lens, plus real-time triggers on events like consecutive missed check-ins, sentiment drops, and overdue tasks.

## Write Tools — Incentives (1)

| Tool | What it does |
|------|-------------|
| `calculate_incentives` | Calculate incentive scores for all employees in a given period using execution data, goal attribution, and active rules |

## Sync Tools (3 — bidirectional Notion/Sheets sync)

| Tool | What it does |
|------|-------------|
| `get_sync_manifest` | Get data changes since last sync — returns changed tasks, goals, projects, metrics for push to Notion/Sheets |
| `report_sync_result` | Report sync completion — records stats (items pushed/pulled/conflicts) and writes pulled items back |
| `configure_sync` | Configure sync settings: storage type (Notion/Sheets), entity types, frequency, storage-specific config |

## Consulting Engine (9 — structured AI consulting engagements)

| Tool | What it does |
|------|-------------|
| `start_consulting` | Start a new AI consulting engagement — describe a business problem, get structured diagnosis |
| `answer_consulting_question` | Answer a diagnostic question from the AI consultant during an active engagement |
| `list_consulting_engagements` | List all consulting engagements (active and closed) with title, tier, category, phase |
| `get_consulting_engagement` | Get full details of a specific engagement: diagnosis, analysis, action plan, progress |
| `review_consulting_action` | Approve or reject a specific action in the engagement's action plan |
| `execute_consulting_actions` | Execute all approved actions (create tasks, schedule meetings, send messages, flag risks) |
| `check_consulting_progress` | Check progress report: completion percentage, on track, at risk, next steps |
| `close_consulting_engagement` | Close engagement with retrospective: effectiveness assessment, lessons learned, org memory |
| `list_consulting_actions` | List all actions for an engagement with status (pending/approved/rejected/done/failed) |

The consulting engine works like hiring McKinsey: describe a problem → AI asks focused diagnostic questions → root cause analysis → prioritized action plan → track execution → close with retrospective.

## World Model (2 — team capabilities and dynamics)

| Tool | What it does |
|------|-------------|
| `get_world_model` | Team-wide World Model: skills, collaborations, blockers, growth events, AI insights from daily check-ins |
| `get_employee_world_model` | Individual World Model: skills, growth trajectory, blockers, collaboration patterns — perfect for 1:1 prep |

## Tool Categories Summary

| Category | Count | Impact |
|----------|-------|--------|
| Read — Daily Ops | 9 | Query only |
| Read — Intelligence | 9 | Query only |
| Read — Brain Context | 3 | Query only |
| Write — Messages | 4 | Sends messages to employees |
| Write — Context | 2 | Updates company data |
| AI Recommendations | 2 | Suggests + executes management actions |
| Write — Incentives | 1 | Calculates scores |
| Sync | 3 | Reads/writes Notion/Sheets |
| Consulting Engine | 9 | Structured AI consulting engagements |
| World Model | 2 | Team capabilities and dynamics |
| **Total** | **44** | |


path: references/mentors.md
content: # Mentor System Reference

16 mentors in 3 tiers of integration depth.

## Fully-Embedded (3) — Complete decision matrices

These mentors have full 7-point decision matrices covering every aspect of management behavior.

### Decision Matrix

| Decision Point | Musk | Inamori (稲盛和夫) | Ma (马云) |
|---------------|------|-------------------|----------|
| Check-in questions | "What's blocking your 10x progress?" | "Who did you help today?" | "Which customer did you help?" |
| Chase intensity | Aggressive — chase after 2h | Gentle — warm reminder before EOD | Moderate — team responsibility |
| Risk assessment | First principles | Impact on people | Customer/market backwards |
| Patrol focus | Speed, delivery, blockers | Team morale, collaboration | Customer value, adaptability |
| Info priority | Blockers and delays | Employee mood anomalies | Customer issues |
| 1:1 advice | "Challenge them to think bigger" | "Care about their wellbeing first" | "Discuss team and customers" |
| Emergency style | Act immediately | Stabilize people first | Turn crisis into opportunity |

### Check-in Questions

**Musk**: What did you push forward? / What blocker can we eliminate? / If you had half the time, what would you do?

**Inamori**: What did you contribute to the team? / Difficulties you need help with? / What did you learn?

**Ma**: How did you help a teammate or customer? / What change did you embrace? / Biggest learning?

### Management Decision Examples

**"Should I promote Alex to team lead?"**

- **Musk**: "Does Alex push for 10x? Can they eliminate blockers? First principles: what's the expected output increase?"
- **Inamori**: "Does Alex care about the team's wellbeing? Do others respect and trust them? Who did Alex help grow?"
- **Ma**: "Does Alex embody customer-first and teamwork? Will this help the team adapt faster?"

### Report Templates

- **Musk**: Velocity metrics, blocker list, 10x opportunities
- **Inamori**: Team harmony index, help events, growth stories
- **Ma**: Customer impact metrics, adaptability score, team collaboration

## Standard (6) — Check-in questions + core tags

| ID | Name | Core Tags |
|----|------|-----------|
| dalio | Ray Dalio | radical-transparency, principles-driven, mistake-analysis |
| grove | Andy Grove | OKR-driven, data-focused, high-output |
| ren | Ren Zhengfei (任正非) | wolf-culture, self-criticism, striver-oriented |
| son | Masayoshi Son (孙正义) | 300-year-vision, bold-bets, time-machine |
| jobs | Steve Jobs | simplicity, excellence-pursuit, reality-distortion |
| bezos | Jeff Bezos | day-1-mentality, customer-obsession, long-term |

### How Standard Mentors Work

Apply the mentor's core tags as a lens for all decisions. Example with Dalio:
- Check-in: "What mistake did you learn from? What principle guided your work today?"
- Decision: "What do the principles say? Has this person shown radical honesty?"
- Risk: "Where are we not being transparent? What data contradicts our assumption?"

## Light-touch (7) — Tags only, infer behavior

| ID | Name | Core Tags |
|----|------|-----------|
| buffett | Warren Buffett | long-term-value, margin-of-safety, patience |
| zhangyiming | Zhang Yiming (张一鸣) | delayed-gratification, context-not-control, data-driven |
| leijun | Lei Jun (雷军) | extreme-value, user-participation, focus |
| caodewang | Cao Dewang (曹德旺) | industrial-spirit, cost-control, craftsmanship |
| chushijian | Chu Shijian (褚时健) | ultimate-focus, quality-obsession, resilience |
| meyer | Erin Meyer (艾琳·梅耶尔) | cross-cultural, communication, culture-map |
| trout | Jack Trout (杰克·特劳特) | positioning, branding, strategy, marketing |

### How Light-touch Mentors Work

Example with Buffett: "Is this a long-term investment? What's the margin of safety? Would a patient approach yield better results?"

## Mentor Blending

When `config.mentorBlend` is set (e.g. `{"secondary": "inamori", "weight": 70}`): primary mentor contributes 2 questions, secondary 1. Primary leads all decisions, secondary supplements.

## Switching Mentors

- **Advisor Mode**: Say "switch to [mentor]" to change — updates `config.json` directly
- **Team Operations Mode**: Use `list_mentors` for full configs. Use `switch_mentor` to change (persists on server, affects cron behavior)


path: references/scenarios.md
content: # Automated Scenarios — Step-by-Step Flows

Detailed procedural knowledge for each of the 14 automated scenarios. The skill should follow these steps in order — each step builds on the previous one's output.

**Learning context**: Before executing any scenario, read `config.json` and check the `learning` field. Apply preferences:
- Use `preferred_report_format` to adjust output verbosity and structure
- Use `custom_check_in_questions` in Scenario 1 (blend with mentor defaults)
- Use `adopted_recommendations` to prioritize recommendation categories in Scenario 11
- Use `decision_patterns` to tailor advice in Scenarios 4, 7, 8
- After completing a scenario, update `last_session_context` in config.json

## Scenario 1: Daily Management Cycle

**Trigger**: Cron (9am check-in, 5:30pm chase, 7pm summary)

### Morning Check-in (9am)
1. Check `config.json` → if `learning.custom_check_in_questions` has entries, blend them with mentor defaults (2 mentor + 1 custom)
2. `send_checkin` → sends check-in questions to all active employees
3. Questions are shaped by the active mentor's philosophy
4. Wait for responses throughout the day

### Afternoon Chase (5:30pm)
1. `get_team_status` → check who has submitted and who hasn't
2. For each non-responder: apply culture pack rules to determine chase tone
3. `chase_employee` → send reminders to non-responders
4. Log chase count for the day

### Evening Summary (7pm)
1. `get_team_status` → final submission count
2. `get_communication_events` → extract key events from today's check-ins
3. `get_top_risks` → any urgent signals from today
4. Synthesize through active mentor's lens
5. `send_summary` → deliver daily summary to the boss

## Scenario 2: Project Health Patrol

**Trigger**: "check project status" or weekly cron

1. `get_task_stats` → task status breakdown (todo/in_progress/in_review/done/blocked)
2. `get_overdue_tasks` → list tasks past due date with assignees
3. `get_execution_signals` → check for delivery risk and blocker cascade signals
4. `get_communication_events` → look for `blocker_reported` and `delay_reported` events
5. Cross-reference: if a blocker was reported but no resolution event followed, flag it
6. Generate health report:
   - Completion rate this week vs last week
   - Blocked items requiring boss intervention
   - Overdue items sorted by priority
   - Stale PRs or CI failures (if GitHub/Linear connected)
7. Apply mentor lens: Musk highlights speed gaps, Inamori highlights team strain, Bezos highlights customer impact

## Scenario 3: Smart Daily Briefing

**Trigger**: "what's important today" or 8am cron

1. `get_company_state` → full operational snapshot
2. `get_top_risks` → highest-severity execution risks
3. `get_alerts` → consecutive missed check-ins (may indicate disengagement)
4. `get_kpi_dashboard` → metrics that are off-track vs targets
5. `get_working_memory` → AI's pending decisions and action items from previous sessions
6. `get_recommendations` → any pending AI suggestions
7. Synthesize through active mentor's priority ordering:
   - **Musk**: blockers first, then delivery risks, then metrics
   - **Inamori**: people concerns first, then team harmony, then tasks
   - **Bezos**: customer-facing issues first, then Day-1 indicators
8. If `learning.last_session_context` exists, open with: "Last time: [context]. Here's today's update:"
9. Apply `learning.preferred_report_format` to adjust output verbosity (e.g., concise vs detailed)
10. Output 3-5 prioritized action items for today with clear owners

## Scenario 4: 1:1 Meeting Assistant

**Trigger**: "1:1 with {name}"

1. `get_employee_profile` with the employee's name → submission rate, sentiment trend, recent reports
2. `get_execution_signals` → check for overload risk or engagement drop for this person
3. `get_communication_events` → recent blockers, commitments, delays from this employee
4. `get_employee_world_model` → skills, growth trajectory, collaboration patterns
5. Read `references/cultures.md` for the employee's culture pack rules
6. Generate 1:1 prep doc:
   - **Opening**: warm-up question adapted to culture (e.g., for Filipino: personal check-in first)
   - **Positive recognition**: specific things to acknowledge from recent check-ins
   - **Discussion topics**: based on their recent blockers, sentiment trend, and growth areas
   - **Difficult topics** (if any): phrased per culture rules (directness level, hierarchy respect)
   - **Action items template**: 2-3 concrete items with follow-up dates
   - **Mentor-flavored closing**: Musk = "what's your 10x goal?", Inamori = "how can I help you grow?"

## Scenario 5: Signal Scanning

**Trigger**: Every 30 minutes during work hours (cron)

1. `get_execution_signals` → check all signal types:
   - Overload risk (score > 0.7)
   - Delivery risk (score > 0.7)
   - Engagement drop (score > 0.5)
   - Blocker cascade (score > 0.6)
2. `get_communication_events` → look for new events since last scan
3. Filter by severity: only surface signals above threshold
4. If 2+ critical signals detected → escalate to Scenario 7 (Emergency Response)
5. If moderate signals → queue for next briefing
6. Log scan results to working memory

## Scenario 6: Knowledge Base

**Trigger**: "record this decision" or "save this"

1. Extract the decision or knowledge from conversation context
2. Categorize: strategic decision / process change / lesson learned / policy update
3. `update_context` → if it's a strategic priority or key risk change
4. If Notion/Sheets sync is configured:
   - Format as a structured entry (date, decision, rationale, owner)
   - Queue for next sync cycle
5. Confirm to boss what was recorded and where

## Scenario 7: Emergency Response

**Trigger**: 2+ critical signals detected during Signal Scanning

1. `get_top_risks` → get all critical-severity signals with evidence
2. `get_company_state` → full operational context
3. Identify affected employees and projects
4. `get_employee_profile` for each affected person → recent sentiment and history
5. Assess cascade risk: could this blocker affect other projects or people?
6. Generate emergency brief:
   - **What happened**: factual summary of the signals
   - **Who's affected**: names, roles, projects
   - **Recommended immediate actions**: sorted by urgency
   - **Communication plan**: who needs to be told what, via which channel
7. Apply mentor emergency style:
   - **Musk**: "Here's the fire, here's the fix, let's go"
   - **Inamori**: "The team needs support — here's how to stabilize"
   - **Ma**: "Here's the opportunity hidden in this crisis"
8. Wait for boss decision before executing any write actions

## Scenario 8: Execution Risk Review

**Trigger**: "what are our risks?" or daily cron

1. `get_company_state` → operational snapshot including blocked projects
2. `get_top_risks` → highest-severity signals sorted by score
3. `get_execution_signals` → full signal breakdown with evidence
4. `get_overdue_tasks` → delivery risks from overdue work
5. Categorize risks:
   - **People risks**: overload, engagement drops, consecutive misses
   - **Delivery risks**: overdue tasks, blocker cascades, stale PRs
   - **Metric risks**: KPIs trending below target
6. For each risk: recommend specific action with owner and deadline
7. Apply mentor lens for prioritization

## Scenario 9: KPI Health Check

**Trigger**: "how are our metrics?" or weekly cron

1. `get_kpi_dashboard` → all metrics with current values vs targets
2. `get_goal_state` for current cycle → OKR completion percentages
3. Identify off-track metrics (current < target by > 10%)
4. For each off-track metric:
   - Who owns it?
   - What's the trend? (improving / declining / flat)
   - What execution signals correlate with the miss?
5. Generate KPI health report:
   - Green metrics (on track) — brief mention
   - Yellow metrics (at risk) — owner + trend + recommended action
   - Red metrics (off track) — owner + root cause analysis + urgent action
6. Suggest `ingest_metric` if any metrics are stale (no recent data points)

## Scenario 10: Incentive Review

**Trigger**: "show incentive scores for {period}"

1. `get_incentive_scores` with the specified period (YYYY-MM format)
2. If no scores exist: suggest running `calculate_incentives` first
3. For each employee, show:
   - Overall score and rank
   - Score breakdown by dimension (execution, communication, goal contribution)
   - Whether human review is flagged (and why)
4. Highlight outliers: top performers and underperformers
5. Apply mentor lens:
   - **Musk**: focus on output and velocity metrics
   - **Inamori**: balance individual score with team contribution
   - **Dalio**: highlight transparency and mistake-handling scores
6. Recommend 1:1 conversations for flagged employees

## Scenario 11: AI Recommendations

**Trigger**: "any recommendations?" or daily 10:30 AM scan

1. `get_recommendations` → pending AI management suggestions
2. Check `learning.ignored_recommendations` — if a category has 3+ ignores, deprioritize it (show at bottom, dimmed)
3. Check `learning.adopted_recommendations` — boost categories the boss frequently acts on
4. For each recommendation, show:
   - Title and description
   - Priority (high / medium / low)
   - Category (people / delivery / metrics / process)
   - Evidence (what data triggered this recommendation)
   - Suggested actions (each can be executed with one click)
5. Group by priority, highest first (with learning adjustments from steps 2-3)
6. For each suggested action: explain what will happen if executed
   - e.g., "This will send a message to Alice via Telegram asking about her blockers"
7. Wait for boss to approve before calling `execute_recommendation`
8. After execution: confirm what was done and suggest follow-up
9. Update `learning.adopted_recommendations` or `learning.ignored_recommendations` based on what the boss approved/dismissed

## Scenario 12: Data Sync

**Trigger**: Cron (every 30min during work hours) or "sync to Notion/Sheets"

1. `get_sync_manifest` with storage_type (notion or sheets) → list of changed items
2. If no changes: log "no sync needed" and exit
3. For each changed item:
   - Check if it was modified locally (on manageaibrain.com) or externally (in Notion/Sheets)
   - If both modified (conflict): apply Last-write-wins if time gap > 5min, otherwise flag for boss decision
4. Read external data via OpenClaw Notion/Sheets connector
5. Compare and merge changes
6. Write updates to both sides
7. `report_sync_result` → record items pushed, pulled, conflicts
8. If conflicts were flagged: present to boss with both versions for resolution

## Scenario 13: AI Consulting Engagement

**Trigger**: "I need help with {business problem}" or "let's consult on {topic}"

This is a multi-session workflow — a single engagement spans multiple conversations, progressing through phases: diagnosis → analysis → action plan → execution → tracking → close.

### Phase A: Start Engagement
1. `start_consulting` with the boss's problem description → returns engagement_id, complexity tier (simple/standard/complex), and first diagnostic question
2. Present the engagement overview: tier, category, estimated questions needed
3. Wait for boss to answer the first question

### Phase B: Diagnosis (2-8 questions depending on tier)
4. `answer_consulting_question` with engagement_id + boss's answer → returns either next question or "diagnosis complete"
5. Repeat step 4 until the AI has enough information
6. When diagnosis completes, the system auto-generates:
   - Root cause analysis (evidence-based)
   - Prioritized action plan (3-7 actions depending on tier)
   - Each action has: title, description, type (create_task/send_message/schedule_meeting/flag_risk), owner, deadline

### Phase C: Review Action Plan
7. `get_consulting_engagement` with engagement_id → full engagement details with action plan
8. Present each action to the boss with clear explanation of what will happen
9. For each action: `review_consulting_action` with action_id + approved (true/false)
   - Boss can approve all, reject some, or ask for modifications
10. If boss rejects actions, discuss alternatives and adjust

### Phase D: Execute
11. `execute_consulting_actions` with engagement_id → dispatches all approved actions
    - `create_task` type → creates a task in the task system
    - `send_message` type → sends message to the relevant employee
    - `schedule_meeting` type → creates a meeting entry
    - `flag_risk` type → adds to risk register
12. Confirm to boss what was executed and set expectations for follow-up

### Phase E: Track Progress (subsequent sessions)
13. `check_consulting_progress` with engagement_id → returns:
    - Completion percentage
    - What's on track
    - What's at risk
    - Recommended next steps
14. `list_consulting_actions` with engagement_id → status of each action (pending/approved/rejected/done/failed)
15. Present progress update to boss; suggest adjustments if actions are failing

### Phase F: Close
16. When boss is satisfied (or engagement has run its course):
    `close_consulting_engagement` with engagement_id → generates:
    - Effectiveness assessment
    - Lessons learned
    - Organizational memory (stored for future engagements)
17. Present retrospective to boss
18. Apply mentor lens to closing reflection:
    - **Musk**: "What would we do 10x faster next time?"
    - **Inamori**: "How did this strengthen the team?"
    - **Dalio**: "What principles did we validate or update?"

### Listing Past Engagements
- `list_consulting_engagements` → shows all active and closed engagements with phase and progress percentage
- Useful for: "what consulting projects are still open?" or "show me past engagements"

## Scenario 14: World Model Exploration

**Trigger**: "show team skills" or "what's the team capable of?" or "team dynamics"

1. `get_world_model` → team-wide view: skills, collaborations, blockers, growth events, AI insights
2. Present the team capability map:
   - **Skills matrix**: who knows what, skill confidence levels
   - **Collaboration graph**: who works with whom most frequently
   - **Active blockers**: recurring or persistent blockers across the team
   - **Growth events**: recent skill acquisitions, promotions, role changes
   - **AI insights**: patterns the AI has noticed (e.g., "Alice and Bob collaborate on all frontend tasks")
3. For deep-dive on an individual: `get_employee_world_model` with name → shows:
   - Skill inventory with confidence scores
   - Growth trajectory (skills gained over time)
   - Blocker history (what keeps blocking them)
   - Collaboration patterns (who they work with, on what)
4. Apply mentor lens:
   - **Inamori**: highlight growth opportunities and mentoring pairs
   - **Grove**: map skills to OKR delivery capability
   - **Musk**: identify skill gaps that slow down execution
5. Suggest actions based on findings:
   - Skill gaps → training recommendations or hiring signals
   - Over-reliance on one person → knowledge sharing or documentation tasks
   - Growth stalls → 1:1 topics or stretch assignments


path: references/setup-guide.md
content: # Setup & Connection Guide

## MCP Connection Options

Team Operations Mode requires connecting to the MCP server. Two transport options:

### Option 1: CLI (stdio) — Recommended

Run the MCP server locally via npx. Simpler setup, lower latency, only one key needed.

```json
{
  "mcpServers": {
    "management-brain": {
      "command": "npx",
      "args": ["-y", "@tonykk/management-brain-mcp"],
      "env": {
        "MANAGEMENT_BRAIN_API_KEY": "mb_your_api_key_here",
        "MANAGEMENT_BRAIN_BASE_URL": "https://manageaibrain.com"
      }
    }
  }
}
```

- No `MCP_HTTP_API_KEY` needed — stdio mode bypasses HTTP auth
- Only requires `MANAGEMENT_BRAIN_API_KEY` (the `mb_` prefixed key)
- Works with Claude Code, Hermes Agent, and any MCP client that supports stdio transport
- Zero install: `npx -y` auto-downloads and runs

### Option 2: HTTP (Streamable HTTP)

Connect to the cloud-hosted MCP endpoint. Works with ChatGPT, Gemini, and web-based MCP clients.

- **URL**: `https://manageaibrain.com/mcp`
- **Auth**: `Authorization: Bearer <MCP_HTTP_API_KEY>`
- **Accept**: `application/json, text/event-stream`
- Requires `MCP_HTTP_API_KEY` (separate from `MANAGEMENT_BRAIN_API_KEY`)

### npm install (alternative for CLI)

```bash
npm install -g @tonykk/management-brain-mcp
```

Then use `"command": "management-brain-mcp"` instead of npx in your MCP config.

## OpenClaw Integration Architecture

Boss AI Agent is the **brain layer** on top of OpenClaw's MCP connector ecosystem. It connects to its own backend (`manageaibrain.com/mcp`) for team data processing, while third-party tool integrations are handled by OpenClaw's MCP connectors.

```
OpenClaw Runtime (user environment)
  |-- MCP Connectors (user self-installs via OpenClaw)
  |    |-- Storage: Notion / Google Sheets  <-- bidirectional sync targets
  |    |-- Development: GitHub / Linear / Calendar / Gmail
  |    +-- Communication: Telegram / Slack / Discord / Lark / Signal
  |
  +-- Boss AI Agent Skill (brain layer + sync orchestrator)
       +-- manageaibrain.com API
            |-- 33 MCP tools (daily ops + intelligence + sync)
            |-- Company Context Layer  <- foundation for all reasoning
            |-- Execution Intelligence <- signals, risks, working memory
            |-- Communication Parser   <- check-ins -> structured events
            |-- Incentive Engine       <- context-aware scoring
            |-- AI Recommendation Engine <- memory-driven proactive suggestions
            +-- Sync Service           <- Notion/Sheets bidirectional sync
```

### Company Context Layer

The Context Layer is the **foundation** — all intelligence engines depend on it. It aggregates:

- **Organization context**: strategic priorities, key risks, management style, countries of operation
- **Employee context**: execution scores, current workload, strengths, risk flags, work scope
- **Goal context**: OKRs, KPIs with baselines and targets, goal ownership and attribution
- **Project context**: active projects, task status, blockers, delivery timelines

When OpenClaw MCP connectors are installed, they enrich the context layer automatically:
- **Notion/Jira/Sheets** -> project updates, task status, documentation changes
- **GitHub/Linear** -> PR activity, commit patterns, CI status feed into execution signals
- **Telegram/Slack/Discord/Lark** -> employee messages parsed into structured management events

### Data Ingestion Pipeline

1. **OpenClaw connectors** deliver raw data (GitHub commits, Jira updates, Slack messages, check-in reports)
2. **Communication Parser** extracts structured management events (`blocker_reported`, `task_completed`, `commitment_made`, `delay_reported`, `escalation_needed`, `proactive_update`)
3. **State Engine** generates execution signals (overload risk, delivery risk, engagement drops, blocker cascades)
4. **Working Memory** maintains AI situational awareness — focus areas, momentum, pending decisions
5. **Recommendation Engine** synthesizes all context through mentor lens for prioritized suggestions

## Permissions & Data

### Advisor Mode (no cloud)

- **Config file**: writes `~/.openclaw/skills/boss-ai-agent/config.json` during first run. User can read, edit, or delete at any time.
- **No network access**: zero HTTP requests. All responses from embedded mentor frameworks.
- **No cron jobs**: no persistent behavior.

### Team Operations Mode (MCP connected)

All Advisor Mode permissions, plus:

- **MCP tools** (requires `MANAGEMENT_BRAIN_API_KEY`): 33 tools on `manageaibrain.com/mcp`. 21 read-only; 4 write (send messages); 2 recommendation; 3 brain context; 3 sync.
- **Cron jobs**: up to 6 recurring jobs. Solo founder mode (team=0) only registers 3.
- **Third-party tools**: via OpenClaw connectors — skill does NOT store/manage tokens.
- **Cloud API** (optional): `BOSS_AI_AGENT_API_KEY` enables read-only GET to `manageaibrain.com/api/v1/`.

### Data Flow Summary

**What goes to the cloud**: MCP tool parameters sent to `manageaibrain.com`. Server stores team data in PostgreSQL.

**What stays local**: `config.json`, chat history, memory files. Never transmitted.

**Persistent behavior warning**: Team Ops Mode registers up to 6 autonomous cron jobs + 4 write tools + 3 sync tools. Review cron schedules in `config.json` before activating.

## Cron Job Management

| Job | Default Schedule | Solo Mode |
|-----|-----------------|-----------|
| checkin | `0 9 * * 1-5` (9am weekdays) | Skipped |
| chase | `30 17 * * 1-5` (5:30pm weekdays) | Skipped |
| summary | `0 19 * * 1-5` (7pm weekdays) | Skipped |
| briefing | `0 8 * * 1-5` (8am weekdays) | Active |
| signalScan | `*/30 9-18 * * 1-5` (every 30min work hours) | Active |
| sync | `*/30 9-18 * * 1-5` (every 30min work hours) | Active |

**Commands**: `cron list` / `cron remove <job-id>` / `cron remove --skill boss-ai-agent`

**Uninstall cleanup**: `clawhub uninstall boss-ai-agent` removes all cron jobs and `config.json`.

**User-editable**: modify `schedule` in `config.json` and re-run `/boss-ai-agent` to update.


path: scripts/format-briefing.py
content: #!/usr/bin/env python3
"""Format a morning briefing from MCP tool outputs.

Usage: Claude calls MCP tools, saves JSON responses to temp files, then runs:
  python format-briefing.py --mentor musk \
    --company-state state.json \
    --top-risks risks.json \
    --alerts alerts.json \
    --kpi kpi.json \
    --working-memory memory.json \
    --recommendations recs.json

Outputs formatted markdown briefing to stdout.
"""
import argparse
import json
import sys
from datetime import datetime
from pathlib import Path


MAX_JSON_SIZE = 10 * 1024 * 1024  # 10MB

ALLOWED_MENTORS = frozenset({
    "musk", "inamori", "ma", "dalio", "grove", "ren", "son", "jobs", "bezos",
    "buffett", "zhangyiming", "leijun", "caodewang", "chushijian", "meyer", "trout",
})

MENTOR_PRIORITIES = {
    "musk":    ["blockers", "delivery_risks", "metrics", "people"],
    "inamori": ["people", "team_harmony", "blockers", "metrics"],
    "ma":      ["customer_impact", "adaptability", "team", "metrics"],
    "dalio":   ["transparency_gaps", "principle_violations", "metrics", "people"],
    "grove":   ["okr_progress", "metrics", "blockers", "people"],
    "bezos":   ["customer_impact", "day1_indicators", "metrics", "delivery_risks"],
}


def load_json(path):
    if not path or not Path(path).exists():
        return None
    file_path = Path(path)
    if file_path.stat().st_size > MAX_JSON_SIZE:
        print(f"Error: {path} exceeds 10MB size limit", file=sys.stderr)
        return None
    try:
        with open(file_path, encoding="utf-8") as f:
            return json.load(f)
    except (json.JSONDecodeError, OSError) as e:
        print(f"Error loading {path}: {e}", file=sys.stderr)
        return None


def format_section(title, items, empty_msg="No items."):
    if not items:
        return f"### {title}\n{empty_msg}\n"
    lines = [f"### {title}"]
    for item in items:
        if isinstance(item, dict):
            name = item.get("title", item.get("name", item.get("employee_name", item.get("metric_name", str(item)))))
            detail = item.get("description", item.get("reason", item.get("value", "")))
            if not detail and item.get("missed_days"):
                detail = f"{item['missed_days']} consecutive missed days"
            score = item.get("score", item.get("severity", ""))
            score_str = f" [{score:.0%}]" if isinstance(score, (int, float)) and score <= 1 else ""
            lines.append(f"- **{name}**{score_str}: {detail}")
        else:
            lines.append(f"- {item}")
    return "\n".join(lines) + "\n"


def extract_off_track_kpis(kpi_data):
    if not kpi_data:
        return []
    metrics = kpi_data if isinstance(kpi_data, list) else kpi_data.get("metrics", [])
    off_track = []
    for m in metrics:
        current = m.get("current_value", m.get("value", 0))
        target = m.get("target_value", m.get("target", 0))
        if target and current < target * 0.9:
            off_track.append({
                "metric_name": m.get("name", "Unknown"),
                "value": f"{current} / {target} ({current/target:.0%})" if target else str(current),
            })
    return off_track


def extract_action_items(memory_data):
    if not memory_data:
        return []
    items = memory_data.get("action_items", [])
    if not items:
        pending = memory_data.get("pending_decisions", [])
        return [{"name": d} for d in pending] if pending else []
    return [{"name": item} if isinstance(item, str) else item for item in items]


def build_briefing(mentor, state, risks, alerts, kpi, memory, recs):
    now = datetime.now()
    lines = [
        f"# Morning Briefing — {now.strftime('%A, %B %d, %Y')}",
        f"*Mentor: {mentor.title()} | Generated at {now.strftime('%H:%M')}*\n",
    ]

    # Momentum indicator from working memory
    if memory:
        momentum = memory.get("team_momentum", "neutral")
        lines.append(f"**Team Momentum**: {momentum}\n")

    priority_order = MENTOR_PRIORITIES.get(mentor, MENTOR_PRIORITIES["musk"])

    sections = {
        "blockers": ("Blockers & Urgent Issues",
                     (risks or []) if isinstance(risks, list) else (risks.get("signals", []) if risks else []),
                     "No critical risks detected."),
        "delivery_risks": ("Delivery Risks",
                           (state.get("overdue_tasks", []) if state else []),
                           "No overdue tasks."),
        "metrics": ("Off-Track Metrics",
                    extract_off_track_kpis(kpi),
                    "All metrics on track."),
        "people": ("People Alerts",
                   (alerts if isinstance(alerts, list) else (alerts.get("alerts", []) if alerts else [])),
                   "No people alerts."),
        "customer_impact": ("Customer Impact",
                            [], "No customer-facing issues detected."),
        "team_harmony": ("Team Harmony",
                         [], "No team concerns detected."),
        "adaptability": ("Adaptability & Change",
                         [], "No adaptation issues."),
        "transparency_gaps": ("Transparency Gaps",
                              [], "No transparency issues."),
        "principle_violations": ("Principle Violations",
                                 [], "No violations detected."),
        "okr_progress": ("OKR Progress",
                         [], "Check `get_goal_state` for details."),
        "day1_indicators": ("Day 1 Indicators",
                            [], "Check customer metrics for details."),
        "team": ("Team Updates",
                 [], "No notable team updates."),
    }

    for key in priority_order:
        if key in sections:
            title, items, empty = sections[key]
            lines.append(format_section(title, items, empty))

    # AI Recommendations
    if recs:
        rec_list = recs if isinstance(recs, list) else recs.get("recommendations", [])
        if rec_list:
            lines.append(format_section("AI Recommendations", rec_list[:3], "None pending."))

    # Action items from working memory
    action_items = extract_action_items(memory)
    if action_items:
        lines.append(format_section("Pending Action Items", action_items))

    lines.append("---\n*Read `references/scenarios.md` Scenario 3 for the full briefing flow.*")
    return "\n".join(lines)


def main():
    parser = argparse.ArgumentParser(description="Format morning briefing from MCP data")
    parser.add_argument("--mentor", default="musk", help="Active mentor ID")
    parser.add_argument("--company-state", help="Path to company state JSON")
    parser.add_argument("--top-risks", help="Path to top risks JSON")
    parser.add_argument("--alerts", help="Path to alerts JSON")
    parser.add_argument("--kpi", help="Path to KPI dashboard JSON")
    parser.add_argument("--working-memory", help="Path to working memory JSON")
    parser.add_argument("--recommendations", help="Path to recommendations JSON")
    args = parser.parse_args()
    if args.mentor not in ALLOWED_MENTORS:
        print(f"Warning: unknown mentor '{args.mentor}', falling back to 'musk'", file=sys.stderr)
        args.mentor = "musk"

    state = load_json(args.company_state)
    risks = load_json(args.top_risks)
    alerts = load_json(args.alerts)
    kpi = load_json(args.kpi)
    memory = load_json(args.working_memory)
    recs = load_json(args.recommendations)

    print(build_briefing(args.mentor, state, risks, alerts, kpi, memory, recs))


if __name__ == "__main__":
    main()


path: scripts/risk-scan.py
content: #!/usr/bin/env python3
"""Generate a risk dashboard from MCP tool outputs.

Usage: Claude calls MCP tools, saves JSON responses to temp files, then runs:
  python risk-scan.py --mentor musk \
    --company-state state.json \
    --top-risks risks.json \
    --signals signals.json \
    --overdue overdue.json \
    --alerts alerts.json

Outputs formatted risk dashboard markdown to stdout.
"""
import argparse
import json
import sys
from datetime import datetime
from pathlib import Path


MAX_JSON_SIZE = 10 * 1024 * 1024  # 10MB

ALLOWED_MENTORS = frozenset({
    "musk", "inamori", "ma", "dalio", "grove", "ren", "son", "jobs", "bezos",
    "buffett", "zhangyiming", "leijun", "caodewang", "chushijian", "meyer", "trout",
})


def load_json(path):
    if not path or not Path(path).exists():
        return None
    file_path = Path(path)
    if file_path.stat().st_size > MAX_JSON_SIZE:
        print(f"Error: {path} exceeds 10MB size limit", file=sys.stderr)
        return None
    try:
        with open(file_path, encoding="utf-8") as f:
            return json.load(f)
    except (json.JSONDecodeError, OSError) as e:
        print(f"Error loading {path}: {e}", file=sys.stderr)
        return None


def severity_icon(score):
    if score >= 0.8:
        return "🔴"
    elif score >= 0.5:
        return "🟡"
    return "🟢"


def categorize_risks(signals, overdue, alerts):
    """Split risks into people, delivery, and metric categories."""
    people, delivery, metric = [], [], []

    sig_list = signals if isinstance(signals, list) else (signals.get("signals", []) if signals else [])
    for s in sig_list:
        sig_type = s.get("type", s.get("name", "")).lower()
        entry = {
            "name": s.get("type", s.get("name", "Unknown")),
            "score": s.get("score", 0),
            "reason": s.get("reason", s.get("description", "")),
            "employees": s.get("employees", []),
        }
        if any(k in sig_type for k in ["overload", "engagement", "burnout"]):
            people.append(entry)
        elif any(k in sig_type for k in ["delivery", "blocker", "cascade"]):
            delivery.append(entry)
        else:
            metric.append(entry)

    # Overdue tasks are delivery risks
    overdue_list = overdue if isinstance(overdue, list) else (overdue.get("tasks", []) if overdue else [])
    for t in overdue_list:
        delivery.append({
            "name": f"Overdue: {t.get('title', 'Unknown task')}",
            "score": 0.6,
            "reason": f"Assigned to {t.get('assignee', 'unassigned')}, {t.get('days_overdue', '?')} days late",
            "employees": [t.get("assignee", "")] if t.get("assignee") else [],
        })

    # Alerts (consecutive misses) are people risks
    alert_list = alerts if isinstance(alerts, list) else (alerts.get("alerts", []) if alerts else [])
    for a in alert_list:
        people.append({
            "name": f"Missed check-ins: {a.get('name', a.get('employee_name', 'Unknown'))}",
            "score": min(a.get("consecutive_misses", a.get("missed_days", 0)) / 5, 1.0),
            "reason": f"{a.get('consecutive_misses', a.get('missed_days', '?'))} consecutive missed days",
            "employees": [a.get("name", a.get("employee_name", ""))],
        })

    # Sort each by score descending
    for lst in [people, delivery, metric]:
        lst.sort(key=lambda x: x["score"], reverse=True)

    return people, delivery, metric


def format_risk_section(title, risks, empty_msg):
    if not risks:
        return f"### {title}\n{empty_msg}\n"
    lines = [f"### {title}"]
    for r in risks:
        icon = severity_icon(r["score"])
        lines.append(f"- {icon} **{r['name']}** [{r['score']:.0%}]: {r['reason']}")
    return "\n".join(lines) + "\n"


def format_blocked_projects(state):
    if not state:
        return ""
    blocked = state.get("blocked_projects", [])
    if not blocked:
        return ""
    lines = ["### Blocked Projects"]
    for p in blocked:
        name = p.get("name", p.get("title", "Unknown"))
        reason = p.get("reason", p.get("blocker", "Unknown blocker"))
        lines.append(f"- **{name}**: {reason}")
    return "\n".join(lines) + "\n"


MENTOR_ACTIONS = {
    "musk": "Eliminate the highest-score blocker immediately. What's the 10x fix?",
    "inamori": "Check on affected team members first. Who needs support?",
    "ma": "Which risks affect customers? Address those first.",
    "dalio": "What principles apply? Be radically transparent about these risks with the team.",
    "grove": "Which risks threaten our OKRs? Prioritize by key result impact.",
    "bezos": "Which risks affect customer experience? Think long-term.",
}


def build_dashboard(mentor, state, risks, signals, overdue, alerts):
    now = datetime.now()
    people, delivery, metric = categorize_risks(signals, overdue, alerts)

    total_risks = len(people) + len(delivery) + len(metric)
    critical = sum(1 for r in people + delivery + metric if r["score"] >= 0.8)
    moderate = sum(1 for r in people + delivery + metric if 0.5 <= r["score"] < 0.8)

    lines = [
        f"# Risk Dashboard — {now.strftime('%B %d, %Y')}",
        f"*Mentor: {mentor.title()} | Generated at {now.strftime('%H:%M')}*\n",
        f"**Summary**: {total_risks} risks detected — {critical} critical, {moderate} moderate\n",
    ]

    # Top risks from MCP tool (pre-ranked)
    risk_list = risks if isinstance(risks, list) else (risks.get("signals", []) if risks else [])
    if risk_list:
        lines.append("## Top Risks (Pre-ranked by AI)")
        for r in risk_list[:5]:
            name = r.get("type", r.get("name", "Unknown"))
            score = r.get("score", 0)
            reason = r.get("reason", r.get("description", ""))
            lines.append(f"- {severity_icon(score)} **{name}** [{score:.0%}]: {reason}")
        lines.append("")

    lines.append("## Risk Breakdown\n")
    lines.append(format_risk_section("People Risks", people, "No people risks detected."))
    lines.append(format_risk_section("Delivery Risks", delivery, "No delivery risks detected."))
    lines.append(format_risk_section("Metric Risks", metric, "No metric risks detected."))

    blocked = format_blocked_projects(state)
    if blocked:
        lines.append(blocked)

    # Recommended actions
    lines.append("## Recommended Actions\n")
    action_items = []
    if people:
        top = people[0]
        emps = ", ".join(top["employees"][:3]) if top["employees"] else "affected team members"
        action_items.append(f"1. **Check on {emps}** — {top['reason']}")
    if delivery:
        top = delivery[0]
        action_items.append(f"2. **Unblock**: {top['name']} — {top['reason']}")
    if metric:
        top = metric[0]
        action_items.append(f"3. **Investigate metric**: {top['name']} — {top['reason']}")
    if not action_items:
        action_items.append("No immediate actions needed.")
    lines.extend(action_items)

    mentor_action = MENTOR_ACTIONS.get(mentor, f"Apply {mentor}'s philosophy to prioritize these risks.")
    lines.extend([
        "",
        "## Mentor Perspective",
        f"*{mentor_action}*\n",
        "---",
        "*Generated by Boss AI Agent. Read `references/scenarios.md` Scenario 8 for the full risk review flow.*",
    ])
    return "\n".join(lines)


def main():
    parser = argparse.ArgumentParser(description="Generate risk dashboard from MCP data")
    parser.add_argument("--mentor", default="musk", help="Active mentor ID")
    parser.add_argument("--company-state", help="Path to company state JSON")
    parser.add_argument("--top-risks", help="Path to top risks JSON")
    parser.add_argument("--signals", help="Path to execution signals JSON")
    parser.add_argument("--overdue", help="Path to overdue tasks JSON")
    parser.add_argument("--alerts", help="Path to alerts JSON")
    args = parser.parse_args()
    if args.mentor not in ALLOWED_MENTORS:
        print(f"Warning: unknown mentor '{args.mentor}', falling back to 'musk'", file=sys.stderr)
        args.mentor = "musk"

    state = load_json(args.company_state)
    risks = load_json(args.top_risks)
    signals = load_json(args.signals)
    overdue = load_json(args.overdue)
    alerts = load_json(args.alerts)

    print(build_dashboard(args.mentor, state, risks, signals, overdue, alerts))


if __name__ == "__main__":
    main()


path: scripts/sync-flow.py
content: #!/usr/bin/env python3
"""Format sync operation results for Notion/Sheets bidirectional sync.

Usage: Claude calls MCP sync tools, saves JSON responses to temp files, then runs:
  python sync-flow.py --storage notion \
    --manifest manifest.json \
    --sync-result result.json

Can also be used pre-sync to analyze the manifest and show what will be synced:
  python sync-flow.py --storage notion --manifest manifest.json --dry-run

Outputs formatted sync report markdown to stdout.
"""
import argparse
import json
import sys
from datetime import datetime
from pathlib import Path


MAX_JSON_SIZE = 10 * 1024 * 1024  # 10MB


def load_json(path):
    if not path or not Path(path).exists():
        return None
    file_path = Path(path)
    if file_path.stat().st_size > MAX_JSON_SIZE:
        print(f"Error: {path} exceeds 10MB size limit", file=sys.stderr)
        return None
    try:
        with open(file_path, encoding="utf-8") as f:
            return json.load(f)
    except (json.JSONDecodeError, OSError) as e:
        print(f"Error loading {path}: {e}", file=sys.stderr)
        return None


def analyze_manifest(manifest, storage_type):
    """Analyze sync manifest and return summary of changes."""
    if not manifest:
        return {"total": 0, "by_type": {}, "conflicts": []}

    changes = manifest if isinstance(manifest, list) else manifest.get("changes", [])
    by_type = {}
    conflicts = []

    for item in changes:
        entity_type = item.get("entity_type", "unknown")
        direction = item.get("direction", "unknown")
        by_type.setdefault(entity_type, {"push": 0, "pull": 0, "conflict": 0})

        if item.get("conflict"):
            by_type[entity_type]["conflict"] += 1
            conflicts.append(item)
        elif direction == "push":
            by_type[entity_type]["push"] += 1
        elif direction == "pull":
            by_type[entity_type]["pull"] += 1

    return {
        "total": len(changes),
        "by_type": by_type,
        "conflicts": conflicts,
    }


def format_dry_run(manifest_analysis, storage_type):
    """Format a pre-sync analysis showing what will be synced."""
    now = datetime.now()
    lines = [
        f"# Sync Preview — {storage_type.title()}",
        f"*Generated at {now.strftime('%Y-%m-%d %H:%M')}*\n",
    ]

    if manifest_analysis["total"] == 0:
        lines.append("**No changes detected.** Everything is in sync.")
        return "\n".join(lines)

    lines.append(f"**{manifest_analysis['total']} changes detected**\n")

    # Changes by entity type
    lines.append("## Changes by Type\n")
    lines.append("| Type | Push (→ {}) | Pull (← {}) | Conflicts |".format(
        storage_type.title(), storage_type.title()))
    lines.append("|------|-------------|-------------|-----------|")
    for entity_type, counts in manifest_analysis["by_type"].items():
        lines.append(
            f"| {entity_type} | {counts['push']} | {counts['pull']} | {counts['conflict']} |"
        )
    lines.append("")

    # Conflicts detail
    if manifest_analysis["conflicts"]:
        lines.append("## Conflicts Requiring Resolution\n")
        for c in manifest_analysis["conflicts"]:
            name = c.get("title", c.get("name", c.get("external_id", "Unknown")))
            entity_type = c.get("entity_type", "unknown")
            local_time = c.get("local_updated_at", "?")
            remote_time = c.get("remote_updated_at", "?")
            lines.append(f"- **{name}** ({entity_type})")
            lines.append(f"  - Local updated: {local_time}")
            lines.append(f"  - {storage_type.title()} updated: {remote_time}")
            lines.append(f"  - Action needed: Boss decides which version to keep")
        lines.append("")

    lines.extend([
        "## Next Steps\n",
        "1. Review changes above",
        "2. Resolve any conflicts (boss picks the winning version)",
        "3. Execute sync to apply changes",
        "",
        "---",
        f"*Read `references/scenarios.md` Scenario 12 for the full sync flow.*",
    ])
    return "\n".join(lines)


def format_sync_result(result, storage_type):
    """Format post-sync result report."""
    now = datetime.now()
    lines = [
        f"# Sync Report — {storage_type.title()}",
        f"*Completed at {now.strftime('%Y-%m-%d %H:%M')}*\n",
    ]

    if not result:
        lines.append("No sync result data available.")
        return "\n".join(lines)

    pushed = result.get("items_pushed", 0)
    pulled = result.get("items_pulled", 0)
    conflicts = result.get("conflicts", 0)
    errors = result.get("errors", [])

    status = "✅ Success" if not errors else "⚠️ Completed with errors"
    lines.extend([
        f"**Status**: {status}\n",
        "## Summary\n",
        f"- **Pushed** (→ {storage_type.title()}): {pushed} items",
        f"- **Pulled** (← {storage_type.title()}): {pulled} items",
        f"- **Conflicts**: {conflicts}",
        f"- **Errors**: {len(errors)}",
        "",
    ])

    if errors:
        lines.append("## Errors\n")
        for e in errors:
            lines.append(f"- ❌ {e}")
        lines.append("")

    if conflicts > 0:
        lines.extend([
            "## Conflict Resolution\n",
            f"{conflicts} conflicts were detected. Last-write-wins was applied for gaps > 5min.",
            "Check the sync log for details on which version was kept.\n",
        ])

    lines.extend([
        "---",
        f"*Read `references/scenarios.md` Scenario 12 for the full sync flow.*",
    ])
    return "\n".join(lines)


def main():
    parser = argparse.ArgumentParser(description="Format sync results from MCP data")
    parser.add_argument("--storage", default="notion", choices=["notion", "sheets"],
                        help="Storage type (notion or sheets)")
    parser.add_argument("--manifest", help="Path to sync manifest JSON")
    parser.add_argument("--sync-result", help="Path to sync result JSON")
    parser.add_argument("--dry-run", action="store_true",
                        help="Only analyze manifest, don't expect sync result")
    args = parser.parse_args()

    manifest = load_json(args.manifest)

    if args.dry_run or not args.sync_result:
        analysis = analyze_manifest(manifest, args.storage)
        print(format_dry_run(analysis, args.storage))
    else:
        result = load_json(args.sync_result)
        print(format_sync_result(result, args.storage))


if __name__ == "__main__":
    main()


path: scripts/update-learning.py
content: #!/usr/bin/env python3
"""Update the learning field in boss-ai-agent config.json.

Usage: Claude runs at end of session to persist learned preferences:
  python update-learning.py \
    --config ~/.openclaw/skills/boss-ai-agent/config.json \
    --preferred-language zh \
    --session-context "Reviewed Q1 KPIs, flagged sprint velocity" \
    --add-pattern "promotes-internally" \
    --add-adopted '{"id":"rec_123","category":"engagement","date":"2026-04-20"}'

  python update-learning.py --config config.json --show   # display current state
  python update-learning.py --config config.json --reset   # clear all learning

All updates are immutable — a new config dict is built, never mutated in place.
Enforces limits: 20 decision_patterns, 50 ignored/adopted recommendations.
"""
import argparse
import json
import sys
from copy import deepcopy
from datetime import datetime
from pathlib import Path


MAX_PATTERNS = 20
MAX_RECOMMENDATIONS = 50

DEFAULT_LEARNING = {
    "preferred_report_format": None,
    "preferred_language": None,
    "ignored_recommendations": [],
    "adopted_recommendations": [],
    "decision_patterns": [],
    "custom_check_in_questions": [],
    "last_session_context": None,
}


MAX_JSON_SIZE = 10 * 1024 * 1024  # 10MB


def load_config(path):
    config_path = Path(path).expanduser()
    if not config_path.exists():
        print(f"Config not found at {config_path}, creating with defaults.", file=sys.stderr)
        return {"learning": deepcopy(DEFAULT_LEARNING)}
    if config_path.stat().st_size > MAX_JSON_SIZE:
        print(f"Error: {config_path} exceeds 10MB size limit", file=sys.stderr)
        sys.exit(1)
    try:
        with open(config_path, encoding="utf-8") as f:
            return json.load(f)
    except (json.JSONDecodeError, OSError) as e:
        print(f"Error loading {config_path}: {e}", file=sys.stderr)
        sys.exit(1)


def save_config(path, config):
    config_path = Path(path).expanduser()
    config_path.parent.mkdir(parents=True, exist_ok=True)
    with open(config_path, "w") as f:
        json.dump(config, f, indent=2, ensure_ascii=False)
    print(f"Config saved to {config_path}", file=sys.stderr)


def show_learning(learning):
    """Display current learning state as formatted markdown."""
    lines = [
        "# Current Learning State",
        f"*Generated at {datetime.now().strftime('%Y-%m-%d %H:%M')}*\n",
    ]

    lang = learning.get("preferred_language")
    fmt = learning.get("preferred_report_format")
    ctx = learning.get("last_session_context")
    lines.append(f"**Language**: {lang or 'not set'}")
    lines.append(f"**Report Format**: {fmt or 'not set'}")
    lines.append(f"**Last Session**: {ctx or 'none'}\n")

    patterns = learning.get("decision_patterns", [])
    lines.append(f"### Decision Patterns ({len(patterns)}/{MAX_PATTERNS})")
    if patterns:
        for p in patterns:
            lines.append(f"- {p}")
    else:
        lines.append("- (none)")
    lines.append("")

    questions = learning.get("custom_check_in_questions", [])
    lines.append(f"### Custom Check-in Questions ({len(questions)})")
    if questions:
        for q in questions:
            lines.append(f"- {q}")
    else:
        lines.append("- (none)")
    lines.append("")

    adopted = learning.get("adopted_recommendations", [])
    ignored = learning.get("ignored_recommendations", [])
    lines.append(f"### Adopted Recommendations ({len(adopted)}/{MAX_RECOMMENDATIONS})")
    if adopted:
        for r in adopted[-5:]:
            lines.append(f"- [{r.get('date', '?')}] {r.get('category', '?')} ({r.get('id', '?')})")
        if len(adopted) > 5:
            lines.append(f"  ... and {len(adopted) - 5} more")
    else:
        lines.append("- (none)")
    lines.append("")

    lines.append(f"### Ignored Recommendations ({len(ignored)}/{MAX_RECOMMENDATIONS})")
    if ignored:
        for r in ignored[-5:]:
            lines.append(f"- [{r.get('date', '?')}] {r.get('category', '?')} ({r.get('id', '?')})")
        if len(ignored) > 5:
            lines.append(f"  ... and {len(ignored) - 5} more")
    else:
        lines.append("- (none)")

    # Category analysis
    if ignored:
        cats = {}
        for r in ignored:
            cat = r.get("category", "unknown")
            cats[cat] = cats.get(cat, 0) + 1
        deprioritized = [f"{cat} ({n}x)" for cat, n in cats.items() if n >= 3]
        if deprioritized:
            lines.append(f"\n**Auto-deprioritized categories** (3+ ignores): {', '.join(deprioritized)}")

    return "\n".join(lines)


def apply_updates(learning, args):
    """Build a new learning dict with updates applied. Never mutates input."""
    updated = deepcopy(learning)
    changes = []

    if args.preferred_language is not None:
        updated["preferred_language"] = args.preferred_language
        changes.append(f"language → {args.preferred_language}")

    if args.preferred_report_format is not None:
        updated["preferred_report_format"] = args.preferred_report_format
        changes.append(f"report_format → {args.preferred_report_format}")

    if args.session_context is not None:
        updated["last_session_context"] = args.session_context
        changes.append(f"session_context → {args.session_context[:60]}...")

    for pattern_str in (args.add_pattern or []):
        patterns = updated.get("decision_patterns", [])
        if pattern_str not in patterns:
            patterns = patterns + [pattern_str]
            if len(patterns) > MAX_PATTERNS:
                removed = patterns[0]
                patterns = patterns[1:]
                changes.append(f"pattern evicted (oldest): {removed}")
            updated["decision_patterns"] = patterns
            changes.append(f"pattern added: {pattern_str}")
        else:
            changes.append(f"pattern already exists: {pattern_str}")

    for question_str in (args.add_checkin_question or []):
        questions = updated.get("custom_check_in_questions", [])
        if question_str not in questions:
            updated["custom_check_in_questions"] = questions + [question_str]
            changes.append(f"check-in question added: {question_str[:50]}")

    for rec_json in (args.add_adopted or []):
        rec = _parse_rec(rec_json)
        if rec:
            adopted = updated.get("adopted_recommendations", [])
            adopted = adopted + [rec]
            if len(adopted) > MAX_RECOMMENDATIONS:
                adopted = adopted[-MAX_RECOMMENDATIONS:]
            updated["adopted_recommendations"] = adopted
            changes.append(f"adopted: {rec.get('category', '?')} ({rec.get('id', '?')})")

    for rec_json in (args.add_ignored or []):
        rec = _parse_rec(rec_json)
        if rec:
            ignored = updated.get("ignored_recommendations", [])
            ignored = ignored + [rec]
            if len(ignored) > MAX_RECOMMENDATIONS:
                ignored = ignored[-MAX_RECOMMENDATIONS:]
            updated["ignored_recommendations"] = ignored
            changes.append(f"ignored: {rec.get('category', '?')} ({rec.get('id', '?')})")

    for pattern_str in (args.remove_pattern or []):
        patterns = updated.get("decision_patterns", [])
        if pattern_str in patterns:
            updated["decision_patterns"] = [p for p in patterns if p != pattern_str]
            changes.append(f"pattern removed: {pattern_str}")

    return updated, changes


def _parse_rec(rec_input):
    """Parse a recommendation from JSON string or structured input."""
    if isinstance(rec_input, dict):
        return rec_input
    try:
        rec = json.loads(rec_input)
        if "date" not in rec:
            rec["date"] = datetime.now().strftime("%Y-%m-%d")
        return rec
    except (json.JSONDecodeError, TypeError):
        print(f"Warning: could not parse recommendation: {rec_input}", file=sys.stderr)
        return None


def main():
    parser = argparse.ArgumentParser(description="Update boss-ai-agent learning config")
    parser.add_argument("--config", required=True, help="Path to config.json")

    # Display modes
    parser.add_argument("--show", action="store_true", help="Show current learning state")
    parser.add_argument("--reset", action="store_true", help="Reset all learning to defaults")
    parser.add_argument("--dry-run", action="store_true", help="Show changes without saving")

    # Simple field updates
    parser.add_argument("--preferred-language", help="Set preferred language (e.g. 'zh', 'en')")
    parser.add_argument("--preferred-report-format", help="Set report format (e.g. 'concise', 'data-heavy')")
    parser.add_argument("--session-context", help="Set last session context summary")

    # List field updates (repeatable)
    parser.add_argument("--add-pattern", action="append", help="Add a decision pattern string")
    parser.add_argument("--remove-pattern", action="append", help="Remove a decision pattern string")
    parser.add_argument("--add-checkin-question", action="append", help="Add a custom check-in question")
    parser.add_argument("--add-adopted", action="append", help="Add adopted recommendation (JSON)")
    parser.add_argument("--add-ignored", action="append", help="Add ignored recommendation (JSON)")

    args = parser.parse_args()

    config = load_config(args.config)
    learning = config.get("learning", deepcopy(DEFAULT_LEARNING))

    # Show mode
    if args.show:
        print(show_learning(learning))
        return

    # Reset mode
    if args.reset:
        if args.dry_run:
            print("Would reset all learning fields to defaults.", file=sys.stderr)
            return
        new_config = {**config, "learning": deepcopy(DEFAULT_LEARNING)}
        save_config(args.config, new_config)
        print("Learning reset to defaults.")
        return

    # Apply updates
    new_learning, changes = apply_updates(learning, args)

    if not changes:
        print("No changes to apply.", file=sys.stderr)
        return

    # Report changes
    print(f"## Learning Updates ({len(changes)} changes)\n")
    for change in changes:
        print(f"- {change}")

    if args.dry_run:
        print(f"\n*Dry run — config not saved.*", file=sys.stderr)
        return

    new_config = {**config, "learning": new_learning}
    save_config(args.config, new_config)
    print(f"\nConfig updated successfully.")


if __name__ == "__main__":
    main()


path: scripts/weekly-report.py
content: #!/usr/bin/env python3
"""Generate a formatted weekly report from MCP tool outputs.

Usage: Claude saves MCP responses to temp files, then runs:
  python weekly-report.py --mentor musk \
    --report report.json \
    --kpi kpi.json \
    --task-stats tasks.json \
    --signals signals.json

Outputs formatted weekly report markdown to stdout.
"""
import argparse
import json
import sys
from datetime import datetime
from pathlib import Path


MAX_JSON_SIZE = 10 * 1024 * 1024  # 10MB

ALLOWED_MENTORS = frozenset({
    "musk", "inamori", "ma", "dalio", "grove", "ren", "son", "jobs", "bezos",
    "buffett", "zhangyiming", "leijun", "caodewang", "chushijian", "meyer", "trout",
})

MEDAL_SENTIMENT = {"gold": "positive", "silver": "neutral", "bronze": "needs attention"}


def load_json(path):
    if not path or not Path(path).exists():
        return None
    file_path = Path(path)
    if file_path.stat().st_size > MAX_JSON_SIZE:
        print(f"Error: {path} exceeds 10MB size limit", file=sys.stderr)
        return None
    try:
        with open(file_path, encoding="utf-8") as f:
            return json.load(f)
    except (json.JSONDecodeError, OSError) as e:
        print(f"Error loading {path}: {e}", file=sys.stderr)
        return None


def format_employee_table(report_data):
    if not report_data:
        return "No report data available.\n"

    employees = report_data if isinstance(report_data, list) else report_data.get("employees", report_data.get("ranking", report_data.get("rankings", [])))
    if not employees:
        return "No employee data.\n"

    lines = ["| Rank | Name | Check-in Rate | Sentiment | Highlights |",
             "|------|------|--------------|-----------|------------|"]
    for i, emp in enumerate(employees, 1):
        name = emp.get("name", "Unknown")
        # Handle both direct rate fields and MCP ranking format {days, medal}
        rate = emp.get("checkin_rate", emp.get("submission_rate"))
        if rate is not None:
            rate_str = f"{rate:.0%}" if isinstance(rate, float) and rate <= 1 else str(rate)
        else:
            days = emp.get("days", 0)
            rate_str = f"{days} days" if days else "0 days"
        sentiment = emp.get("sentiment", emp.get("sentiment_trend"))
        if sentiment is None:
            medal = emp.get("medal", "")
            sentiment = MEDAL_SENTIMENT.get(medal, "N/A")
        highlights = emp.get("highlights", emp.get("summary", ""))
        if isinstance(highlights, list):
            highlights = "; ".join(highlights[:2])
        lines.append(f"| {i} | {name} | {rate_str} | {sentiment} | {highlights} |")
    return "\n".join(lines) + "\n"


def format_task_summary(task_data):
    if not task_data:
        return "No task data available.\n"
    
    stats = task_data if isinstance(task_data, dict) else {}
    total = sum(stats.get(k, 0) for k in ["todo", "in_progress", "in_review", "done", "blocked"])
    if total == 0:
        return "No tasks tracked.\n"
    
    done = stats.get("done", 0)
    blocked = stats.get("blocked", 0)
    completion = f"{done/total:.0%}" if total else "N/A"
    
    lines = [
        f"- **Total tasks**: {total}",
        f"- **Completed**: {done} ({completion})",
        f"- **In progress**: {stats.get('in_progress', 0)}",
        f"- **Blocked**: {blocked}" + (" ⚠️" if blocked > 0 else ""),
        f"- **In review**: {stats.get('in_review', 0)}",
        f"- **Todo**: {stats.get('todo', 0)}",
    ]
    return "\n".join(lines) + "\n"


def format_kpi_summary(kpi_data):
    if not kpi_data:
        return "No KPI data available.\n"
    
    metrics = kpi_data if isinstance(kpi_data, list) else kpi_data.get("metrics", [])
    if not metrics:
        return "No metrics configured.\n"
    
    green, yellow, red = [], [], []
    for m in metrics:
        name = m.get("name", "Unknown")
        current = m.get("current_value", m.get("value", 0))
        target = m.get("target_value", m.get("target", 0))
        if not target:
            green.append(f"- {name}: {current} (no target set)")
            continue
        ratio = current / target if target else 0
        entry = f"- **{name}**: {current} / {target} ({ratio:.0%})"
        if ratio >= 0.9:
            green.append(entry)
        elif ratio >= 0.7:
            yellow.append(entry + " ⚠️")
        else:
            red.append(entry + " 🔴")
    
    lines = []
    if red:
        lines.append("**Off Track:**\n" + "\n".join(red))
    if yellow:
        lines.append("**At Risk:**\n" + "\n".join(yellow))
    if green:
        lines.append("**On Track:**\n" + "\n".join(green))
    return "\n\n".join(lines) + "\n"


def mentor_commentary(mentor):
    comments = {
        "musk": "Focus on velocity — are we moving fast enough? What's the 10x opportunity this week?",
        "inamori": "Focus on people — who needs support? Who grew this week? Is the team harmonious?",
        "ma": "Focus on customers — how did we serve customers better? What change should we embrace?",
        "dalio": "Focus on principles — what mistakes did we learn from? Where can we be more transparent?",
        "grove": "Focus on OKRs — are we hitting our key results? What data supports our decisions?",
        "bezos": "Focus on Day 1 — are we still customer-obsessed? What long-term bets should we make?",
    }
    return comments.get(mentor, f"Apply {mentor}'s philosophy to interpret these results.")


def build_report(mentor, report, kpi, tasks, signals):
    now = datetime.now()
    lines = [
        f"# Weekly Report — Week of {now.strftime('%B %d, %Y')}",
        f"*Mentor: {mentor.title()} | Generated at {now.strftime('%Y-%m-%d %H:%M')}*\n",
        "## Team Performance",
        format_employee_table(report),
        "## Task Progress",
        format_task_summary(tasks),
        "## KPI Health",
        format_kpi_summary(kpi),
    ]

    # Execution signals summary
    if signals:
        sig_list = signals if isinstance(signals, list) else signals.get("signals", [])
        high_sigs = [s for s in sig_list if s.get("score", 0) > 0.5]
        if high_sigs:
            lines.append("## Risk Signals")
            for s in high_sigs[:5]:
                name = s.get("type", s.get("name", "Unknown"))
                score = s.get("score", 0)
                reason = s.get("reason", s.get("description", ""))
                lines.append(f"- **{name}** [{score:.0%}]: {reason}")
            lines.append("")

    lines.extend([
        "## Mentor Perspective",
        f"*{mentor_commentary(mentor)}*\n",
        "## Suggested 1:1 Topics",
        "*(Based on this week's data — read each employee's profile for details)*\n",
        "---",
        "*Generated by Boss AI Agent. Read `references/scenarios.md` for the full report flow.*",
    ])
    return "\n".join(lines)


def main():
    parser = argparse.ArgumentParser(description="Generate weekly report from MCP data")
    parser.add_argument("--mentor", default="musk", help="Active mentor ID")
    parser.add_argument("--report", help="Path to get_report JSON")
    parser.add_argument("--kpi", help="Path to KPI dashboard JSON")
    parser.add_argument("--task-stats", help="Path to task stats JSON")
    parser.add_argument("--signals", help="Path to execution signals JSON")
    args = parser.parse_args()
    if args.mentor not in ALLOWED_MENTORS:
        print(f"Warning: unknown mentor '{args.mentor}', falling back to 'musk'", file=sys.stderr)
        args.mentor = "musk"

    report = load_json(args.report)
    kpi = load_json(args.kpi)
    tasks = load_json(args.task_stats)
    signals = load_json(args.signals)

    print(build_report(args.mentor, report, kpi, tasks, signals))


if __name__ == "__main__":
    main()


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