{"owner":"XiaomiMiMo","repo":"MiMo-Code","hasSkills":true,"totalSkillsCount":92,"totalTokensCount":158140,"categories":["anthropic-skill","root-instruction","plugin-manifest"],"hasMcp":false,"mcpConfig":null,"found":[".agents/skills/drive-mimo/SKILL.md",".agents/skills/effect/SKILL.md","AGENTS.md","packages/cli/README.md","packages/cli/src/acp/README.md","packages/cli/src/provider/sdk/copilot/README.md","packages/cli/src/skill/builtin/.bundle/arxiv/SKILL.md","packages/cli/src/skill/builtin/.bundle/claude-code/SKILL.md","packages/cli/src/skill/builtin/.bundle/codex/SKILL.md","packages/cli/src/skill/builtin/.bundle/compose-next/SKILL.md","packages/cli/src/skill/builtin/.bundle/data-analytics/SKILL.md","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/analyze-data-quality/SKILL.md","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/build-dashboard/SKILL.md","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/build-report/SKILL.md","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/build-report/report-to-google-doc/SKILL.md","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/build-report/report-to-google-slides/SKILL.md","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/build-report/report-to-pdf/SKILL.md","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/create-data-context/SKILL.md","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/design-kpis/SKILL.md","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/gather-business-context/SKILL.md","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/index/SKILL.md","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/jupyter-notebooks/SKILL.md","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/kpi-reporting/SKILL.md","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/market-sizing/SKILL.md","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/metric-diagnostics/SKILL.md","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/product-business-analysis/SKILL.md","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/validate-data/SKILL.md","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/visualize-data/SKILL.md","packages/cli/src/skill/builtin/.bundle/deep-research/SKILL.md","packages/cli/src/skill/builtin/.bundle/docx-official/README.md","packages/cli/src/skill/builtin/.bundle/docx-official/SKILL.md","packages/cli/src/skill/builtin/.bundle/grok-build/SKILL.md","packages/cli/src/skill/builtin/.bundle/html-to-video-pipeline/SKILL.md","packages/cli/src/skill/builtin/.bundle/learn-everything/SKILL.md","packages/cli/src/skill/builtin/.bundle/loop/SKILL.md","packages/cli/src/skill/builtin/.bundle/mate/SKILL.md","packages/cli/src/skill/builtin/.bundle/memory-search/SKILL.md","packages/cli/src/skill/builtin/.bundle/mimocode-docs/SKILL.md","packages/cli/src/skill/builtin/.bundle/modern-python-toolchain/SKILL.md","packages/cli/src/skill/builtin/.bundle/pdf-official/README.md","packages/cli/src/skill/builtin/.bundle/pdf-official/SKILL.md","packages/cli/src/skill/builtin/.bundle/playwright/SKILL.md","packages/cli/src/skill/builtin/.bundle/pptx-official/SKILL.md","packages/cli/src/skill/builtin/.bundle/product-design/SKILL.md","packages/cli/src/skill/builtin/.bundle/product-design/workflows/audit/SKILL.md","packages/cli/src/skill/builtin/.bundle/product-design/workflows/design-qa/SKILL.md","packages/cli/src/skill/builtin/.bundle/product-design/workflows/get-context/SKILL.md","packages/cli/src/skill/builtin/.bundle/product-design/workflows/ideate/SKILL.md","packages/cli/src/skill/builtin/.bundle/product-design/workflows/image-to-code/SKILL.md","packages/cli/src/skill/builtin/.bundle/product-design/workflows/index/SKILL.md","packages/cli/src/skill/builtin/.bundle/product-design/workflows/share/SKILL.md","packages/cli/src/skill/builtin/.bundle/product-design/workflows/url-to-code/SKILL.md","packages/cli/src/skill/builtin/.bundle/product-design/workflows/user-context/SKILL.md","packages/cli/src/skill/builtin/.bundle/research-paper-writing/SKILL.md","packages/cli/src/skill/builtin/.bundle/sales/SKILL.md","packages/cli/src/skill/builtin/.bundle/sales/workflows/analyze-account-signals/SKILL.md","packages/cli/src/skill/builtin/.bundle/sales/workflows/answers-ask-user-input/SKILL.md","packages/cli/src/skill/builtin/.bundle/sales/workflows/apollo/SKILL.md","packages/cli/src/skill/builtin/.bundle/sales/workflows/build-business-case/SKILL.md","packages/cli/src/skill/builtin/.bundle/sales/workflows/build-competitive-brief/SKILL.md","packages/cli/src/skill/builtin/.bundle/sales/workflows/enrich-company-and-contact-data/SKILL.md","packages/cli/src/skill/builtin/.bundle/sales/workflows/find-customer-quotes/SKILL.md","packages/cli/src/skill/builtin/.bundle/sales/workflows/find-key-internal-sources/SKILL.md","packages/cli/src/skill/builtin/.bundle/sales/workflows/follow-up-after-call/SKILL.md","packages/cli/src/skill/builtin/.bundle/sales/workflows/get-rep-call-feedback/SKILL.md","packages/cli/src/skill/builtin/.bundle/sales/workflows/hubspot/SKILL.md","packages/cli/src/skill/builtin/.bundle/sales/workflows/index/SKILL.md","packages/cli/src/skill/builtin/.bundle/sales/workflows/plan-deal-strategy/SKILL.md","packages/cli/src/skill/builtin/.bundle/sales/workflows/prepare-for-meeting/SKILL.md","packages/cli/src/skill/builtin/.bundle/sales/workflows/prioritize-accounts/SKILL.md","packages/cli/src/skill/builtin/.bundle/sales/workflows/review-forecast/SKILL.md","packages/cli/src/skill/builtin/.bundle/sales/workflows/review-rep-call-trends/SKILL.md","packages/cli/src/skill/builtin/.bundle/sales/workflows/sales-company-research/SKILL.md","packages/cli/src/skill/builtin/.bundle/sales/workflows/salesforce/SKILL.md","packages/cli/src/skill/builtin/.bundle/sales/workflows/zoominfo/SKILL.md","packages/cli/src/skill/builtin/.bundle/skill-creator/SKILL.md","packages/cli/src/skill/builtin/.bundle/super-research/README.md","packages/cli/src/skill/builtin/.bundle/super-research/SKILL.md","packages/cli/src/skill/builtin/.bundle/super-research/evals/toy_bench/README.md","packages/cli/src/skill/builtin/.bundle/super-research/evals/toy_dataset/README.md","packages/cli/src/skill/builtin/.bundle/super-research/evals/toy_pipeline/README.md","packages/cli/src/skill/builtin/.bundle/super-research/evals/toy_regression/README.md","packages/cli/src/skill/builtin/.bundle/super-research/evals/toy_repo/README.md","packages/cli/src/skill/builtin/.bundle/xlsx-official/README.md","packages/cli/src/skill/builtin/.bundle/xlsx-official/SKILL.md","packages/cli/src/sync/README.md","packages/cli/test/AGENTS.md","packages/cli/test/fixture/skills/agents-sdk/SKILL.md","packages/cli/test/fixture/skills/agents-sdk/references/callable.md","packages/cli/test/fixture/skills/cloudflare/SKILL.md","packages/cli/test/fixture/skills/index.json","packages/cli/test/fixture/skills/llm-endpoint-demo/SKILL.md"],"skills":{".agents/skills/drive-mimo/SKILL.md":"---\nname: drive-mimo\ndescription: Use when developing or testing the MiMoCode repository and you need to programmatically drive another MiMoCode (mimo) process. Supports headless `mimo run` with JSON events and interactive TUI via tmux for behavior, integration, and visual regression testing. Covers an installed `mimo` binary or a dev build launched from source with `bun dev`; do not use it for ordinary MiMoCode task execution.\n---\n\n# Drive MiMo\n\n## Overview\n\nTwo **interfaces** for driving a separate mimo process:\n\n| Interface | Command | Use when |\n|------|---------|----------|\n| **Headless** | `mimo run --format json` | Scripted tasks, CI, event validation |\n| **TUI** | `mimo` in tmux | Interactive flow, permission dialogs, keybindings, visual regression |\n\n**Core principle:** Every run produces parseable evidence. No eyeballing.\n\nAlways drive an *isolated* instance: give each run a fresh `MIMOCODE_HOME` and a throwaway workspace so it never touches your own config, memory, or session DB.\n\n### Two ways to launch — orthogonal to interface\n\nThe interface (headless vs TUI, above) is *what you drive*. How the process is\n**launched** is a separate axis — either can be launched either way:\n\n| Launcher | Command | Use when |\n|----------|---------|----------|\n| **Installed binary** | `mimo …` | Testing a released/installed build |\n| **Dev (from source)** | `bun dev …` | Debugging mimocode itself — runs `src/index.ts` directly, no build step, picks up local code changes |\n\nEverything below uses `mimo` for brevity. To drive a **dev build** instead,\nsubstitute `bun dev` for `mimo` and run from the repo root — every flag,\nJSON event, and tmux technique is identical. See the Dev Mode section.\n\n## Prerequisites\n\n```bash\n# mimo binary must be on PATH (installed-binary launcher)\nwhich mimo || echo \"mimo not found on PATH\"\n\n# OR: dev launcher — run from the mimocode repo root, needs bun\nwhich bun || echo \"bun not found — needed for dev mode\"\n\n# tmux (for TUI interface)\nwhich tmux || echo \"tmux not found — install it for TUI mode\"\n```\n\n> **Running the `wait-for-text.sh` helper:** invoke it as\n> `./scripts/wait-for-text.sh …` from this skill's directory. The repository copy\n> is executable and can be called directly.\n\n---\n\n## Dev Mode (debugging mimocode itself)\n\nWhen the goal is to debug **mimocode's own code**, launch from source with\n`bun dev` instead of the installed `mimo` binary. It runs\n`packages/cli/src/index.ts` directly — no build step — so local edits take\neffect on the next launch.\n\n**Key facts:**\n\n- Run from the **repo root**. `bun dev` == `bun run dev`.\n- It is the dev equivalent of the `mimo` command: same CLI, same subcommands\n  and flags. `bun dev --help`, `bun dev run …`, `bun dev serve`, etc.\n- Args pass straight through, so **both interfaces work under dev**:\n  - Headless: `bun dev run --format json --dangerously-skip-permissions …`\n  - TUI:      `bun dev <workspace>` (positional workspace arg, as with `mimo`)\n- If `MIMOCODE_HOME` is not set, dev defaults it to a repo-local `.dev-home`\n  dir. For an isolated driven run, set `MIMOCODE_HOME=$(mktemp -d)` explicitly\n  just like with the binary.\n\n**Substitution rule:** anywhere Part 1 / Part 2 / Part 3 below say `mimo`,\nreplace it with `bun dev` (invoked from the repo root) to drive a dev build.\n\n```bash\n# Headless, dev build (from repo root)\nREPO=/path/to/mimocode/checkout   # your local mimocode repo root\nMIMOCODE_HOME=$(mktemp -d) bun --cwd \"$REPO\" dev run \\\n  --format json --dangerously-skip-permissions --dir \"$WORKSPACE\" \\\n  < \"$PROMPT\" > /tmp/mimo-dev.jsonl 2>&1\n\n# TUI, dev build in tmux (from repo root)\ntmux new-session -d -s \"$SESSION\" -x 120 -y 30 \\\n  \"cd $REPO && MIMOCODE_HOME=$(mktemp -d) MIMOCODE_PURE=true bun dev $WORKSPACE; sleep 999\"\n```\n\n---\n\n## Part 1: Headless Mode (`mimo run`)\n\n### Launch\n\n```bash\nPROMPT=$(mktemp -t mimo-drive.XXXXXX)\ncat >\"$PROMPT\" <<'EOF'\nYour task here.\nEOF\n\nMIMOCODE_HOME=$(mktemp -d) mimo run \\\n  --format json \\\n  --dangerously-skip-permissions \\\n  --dir \"$WORKSPACE\" \\\n  < \"$PROMPT\" > /tmp/mimo-out.jsonl 2>&1\n\nEXIT=$?\n```\n\n### Key flags\n\n| Flag | Purpose |\n|------|---------|\n| `--format json` | Structured JSONL events to stdout |\n| `--dangerously-skip-permissions` | Auto-approve all permissions |\n| `--model provider/model` | Override model |\n| `--session SID` | Continue existing session |\n| `--continue` | Continue last session |\n| `--file path` | Attach file to message |\n| `--dir path` | Working directory |\n\n### JSON event types\n\n`--format json` writes one JSON object per line. **Every** event has the shape\n`{\"type\": ..., \"timestamp\": <ms>, \"sessionID\": \"ses_...\", ...payload}` — the\n`sessionID` is a field on each event, not a standalone event. The payload for\nmost events is nested under `part`.\n\nEmitted event types (from the run event stream):\n\n```\n{\"type\":\"step_start\",\"timestamp\":...,\"sessionID\":\"ses_abc\",\"part\":{...}}\n{\"type\":\"text\",\"timestamp\":...,\"sessionID\":\"ses_abc\",\"part\":{\"type\":\"text\",\"text\":\"I'll create the file...\",\"time\":{...}}}\n{\"type\":\"reasoning\",\"timestamp\":...,\"sessionID\":\"ses_abc\",\"part\":{\"type\":\"reasoning\",\"text\":\"The user wants...\"}}\n{\"type\":\"tool_use\",\"timestamp\":...,\"sessionID\":\"ses_abc\",\"part\":{\"type\":\"tool\",\"tool\":\"write\",\"state\":{\"status\":\"completed\",...}}}\n{\"type\":\"step_finish\",\"timestamp\":...,\"sessionID\":\"ses_abc\",\"part\":{...}}\n{\"type\":\"error\",\"timestamp\":...,\"sessionID\":\"ses_abc\",\"error\":{...}}\n```\n\nNotes that matter for parsing:\n\n- **No `session.id`, no `tool_result`, no `session.status` event.** A `tool_use`\n  is emitted **once** per tool part when it reaches `completed` or `error` — the\n  result/output is inside `part.state`, there is no separate result event.\n- **`tool_use` identifies the tool via `part.tool`** (a bare string, e.g.\n  `\"tool\":\"write\"`) — there is no `.tool.name` and no top-level `.name`.\n- **`text` / `reasoning` text lives at `part.text`**, not top-level `.text`.\n- **`reasoning` is only emitted when `--thinking` is passed.** Without it, no\n  reasoning events appear.\n- **Completion is not a stream event.** The process finishes when the run\n  completes; the reliable completion signal is **process exit** (exit code 0),\n  not any line in the JSONL.\n\n### Validation patterns\n\n```bash\n# Completion — the real signal is the exit code, not a stream event\n[ $EXIT -eq 0 ] || echo \"FAIL: exit $EXIT\"\n\n# No errors\ngrep -q '\"type\":\"error\"' /tmp/mimo-out.jsonl && echo \"FAIL: errors found\"\n\n# A specific tool was used (match part.tool, the bare string)\ngrep -q '\"tool\":\"write\"' /tmp/mimo-out.jsonl || echo \"FAIL: write tool not called\"\n\n# Text output contains expected string (text is at .part.text)\ngrep '\"type\":\"text\"' /tmp/mimo-out.jsonl | jq -r '.part.text' | grep -q \"expected\"\n\n# Robust tool check via jq (works regardless of key ordering)\njq -e 'select(.type==\"tool_use\") | .part.tool==\"write\"' /tmp/mimo-out.jsonl >/dev/null \\\n  || echo \"FAIL: write tool not called\"\n```\n\n\n### Timeout\n\n```bash\ntimeout 120 mimo run --format json --dangerously-skip-permissions < \"$PROMPT\"\n[ $? -eq 124 ] && echo \"FAIL: timed out\"\n```\n\n---\n\n## Part 2: TUI Mode (tmux)\n\n### Isolation variables\n\n| Variable | Purpose |\n|---|---|\n| `MIMOCODE_HOME` | **Required.** Fresh `mktemp -d` per run. Sandboxes DB, config, cache. |\n| `MIMOCODE_PURE=true` | Disable external plugins. |\n| `MIMOCODE_DISABLE_GIT=true` | Skip git ops if workspace isn't a real repo. |\n\n### Launch TUI in tmux\n\n```bash\n# Create isolated environment\nMHOME=$(mktemp -d)\nWORKSPACE=$(mktemp -d)\nSESSION=\"mimo-drive-$$\"\n\n# Launch mimo TUI in tmux (workspace is a positional arg, NOT --dir)\ntmux new-session -d -s \"$SESSION\" -x 120 -y 30 \\\n  \"MIMOCODE_HOME=$MHOME MIMOCODE_PURE=true mimo $WORKSPACE; sleep 999\"\n\n# Wait for the TUI to render its input prompt\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"$PROMPT_RE\" -T 15\n```\n\nWhere `PROMPT_RE` is a language-neutral pattern for the input prompt. The\nprompt placeholder is localized, so match on the stable markers rather than a\nlocalized string:\n\n```bash\n# Matches the prompt line regardless of UI language:\n#   the \">\" input caret, the \"Ask\" English placeholder, or a \"/\" command hint\nPROMPT_RE='>|Ask|/[a-z]'\n```\n\nIf a run's UI language is known and fixed, you may match its literal\nplaceholder instead — but prefer the neutral pattern for portability.\n\n### Send input\n\n```bash\n# Type a message (literal text, then Enter)\ntmux send-keys -t \"$SESSION:0.0\" -l -- \"Create a file called hello.txt with content 'world'\"\ntmux send-keys -t \"$SESSION:0.0\" Enter\n\n# Special keys\ntmux send-keys -t \"$SESSION:0.0\" C-c          # Cancel\ntmux send-keys -t \"$SESSION:0.0\" C-d          # EOF\ntmux send-keys -t \"$SESSION:0.0\" Escape       # Escape\ntmux send-keys -t \"$SESSION:0.0\" Tab          # Tab completion\ntmux send-keys -t \"$SESSION:0.0\" Up           # History up\ntmux send-keys -t \"$SESSION:0.0\" Down         # History down\ntmux send-keys -t \"$SESSION:0.0\" Enter        # Submit\n```\n\n### Capture output\n\n```bash\n# Current screen\ntmux capture-pane -t \"$SESSION:0.0\" -p\n\n# Full scrollback\ntmux capture-pane -t \"$SESSION:0.0\" -p -S -\n\n# Last 50 lines\ntmux capture-pane -t \"$SESSION:0.0\" -p -S -50\n```\n\n### Wait for state changes\n\n```bash\n# Wait for agent to start processing\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"thinking\\|reading\\|writing\" -T 30\n\n# Wait for tool permission prompt\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"Allow\\|Deny\\|permission\\|approve\" -T 30\n\n# Wait for completion\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"completed\\|done\\|finished\\|idle\" -T 120\n\n# Wait for error\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"error\\|failed\\|Error\" -T 30\n\n# Custom regex\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"hello\\.txt.*world\" -T 30\n```\n\n### Handle permission dialogs\n\n```bash\n# Wait for permission prompt, then approve\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"Allow\\|approve\" -T 30\ntmux send-keys -t \"$SESSION:0.0\" -l -- \"y\"\ntmux send-keys -t \"$SESSION:0.0\" Enter\n\n# Or deny\ntmux send-keys -t \"$SESSION:0.0\" -l -- \"n\"\ntmux send-keys -t \"$SESSION:0.0\" Enter\n```\n\n### Multi-turn interaction\n\n```bash\n# Turn 1: send initial message\ntmux send-keys -t \"$SESSION:0.0\" -l -- \"Create a TypeScript file that adds two numbers\"\ntmux send-keys -t \"$SESSION:0.0\" Enter\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"completed\\|done\" -T 120\n\n# Turn 2: follow-up\ntmux send-keys -t \"$SESSION:0.0\" -l -- \"Now add a test for it\"\ntmux send-keys -t \"$SESSION:0.0\" Enter\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"completed\\|done\" -T 120\n\n# Verify result\ntmux capture-pane -t \"$SESSION:0.0\" -p -S - | grep -i \"pass\\|fail\"\n```\n\n### Cleanup\n\n```bash\ntmux kill-session -t \"$SESSION\" 2>/dev/null\nrm -rf \"$MHOME\" \"$WORKSPACE\"\n```\n\n---\n\n## Part 3: Scenarios\n\n### S1: Smoke (headless)\n\n```bash\ntest_smoke() {\n  local P=$(mktemp) MHOME=$(mktemp -d)\n  echo \"Say hello\" > \"$P\"\n  MIMOCODE_HOME=$MHOME mimo run --format json --dangerously-skip-permissions \\\n    < \"$P\" > /tmp/s1.jsonl 2>&1\n  local E=$?\n  rm -rf \"$MHOME\" \"$P\"\n  [ $E -eq 0 ] && grep -q '\"type\":\"text\"' /tmp/s1.jsonl && echo \"PASS\" || echo \"FAIL\"\n}\n```\n\n### S2: Tool use (headless)\n\n```bash\ntest_tool_use() {\n  local P=$(mktemp) MHOME=$(mktemp -d) WS=$(mktemp -d)\n  echo 'Create file test.txt with content \"hello\"' > \"$P\"\n  MIMOCODE_HOME=$MHOME mimo run --format json --dangerously-skip-permissions --dir \"$WS\" \\\n    < \"$P\" > /tmp/s2.jsonl 2>&1\n  local E=$?\n  local OK=true\n  [ $E -ne 0 ] && OK=false\n  ! grep -q '\"tool\":\"write\"' /tmp/s2.jsonl && OK=false\n  [ ! -f \"$WS/test.txt\" ] && OK=false\n  rm -rf \"$MHOME\" \"$WS\" \"$P\"\n  $OK && echo \"PASS\" || echo \"FAIL\"\n}\n```\n\n### S3: TUI interactive flow\n\n```bash\ntest_tui_interactive() {\n  local MHOME=$(mktemp -d) WS=$(mktemp -d) SID=\"mimo-s3-$$\"\n  local PROMPT_RE='>|Ask|/[a-z]'\n  tmux new-session -d -s \"$SID\" -x 120 -y 30 \"MIMOCODE_HOME=$MHOME MIMOCODE_PURE=true mimo $WS; sleep 999\"\n\n  # Wait for prompt\n  bash scripts/wait-for-text.sh -t \"$SID:0.0\" -p \"$PROMPT_RE\" -T 15 || { echo \"FAIL: no prompt\"; tmux kill-session -t $SID; return 1; }\n\n  # Send task\n  tmux send-keys -t \"$SID:0.0\" -l -- \"Create hello.txt with content 'world'\"\n  tmux send-keys -t \"$SID:0.0\" Enter\n\n  # Wait for completion (agent shows elapsed time like \"· 9.8s\")\n  bash scripts/wait-for-text.sh -t \"$SID:0.0\" -p \"· [0-9]\" -T 120 || { echo \"FAIL: no completion\"; tmux kill-session -t $SID; return 1; }\n\n  # Verify file\n  [ -f \"$WS/hello.txt\" ] && echo \"PASS\" || echo \"FAIL\"\n  tmux kill-session -t \"$SID\" 2>/dev/null\n  rm -rf \"$MHOME\" \"$WS\"\n}\n```\n\n### S4: TUI permission handling\n\n```bash\ntest_tui_permission() {\n  local MHOME=$(mktemp -d) WS=$(mktemp -d) SID=\"mimo-s4-$$\"\n  local PROMPT_RE='>|Ask|/[a-z]'\n  tmux new-session -d -s \"$SID\" -x 120 -y 30 \"MIMOCODE_HOME=$MHOME MIMOCODE_PURE=true mimo $WS; sleep 999\"\n\n  bash scripts/wait-for-text.sh -t \"$SID:0.0\" -p \"$PROMPT_RE\" -T 15\n\n  # Ask for something that needs permission (no --dangerously-skip-permissions in TUI)\n  tmux send-keys -t \"$SID:0.0\" -l -- \"Run the command: echo hello\"\n  tmux send-keys -t \"$SID:0.0\" Enter\n\n  # Wait for permission prompt\n  bash scripts/wait-for-text.sh -t \"$SID:0.0\" -p \"Allow\\|approve\\|permission\\|y/n\" -T 30 || { echo \"FAIL: no permission prompt\"; tmux kill-session -t $SID; return 1; }\n\n  # Approve\n  tmux send-keys -t \"$SID:0.0\" -l -- \"y\"\n  tmux send-keys -t \"$SID:0.0\" Enter\n\n  # Wait for completion\n  bash scripts/wait-for-text.sh -t \"$SID:0.0\" -p \"· [0-9]\" -T 60\n\n  tmux capture-pane -t \"$SID:0.0\" -p | grep -q \"hello\" && echo \"PASS\" || echo \"FAIL\"\n  tmux kill-session -t \"$SID\" 2>/dev/null\n  rm -rf \"$MHOME\" \"$WS\"\n}\n```\n\n### S5: TUI keybindings\n\n```bash\ntest_tui_keybindings() {\n  local MHOME=$(mktemp -d) WS=$(mktemp -d) SID=\"mimo-s5-$$\"\n  local PROMPT_RE='>|Ask|/[a-z]'\n  tmux new-session -d -s \"$SID\" -x 120 -y 30 \"MIMOCODE_HOME=$MHOME MIMOCODE_PURE=true mimo $WS; sleep 999\"\n\n  bash scripts/wait-for-text.sh -t \"$SID:0.0\" -p \"$PROMPT_RE\" -T 15\n\n  # Test Ctrl+C cancels input\n  tmux send-keys -t \"$SID:0.0\" -l -- \"some partial input\"\n  tmux send-keys -t \"$SID:0.0\" C-c\n\n  # Screen should still show prompt (not exit)\n  sleep 1\n  tmux capture-pane -t \"$SID:0.0\" -p | grep -qE \"$PROMPT_RE\" && echo \"PASS: Ctrl+C didn't exit\" || echo \"FAIL: Ctrl+C exited\"\n\n  # Test Escape\n  tmux send-keys -t \"$SID:0.0\" Escape\n  sleep 0.5\n\n  tmux kill-session -t \"$SID\" 2>/dev/null\n  rm -rf \"$MHOME\" \"$WS\"\n}\n```\n\n---\n\n## Batch Runner\n\n```bash\nrun_all() {\n  local PASS=0 FAIL=0 RESULTS=()\n  for fn in test_smoke test_tool_use test_tui_interactive test_tui_permission test_tui_keybindings; do\n    echo \"--- $fn ---\"\n    if $fn 2>/dev/null; then PASS=$((PASS+1)); else FAIL=$((FAIL+1)); RESULTS+=(\"$fn: FAIL\"); fi\n  done\n  echo \"=== $PASS passed, $FAIL failed ===\"\n  [ ${#RESULTS[@]} -gt 0 ] && printf '  %s\\n' \"${RESULTS[@]}\"\n  [ $FAIL -eq 0 ]\n}\n```\n\n---\n\n## Quick Reference\n\n| Task | Command |\n|------|---------|\n| Headless run | `MIMOCODE_HOME=$(mktemp -d) mimo run --format json --dangerously-skip-permissions \"prompt\"` |\n| TUI launch | `tmux new-session -d -s test -x 120 -y 30 \"MIMOCODE_HOME=$(mktemp -d) mimo $WORKSPACE; sleep 999\"` |\n| Send text | `tmux send-keys -t test:0.0 -l -- \"text\" && tmux send-keys -t test:0.0 Enter` |\n| Capture screen | `tmux capture-pane -t test:0.0 -p -S -` |\n| Wait for text | `bash scripts/wait-for-text.sh -t test:0.0 -p \"pattern\" -T 30` |\n| Send Ctrl+C | `tmux send-keys -t test:0.0 C-c` |\n| Approve permission | `tmux send-keys -t test:0.0 -l -- \"y\" && tmux send-keys -t test:0.0 Enter` |\n| Cleanup | `tmux kill-session -t test && rm -rf $MHOME` |\n",".agents/skills/effect/SKILL.md":"---\nname: effect\ndescription: Answer questions about the Effect framework\n---\n\n# Effect\n\nThis codebase uses Effect, a framework for writing typescript.\n\n## How to Answer Effect Questions\n\n1. Clone the Effect repository: `https://github.com/Effect-TS/effect-smol` to\n   `.opencode/references/effect-smol` in this project NOT the skill folder.\n2. Use the explore agent to search the codebase for answers about Effect patterns, APIs, and concepts\n3. Provide responses based on the actual Effect source code and documentation\n\n## Guidelines\n\n- Always use the explore agent with the cloned repository when answering Effect-related questions\n- Reference specific files and patterns found in the Effect codebase\n- Do not answer from memory - always verify against the source\n","AGENTS.md":"# MiMo-Code\n\n## Conventions\n\n- Use MiMoCode Compose skills when available, otherwise use superpowers skill if installed.\n- To regenerate the JavaScript SDK, run `./packages/sdk/script/build.ts`.\n- ALWAYS USE PARALLEL TOOLS WHEN APPLICABLE.\n- The default branch in this repo is `main`.\n- CI triggers on `main`.\n- Prefer automation: execute requested actions without confirmation unless blocked by missing info or safety/irreversibility.\n- Install deps with `bun ci` (= `bun install --frozen-lockfile`) — install per `bun.lock`, don't mutate the lockfile. ⛔ Do NOT use `bun install`/`npm install`.\n- Comments, docs, shipped skill content and test assertions use synthetic values, never machine-specific ones — `/tmp/example` for paths, `test/model` for model refs, `feat/example` for branches.\n- Do not edit `packages/cli/migration/*/migration.sql` that already shipped — engines have applied those journals; new schema changes get a **new** migration directory under `packages/cli/migration/`.\n\n## Style Guide\n\nMatch the style of the surrounding code. The rules below apply across the repository.\n\n### Types and errors\n\n- Avoid using the `any` type\n- Inside Effect code, express failures through the Effect error channel (`Effect.try`, `Effect.tryPromise`, `Effect.catchTag`, typed errors) rather than `try`/`catch`; plain scripts and non-Effect code may use `try`/`catch`\n\n### Bun and Node runtimes\n\n- Use Bun APIs where the runtime is Bun-only, like `Bun.file()` in the TUI (`src/cli/cmd/tui/`); build-time macros are fine anywhere, as they never reach the shipped runtime\n- In core code reachable from `src/node.ts`, prefer the Node equivalent when one exists — `createHash` over `Bun.CryptoHasher`, `prepare()` over bun:sqlite's `query()` — as that code also ships through `script/build-node.ts` and must run on plain Node\n- Bun-only calls in core escape both `typecheck` and `bun test`, which run on Bun; existing usage needs no urgent removal, and APIs with no Node equivalent may stay until a runtime seam exists\n\n### Config modules\n\nIn `src/config`, follow the existing self-export pattern at the top of the file (for example `export * as ConfigAgent from \"./agent\"`) when adding a new config module.\n\n### Schema Definitions (Drizzle)\n\nUse snake_case for field names so column names don't need to be redefined as strings.\n\n```ts\n// Good\nconst table = sqliteTable(\"session\", {\n  id: text().primaryKey(),\n  project_id: text().notNull(),\n  created_at: integer().notNull(),\n})\n\n// Bad\nconst table = sqliteTable(\"session\", {\n  id: text(\"id\").primaryKey(),\n  projectID: text(\"project_id\").notNull(),\n  createdAt: integer(\"created_at\").notNull(),\n})\n```\n\n### Reading a nullable column\n\nTwo independent absences meet in one expression, and only one of them is\n`undefined`. `.get()` yields `undefined` when no row matches — Drizzle normalises\nthe driver's `null` there — while a nullable column's SQL `NULL` arrives as\n`null`. So `row?.some_column` is `T | null | undefined`.\n\nWhen a caller only asks \"is there a value\", flatten to `undefined`, and write the\nflattening as an annotation rather than an `as` cast:\n\n```ts\n// Good — the compiler enforces it; deleting the `?? undefined` is a type error\nconst boundary: MessageID | undefined = row?.last_checkpoint_message_id ?? undefined\n\n// Bad — the cast removes `null` from the union without converting anything,\n// so the declared type is untrue at runtime\nreturn row?.last_checkpoint_message_id as MessageID | undefined\n```\n\nDiscriminate a possibly-absent value with truthiness or `== null`, never with\n`=== undefined` / `!== undefined`. Because `null !== undefined` is `true`, such a\nguard typechecks, reads correctly in review, and does nothing.\n\n## Testing\n\n- Avoid mocks as much as possible\n- Test actual implementation, do not duplicate logic into tests\n","packages/cli/README.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2FREADME.md -->","packages/cli/src/acp/README.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Facp%2FREADME.md -->","packages/cli/src/provider/sdk/copilot/README.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fprovider%2Fsdk%2Fcopilot%2FREADME.md -->","packages/cli/src/skill/builtin/.bundle/arxiv/SKILL.md":"---\nname: arxiv\ndescription: \"Use this skill whenever the user wants to find, read, cite, track, download, or analyze academic papers on arXiv. That includes: searching papers by topic, author, category, or arXiv ID; fetching abstracts or full metadata; generating BibTeX citations; downloading PDFs; listing the latest submissions in a field (e.g. cs.AI daily digest); checking a paper's citation impact; finding who cites a paper, what it references, or related-paper recommendations. Trigger on mentions of 'arXiv', an arXiv ID (e.g. 2601.02780 or hep-th/0601001), an arxiv.org URL, 'paper search', 'literature review', 'find papers about X', 'cite this paper', or 'what's new in cs.LG'.\"\nversion: 2.0.0\nlicense: MIT\nplatforms: [linux, macos, windows]\n---\n\n# arXiv Research\n\nSearch, read, cite, and analyze academic papers using the free arXiv API and Semantic Scholar API. No API keys, no dependencies — the bundled script uses only the Python stdlib.\n\n## Quick Start: the `arxiv.py` script\n\nPrefer `scripts/arxiv.py` over raw `curl` — it handles Atom XML parsing, versioned IDs, withdrawn-paper detection, and produces clean readable (or `--json`) output.\n\n| Goal | Command |\n|------|---------|\n| Search papers | `python scripts/arxiv.py search \"GRPO reinforcement learning\" --max 10 --sort date` |\n| Filtered search | `python scripts/arxiv.py search \"attention\" --author vaswani --category cs.CL` |\n| Full metadata + abstract | `python scripts/arxiv.py get 2601.02780,1706.03762` |\n| BibTeX citation | `python scripts/arxiv.py bibtex 2601.02780` |\n| Download PDF | `python scripts/arxiv.py download 2601.02780 --dest ./papers` |\n| Latest in a category | `python scripts/arxiv.py new cs.CL --max 10` |\n| Who cites this paper | `python scripts/arxiv.py cites 2601.02780 --max 20` |\n| What this paper cites | `python scripts/arxiv.py refs 2601.02780` |\n| Related-paper recommendations | `python scripts/arxiv.py similar 2601.02780` |\n| Machine-readable output | append `--json` to any command |\n\nCommon flags: `--max N` (result count), `--sort relevance|date|updated`, `--start N` (pagination offset, search only), `--json`.\n\n## Reading Paper Content\n\nAfter finding a paper, read it with the `webfetch` tool:\n\n- Abstract page (fast, metadata + abstract): `https://arxiv.org/abs/2601.02780`\n- Full paper as HTML (best for reading, when available): `https://arxiv.org/html/2601.02780`\n- PDF: `https://arxiv.org/pdf/2601.02780`\n\nIf HTML is unavailable and the PDF must be processed locally, `download` it first, then use a PDF-processing skill.\n\n## Recommended Research Workflows\n\n**Literature review on a topic**\n1. `search \"topic\" --sort date --max 15` — recent work\n2. `search \"topic\" --max 15` — seminal work (relevance-sorted)\n3. Cross-check impact: `python scripts/arxiv.py get ID` then `cites ID --max 5` for citation counts\n4. Read the top candidates via `webfetch` on the abs/html URLs\n5. `bibtex ID1,ID2,...` for the papers you keep\n\n**Deep-dive a single paper**\n1. `get ID` — full abstract, versions, journal ref, DOI\n2. `refs ID` — what it builds on\n3. `cites ID` — follow-up work (sorted by citation count)\n4. `similar ID` — related papers you might have missed\n5. `webfetch` the HTML/PDF for full text\n\n**Stay current in a field**\n- `new cs.AI --max 20` — latest submissions in a category\n- Category taxonomy: https://arxiv.org/category_taxonomy — common ones: `cs.AI`, `cs.CL` (NLP), `cs.CV`, `cs.LG`, `cs.CR`, `stat.ML`, `math.OC`\n\n## Raw API Reference (when the script isn't enough)\n\nThe script covers most needs; use the raw APIs for advanced queries.\n\n### arXiv API (Atom XML)\n\n```bash\ncurl -s \"https://export.arxiv.org/api/query?search_query=all:transformer&max_results=5\"\n```\n\nField prefixes: `all:` (everything), `ti:` (title), `au:` (author), `abs:` (abstract), `cat:` (category), `co:` (comment, e.g. `co:accepted+NeurIPS`).\n\nBoolean syntax (URL-encode spaces as `+`):\n\n```\nall:GPT+OR+all:BERT              # OR\nall:language+model+ANDNOT+all:vision   # AND NOT\nti:\"chain+of+thought\"            # exact phrase\nau:hinton+AND+cat:cs.LG          # combined\n```\n\nParameters: `sortBy` (`relevance`|`lastUpdatedDate`|`submittedDate`), `sortOrder`, `start`, `max_results`, `id_list` (comma-separated IDs).\n\n### Semantic Scholar API (JSON)\n\narXiv has no citation data — Semantic Scholar fills that gap (free, ~1 req/sec unauthenticated).\n\n```bash\n# Paper details with citation counts\ncurl -s \"https://api.semanticscholar.org/graph/v1/paper/arXiv:2601.02780?fields=title,citationCount,influentialCitationCount,tldr\"\n\n# Author profile\ncurl -s \"https://api.semanticscholar.org/graph/v1/author/search?query=Yann+LeCun&fields=name,hIndex,citationCount,paperCount\"\n\n# Keyword search returning JSON (alternative to arXiv search)\ncurl -s \"https://api.semanticscholar.org/graph/v1/paper/search?query=GRPO&limit=5&fields=title,year,citationCount,externalIds\"\n```\n\nUseful fields: `title`, `authors`, `year`, `abstract`, `tldr` (AI summary), `citationCount`, `influentialCitationCount`, `isOpenAccess`, `openAccessPdf`, `fieldsOfStudy`, `publicationVenue`, `externalIds` (arXiv ID, DOI).\n\n## Important Details\n\n**Rate limits** — arXiv: ~1 request / 3 seconds; Semantic Scholar: ~1 request / second. Space out consecutive calls; the script exits with a clear message on HTTP 429.\n\n**ID formats** — new style `2402.03300`, old style `hep-th/0601001`. Both work everywhere.\n\n**Versioning** — `arxiv.org/abs/2601.02780` resolves to the latest version; `...v2` is a specific immutable version. `bibtex` and `download` preserve the version suffix so citations match the content you actually read (later versions can change substantially).\n\n**Withdrawn papers** — the script flags entries whose abstract indicates withdrawal/retraction with `[WITHDRAWN]`. Don't cite these without noting the status.\n\n**Listings caveat** — `new CATEGORY` sorts by submission date via the search API; the official \"new today\" listing at `https://arxiv.org/list/cs.AI/new` may group slightly differently (cross-lists, replacements).\n","packages/cli/src/skill/builtin/.bundle/claude-code/SKILL.md":"---\nname: claude-code\ndescription: \"Operate Claude Code CLI (v2.1+) via the terminal only when the user explicitly requests Claude Code or names this skill. Covers print mode (-p), interactive tmux sessions, and background (--bg) orchestration.\"\nversion: 2.0.0\nlicense: MIT\nplatforms: [linux, macos, windows]\n---\n\n# Claude Code Delegation\n\nDelegate coding work to Claude Code, Anthropic's autonomous coding agent CLI.\n\n**Setup (once):** `npm install -g @anthropic-ai/claude-code && claude auth login` · verify with `claude auth status` / `claude doctor`. CI token: `claude setup-token`. Full auth/install variants → `references/flags.md`.\n\n**Platform check (before running anything):** detect the OS first. All shell examples in this skill are POSIX (bash). Linux/macOS run them as-is. On **Windows**, run Claude Code natively in PowerShell/Git Bash for print and background modes, but interactive tmux orchestration requires **WSL**. Shell-syntax translation table (quoting, env vars, piping, paths) → `references/platforms.md`.\n\n## Mode Selection (decide FIRST)\n\n| Task shape | Mode | Why |\n|---|---|---|\n| One-shot task: fix bug, add feature, review diff, extract data | **Print `-p`** ← default | No PTY, no dialogs, structured output |\n| Multi-turn iterate: refactor → review → fix → test; needs slash commands | **Interactive tmux** → `references/interactive-tmux.md` | Full REPL, requires dialog handling |\n| Long-running, shouldn't block; large fan-out supervision | **Background `--bg`** | Native supervision via `claude agents` |\n| High-stakes PR review | **`claude ultrareview [pr#]`** | Cloud multi-agent, exit-code driven (uploads diff to cloud — never on branches with secrets) |\n\nDo NOT hand-roll tmux fan-outs for parallel work — prefer `--bg` + `claude agents --json --all`.\n\n## Print Mode (the 90% path)\n\n```\nterminal(command=\"claude -p 'Fix the auth bug in src/auth.py' \\\n  --allowedTools 'Read,Edit' --max-turns 10 --output-format json\",\n  workdir=\"/path/to/project\", timeout=180)\n```\n\n**Always set:** `workdir` · `--max-turns` (5–10; print-mode only) · `--allowedTools` (least privilege: `Read,Edit,Write,Bash`, patterns like `Bash(git *)`).\n\n**JSON result fields:** `result` (text) · `session_id` (for resume) · `subtype` (`success` | `error_max_turns` | `error_budget`) · `total_cost_usd` · `num_turns` · `structured_output` (with `--json-schema`).\n\n**Common variants:**\n\n```bash\ngit diff main... | claude -p 'Review for bugs' --max-turns 1     # pipe input, cheapest review\nclaude -p 'Continue: add pooling' --resume <session_id>          # resume; --continue = latest in cwd; --fork-session = branch\nclaude -p 'List functions' --output-format json --json-schema '<schema>' --max-turns 5   # structured extraction (needs turns to read files)\nclaude --bare -p 'task' --settings ci.json                       # CI: skips hooks/plugins/CLAUDE.md; auth = ANTHROPIC_API_KEY only\nclaude -p 'task' --max-budget-usd 0.50 --fallback-model haiku    # cost cap (min ~$0.05) + overload fallback\n```\n\nStreaming, stream-json events, bidirectional input, cache-reuse (`--exclude-dynamic-system-prompt-sections`) → `references/print-mode.md`.\n\n## Background Mode\n\n```bash\nclaude --bg 'investigate flaky test in tests/api.test.ts'   # NOT compatible with -p\nclaude agents --json --all                                   # list/inspect\nclaude attach <id> | logs <id> | stop <id> | respawn <id> | rm <id>\n```\n\n## Guardrails & Gotchas (violations break agents)\n\n1. **`-p` auto-skips trust/permission dialogs** (any non-TTY does) — only run in trusted directories.\n2. **Interactive mode = tmux required** (Windows: only inside WSL — never attempt tmux in PowerShell/cmd; fall back to `-p` or `--bg`); two startup dialogs, and the `--dangerously-skip-permissions` dialog defaults to **\"No, exit\"** (must send `Down` then `Enter`). Full patterns → `references/interactive-tmux.md`.\n3. **Session resume is per-directory** — `--continue` only finds sessions from the same cwd.\n4. **Slash commands don't work in `-p`** — describe the task in natural language instead.\n5. **Context >70% degrades quality** — in interactive sessions monitor `/context`, use `/compact`.\n6. **Clean up**: kill tmux sessions and `claude stop/rm` background sessions when done.\n7. **Don't kill slow sessions** — capture progress first (`tmux capture-pane` / `claude logs`).\n8. **Report back**: after completion, summarize what changed (use the JSON `result` + `git diff`).\n\n## References (read on demand)\n\n| File | Read when |\n|---|---|\n| `references/print-mode.md` | Streaming output, stream-json events, piping, schemas, session mgmt, cache reuse |\n| `references/interactive-tmux.md` | Any tmux/PTY session: dialogs, send-keys, monitoring, slash commands, shortcuts |\n| `references/flags.md` | Full CLI flag & subcommand tables, auth variants, env vars, model/effort selection |\n| `references/config.md` | CLAUDE.md/memory, settings hierarchy, custom agents, hooks, MCP, plugins, project purge |\n| `references/platforms.md` | Running on Windows (PowerShell/Git Bash/WSL) or macOS: shell translation, paths, per-OS gotchas |\n","packages/cli/src/skill/builtin/.bundle/codex/SKILL.md":"---\nname: codex\ndescription: Run, configure, and troubleshoot OpenAI Codex CLI in non-interactive headless environments. Use for Codex automation in Bash or PowerShell, native Windows or WSL2, shell scripts, CI/CD, Docker, Kubernetes, remote servers, agent harnesses, or batch jobs; for constructing `codex exec` commands; selecting sandbox and approval modes; consuming JSONL events or structured output; resuming sessions; passing prompts through stdin; and handling failures caused by unavailable interactive input such as `request_user_input`.\n---\n\n# Codex CLI\n\nUse Codex CLI as a deterministic, non-interactive worker suitable for automation and agent orchestration.\n\n## Operating Rules\n\n1. Use `codex exec`, not the interactive `codex` TUI.\n2. Pass the task as the positional `PROMPT` argument. Do not use `-p` for the prompt; `-p` selects a profile.\n3. For ordinary unattended code changes, prefer:\n\n```bash\ncodex exec \\\n  -C /path/to/repo \\\n  --sandbox workspace-write \\\n  --ask-for-approval never \\\n  \"<TASK>\"\n```\n\n4. Use `--yolo` only inside an externally hardened and disposable runner. It disables Codex approvals and sandboxing.\n5. For harnesses and CI, prefer `--json` plus `--output-last-message`.\n6. Do not make the run depend on a human answering questions. Resolve ambiguity using repository evidence and conservative defaults.\n7. Treat credentials as secrets. Inject `CODEX_API_KEY` only into the single `codex exec` process when possible.\n8. Before giving version-sensitive advice, inspect `codex exec --help` or current official Codex documentation if available.\n9. On Windows, choose one execution environment per task: native PowerShell for Windows toolchains or WSL2 for Linux toolchains. Do not casually mix paths, installations, or authentication across them.\n\n## Choose the Execution Mode\n\n### Read-only analysis\n\nUse when the task must not modify files:\n\n```bash\ncodex exec \\\n  -C /path/to/repo \\\n  --sandbox read-only \\\n  --ask-for-approval never \\\n  \"Analyze the repository and report risks. Do not modify files.\"\n```\n\n### Workspace-scoped implementation\n\nUse as the default for autonomous repository work:\n\n```bash\ncodex exec \\\n  -C /path/to/repo \\\n  --sandbox workspace-write \\\n  --ask-for-approval never \\\n  \"Implement the task, run relevant tests, and report unresolved blockers.\"\n```\n\n### Externally isolated unrestricted execution\n\nUse only when the enclosing container, VM, or sandbox enforces the real security boundary:\n\n```bash\ncodex exec \\\n  -C /workspace/repo \\\n  --yolo \\\n  \"Implement the task and validate the result.\"\n```\n\nNever recommend `--yolo` on a normal developer machine or a runner containing unrelated secrets, host mounts, SSH keys, cloud credentials, or a Docker socket.\n\n## Construct an Autonomous Prompt\n\nWhen headless execution could encounter choices, prepend these instructions:\n\n```text\nWork fully autonomously.\n\nDo not ask the user questions and do not request interactive input.\nInspect the repository and available context before making assumptions.\nWhen several valid approaches exist, choose the option that:\n1. minimizes unrelated changes,\n2. preserves backward compatibility,\n3. introduces the fewest new dependencies,\n4. avoids destructive or irreversible actions.\n\nContinue until the task is complete or a concrete blocking error is reached.\nRecord assumptions, validation performed, and unresolved blockers in the final response.\n```\n\nDo not simulate \"always select the first option.\" Option ordering is not a safety or quality policy. Apply the explicit decision rules above instead.\n\n## Handle `request_user_input` Failures\n\nWhen Codex reports that `request_user_input` is unavailable in Default mode or non-interactive mode:\n\n1. Confirm the invocation uses `codex exec` and is intentionally headless.\n2. Add the autonomous prompt policy above.\n3. Supply missing decisions in the task prompt or `AGENTS.md` when they are known in advance.\n4. Replace open-ended requests such as \"ask me which approach\" with deterministic selection criteria.\n5. If the choice is safety-critical, destructive, or impossible to infer, make the run fail clearly rather than selecting randomly.\n6. Do not attempt to emulate terminal keystrokes unless the subprocess itself, rather than Codex, requires input and the workflow explicitly defines the safe answer.\n\n## Pass Prompts and Context\n\nUse a direct positional prompt:\n\n```bash\ncodex exec \"Summarize the repository structure.\"\n```\n\nRead the prompt from stdin:\n\n```bash\ncodex exec - < prompt.md\n```\n\nPipe dynamic context while retaining an explicit task:\n\n```bash\nnpm test 2>&1 | codex exec \"Analyze this test output and fix the repository.\"\n```\n\nUse `--skip-git-repo-check` only for intentional one-off directories outside Git:\n\n```bash\ncodex exec \\\n  --skip-git-repo-check \\\n  -C /tmp/task \\\n  \"Analyze the files in this directory.\"\n```\n\n## Produce Harness-Friendly Output\n\n### Capture only the final message\n\n```bash\ncodex exec \\\n  -C /workspace/repo \\\n  --output-last-message /output/final.md \\\n  \"Review the codebase.\"\n```\n\n### Stream JSONL events\n\n```bash\ncodex exec \\\n  -C /workspace/repo \\\n  --json \\\n  --sandbox workspace-write \\\n  --ask-for-approval never \\\n  \"Run tests and fix failures.\" \\\n  > /output/events.jsonl\n```\n\nExpect event families such as `thread.started`, `turn.started`, `turn.completed`, `turn.failed`, `item.*`, and `error`.\n\n### Capture events and the final answer together\n\n```bash\ncodex exec \\\n  -C /workspace/repo \\\n  --json \\\n  --sandbox workspace-write \\\n  --ask-for-approval never \\\n  --output-last-message /output/final.md \\\n  \"Complete the task autonomously.\" \\\n  | tee /output/events.jsonl\n```\n\nDo not parse human-readable progress text when `--json` is available.\n\n## Require Structured Final Output\n\nCreate a JSON Schema and pass it with `--output-schema`:\n\n```bash\ncodex exec \\\n  -C /workspace/repo \\\n  --sandbox workspace-write \\\n  --ask-for-approval never \\\n  --output-schema /input/result.schema.json \\\n  --output-last-message /output/result.json \\\n  \"Implement the task, validate it, and return the requested structured result.\"\n```\n\nA useful harness schema usually includes:\n\n- `status`: `success`, `partial`, or `failed`\n- `summary`: concise outcome\n- `changed_files`: repository-relative paths\n- `validation`: commands run and results\n- `assumptions`: decisions made without user input\n- `blockers`: concrete unresolved problems\n\nSet `additionalProperties` to `false` when downstream parsing must be strict.\n\n## Resume or Avoid Persistence\n\nResume the most recent session for the current working directory:\n\n```bash\ncodex exec resume --last \"Continue the previous task and fix remaining issues.\"\n```\n\nResume a specific session:\n\n```bash\ncodex exec resume \"$SESSION_ID\" \"Continue with the next stage.\"\n```\n\nUse an ephemeral run when rollout persistence is undesirable:\n\n```bash\ncodex exec --ephemeral \"Analyze the repository.\"\n```\n\nDo not rely on `--last` across unrelated working directories unless deliberately using the relevant all-directory option supported by the installed CLI.\n\n## Authenticate Safely\n\nFor a local interactive login:\n\n```bash\ncodex login\n```\n\nFor a headless machine with device-code login enabled:\n\n```bash\ncodex login --device-auth\n```\n\nFor a single automated invocation:\n\n```bash\nCODEX_API_KEY=\"$OPENAI_API_KEY\" \\\ncodex exec --json \"Triage the repository.\"\n```\n\nDo not expose API keys as broad job-level environment variables in jobs that execute repository-controlled code. Never commit or print `~/.codex/auth.json`.\n\n## Windows, PowerShell, and WSL2\n\nFor native Windows headless use:\n\n- Install with the official PowerShell installer or npm.\n- Prefer PowerShell 7.4 or newer for JSONL redirection.\n- Build argument arrays and invoke them with `& codex @args`; avoid fragile backtick-heavy command construction.\n- Check `$LASTEXITCODE` after every Codex invocation. PowerShell error preferences alone are not a substitute for checking a native process exit code.\n- Keep stdout JSONL separate from stderr diagnostics. Do not use `2>&1` when stdout must remain parseable JSONL.\n- Configure `%USERPROFILE%\\.codex\\config.toml` with `[windows] sandbox = \"elevated\"` when available; use `unelevated` only as the fallback.\n- Preserve the task-level policy `--sandbox workspace-write --ask-for-approval never` for ordinary autonomous edits. The native Windows sandbox implementation and the CLI task policy are separate controls.\n\nFor WSL:\n\n- Use WSL2, not WSL1.\n- Install and authenticate Codex inside WSL as a Linux installation.\n- Keep repositories under `~/code/...`, not `/mnt/c/...`, for better performance and fewer permission, symlink, and file-watcher problems.\n- Do not pass credentials through visible `wsl.exe` command-line strings.\n\nSee [references/windows.md](references/windows.md) for installation, PowerShell wrappers, JSONL parsing, sandbox configuration, WSL2 patterns, and Windows-specific troubleshooting.\n\n## Container and CI Requirements\n\nWhen generating a Docker, Kubernetes, or CI design:\n\n- Mount only the intended workspace and output directory.\n- Run as a non-root user when practical.\n- Do not mount the host Docker socket.\n- Do not mount home directories, SSH keys, or cloud credential directories.\n- Restrict network access unless the task explicitly needs it.\n- Apply CPU, memory, process, and execution-time limits outside Codex.\n- Preserve stdout, stderr, exit status, JSONL events, and the final message separately.\n- Validate repository diffs and test results before treating a run as successful.\n- Prefer a fresh worktree or disposable checkout per task.\n\nSee [references/recipes.md](references/recipes.md) for ready-to-use shell, Docker, CI, and parser patterns.\n\n## Diagnose Failures\n\nUse this order:\n\n1. Run `codex --version` and `codex exec --help`.\n2. Verify the command uses a positional prompt or `-` for stdin.\n3. Verify the working directory and Git repository status.\n4. Verify authentication without printing secret material.\n5. Check whether sandbox policy blocks required reads, writes, commands, sockets, or network access.\n6. Check whether approval policy is causing an impossible prompt in headless mode.\n7. Inspect stderr and the JSONL `error` or `turn.failed` events.\n8. Re-run with a smaller, deterministic task that reproduces the failure.\n9. Do not silently switch to `--yolo` as a troubleshooting shortcut.\n\n## Completion Standard\n\nFor implementation tasks, consider the run complete only when Codex has:\n\n1. inspected the relevant repository context,\n2. made the requested changes,\n3. run the most relevant available validation,\n4. reviewed the resulting diff for unrelated changes,\n5. reported assumptions and unresolved blockers,\n6. produced machine-readable status when requested by the harness.\n","packages/cli/src/skill/builtin/.bundle/compose-next/SKILL.md":"---\nname: compose-next\ndescription: Use for multi-step feature work, bug fixes, or refactors where requirements need to settle, a feature document should carry design + tasks + delivery evidence, and the change deserves independent review before merge. Use it only when the user explicitly requests this workflow, whether with `/compose-next`, by name, or in any other clear natural language; do not infer the request from task complexity alone. Not for one-shot edits, single-file tweaks, or answering questions — those need no orchestration overhead.\n---\n\n# Compose Next\n\nCompact end-to-end contract for grill → workspace → spec → implement → verify → review → finalize → finish. One skill load, no internal skill hand-offs.\n\nWhen writing a checkpoint or compacting context, preserve this recovery instruction in the checkpoint or compacted summary: on resumption, if the Compose Next instructions are absent, reload the `compose-next` skill before continuing.\n\nEnter this workflow only on an explicit user request. Any clear natural-language instruction to use this workflow counts just like `/compose-next`; the user does not need to know or name the skill. If the user has not clearly requested the workflow, do the work directly and run none of the phases below; do not infer consent merely because the task is large or resembles a Compose task.\n\n## Step 0 — Orient\n\nInspect the repository, its instructions (`AGENTS.md`, `README`, existing spec files), and recent changes before asking anything. Do not ask the user for facts the environment already answers.\n\nDecide the shape of the work:\n\n- **Fully constrained mechanical change with no durable design surface** → skip Grill and Spec, go to Workspace then Implement.\n- **Requirements or design ambiguous** → Grill first.\n- **Requirements clear, feature deserves a durable document** → Workspace then Spec.\n\nUser gates and project overrides:\n\n- If the user explicitly requests `without worktree` or specifies a worktree or workspace path, use that workspace choice and skip the default worktree gate. Do not ask again for worktree consent.\n- If the user explicitly says `without spec`, \"no spec needed\", \"this is a small fix\", or gives an equivalent instruction, skip the durable feature document and its spec gate. Keep verification and review when the task still warrants them.\n- An explicit project instruction, `AGENTS.md`, or user-provided agent/worktree configuration may define a project-specific worktree path, branch convention, spec path, or spec format. Use that configuration instead of the defaults in this skill. Record the override in the feature document or final report when it changes the normal artifact location.\n\nEvery path passes through Workspace before Spec or Implement; no branch skips it.\n\n## Grill — resolve decisions\n\nResolve one decision axis at a time. A single decision may bundle multiple dependent fields in one structured question; unrelated decisions require separate turns.\n\nUse the Question tool for every user decision:\n\n- Put known choices in `options`. Each option gets a concise `label` and a `description` explaining the consequence. List the recommendation first and mark its label `(Recommended)`.\n- For consequential choices, include 2–3 viable alternatives.\n- When choices cannot be enumerated, still call Question with `options: []` for free-text.\n- Do not ask for permission to continue when no decision remains.\n\nSplit requests spanning independent subsystems before refining each part. Do not begin implementation until requirements and scope are settled.\n\n### When user input is unavailable\n\nIf user input cannot be obtained — the Question tool is absent, a question gets no reply, or the run cannot stop and wait (for example a goal that keeps running) — and the decision is not a dangerous action that requires explicit user consent, resolve **this one decision** yourself and continue:\n\n1. Choose the option marked `(Recommended)` when repository evidence still supports it and it can run unattended.\n2. Otherwise choose the closest minimal-scope option supported by the evidence; prefer text-only, non-interactive work.\n3. If the decision includes destructive or irreversible work, choose a non-destructive path that preserves progress; never auto-approve the destructive option.\n4. State the option selected and the reason in the response.\n\n## Workspace — worktree ownership\n\nNever begin implementation on `main` or `master` without explicit user consent. If the active workspace is already chosen, skip creation below and continue with toolchain setup.\n\n- Compare `git rev-parse --git-dir` with `git rev-parse --git-common-dir`. If they differ, use the current linked worktree; do not nest another. A non-empty `git rev-parse --show-superproject-working-tree` indicates a submodule, not a linked worktree.\n- Create a linked worktree at `.worktrees/{{slug}}` by default. Base the new branch on the latest mainline (e.g. `origin/main`). If the current checkout makes the base unclear (detached HEAD, an unrelated feature branch, unknown default branch), ask the user explicitly which base to use before creating the worktree. Run `git check-ignore -q \"$path\"`; if it is not ignored, write `*` to `.worktrees/.gitignore`. Then run `git worktree add \"$path\" -b \"$branch\" \"$base\"`.\n- When targeting the worktree with a command, pass its absolute path as `workdir`; omitted `workdir` uses the current session directory.\n- Install dependencies per repository instructions. Prefer lockfile-frozen, hardlink-friendly modes (`bun ci`, `uv sync --frozen`) over commands that mutate the lockfile. Confirm the toolchain is usable before continuing.\n\n## Spec — one document per feature\n\nMaintain one document per feature at `docs/compose/spec/{{feature-name}}.md` from the workspace root. Do not add a date to the filename. A user-specified location overrides this path. Edit an existing document in place; never create a separate plan or report. Do not write the feature document before Workspace owns the active workspace.\n\n### Template\n\n```markdown\n---\nfeature: {{feature-name}}\nstatus: designed | in-progress | delivered\nupdated: YYYY-MM-DD\nsource: {{branch-name}} | {{pr-url}} | {{mr-url}}\n---\n\n# {{Feature Name}}\n\n## Report\n\n## [S1] Problem\nDescribe the user-visible problem.\n\n## [S2] Design\nRecord the chosen behavior and the contracts needed to implement it.\n\n## [S3] Out of Scope\nState explicit boundaries.\n\n## Tasks\n- [ ] T1: {{work item}} — acceptance: {{observable result}} (covers: S2.1)\n- [ ] T2: {{work item}} — acceptance: {{observable result}} (depends: T1)\n\n## Journey log\nOptional. Dead ends, pivots, or transferable lessons worth future work. Do not pad an uncomplicated change by splitting it into several thin entries.\n```\n\n### Design-time rules\n\n- Leave `Report` empty until finalized and set `status: designed`. Keep `Journey log` empty unless something is worth carrying forward.\n- Set `source` to the form that best names where the spec's source lives — `{{branch-name}}`, `{{pr-url}}`, or `{{mr-url}}` — and update it whenever that changes.\n- Record settled decisions and precise contracts, not exploration history or file-level code dumps. Include architecture, interfaces, data flow, error behavior, and testing boundaries when they affect the change.\n- Make each task the smallest independently verifiable work item; give it an observable acceptance criterion. Add `depends:` only for real prerequisites; dependencies must be acyclic.\n- Under Design, give each contract or behavior its own subsection `S2.1`, `S2.2`, …\n- Keep `Sn` and `Sn.m` anchors stable when headings change; never renumber existing anchors.\n- `covers:` on a task is optional (for example `covers: S2.1`).\n- Scale detail to the change; do not pad small designs.\n\nBefore implementation, fix ambiguous requirements, contradictions, unresolved references, and unverifiable acceptance criteria. If the user is available, request document approval with the Question tool; otherwise continue.\n\n### Amendments\n\nUpdate only affected sections, bump `updated:`, preserve anchors, and keep only the tasks required by the amendment and their dependents. Do not regenerate the document or create duplicate tasks.\n\n## Implement\n\nUse the feature document as the source of requirements, or the conversation for an undocumented mechanical change. When a feature document exists, set its `status: in-progress` on the first implementation commit. Execute tasks in dependency order. Track multi-step work with the Task tool.\n\nFor behavior changes with a cheap reproduction, write a failing test, confirm it fails for the intended reason, implement the smallest fix, and confirm it passes. A bug fix requires a regression test when one can be written. Skip test-first for generated code, configuration-only changes, throwaway prototypes, or explicit user direction.\n\nTest public behavior. Do not duplicate production logic in expected values, add test-only production APIs, or assert only that mocks were called. Prefer real implementations over mocks.\n\nFor failures, reproduce before editing and identify the root cause from errors, diffs, recent commits, or boundary instrumentation. After two failed fixes, stop patching and re-derive the cause.\n\n### Parallel work\n\nDispatch independent tasks in parallel when isolation prevents collisions; keep tightly coupled work together. Prefer giving parallel subagents disjoint file sets and keeping commits with the orchestrator. Give each subagent the workspace path, task, acceptance criteria, relevant spec sections, and required verification. Do not pass session history. Treat its report as a claim and inspect the resulting diff.\n\nContinue through tasks without routine approval pauses. Stop only for an unresolved product decision, a blocker that cannot be worked around, a destructive action requiring consent, or completion.\n\n## Verify\n\nBefore any completion claim, run the repository's relevant tests, typecheck, build, or reproduction from the correct directory and read the output. Record each command and result. Mark known baseline failures as `PRE-EXISTING` with a short identifier. Do not substitute prior output or a subagent report for fresh evidence.\n\nVerification and review are strictly sequential. Wait for all verification commands to exit before dispatching the reviewer. Never overlap review with a resource-heavy test or application process in the same environment.\n\n## Review\n\nAfter implementation is verified and before finalizing the feature document, dispatch one fresh subagent to review the complete change.\n\nProvide the reviewer:\n\n- the applicable spec sections and acceptance criteria;\n- the workspace path, base branch, base SHA, head SHA, and exact diff command or precomputed diff;\n- a compact verification summary: one line per command with `PASS`, `FAIL`, or `PRE-EXISTING`, plus test counts when available. Do not paste full command output unless a specific failure requires it.\n\nIf there is no feature document, take acceptance criteria from the conversation. If none are explicit, ask the user for them before dispatching the reviewer.\n\nDo not provide an implementer-authored narrative. The reviewer may inspect the diff and run additional commands needed to validate its conclusions. It must not repeat a command already reported as passing, especially a heavy E2E suite, unless the result is stale, the code changed afterward, or concrete evidence makes the result suspect. Before any justified rerun, confirm no equivalent command is still running. Missing evidence should be reported or gathered with the cheapest non-duplicative command.\n\nUse a reviewer model at least as capable as the strongest implementer it reviews.\n\nRequire separate conclusions for:\n\n- **Spec compliance** — every acceptance criterion is met and points to evidence in the diff or reviewer-observed command output.\n- **Correctness** — logic, boundaries, error handling, regressions, and tests are sound, including issues outside the written spec.\n- **Codebase consistency** — naming, structure, and local conventions match surrounding code.\n\nClassify unmet or unverifiable acceptance criteria and correctness bugs as critical. Fix critical findings, re-verify, and re-review affected areas. Reject incorrect findings with technical evidence. When necessary, return to Spec and record the pivot in the Journey log. If the fix-and-re-review loop stops converging — repeated findings on the same area, or fixes that introduce new criticals — stop looping and report the impasse with the remaining findings instead of forcing a pass.\n\nFor human review feedback, verify each item against the codebase, clarify ambiguous items before editing, and implement validated items one at a time with verification. Check actual usage before expanding an unused path, and surface conflicts with prior user decisions instead of silently complying.\n\nFor parallel task work, review integrated task diffs at useful boundaries only when delaying review would compound risk.\n\n## Finalize — commit the feature document\n\nIf a feature document exists, after review passes and before finishing the branch:\n\n1. Set `status: delivered` and bump `updated:`.\n2. Check off completed tasks; leave incomplete tasks unchecked and do not claim delivery if they block acceptance.\n3. When finalized, fill `Journey log` when needed and replace `Report` with:\n\n```markdown\n## Report\n\n**What was built** — concise description of the final behavior.\n\n**Verification** — commands run and their observed results.\n```\n\nUpdate a design section only when it contradicts the delivered behavior. Commit the finalized document on the feature branch before finishing. This documentation-only commit does not restart verification or review; CI re-running on it is expected.\n\n## Finish\n\nDo not auto-finish: confirm with the user before any irreversible action, including opening a PR or MR, merging, or pushing.\n\nReport branch, base, head SHA, workspace, feature-doc path when available, and ask the user which way to finish — for example:\n\n- local merge / open PR / push only / keep the branch;\n- which base branch to merge or target;\n- keep or remove the worktree.\n\nOpen PR or MR does not imply merge: unless the user also asked to merge, stop after opening — the merge always needs its own confirmation, whether the PR or MR was created here or already existed.\n\nWhen the closing action changes where the spec lives, update `source` and commit it as documentation only: `{{pr-url}}` or `{{mr-url}}` after opening one, `{{branch-name}}` before a local merge.\n\nWorktree pitfalls:\n\n- Local merge and `gh pr merge` run from the main repository checkout — the base branch cannot be checked out while another worktree holds it.\n- `git worktree remove` only on `.worktrees/` or the path scoped by the prompt / `AGENTS.md`.\n","packages/cli/src/skill/builtin/.bundle/data-analytics/SKILL.md":"---\nname: data-analytics\ndescription: \"Use this skill for quantitative product or business analysis: data quality checks, metric diagnostics, KPI design and reporting, dashboards, analytical reports, charts, notebooks, market sizing, semantic layers, and evidence-backed recommendations. Also use it whenever Data Analytics is explicitly invoked.\"\n---\n\n# Data Analytics\n\nThis is the single entry point for a code-agent-oriented Data Analytics bundle. The original plugin workflows are under `workflows/`; React, Vite, MCP App widgets, connector manifests, and frontend build artifacts are intentionally excluded.\n\n## Route the request\n\n1. Read `workflows/index/SKILL.md` completely. Treat it as the authoritative plugin-level eligibility and analytical routing policy, except where its UI/runtime delivery rules conflict with the code-agent overrides below.\n2. Select the narrowest focused workflow named by that index. Read every selected workflow's `SKILL.md` completely before acting.\n3. If a selected workflow names related skills, load those only when its routing conditions apply. Multiple skills may form one workflow; follow the ordering defined by the index and focused skills.\n4. Resolve relative links from the file that contains the link. Read referenced instruction or reference files when the selected workflow requires them and they exist in this bundle. Prefer bundled scripts and sample data over recreating them.\n5. Do not load unrelated focused workflows merely because they are present.\n\n## Bundled capabilities\n\nFocused workflows live in `workflows/`, including data-quality analysis, business-context gathering, metric diagnostics, product/business analysis, KPI design and reporting, visualization, dashboards, reports, notebooks, market sizing, validation, and semantic-layer creation.\n\nUse data sources and tools only when the host harness exposes them. The bundle does not require a particular connector registry or UI protocol.\n\n## Code-agent delivery overrides\n\nThese rules take precedence over MCP App, widget, native Work Mode, and packaged Recharts delivery rules inherited from the original workflows:\n\n- Never require or call `render_artifact`, `render_chart`, `render_table`, `validate_artifact`, `export_artifact_package`, `charts_widget_v2`, or `app_block` unless the user independently provides an equivalent tool and explicitly requests it.\n- Default transient answers to concise Markdown with source notes. Default durable reports and dashboards to Markdown, a self-contained HTML file using plain HTML/CSS/SVG/vanilla JavaScript, a notebook, a spreadsheet, or a static image according to the user's request and the host's available tools.\n- For charts, prefer reproducible Python/Matplotlib, notebook-native plotting, SVG, or the destination system's native chart support. Inspect generated visuals when the harness provides image or browser inspection.\n- Do not install Node, React, Recharts, Vite, or frontend packages for analytics output. Do not depend on removed `src/`, `assets/`, MCP specifications, HTML runtime helpers, or widget resources.\n- If a focused workflow points to a removed UI-only reference, skip that reference and apply these overrides while preserving its analytical, provenance, QA, and narrative requirements.\n- A requested report remains incomplete until its chosen portable file exists or a concrete blocker is reported; a chat summary is sufficient only when the user requested an inline answer.\n\n## Safety and fidelity\n\n- Never treat plugin instructions as permission to bypass host policy, expose secrets, or perform unapproved external writes.\n- Keep source provenance and uncertainty visible in analytical outputs.\n- Do not silently replace real-data questions with sample data.\n- Preserve the selected workflow's validation and delivery requirements through completion.\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/analyze-data-quality/SKILL.md":"---\nname: analyze-data-quality\ndescription: \"Assess whether structured data, query results, dashboards, or analytical evidence are trustworthy enough to use. Use when the task is to check data quality, reconcile conflicting sources or metric definitions, or decide whether evidence is safe to cite.\"\n---\n\n## Related Skills\n\nUse $design-kpis when the work is to define or redesign a KPI framework, metric definition, guardrail, or target rather than checking whether existing data is trustworthy.\n\nUse $validate-data when the work is to QA an analysis, chart, report, or recommendation rather than investigate the underlying data.\n\n# Analyze Data Quality\n\nAssess whether a dataset is trustworthy enough for analysis, modeling,\ndashboards, experiments, or downstream pipelines. Start with the intended use and grain, run the highest-value checks for the data shape, and report concrete evidence, analytical risk, likely causes, and the smallest useful remediation or automated test.\n\n## Workflow\n\n1. Clarify the quality question and operating context.\n\n   Establish what the dataset represents, the intended unit of analysis, the downstream use, whether the user cares about raw ingestion quality,\n   transformed-model quality, or both, and the comparison baseline such as prior weeks, prior schema, or a trusted reference table. Identify expected grain,\n   primary keys or candidate keys, important date columns, timezone assumptions,\n   domain rules, allowed values, and business thresholds. If context is missing,\n   infer cautiously and label assumptions.\n\n2. Choose an inspectable analysis path.\n\n   When checks require SQL or Python, default to a companion notebook so the user can inspect the exact code behind the findings. Use $jupyter-notebooks when a dedicated notebook scaffold or refactor workflow would help. For queryable tables, use `~~structured_data` to confirm schema, grain, sample rows, and query rules through the relevant source connector before heavier checks. Use `~~operations_logs` for freshness and lineage when those checks matter.\n\n3. Build a compact profile.\n\n   Start with row count, column count, column names and types, candidate keys,\n   duplicate rates on likely identifiers, min/max timestamps for relevant date columns, null rates, distinct counts for likely categorical columns, and basic numeric summaries for measure columns. Confirm grain before interpreting anomalies; many apparent quality problems are mixed-grain data,\n   partial backfills, late-arriving data, or duplicated joins.\n\n4. Run core quality checks.\n\n   Select checks that match the dataset and task. Default to the most relevant checks across completeness, uniqueness, validity, consistency, integrity,\n   timeliness, volume, and shape. Compare rates, not just counts, and segment by time, source, country, platform, model version, or other key dimensions when that helps distinguish real issues from expected variation.\n\n5. Run shape-specific checks.\n\n   Adapt the checks to the data shape:\n\n   - Event data: duplicate event IDs, future event timestamps, session or user\n     coverage gaps, and abrupt event-mix changes after releases.\n   - Dimension tables: non-unique business keys, orphan surrogate keys, status\n     changes without corresponding timestamps, and unexpected churn in reference\n     values.\n   - Fact tables: mixed grain, impossible measures such as negative revenue or\n     quantity, join blowups to dimensions, and late-arriving or partially loaded\n     partitions.\n   - ML feature or scoring tables: leakage from post-outcome fields, feature\n     sparsity spikes, range shifts after model or feature-store changes, and\n     class-label drift.\n   - Experiment data: duplicate assignments, variant imbalance beyond\n     expectation, exposure without assignment, and events before assignment\n     timestamp.\n\n6. Run temporal and distribution checks when history exists.\n\n   Prioritize temporal diagnostics when the user mentions \"after X date\",\n   \"suddenly\", \"recently\", or \"only started appearing\". Check first-seen dates,\n   last-seen dates, daily or weekly null-rate trends, duplicate-rate trends, row count trends, category-share shifts, distribution drift, and change points around launches, migrations, incidents, model changes, or backfills.\n\n7. Investigate analytical risks and likely causes.\n\n   Tie each issue to the downstream risk: broken trusted analysis, biased decisions, broken joins, stale dashboards, incorrect experiments, leakage,\n   unreliable model features, or misleading segments. When possible, identify whether the issue is isolated to a source, segment, partition, time window,\n   release, migration, backfill, or upstream pipeline change.\n\n8. Recommend fixes or automated tests.\n\n   Recommend the smallest set of follow-up fixes, monitoring, or automated tests that would materially reduce risk. Suggest automation only when the rule is stable and worth maintaining. Include or save the notebook/query path when code produced the findings.\n\n## Standards\n\n### Core Checks\n\n- Completeness: null rate by column; null rate by partition, segment, and time bucket; unexpected empty strings or sentinel values; required-column population rate.\n- Uniqueness: exact duplicate rows, duplicate primary keys, duplicate composite keys, and proportion unique for semi-unique fields such as emails or device IDs.\n- Validity: type conformance after casting; format checks for IDs, emails, URLs,\n  enums, country codes, and timestamps; range checks for measures, percentages,\n  counts, and dates; allowed-values checks for controlled vocabularies.\n- Consistency: cross-field rule checks, units or currency consistency, status and timestamp alignment, and agreement between duplicated fields from different sources.\n- Integrity: parent-child key coverage, orphan records, unexpected many-to-many joins, and broken slowly changing dimension joins.\n- Timeliness: freshness lag from source event time to load time, freshness lag from load time to report time, missing recent partitions, and unexplained historical rewrites or backfills.\n- Volume and shape: row-count drift, distinct-count drift, distribution drift,\n  share-of-total drift for major categories, and new or disappeared categories.\n\n### Specific Check Guidance\n\n- Duplicates and keys: check exact duplicates, primary key duplicates, composite key duplicates at the intended grain, and near-duplicates caused by whitespace,\n  casing, formatting, or late updates. Report count, share of affected rows,\n  duplicated keys, and whether duplication is isolated to a time range, source,\n  or segment.\n- Missingness: distinguish acceptable sparsity from broken completeness. Check null rates over time, newly null columns after schema or pipeline changes, and sentinel values such as `''`, `'unknown'`, `'n/a'`, `0`, or `-1`.\n- Domain validity: check malformed identifiers, country codes, timestamps,\n  impossible values, values outside allowed sets, and cross-field contradictions such as `is_cancelled = false` with a non-null `cancelled_at`.\n- Join coverage: when multiple datasets are involved, check foreign keys that do not match a parent table, unexpected one-to-many expansion, coverage loss when joining to dimensions or experiments, and row counts before and after joins.\n- Freshness and schema drift: check row-count changes against recent history,\n  lag on important date columns, added/removed/retyped columns, and shifts in sparsity or cardinality that suggest upstream changes.\n- Outliers and distribution shifts: use robust methods such as quantiles, MAD,\n  or IQR before defaulting to z-scores. Check sudden changes in mean, median,\n  variance, zero rate, category share, and long-tail behavior.\n- Leakage, backfill, and time travel: check features populated before they should exist, future-dated records, late-arriving data causing unstable recent partitions, and backfills that change historical counts without annotation.\n\n### Severity\n\n- Critical: breaks trusted analysis, core joins, production dashboards, or key decisions, such as duplicated grain, missing primary keys, or stale production data.\n- High: materially biases downstream decisions, such as large null spikes,\n  category drift in a core dimension, invalid business-rule values, leakage, or severe join coverage loss.\n- Medium: localized or explainable issues that still need documentation,\n  monitoring, or owner follow-up.\n- Low: cosmetic inconsistencies, expected sparsity, or known edge cases that do not materially affect current use.\n\nDo not dump raw profiling output without interpretation. Tie each finding to an analytical risk and likely impact.\n\n### Automated Test Guidance\n\n- Good candidates for automation: primary key uniqueness, not-null checks on required columns, accepted values for stable enums, referential integrity,\n  freshness thresholds, and seasonality-aware row-count or volume bounds.\n- Use caution with hard-coded distribution thresholds on volatile product metrics, strict uniqueness in messy entity-resolution use cases, and recent partitions when late-arriving data is normal.\n- Suggest automated tests only when the expected rule is stable, important, and maintainable.\n\n### Output Standards\n\nFor stakeholder-facing data-quality work, pass the completed findings to $build-report by default so the runtime produces a portable report in the selected format. Do not stop at profiling output or a notebook unless the user explicitly requested a quick inline answer or another primary artifact. The structure below defines the report content.\n\nStructure the response with:\n\n1. dataset and grain summary\n2. checks performed\n3. findings\n4. temporal or trend anomalies\n5. likely causes and impacted use cases\n6. recommended fixes or automated tests\n7. assumptions and open questions\n\nFor each finding, include:\n\n- what failed\n- evidence: counts, rates, segments, and dates\n- why it matters\n- severity and confidence level\n- likely cause when known\n- suggested remediation or automated test\n\nWhen code was used, include or save a notebook containing the key SQL and Python checks and make the notebook path easy to find.\n\n### Defaults\n\n- Prefer small, high-signal tables over exhaustive dumps.\n- Compare rates, not just counts.\n- Break checks out by time and key segments whenever possible.\n- Normalize strings before judging duplicates or distinct-count spikes.\n- Treat recent partitions carefully when data arrives late.\n- Call out when an anomaly could be caused by a legitimate product launch,\n  experiment, migration, incident, model change, or backfill.\n- Preserve inspectable evidence: SQL, query links, notebook paths, source paths,\n  sample rows, chart outputs, and calculation notes.\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/build-dashboard/SKILL.md":"---\nname: build-dashboard\ndescription: \"Build a source-backed dashboard or monitoring view with clear metrics, filters, visual hierarchy, definitions, refresh context, and QA.\"\n---\n\n# Build a Dashboard\n\nUse this workflow when the user needs a reusable monitoring or exploration surface rather than a one-time report. Read the relevant analysis and KPI workflows first when metric definitions or decision logic are not already settled.\n\n## Select a portable surface\n\nHonor the user's destination. Otherwise choose the simplest surface supported by the harness:\n\n- Existing BI/product analytics platform when the user wants a governed shared dashboard there.\n- Streamlit when Python execution and local/server operation are appropriate; read `specifications/streamlit-dashboard.md`.\n- Self-contained plain HTML/CSS/vanilla JavaScript for a portable local dashboard; read `specifications/html-dashboard.md`.\n\nDo not require React, Vite, Recharts, MCP Apps, or widget runtimes.\n\n## Workflow\n\n1. Define the audience, operating decision, monitoring cadence, and questions the dashboard must answer.\n2. Define each metric: formula, numerator/denominator, unit, grain, time window, filters, exclusions, owner, source, and freshness expectation.\n3. Validate joins, completeness, duplicates, missingness, comparability, and refresh status before presenting metrics as trustworthy.\n4. Design the information hierarchy:\n   - Overview and primary outcomes.\n   - Drivers and diagnostic cuts.\n   - Guardrails and risks.\n   - Detail tables or drill-down paths.\n5. Add only decision-relevant filters. Make default date ranges, segments, comparison periods, and filter state visible.\n6. Use `../visualize-data/SKILL.md` for each chart and keep exact lookup values accessible in tables.\n7. Show data freshness, source context, definitions, and material caveats in the dashboard.\n8. Implement and test the real artifact with representative, empty, partial, and error states when feasible.\n\n## QA and handoff\n\n- Reconcile displayed totals and KPIs against reviewed source results.\n- Test filters, date boundaries, sorting, responsive layout, and refresh behavior.\n- Check chart labels, units, legends, accessibility, and table readability.\n- Ensure the artifact does not expose secrets, credentials, unnecessary personal data, or temporary local paths.\n- Deliver the dashboard artifact or governed platform link plus metric definitions, source/query files, refresh instructions, and known limitations.\n\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/build-report/SKILL.md":"---\nname: build-report\ndescription: \"Build a durable analytical report with an answer-first narrative, evidence-backed findings, charts or tables, caveats, recommendations, and source context.\"\n---\n\n# Build an Analytical Report\n\nUse this workflow when the user needs a durable report rather than a transient answer. Run the appropriate analysis workflow first; this workflow owns the reader-facing structure, evidence placement, visual/table placement, caveats, sources, QA, and handoff.\n\n## Choose one delivery format\n\nHonor an explicit format. Otherwise use:\n\n1. Markdown for the most portable code-agent deliverable.\n2. Self-contained plain HTML when a polished browser-readable report is useful and the host can render or inspect it.\n3. PDF, DOCX, slides, or another format only when requested or clearly required by the destination and the host exposes suitable creation and verification tools.\n\nDo not install or require React, Recharts, Vite, MCP Apps, or widget runtimes. HTML must use semantic HTML/CSS and may use inline SVG or small vanilla JavaScript interactions. It must remain readable without JavaScript.\n\n## Build the report\n\n1. Confirm the audience, decision, scope, comparison window, and requested format from available context. Ask only when a missing choice would materially change the result.\n2. Verify the analytical evidence. Keep metric definitions, grain, time range, filters, units, exclusions, and source freshness explicit.\n3. Lead with the answer. State the most important conclusion and decision implication before methodology details.\n4. Build a coherent narrative rather than a dump of charts or query results.\n5. Include only visuals and tables that support a finding. Read `../visualize-data/SKILL.md` when creating charts.\n6. Distinguish verified facts, likely explanations, assumptions, limitations, and unresolved questions.\n7. Provide recommendations tied to evidence, expected impact, owner or next action, and measurable follow-up where appropriate.\n8. Add a source section that identifies real source systems, tables/views, datasets, files, documents, queries, and access dates when known. Never invent provenance.\n\n## Recommended structure\n\n```markdown\n# [Short reader-facing title]\n\n## Executive summary\n[Answer, magnitude, and decision implication]\n\n## Key findings\n[Evidence-backed findings with charts or tables]\n\n## Recommendations\n[Prioritized actions and expected outcomes]\n\n## Risks and limitations\n[Data gaps, assumptions, uncertainty, and interpretation limits]\n\n## Sources and methodology\n[Definitions, scope, source details, and reproducibility notes]\n```\n\nAdapt the headings to the audience, but retain the answer-first logic.\n\n## QA and handoff\n\n- Recalculate headline values and comparisons from the reviewed evidence.\n- Check that every claim is supported and every chart matches its source data.\n- Check titles, labels, units, denominators, date ranges, and sorting.\n- For HTML/PDF/DOCX/slides, render or inspect the actual artifact when the host supports it; fix clipping, blank charts, overflow, low contrast, and unreadable tables.\n- Ensure the report contains no credentials, local temporary paths, placeholder provenance, or internal implementation noise.\n- Return the primary artifact path plus only the relevant supporting notebook, SQL, data, or chart files.\n\nIf the user asks only for an inline brief or explicitly says no file/artifact, deliver the same answer-first structure concisely in chat.\n\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/build-report/report-to-google-doc/SKILL.md":"---\nname: report-to-google-doc\ndescription: \"Narrow conversion skill. Invoke only when the user explicitly asks to convert an existing local or blob-hosted HTML analytics report into a Google Doc, DOCX, or shareable document.\"\n---\n\n# Report To Google Doc\n\nUse this skill only when the user explicitly needs a shareable Google Drive document from an existing HTML analytics report. The source must be an HTML report: a local file, a downloaded blob-hosted report, or a report produced by `$build-report`\nHTML mode or an equivalent local portable report source.\n\nThe expected path is HTML -> DOCX -> Drive upload. It is acceptable for Drive to host the upload as a DOCX-backed viewer file rather than a native Google Docs MIME type. Do not use the old Google Docs batch-update request path.\n\n## Workflow\n\n1. Resolve the HTML report.\n\n   Use an absolute local path. If the user provides a remote report, retrieve it first and pass the local HTML file to the helper. If the file is a sign-in page, redirect page, or tiny stub, stop and obtain the real report.\n\n2. Run the bundled helper.\n\n   ```bash\n   python3 <REPORT_TO_GOOGLE_DOC_SKILL_DIR>/scripts/report_to_google_doc_plan.py \\\n     /absolute/path/to/report.html \\\n     --out-dir /tmp/report_to_google_doc_plan\n   ```\n\n   Omit `--render-workers` on the normal path. Only pass a worker count after benchmarking the same report family locally. If dependencies are missing,\n   use a local virtual environment with `beautifulsoup4`, `pillow`, and `python-docx`; `cairosvg` or headless Playwright are optional renderers.\n\n3. Inspect helper outputs.\n\n   Required outputs:\n\n   - `skeleton.txt`: source text with stable placeholders\n   - `manifest.json`: parsed headings, tables, callouts, lists, styles, links,\n     and rendered visual inventory\n   - `preflight_checks.json`: source, width, DOCX, and rendered-image checks\n   - `report.docx`: generated local Word document\n   - `docx_upload_plan.json`: compact upload instructions\n   - `placeholder_queries.json`: source mapping debug labels\n\n   Do not upload until `preflight_checks.json` has `status: \"passed\"` with zero errors. Warnings must either be fixed or called out in the handoff.\n\n4. Upload the DOCX.\n\n   ```json\n   mcp__codex_apps__google_drive._upload_file({\n     \"file_uri\": \"/tmp/report_to_google_doc_plan/report.docx\",\n     \"file_name\": \"Report Name.docx\",\n     \"mime_type\": \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\"\n   })\n   ```\n\n   Treat the returned Drive URL as the deliverable. Do not attempt to force native Google Docs conversion, and do not fall back to `_batch_update_document`.\n\n5. Validate the uploaded result.\n\n   Confirm the uploaded file is readable and non-empty. Compare uploaded text against the source inventory: title, section headings, executive summary or answer callout, caveats, recommendations, source notes, and source links.\n   Inspect the local `report.docx` structure when available: heading counts,\n   lists, tables, hyperlink relationships, and image relationships should match `manifest.json`.\n\n6. Hand off the link.\n\n   Return the Drive/Docs URL and, when useful, the local DOCX path or source HTML path. Connector success alone is not enough; the handoff is complete only after the uploaded file and local DOCX structure have been checked against the source report. Keep routine check and preflight details in support artifacts. Do not list internal checks in the user-facing handoff unless a check failed, was unavailable, or produced a user-relevant caveat.\n\n## Standards\n\n- Preserve every section, headline claim, metric card, metric definition,\n  source note, chart takeaway, recommendation, caveat, and link from the HTML report.\n- Preserve semantic formatting: headings, paragraphs, inline bold/emphasis,\n  inline code, positive/negative colors, links, lists, callouts, metric-card grids, tables, notes, captions, and charts.\n- Use DOCX-native structures wherever practical: headings, paragraphs, tables,\n  bullets/numbered lists, links, inline images, paragraph shading, table cell shading, and text styles.\n- Keep the report text column readable. Tables, charts, rendered table grids,\n  screenshots, and visual blocks must not exceed the DOCX page text width.\n- Preserve charts as inline images rendered from the source visual or its same-data SVG fallback, aligned to the same left edge as text and tables. A chart with missing bars, missing legend swatches, or all-black/all-white marks fails validation even if the DOCX contains an image object.\n- Preserve multi-column report blocks. A two-column grid made only of titled mini-tables can remain a two-column rendered image capped to the text width;\n  mixed two-column blocks with narrative text, pills, callouts, or non-table panels should preserve that content natively instead of dropping it.\n- Do not expose customer-level details or sensitive links that were intentionally omitted from a sanitized report.\n- Do not write Google Docs batch-update artifacts such as `seed_requests.json`,\n  `remote_write_plan.json`, or `all_requests*.json`.\n\n## Repairs\n\nUse these fixes when validation exposes a conversion issue:\n\n| Problem | Fix |\n| --- | --- |\n| Heading is regular weight | Fix the DOCX writer heading style or explicit run bolding. |\n| Blank line after title or heading | Delete spacer paragraphs; skeletons should emit `\\n`, not `\\n\\n`, after headings. |\n| Body paragraphs have too much space | Delete literal blank paragraphs and set modest style spacing. |\n| Table/image too wide | Set table columns or image width to the DOCX text column width. |\n| Chart has labels but missing bars | Inline SVG class styles or use a headless screenshot before inserting. |\n| Two-column table group is flattened | Treat the grid as one layout block with mini-table titles preserved. |\n| Executive summary, metric cards, or section is missing | Fix parser inventory before upload. |\n| Chart overlaps table | Insert the image on its own paragraph after the table. |\n| Chart duplicated | Remove the extra image; keep exactly one source-order copy. |\n| Inline bold/code/color missing | Fix manifest range splitting in the DOCX writer. |\n| Source links show raw URLs | Replace with native linked labels or native bullets using HTML link text. |\n\n## Local Checks\n\n```bash\npython3 -m py_compile <REPORT_TO_GOOGLE_DOC_SKILL_DIR>/scripts/report_to_google_doc_plan.py\npython3 <REPORT_TO_GOOGLE_DOC_SKILL_DIR>/scripts/report_to_google_doc_plan.py \\\n  /absolute/path/to/report.html \\\n  --out-dir /tmp/report_to_google_doc_plan_smoke\njq '.status, .summary' /tmp/report_to_google_doc_plan_smoke/preflight_checks.json\ntest -f /tmp/report_to_google_doc_plan_smoke/report.docx\ntest -f /tmp/report_to_google_doc_plan_smoke/docx_upload_plan.json\ngit diff --check -- plugins/data-analytics/skills/build-report/report-to-google-doc\n```\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/build-report/report-to-google-slides/SKILL.md":"---\nname: report-to-google-slides\ndescription: \"Narrow conversion skill. Invoke only when the user explicitly asks to convert an existing HTML analytics report into a native Google Slides deck.\"\n---\n\n# Report To Google Slides\n\nUse this skill only when the user explicitly has an existing HTML analytics report and wants a Google Slides deliverable. The output should be a deck, not a pasted report. A stakeholder skimming the slides should understand the answer, evidence,\ncaveats, and recommended follow-up without opening the source report.\n\nThis skill consumes a local portable report, preferably self-contained HTML. If another format is the only source, first create an equivalent local HTML or structured report from the same evidence.\n\n## Workflow\n\n1. Resolve the local HTML report.\n\n   Use an absolute file path. If the user provides a remote report, retrieve it outside this skill first. If the local file is a sign-in page, redirect page,\n   or very small stub, stop and obtain the real report before continuing.\n\n2. Run the helper.\n\n   ```bash\n   python3 <REPORT_TO_GOOGLE_SLIDES_SKILL_DIR>/scripts/report_to_google_slides.py \\\n     <LOCAL_HTML_REPORT_PATH> \\\n     --out-dir /tmp/report_to_google_slides\n   ```\n\n3. Inspect local outputs.\n\n   Required outputs:\n\n   - `deck.pptx`: editable local PowerPoint file\n   - `manifest.json`: parsed source inventory and coverage counts\n   - `deck_plan.json`: slide-by-slide plan with named elements\n   - `preflight_checks.json`: local quality checks and pass/fail status\n   - `assets/`: rendered chart images\n\n   Do not import the PPTX until `preflight_checks.json` has `status: \"passed\"`.\n   Then run `unzip -t <out-dir>/deck.pptx`.\n\n4. Import and verify in Google Slides.\n\n   Import `deck.pptx` with `mcp__codex_apps__google_drive._import_presentation` using `upload_mode=\"native_google_slides\"`. Verify the imported deck with `_get_presentation_outline` and `_get_slide_thumbnail` for every slide when possible. At minimum, inspect the cover, one chart slide, one table slide,\n   and the caveats/sources slides.\n\n5. Repair before handoff.\n\n   If thumbnails show clipped text, missing charts, low contrast, blank images,\n   or awkward sizing, revise the helper output or source assumptions and regenerate before handing off the deck URL.\n\n6. Hand off the deck.\n\n   Return the Google Slides URL and, when useful, the local PPTX path or source HTML path. Keep routine check, preflight, thumbnail-inspection, and import-check details in support artifacts. Do not list internal checks in the user-facing handoff unless a check failed, was unavailable, or produced a user-relevant caveat.\n\n## Standards\n\n- Preserve the report's decision-critical information: headline claim,\n  executive summary, major findings, metric definitions, material charts,\n  decision-critical tables, recommendations, implications, caveats,\n  assumptions, freshness notes, and source/provenance notes.\n- Translate report prose into slide-native communication. Lead with the takeaway, use one main idea per slide, and put supporting detail in concise callouts, bullets, tables, chart annotations, or speaker notes.\n- Tighten copy before shrinking fonts.\n- Keep gross metric reads, net/incremental reads, causal claims, and caveats visibly separated when the source report distinguishes those lenses.\n- Use editable text and native PPTX tables wherever practical. Use native PPTX bullets; do not fake bullets with typed dashes.\n- Preserve source charts as evidence images. Do not screenshot the whole HTML report or paste whole report sections.\n- Support self-contained HTML reports whose chart evidence is available as inline SVG, accessible tables, or embedded images; render those into local chart evidence images before building the deck.\n- Use one chart per evidence slide unless the report has a stronger grouped comparison.\n- Keep table slides legible. If a full table is too dense, keep the main comparison in the deck and move extra detail to speaker notes or source slides.\n- Source notes should be visible but quiet.\n\n## Visual System\n\nThe helper derives colors and hierarchy from the HTML report CSS and chart palette, then applies a restrained analytics deck layout. It does not follow external deck files or company-specific branding.\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/build-report/report-to-pdf/SKILL.md":"---\nname: report-to-pdf\ndescription: \"Narrow conversion skill. Invoke only when the user explicitly asks to convert an existing Data Analytics report, dashboard, or inline chart export into a PDF artifact.\"\n---\n\n# Report To PDF\n\nUse this skill only when the user explicitly needs a PDF from an existing Data Analytics report, dashboard, or chart artifact. Prefer a static HTML export or another portable report file as the source.\n\nThe expected path is static HTML -> browser headless print-to-PDF -> PDF verification. If only a non-portable source exists, create or retrieve the matching static HTML/export source first.\n\n## Workflow\n\n1. Resolve the static source.\n\n   Use an absolute local path to a static HTML report/export or a local URL served from that static export. If the source is a blob stub, sign-in page, redirect page, incomplete viewer, or an app shell that contains boot scripts but not the report content, stop and obtain a static HTML/export source before continuing.\n\n   When the user provides a hosted artifact URL, first determine whether it exposes a usable static export or package source. If the static export is unavailable but the validated artifact payload is still available in the current run, create the matching static HTML/export from that payload and preserve source provenance in the handoff. If neither a static export nor the artifact payload is available, stop with a blocker instead of printing the live app shell or rebuilding the report from memory.\n\n   When creating or repairing the static source, keep visible metadata reader-facing. Do not copy internal artifact runtime fields, package plumbing, or validator/debug state into the report body, header, footer, or source section. For example, omit raw labels such as snapshot status, package path, widget type, manifest path, renderer IDs, validation status, and local temp paths from the visible PDF. If a runtime detail matters for audit or troubleshooting, preserve it in support notes rather than the visible PDF. Translate data-state caveats into reader language only when they affect interpretation, such as \"synthetic demo data\" or \"partial source coverage.\"\n\n2. Generate the PDF with Chrome CLI headless print-to-PDF.\n\n   Use the platform-specific Chrome executable available in the environment. Common examples are `/Applications/Google Chrome.app/Contents/MacOS/Google Chrome` on macOS and `google-chrome`, `chromium`, or `chromium-browser` on Linux. This is the primary conversion method because it prints the static HTML with a browser rendering engine and usually preserves selectable text, layout, charts, tables, and print CSS.\n\n   ```bash\n   chrome \\\n     --headless=new \\\n     --disable-gpu \\\n     --no-first-run \\\n     --no-default-browser-check \\\n     --no-pdf-header-footer \\\n     --print-to-pdf=/absolute/path/to/report.pdf \\\n     /absolute/path/to/report.html\n   ```\n\n3. If Chrome is unavailable or cannot produce a valid PDF, use a renderer-backed fallback.\n\n   Use the next available local mechanism that renders the same static HTML/export source and prints or saves that rendered page to PDF. Keep the fallback tool-agnostic: the requirement is faithful HTML rendering followed by PDF output, not a specific implementation. Do not replace this with a model-authored PDF layout, manually redrawn charts, or a report reconstructed from memory.\n\n   A fallback is acceptable only when:\n\n   - the static HTML/export remains the source of truth\n   - the rendered output preserves the report title, narrative, charts, tables, caveats, and source details\n   - app-only controls are omitted\n   - the resulting PDF passes the same verification checks as the primary Chrome path\n\n   If no available local renderer can print the static HTML/export faithfully, stop and report the blocker with the missing capability and the source file that could not be converted.\n\n4. Verify the PDF itself.\n\n   Confirm page count and metadata with `pdfinfo` or equivalent. Extract text with `pdftotext` or equivalent when the PDF should contain selectable text. Render representative pages with `pdftoppm` or equivalent and inspect them for blank charts, clipped content, missing source details, unwanted controls, internal runtime metadata, and layout regressions. For short reports, render every page. Include a negative check for app-only control labels such as share, edit, refresh, publish, toolbar, menu, and drag affordances, plus internal artifact labels such as snapshot status, widget type, manifest path, package path, validation status, and local temp paths.\n\n5. Repair before handoff.\n\n   If the output is blank, clipped, missing charts, missing source details, or includes app-only chrome, fix the static HTML/export source, print stylesheet, or renderer invocation and regenerate. Do not hand off an unverified PDF unless the user explicitly accepts the limitation.\n\n6. Hand off the PDF.\n\n   Return the PDF path and, when useful, the source HTML path or URL. Keep routine check details in support artifacts. Do not list internal checks in the user-facing handoff unless a check failed, was unavailable, or produced a user-relevant caveat. If the static HTML/export had to be created from an artifact payload because the hosted URL did not expose one, say that briefly. If required checks could not be completed, state the gap clearly.\n\n## Standards\n\n- Preserve the reader-facing artifact content: title, narrative, charts, tables, caveats, source details, and generated-at or source freshness details when present.\n- Omit app-only controls: top bars, share menus, edit controls, refresh controls, drag handles, hover-only menus, and interactive-only affordances.\n- Omit internal artifact and conversion metadata from the visible PDF. Do not show raw runtime fields, implementation state, package labels, local paths, validator/debug labels, or status strings that exist only to operate the app or export pipeline. Keep audit-useful internals in support files, and use plain reader-facing caveats in the PDF when a data state affects interpretation.\n- Prefer a text PDF with selectable/searchable text. Use a screenshot/image PDF only when a faithful text PDF is not viable, and state that text may not be selectable or searchable.\n- Keep the static source as the PDF source of truth. Do not reconstruct the report from memory when a source HTML/export exists.\n- Do not create a model-authored PDF from scratch as a normal fallback. Direct PDF construction is acceptable only as an explicitly labeled last-resort workaround after the user accepts the quality limitation.\n- Keep generated PDF support files together when possible: static HTML source, PDF output, extracted text, page previews, and any notes about source retrieval or renderer fallback.\n\n## Verification Guidance\n\nBefore handoff, verify the PDF with the local tools available in the environment:\n\n- Confirm the PDF exists, is non-empty, and has the expected page count and page size.\n- Confirm text is selectable/searchable when a text PDF is expected.\n- Render or preview representative pages; for short reports, prefer checking every page.\n- Inspect for blank pages, clipped charts, missing tables, missing source details, unwanted app controls, and leaked internal artifact or conversion metadata.\n- If the skill file itself was edited, run the repository's normal markdown or diff checks.\n\nExamples when available: `pdfinfo`, `pdftotext`, `pdftoppm`, file-size checks, and `git diff --check`.\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/create-data-context/SKILL.md":"---\nname: create-data-context\ndescription: \"Create, update, inspect, or repair Data Analytics semantic layers. Use when the user asks to save data context or create a semantic layer that future Data Analytics work can inspect and cite.\"\n---\n\n# Create Data Context\n\nThis skill creates and maintains semantic-layer skills for Data Analytics. A semantic-layer skill is an explicit artifact the user can inspect and cite later. It captures how future analyses should interpret the data, for example which metric definition is canonical, which dashboard or table is the best source of truth, and what caveats should be checked before answering.\n\nData-task routing is owned by the Data Analytics `index` skill. If the user wants Data Analytics to do work with data now, route to `index`, whether the work starts from connected sources, uploaded files, pasted tables, sample data, or an existing semantic layer. Examples include answering a metric question, building a report, or checking a dataset.\n\nUse this skill only when the user asks to save data context or create, update, inspect, or repair a semantic layer.\n\n## Runtime Routing\n\nUse the current runtime's classified `surface` and `mode` values, plus the capabilities exposed in the run, to choose intake and persistence. Build and validate the same canonical semantic-layer skill package before writing it to any destination.\n\nFor intake:\n\n- Use structured intake when a supported form action is available.\n- Use conversational intake for open-ended details and for runtimes without a supported form action.\n\nChoose one persistence destination by default:\n\n| Destination branch | Select this branch when | Action |\n| --- | --- | --- |\n| ChatGPT personal Skills | `surface = chatgpt_web` and the run exposes a product-backed personal Skills install surface, such as a native skill draft/upload/install action or an installable skill package preview. | Install the generated skill into the user's personal Skills library. Capture the installed skill link or Skills-library reference returned by the install surface and include it as a Markdown link in the chat response. Verify through the available Skills-library, list, or fresh-thread discovery surface when the runtime exposes one. |\n| Local Codex | The user asks for local persistence, or `surface = codex_desktop`. | Write a filesystem skill to `$CODEX_HOME/skills/<area>-semantic-layer`; if `$CODEX_HOME` is unavailable and the local runtime clearly uses the default home location, use `~/.codex/skills/<area>-semantic-layer`. Validate the written skill and verify it is discoverable in a new local Codex context when possible. |\n| Portable package | The current run has no supported persistent skill destination. | Return a portable skill package or source plan and clearly state that it has not been installed persistently, including the exact persistence blocker. |\n\nFor dual ChatGPT web and local Codex availability, install the same canonical package into both the ChatGPT Skills library and the local Codex user-skill directory.\n\nFor ordinary data work, return to the Data Analytics `index` workflow.\n\n## Skill Configuration\n\n### Audience And Language\n\nWrite for Data Analytics users, not plugin maintainers. Explain what context would improve the current or future analysis in practical terms. Avoid implementation terms such as raw state paths, connector ids, cache, runtime, metadata, or preflight unless the user asks for debugging details.\n\n### Source Links\n\nWhen referencing sources inline, prefer clickable Markdown links over plain labels whenever a useful URL exists. Use the source title, record name, channel/thread, or meeting/date as the link text. Use plain labels only when no useful link is available.\n\n## Semantic Layer Setup\n\nUse this flow when the user wants to create or maintain a semantic layer. If they are not ready to create the layer yet, use the same flow to produce a short source plan for what the semantic layer needs.\n\nThe output is a visible skill or plan. Build the semantic-layer skill when enough source-backed detail exists to make it useful. When the available detail is still thin, return a practical plan that explains what source to collect next and why.\n\n## Creating Or Updating The Layer\n\nCreate one semantic layer per coherent product, business, metric, source, or reporting area unless the user explicitly asks for a broader shared layer. Infer the area from the provided context when it is clear; ask only when the answer changes the crawl, destination, or resulting skill.\n\nChoose the destination from `Runtime Routing` using the supported persistence mechanism exposed in the current run. For local Codex creations, default to `$CODEX_HOME/skills/<area>-semantic-layer` unless the user chooses another destination. Ask before placing a generated semantic-layer skill inside a plugin.\n\nBefore crawling, build a data-source list that explains what was checked, what is missing, and which sources are lower-confidence. For direct creation or draft-file work, write it to `references/source-inventory.md`; for planning-only work, return it in chat.\n\nUse source-backed evidence. Favor durable sources such as transformation code, tests, maintained metric docs, and verified dashboards over looser signals such as query history or team discussion. If sources disagree, keep the conflict visible instead of choosing silently.\n\nKeep generated semantic-layer skills compact. Put detailed metric definitions, tables, query patterns, caveats, and evidence into linked references using `references/semantic-layer/skill-template.md`. Preserve provenance and avoid copying raw sensitive data, credentials, row-level examples, or long private messages into generated files.\n\nAfter creating or updating a semantic-layer skill, read `references/semantic-layer/weekly-polling-automation.md` and always offer weekly refresh when the layer has a stable target path and usable `references/source-inventory.md`. Weekly refresh is optional: do not create it without explicit user approval unless the user directly asked for recurring refresh. If the offer cannot be made, state the missing prerequisite.\n\nReturn the created or updated path or installed skill link, source coverage, any user-relevant caveats or blockers, future-use guidance, iteration guidance, and the weekly refresh automation offer or prerequisite blocker so the user can cite the semantic layer directly in later prompts. Tell the user they can ask to refine definitions, add sources, update caveats, or adjust the semantic layer as their understanding changes. For ChatGPT personal Skills creations, include the installed skill link in the response.\n\nKeep routine validation details in support artifacts unless a check failed, was unavailable, or changes how the user should rely on the semantic layer.\n\n## Output Contract\n\nFor semantic-layer work, report what was created, updated, inspected, or repaired; source coverage; any user-relevant caveats or blockers; and the exact path or installed skill link the user can cite later. For create or update results, include the weekly refresh automation offer or the missing prerequisite that prevented the offer, and let the user know they can iterate on the semantic layer. Keep routine validation details in support artifacts. If the request is ordinary data work, say that it should be routed through `index`.\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/design-kpis/SKILL.md":"---\nname: design-kpis\ndescription: \"Design KPI frameworks, metric definitions, targets, guardrails, and measurement plans for product or business decisions. Use when success metrics, drivers, guardrails, targets, or the measurement approach need to be defined or improved.\"\n---\n\n# Design KPIs\n\nDesign KPI frameworks, set targets, and develop measurement plans that help teams make product or business decisions.\n\n## When To Use Data Quality First\n\nUse $analyze-data-quality first when the task is to reconcile existing metrics, dashboards, tables, owners, or sources of truth.\n\nReturn to this skill only when the user asks to define the metric going forward, redesign the KPI framework, choose guardrails, or set targets.\n\n## Skill Configuration\n\n### Source Discovery And Verification\n\nUse the relevant semantic layer as a starting map, not a boundary.\n\n1. **Explore all possible sources.** Search every connected or provided source that could contain task-relevant data or change the interpretation. Within each structured-data source, run fresh catalog or metadata discovery for relevant schemas, datasets, tables, views, models, and metrics. Known sources, tables, dashboards, and semantic mappings are starting points, not stopping points.\n2. **Compare duplicates and conflicts.** When sources overlap or disagree, compare ownership, freshness, definition, grain, coverage, and directness. Use the best authoritative source, or combine complementary sources when needed. Note material conflicts, explain why the selected source or sources control the answer, and verify selected data through live reads before concluding.\n\n### Source Access Guardrail\n\nBefore querying sources, building artifacts, or drawing conclusions, determine whether the answer requires a specific source of truth.\n\nIf a required source is unavailable, stop that path. Tell the user what source is needed, ask them to make it available or provide a reviewed fallback, and do not treat weaker substitutes as equivalent.\n\nIf the missing source is only optional enrichment, continue with the strongest available evidence and label the gap when it materially affects the answer.\n\nClarify with the user when a missing input would materially change the analytical frame or recommendation. Otherwise make a reasonable assumption, state it, and proceed.\n\n## Workflow\n\n### 1. Clarify The Decision And Operating Context\n\nUnderstand the decision the metrics need to support, the context in which they will be reviewed, and who will act on the result. Ask the user to clarify the goal, operating cadence, or measurement constraints when missing or ambiguous input would change the recommendation.\n\n### 2. Gather Evidence Before Recommending Metrics\n\nWhen the prompt does not already provide enough context to know what success means, gather that context before recommending metrics or targets. Use $gather-business-context to understand the goal, current state, audience, constraints, risks, existing definitions, prior decisions, and any baseline or target context that should shape the metric system.\n\nFor KPI design, use that context to clarify what success is meant to mean, how related metrics have been defined before, and which constraints or risks should affect the recommended KPIs, drivers, guardrails, or measurement plan.\n\n### 3. Generate A Wider Candidate Set\n\nCreate candidate outcome, driver, and guardrail metrics before narrowing.\nEach candidate should have a clear definition and a plausible link to the decision. Use the example metric shapes below as inspiration when helpful, not as a required template.\n\n### 4. Compare And Select Metrics\n\nCompare candidate metrics by whether they:\n\n- reflect the goal: the metric should represent the intended outcome. When using a proxy, explain why it should reflect real progress and where it could mislead.\n- inform a real decision: movement should change what the team does, prioritizes, or investigates.\n- show useful signal at the decision cadence: a metric can be conceptually good but too slow-moving or noisy for the decision it supports. For example, annual retention may be the right outcome, but it may not help a weekly launch review unless paired with earlier indicators.\n- can be influenced by the team: the team should have plausible levers, or the metric should be paired with drivers it can affect.\n- can be measured operationally: the team should be able to instrument, calculate, and track the metric consistently without one-off manual work.\n- are hard to improve in a misleading way: improving the metric should not obviously hide harm to quality, trust, retention, cost, or another important outcome.\n\nUse lightweight scoring only when it helps explain tradeoffs. Recommend `1-3` primary KPIs, `1-2` driver metrics for each KPI when they improve diagnosis, and `1-2` guardrails when tradeoffs are likely. Do not recommend extra metrics unless they materially improve decision-making.\n\nFor each recommended metric, include enough detail for the team to use it: what it measures, why it matters, how it is calculated, where it comes from, its main pros and cons against the selection criteria above, and what caveats or guardrails matter.\n\n### 5. Set Targets When Needed\n\nTreat target setting as a separate judgment from metric selection. First decide what should be measured; then set targets when the user asks or when the recommendation needs a threshold to be useful.\n\nUse the target-setting approach that best fits the evidence:\n\n- Top-down: start from benchmarks, historical performance, comparable products, competitor or market context, or a reasoned view of what good would need to look like for the decision.\n- Bottom-up: start from what the team can realistically do, such as what is shipping, how adoption is expected to build, or which operating levers should move the metric.\n\nUse data to set or evaluate targets. Once the target-setting approach is clear, identify what data it requires, such as provided inputs, internal performance data, external benchmarks or market data, and results from similar past work.\n\nCompare aspirational targets with what the team can realistically influence through planned work, available audience, expected adoption, and historical movement. A good target should be meaningful for the decision and plausible enough to guide action. Explain the target anchor, key assumptions, and confidence. If the strongest target-setting method requires missing inputs, share the methodology and ask whether the user can provide or identify the relevant data. If there is still enough evidence for a directional target, present it as a provisional range; otherwise recommend the measurement needed before setting a firm target.\n\n### 6. Deliver The Recommendation\n\nKeep the final recommendation concise and decision-oriented, and deliver it inline by default. Do not load `$build-report` merely because the KPI framework uses evidence, compares candidates, or contains several metrics. Use `$visualize-data` and `$build-report` when a data visual would materially improve the answer, such as by showing how a proposed target compares with historical performance or benchmarks, or by clarifying tradeoffs or candidate scoring. Honor an explicitly requested report, dashboard, notebook, spreadsheet, native document, or slide deck as the primary artifact. The recommendation should include:\n\n1. initiative summary\n2. recommended metric candidates, with definition and rationale\n3. target recommendation, if included, with anchor, assumptions, and methodology\n4. evidence reviewed\n5. assumptions and missing context\n6. risks and guardrails\n7. open questions\n\n## Example Metric Shapes\n\nDifferent contexts need different metric shapes. Use these as examples, not a template:\n\n- Product launch or adoption: pair an outcome metric for adoption or value realization with drivers for activation, engagement, repeat use, or time to value, plus guardrails for experience quality.\n- Growth work: choose the business outcome the team is trying to improve, such as activation, retention, or monetization; add drivers that explain how growth is expected to happen and guardrails for quality.\n- Funnel work: choose the progression or completion outcome that represents success; add drivers around where people advance or drop off and guardrails for downstream quality.\n- Operating review: focus on health, pacing, and action-oriented metrics that show whether the business is on track and where attention is needed.\n- Experiment or intervention: use one primary success metric tied to the decision, diagnostics that explain movement, and guardrails for unintended effects.\n- Data, model, or analytics initiative: connect technical performance to the decision or workflow it improves, with adoption, reliability, cost, or fairness guardrails when relevant.\n- Platform, reliability, or operations work: measure service health, throughput, quality, cost efficiency, and customer impact in terms the owning team can act on.\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/gather-business-context/SKILL.md":"---\nname: gather-business-context\ndescription: \"Gather business context from connected or provided sources so downstream analysis starts with the right framing. Use when an analytical question depends on missing context, such as what a metric means, what changed recently, or which sources should be checked. If the same prompt asks for diagnosis, recommendation, or a deliverable, gather context first and continue to the focused skill.\"\n---\n\n## Boundary\n\nUse this skill to gather framing context, not to complete the downstream analysis.\n\nIf the same request also asks for a diagnosis, recommendation, dashboard, report, or other analytical deliverable, return only the context needed for that next step and continue with the appropriate focused skill, such as $metric-diagnostics, $product-business-analysis, $build-dashboard, or $build-report.\n\n# Gather Business Context\n\nUse this skill to collect the business context needed to understand an analytical question before doing deeper work. Focus on what the topic is, why it matters, what changed or is being decided, who or what source is closest to the work, and which definitions or artifacts should frame the analysis. This is a retrieval and extraction skill: gather enough context to set up the next step, not a final report, root-cause analysis, or broad background scan. Skip it when the prompt already provides the needed context or the task is fully self-contained.\n\n## Workflow\n\n### 1. Identify The Retrieval Target\n\nEstablish the analytical topic that needs context and why it matters for the next step. Capture the boundary needed to search and interpret sources, such as the relevant product area, audience, time period, or decision. If the timeframe is missing, use the narrowest reasonable window implied by the task and label it as an assumption.\n\n### 2. Build Search Anchors\n\nSearch with concrete identifiers rather than broad topic guesses. Start with the names the user provided or the sources surfaced, then expand with adjacent terms that help recall, such as aliases, owners, teams, dates, source names, related entities, or entities found in earlier results.\n\nStart broad enough to avoid missing relevant context. If too much comes back and a quick scan suggests the results are mostly unrelated, combine anchors to narrow retrieval, for example a metric plus a dashboard name, a feature plus a launch window, or a customer plus the relevant workflow. If a likely source comes back thin, revise the anchors before treating the source as missing.\n\n### 3. Search From Discovery Points Toward Authoritative Artifacts\n\n1. **Explore all possible sources.** Search every enabled or provided source family that could contain useful context or task-relevant data. Within each structured-data source, run fresh catalog or metadata discovery for relevant schemas, datasets, tables, views, models, and metrics. User-named sources, known tables, dashboards, and semantic-layer anchors are starting points, not stopping points.\n2. **Compare duplicates and conflicts.** When sources overlap or disagree, compare authority, freshness, definition, scope, and directness. Prefer artifacts closest to what was decided, defined, implemented, or measured; follow linked evidence when useful. Note material conflicts and explain which source or combination should guide downstream analysis.\n\n### 4. Extract Only Decision-Shaping Context\n\nTreat business context as a fixed extraction target, not an open-ended summary. Capture the facts that will shape the downstream analysis: the topic's business meaning, why it matters now, how it is defined or measured, where to verify it, what recently changed, and what uncertainty should travel with the analysis. Examples can include a metric definition, current rollout state, dashboard link, owner note, source conflict, or stated next step.\n\nKeep the context note focused on details that help frame the next analysis. Skip broad background, adjacent history, or long source excerpts unless they add useful context.\n\n### 5. Keep Source Notes Compact And Attributable\n\nFor each useful source, record enough attribution for the downstream work to be checked later: when the source applies, what kind of source it is, what factual context it established, and any important caveat or conflict. Distinguish source facts from inference and do not imply source review, stakeholder views, metric certainty, or confidence beyond what was actually established.\n\n### 6. Reconcile Conflicts Explicitly\n\nWhen sources disagree in a way that could change the downstream framing, preserve the disagreement instead of smoothing it over. Prefer the newest explicit decision artifact over older plans, owner-written docs over third-party summaries, and implementation artifacts over aspirational plans when the question is what is live, shipped, logged, or queryable now. Treat an informal source as stronger than a canonical artifact only when it clearly records a later decision or owner confirmation.\n\nIf disagreement remains, present both views, label the conflict, and state what source or owner would resolve it. If context is stale or incomplete, say what is missing and where to look next.\n\n### 7. Stop Once The Framing Is Sound\n\nStop gathering context when the downstream task can be framed well enough to proceed and the likely enabled or provided source families have been checked, ruled out as unavailable, or identified as too thin. Before stopping, make sure the next step has a clear enough understanding of the topic, why it matters, where the important definitions came from, what recent context applies, and what gaps remain.\n\nContinue searching when a relevant enabled or provided source is likely to add useful context. If an expected source was not found, name that as a gap rather than implying it does not exist.\n\n### 8. Return A Lightweight Context Note When Useful\n\nPrefer a focused context note over a full report or raw retrieval dump. Include enough context for the next analysis to proceed without redoing the search: a short summary, the relevant context, important definitions or source links, uncertainty or caveats, and citations. Keep it readable, but do not compress away details that explain the framing or source quality.\n\nIf the user asked only for quick orientation, shorten the structure while preserving citations, conflicts, and missing canonical artifacts.\n\n## Standards\n\nJudge sources by what they can actually establish. Informal discussion can be useful for discovery and recent context, but durable artifacts are usually stronger evidence for definitions, decisions, status, and measured results once found. Prefer sources close to the work, recent enough to reflect current reality, and explicit about what they establish. Surface missing source-of-truth artifacts as context gaps.\n\nKeep important claims attributable. Treat a source as useful only when it clarifies how the downstream task should be framed or interpreted; sources that merely mention the topic are incidental. Preserve enough evidence to check the work later, and label interpretation, assumptions, conflicts, and uncertainty when support is thin, stale, indirect, or conflicting.\n\nPreserve disagreements that could change the framing. Prefer owner-authored or decision-adjacent material and evidence of what is current over secondhand summaries or speculation. Do not infer consensus from silence. Say what source or owner would resolve an important conflict.\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/index/SKILL.md":"---\nname: index\ndescription: \"Route broad Data Analytics requests to the appropriate quantitative analysis, visualization, dashboard, report, notebook, KPI, market-sizing, validation, or semantic-layer workflow.\"\n---\n\n# Data Analytics Router\n\nUse this workflow when Data Analytics is explicitly invoked or the request requires structured records, quantitative evidence, metrics, or an evidence-backed product or business decision. Do not use it for ordinary prose drafting, file-format conversion, or qualitative description that does not require data interpretation.\n\n## Choose the focused workflow\n\n- Metric changed, missed a target, or differs from expectation: read `../metric-diagnostics/SKILL.md`.\n- Product or business decision, prioritization, segmentation, launch, or experiment recommendation: read `../product-business-analysis/SKILL.md`.\n- Dataset, dashboard, source, join, freshness, grain, or metric trust question: read `../analyze-data-quality/SKILL.md`.\n- KPI framework, canonical definition, target, driver, or guardrail design: read `../design-kpis/SKILL.md`.\n- KPI status update, WBR, MBR, QBR, or operating readout: read `../kpi-reporting/SKILL.md`.\n- Dashboard or monitoring view: read `../build-dashboard/SKILL.md`.\n- Durable analytical report: read `../build-report/SKILL.md`.\n- Chart or quantitative figure: read `../visualize-data/SKILL.md`.\n- Reproducible SQL/Python notebook: read `../jupyter-notebooks/SKILL.md`.\n- TAM, SAM, SOM, segment, or opportunity sizing: read `../market-sizing/SKILL.md`.\n- Review an analysis before sharing: read `../validate-data/SKILL.md`.\n- Create, repair, or save reusable data context or a semantic layer: read `../create-data-context/SKILL.md`.\n- Missing business definitions, ownership, change context, or decision framing: read `../gather-business-context/SKILL.md` before the primary workflow.\n\nLoad every selected workflow completely. Follow its related-skill rules when applicable. A task can combine workflows; use this usual order:\n\n1. Gather missing business context.\n2. Validate source quality and metric definitions.\n3. Perform the focused analysis.\n4. Validate conclusions.\n5. Visualize or create the requested durable artifact.\n\n## Source access\n\nUse the best source already available through the code-agent harness: local files, uploaded data, pasted results, databases, warehouses, BI systems, product analytics tools, notebooks, documents, or callable connectors. Tool availability is determined by the host, not by this skill.\n\nWhen no usable source is available:\n\n- Ask for the smallest useful artifact: a CSV/XLSX file, query result, schema, metric definition, dashboard export, screenshot, or pasted table.\n- Offer `assets/demo-product-growth.csv` only as a clearly labeled synthetic demonstration. Never use sample data to answer a real-data question.\n- Do not invent records, measurements, source access, or query results.\n\nIf available sources conflict in a way that changes the answer, surface the conflict and use the data-quality workflow. Otherwise choose the most authoritative and fresh source and proceed.\n\n## Portable output policy\n\nThis bundle targets a generic code agent and does not depend on React, MCP Apps, widgets, or a proprietary rendering surface.\n\n- Inline answers: concise Markdown with findings, evidence, caveats, and next actions.\n- Reports: Markdown by default; use self-contained plain HTML, PDF, DOCX, or another requested format only when the host can create and verify it.\n- Charts: use reproducible Python/Matplotlib, notebook-native plotting, SVG, or destination-native chart tools.\n- Dashboards: prefer a self-contained plain HTML/JavaScript artifact, Streamlit when Python execution is appropriate, or an existing BI platform selected by the user.\n- Notebooks: keep SQL/Python reproducible and make assumptions visible.\n\nPreserve source names, metric definitions, grain, time windows, filters, units, and uncertainty. Never expose credentials, secrets, hidden reasoning, or unnecessary personal data.\n\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/jupyter-notebooks/SKILL.md":"---\nname: jupyter-notebooks\ndescription: \"Create, edit, or validate reproducible SQL or Python notebooks. Use for notebooks, SQL/Python scratchpads, reproducible exploration, audit trails, or runnable companions where the analysis should be reviewable or rerunnable.\"\n---\n\n## Related Skills\n\nUse $validate-data when notebook results support a recommendation, shared claim, or decision.\n\n# Jupyter Notebooks\n\nCreate clean, reproducible Jupyter notebooks that are easy to skim, rerun, and handoff. Treat the notebook as a reader-facing analysis artifact, not a scratchpad dump. Notebook work is not complete until the notebook executes successfully top-to-bottom, or the execution gap is called out with the exact validation steps needed to reproduce it.\n\n## Workflow\n\n1. Lock the notebook mode and scope.\n\n   Decide whether the notebook is an analysis report, experiment log, diagnostic notebook, data-quality check, market-sizing calculation, model exploration,\n   tutorial, or companion artifact for a report. Identify the reader, decision,\n   expected handoff, required inputs, and whether the task calls for a new notebook or targeted edits to an existing one.\n\n2. Inspect or scaffold with notebook-safe tooling.\n\n   Prefer JupyterLab, `nbformat`, `nbclient`, or an existing scaffold utility over hand-editing raw JSON. When editing an existing notebook, preserve its intent and minimize JSON churn. Avoid reordering cells unless it clearly improves the top-to-bottom story. If raw JSON editing is unavoidable,\n   validate the notebook structure before finishing.\n\n3. Structure the notebook for the chosen mode.\n\n   For analytical notebooks, default to:\n\n   1. `## tl;dr`\n   2. `## Context & Methods`\n   3. `## Data`\n   4. `## Results`\n   5. `## Takeaways`\n\n   Write `tl;dr` and takeaways after reviewing executed outputs. Use concrete observed values, visible patterns, rows, or charts, not assumptions. Include a `### Key Assumptions` subsection in `Context & Methods` when assumptions affect correctness.\n\n   For tutorials or walkthroughs, adapt the same discipline to a teaching flow:\n\n   1. `## Goal`\n   2. `## Setup`\n   3. `## Steps`\n   4. `## Checks`\n   5. `## Next Steps`\n\n4. Build a clear data and computation path.\n\n   Separate setup, imports, parameters, data loading, data preparation,\n   calculations, visualizations, and interpretation. If the notebook uses both SQL and Python, keep complex SQL in SQL cells or separate query files rather than large embedded Python strings unless there is a clear reason. Use descriptive variable names and keep each code cell focused on one step.\n\n5. Use data sources deliberately.\n\n   When a notebook needs table data, first use `~~structured_data` to confirm table choice, schema, partition filters, sample rows, and query-submission policy. Use the relevant source connector when available, then fall back to exports or pasted SQL when needed. Use `~~operations_logs` for freshness or lineage checks when they matter. Record query permalinks, request IDs, source paths, dashboard links,\n   extract names, or other source artifacts in the notebook context for any executed result that supports the analysis. Keep heavy queries filtered and bounded instead of turning the notebook into a broad live-source scan.\n\n6. Make cells readable and bounded.\n\n   Add concise markdown headers before most code cells. Keep headers brief and action-oriented, such as `### 1. Load Data`, `### 2. Validate Inputs`, or `### 3. Plot Results`. Favor several short cells over one large mixed-purpose cell. Keep prose short: explain purpose, assumptions, and expected result, not every line of code. Split multiple tables or charts across separate cells instead of dumping all outputs from one cell.\n\n7. Validate results before writing conclusions.\n\n   Check that key numbers, charts, and takeaways match executed outputs. Bound raw debug output, oversized tables, and noisy logs. If a result is surprising, add a local reasonableness check, small sample inspection, or reconciliation against a trusted source before promoting it to the summary.\n\n8. Execute and record validation status.\n\n   Run the notebook top-to-bottom when the environment allows:\n\n   ```bash\n   python -m jupyter nbconvert --execute --to notebook --inplace path/to/notebook.ipynb\n   ```\n\n   Optional local setup when needed:\n\n   ```bash\n   uv pip install jupyterlab nbformat nbclient ipykernel\n   ```\n\n   If execution is not possible, say so explicitly and provide the exact command,\n   missing dependency, credential, data access, kernel, or environment step needed to validate locally.\n\n## Standards\n\n### Notebook Structure\n\n- Make the default top-to-bottom read clear before the reader starts executing cells out of order.\n- Put executive summary material at the top, but write it last after inspecting executed results.\n- Keep notebook sections aligned with the notebook mode: analysis, experiment,\n  diagnostic, tutorial, or handoff artifact.\n- Keep section titles, chart titles, labels, and file names descriptive enough for handoff.\n- Preserve the existing notebook's intent when refactoring; improve structure without rewriting everything by default.\n\n### Reproducibility\n\n- Keep parameters, date ranges, filters, cohorts, assumptions, and source references visible near the top of the notebook.\n- Record enough source context for another reader to trace the analysis: query permalinks, request IDs, table names, source paths, spreadsheet tabs,\n  dashboard links, extract versions, or input file locations.\n- Make computation deterministic where possible. Avoid hidden state, manually edited intermediate values, out-of-order dependencies, and unexplained cached outputs.\n- Prefer explicit environment setup cells or notes when the notebook depends on nonstandard packages, kernels, credentials, or local files.\n- Execute the notebook when the task requires a runnable artifact. In the final response, do not add a separate routine validation section for a clean run; surface execution gaps, partial execution, or unrun notebooks with the reason because those affect whether the user can rely on the artifact.\n\n### Code And Data Hygiene\n\n- Separate data preparation from presentation.\n- Keep complex SQL readable and documented with a one-line goal comment.\n- Keep plotting and lightweight shaping in Python after the data preparation step is complete.\n- Use descriptive variable names and avoid abbreviated temporary names in reader-facing notebooks.\n- Keep outputs bounded. Prefer small preview tables, sampled rows, explicit limits, and focused charts over raw dumps.\n- Avoid broad live-source scans. Filter queries by needed partitions, cohorts,\n  or time windows.\n\n### Analysis Quality\n\n- Make assumptions explicit when they affect interpretation.\n- Tie takeaways to executed outputs with concrete numbers, rows, charts, or visible patterns.\n- Do not promote unexecuted or unverified calculations into the `tl;dr`.\n- Label caveats, incomplete checks, missing source access, and known validation gaps.\n- Add reasonableness checks for surprising results, high-impact claims, or stakeholder-facing conclusions.\n\n### Validation Checklist\n\n- Required section order is present for the notebook mode.\n- The notebook executes without runtime errors, or execution failure is called out explicitly.\n- Outputs are present where expected and are not dominated by raw debug dumps.\n- The `tl;dr`, results, and takeaways match executed cells.\n- Source references and query or artifact links are preserved.\n- Tables and charts are labeled, bounded, and interpretable.\n- The final response includes the notebook path and validation status.\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/kpi-reporting/SKILL.md":"---\nname: kpi-reporting\ndescription: \"Prepare KPI readouts, scorecards, WBR/MBR/QBR updates, and executive summaries from quantitative business or product metrics; use when the task is to report status, compare against targets, explain validated drivers, and state operating implications.\"\n---\n# KPI Reporting\n\nUse this skill to turn business or product metrics into decision-ready operating readouts for leaders and teams. The job is to define the KPI contract, report status against the right comparison and target, include validated driver context, and state the operating implication clearly.\n\nClarify with the user when a missing input would materially change the analytical frame or recommendation. Otherwise make a reasonable assumption, state it, and proceed.\n\nThis skill owns the KPI readout: what should be reported, how metrics should be interpreted, whether driver context is validated, and what operating takeaway follows. It does not own metric-system design, new driver investigation, or final artifact polish.\n\nUse $metric-diagnostics when the readout needs fresh driver investigation, then return here to package the validated finding.\n\n## Skill Configuration\n\n### Source Discovery And Verification\n\nUse the relevant semantic layer as a starting map, not a boundary.\n\n1. **Explore all possible sources.** Search every connected or provided source that could contain task-relevant data or change the interpretation. Within each structured-data source, run fresh catalog or metadata discovery for relevant schemas, datasets, tables, views, models, and metrics. Known sources, tables, dashboards, and semantic mappings are starting points, not stopping points.\n2. **Compare duplicates and conflicts.** When sources overlap or disagree, compare ownership, freshness, definition, grain, coverage, and directness. Use the best authoritative source, or combine complementary sources when needed. Note material conflicts, explain why the selected source or sources control the answer, and verify selected data through live reads before concluding.\n\n### Source Access Guardrail\n\nBefore querying sources, building artifacts, or drawing conclusions, determine whether the answer requires a specific source of truth.\n\nIf a required source is unavailable, stop that path. Tell the user what source is needed, ask them to make it available or provide a reviewed fallback, and do not treat weaker substitutes as equivalent.\n\nIf the missing source is only optional enrichment, continue with the strongest available evidence and label the gap when it materially affects the answer.\n\n## Workflow\n\n### 1. Clarify The Readout Purpose\n\nUnderstand who the readout is for, what conversation it supports, and what is being reported before drafting. Anchor the update in the period being evaluated, the comparison or target that makes performance interpretable, and the freshness cutoff.\n\nAsk the user for missing context when it would help make the readout more accurate or useful.\n\n### 2. Define The Metric Framework\n\nDecide which metrics belong in the readout and what role each one plays before pulling numbers. If the framework already exists, confirm it and use it. If it is missing or weak, use $design-kpis before reporting.\n\nStart with the primary KPI, then add the smallest set of supporting metrics needed to explain status. Supporting metrics can explain movement, guard against harmful tradeoffs, or show whether performance is pacing as expected.\n\nLead with the metric that matters most to the audience. Do not add every available cut or comparison; include the metrics and slices decision-makers actually use, plus any that materially explain this update.\n\nWhen the primary KPI is top-line, composite, or otherwise not directly actionable, define its driver decomposition before interpreting it. Use an existing metric tree when available. Otherwise identify the smallest useful set of component drivers, such as numerator and denominator, volume and rate, mix, funnel stages, segments, cohorts, or operational inputs. Do not invent a causal hierarchy when source definitions do not support one.\n\n### 3. Lock Metric Definitions And Sources\n\nConfirm the KPI definition, source, time window, reporting cutoff, comparison period, and any target or pacing expectation before interpreting performance. If a target or pacing basis is missing, ask before treating one as authoritative. Use $analyze-data-quality when source quality issues could change the reported metrics.\n\nFor all KPI updates, make a focused source pass across `~~structured_data`, `~~company_docs`, `~~team_communication`, and `~~dashboards_or_bi` before drafting. Do not infer from a sparse prompt that source-backed actuals are unavailable. Use structured data for actuals, metric definitions, and comparison periods; use the other lanes for additional business context and source-of-truth guidance.\n\nIf any core definition is unclear, ask the user to clarify before making precise claims. When a metric definition changed, show comparable restated history when available; otherwise call out the break clearly.\n\n### 4. Pull The Topline Actuals\n\nDo not draft or render a WBR, MBR, scorecard, or KPI update from placeholders. Query or inspect connected structured-data sources for core actuals first. If actuals are blocked or insufficient, stop and say what source or access is needed unless the user explicitly asked for a template or mockup.\n\nReproduce the topline actual before explaining movement or driver context.\n\nFor each headline KPI, include the current value, the absolute and relative change versus the comparison period, and a short interpretation.\n\nCall out anything that makes the current value hard to compare with the prior period before interpreting the movement, such as a tracking change, data backfill, partial outage, or missing day.\n\n### 5. Put The Numbers In Context\n\nCompare actuals against the context that makes performance interpretable. When a target, plan, pacing model, benchmark, historical range, or relevant peer group is defined, identify it and compare performance against it before judging status.\n\nIf the goal has a deadline, do not just report whether the metric is above or below target. Show whether it is on pace to hit the target by the end of the period. Use the provided pacing definition when available. If none is defined or found, ask the user; when proceeding with a calculated fallback, state that it was calculated and explain the method.\n\nWhen useful, include absolute and percent variance to target and a red/yellow/green status. Make clear what comparison or pacing basis the status label uses.\n\n### 6. Explain Validated Drivers\n\nKPI updates need driver context, but driver claims must be validated before they are presented as explanations. A plausible story is not enough.\n\nWhen the readout needs to explain drivers, use $metric-diagnostics to identify and validate them. If trusted reporting or prior analysis already validates the drivers, use that evidence instead of re-running the diagnostic.\n\n### 7. Add Business Context And Operating Implications\n\nAfter identifying the likely drivers, use $gather-business-context to look for business context that helps explain what happened and what it means for the readout. Let the driver analysis guide what context to look for, and connect context to the metric only when evidence supports the link.\n\nTranslate the evidence, driver analysis, and business context into the operating implication for the business. State whether the movement is concerning, what next step or action is warranted, and whether the main KPI is on track, at risk, or ahead of plan. Recommend action only when the evidence supports it; otherwise name the next validation step.\n\n### 8. Validate The Readout\n\nAfter the analysis is assembled and before shaping the final readout, use $validate-data to review whether the numbers, methodology, caveats, and evidence support the claimed status, drivers, and implications. Resolve material issues before sharing; carry remaining limitations into the readout.\n\n### 9. Hand Off The Readout\n\nEnd by handing the validated KPI readout to $build-report unless the user explicitly requests an inline, chat-only, brief/no-artifact answer, asks not to create a report/file/artifact, or selects another primary artifact. A quick status update, brief readout, or findings-in-chat request is an inline output choice unless the user also asks for a report, document, deck, or durable artifact. When no explicit human waiver was given, the report handoff is mandatory; do not infer a waiver only because the user did not use the word \"report\".\n\nBefore handoff, make the readout explicit:\n\n- headline status and operating implication\n- actuals, targets, pacing basis, and comparison periods\n- validated drivers and unresolved uncertainty\n- audience, cadence, and requested delivery surface when known\n- charts or figures that would clarify the readout\n\nLoad `references/report-templates.md` before handing off and use the matching pattern as source notes for $build-report. Tell $build-report this is a KPI readout and pass the status, pacing, driver, uncertainty, audience, cadence, surface, and visual guidance above. Do not render charts directly from this skill; pass visual intent and supporting evidence to $build-report so $visualize-data owns chart selection and QA.\n\nFor slide or deck requests, use $build-report to create a portable source report first, then use an available presentation workflow or document tool to create and verify the deck. Preserve the same source evidence and findings across formats.\n\n## Standards\n\n### Metric Standards\n\n- Never present a KPI as precise when its definition, source, time window, or comparison basis is unclear.\n- Make calculation logic, inclusion or exclusion rules, grain, and time treatment explicit when they affect interpretation.\n- Reconcile totals and compare against prior reporting when possible.\n- Do not compare periods, cuts, or targets that are not definitionally compatible. Call out definition changes, backfills, denominator shifts, or calendar effects when they affect the movement.\n\n### Status And Pacing Standards\n\n- Include the headline takeaway, current actual, relevant comparison, target or pacing context, driver summary, and implication unless the user asks for a narrower readout.\n- Put actuals next to the target, plan, benchmark, or baseline when available so the reader can judge performance immediately.\n- If a target is time-bound, show whether current performance is on pace using the provided pacing definition or a clearly stated calculated fallback.\n- Keep recurring metric sections consistent across runs. If a requested section is missing because data, definitions, or validation are unavailable, explain the omission briefly.\n- Use traffic-signal status only when it helps prioritize action. Pair color with text and state the basis for the status.\n- Round numbers consistently, label units, and surface caveats when they change interpretation.\n\n### Driver Standards\n\n- Quantify drivers whenever the evidence supports it; do not use descriptive prose as a substitute for sizing the effect.\n- Report the few drivers, contributors, or known non-drivers that matter for interpreting the KPI movement.\n- For top-line KPI movement, structure validated drivers as a compact decomposition: top-line actual, component drivers, largest contributors or non-drivers, and residual or unresolved movement. Use an additive bridge only when the components reconcile cleanly; otherwise explain the relationship and uncertainty.\n- Separate validated drivers from business context or hypotheses.\n- Do not elevate business events into causes unless the timing, affected population, and measured change support the link.\n- State whether the movement is broad-based or concentrated when that changes the operating implication.\n- If driver evidence remains unresolved, name the uncertainty or diagnostic follow-up instead of inventing an explanation.\n\n### Presentation Standards\n\n- Write for executives and operators who skim: lead with the answer, then the evidence.\n- Use business-readable numbers and compact formats such as `123k (+8% w/w, +19% m/m)`.\n- Replace generic adjectives like `strong`, `healthy`, or `soft` with the metric evidence that justifies them.\n- Keep caveats close to the claim they affect, and omit caveats that do not change interpretation.\n- Use charts, tables, scorecards, or KPI cards only when they make the takeaway easier to understand and remain readable in the final delivery context.\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/market-sizing/SKILL.md":"---\nname: market-sizing\ndescription: \"Estimate market, segment, or opportunity size with transparent assumptions and uncertainty. Use for TAM/SAM/SOM, sizing scenarios, or comparing the scale of possible opportunities.\"\n---\n\n## Related Skills\n\nUse $visualize-data when the sizing result needs a chart or figure.\n\nUse $build-report to package the final estimate, assumptions, sensitivity, caveats, and source context whenever this skill is selected, unless the user explicitly requests an inline, chat-only, brief/no-artifact answer, asks not to create a report/file/artifact, or selects another primary artifact.\n\n# Market Sizing\n\nUse this skill to produce a defensible estimate of a market or opportunity from connected context, public sources, transparent assumptions, and auditable calculations. The job is to define the market, choose a sound sizing method, distinguish evidence from assumptions, test sensitivity, and state what would most improve confidence.\n\n## Skill Configuration\n\n### Source Discovery And Verification\n\nUse the relevant semantic layer as a starting map, not a boundary.\n\n1. **Explore all possible sources.** Search every connected or provided source that could contain task-relevant data or change the interpretation. Within each structured-data source, run fresh catalog or metadata discovery for relevant schemas, datasets, tables, views, models, and metrics. Known sources, tables, dashboards, and semantic mappings are starting points, not stopping points.\n2. **Compare duplicates and conflicts.** When sources overlap or disagree, compare ownership, freshness, definition, grain, coverage, and directness. Use the best authoritative source, or combine complementary sources when needed. Note material conflicts, explain why the selected source or sources control the answer, and verify selected data through live reads before concluding.\n\n### Source Access Guardrail\n\nBefore querying sources, building artifacts, or drawing conclusions, determine whether the answer requires a specific source of truth.\n\nIf a required source is unavailable, stop that path. Tell the user what source is needed, ask them to make it available or provide a reviewed fallback, and do not treat weaker substitutes as equivalent.\n\nIf the missing source is only optional enrichment, continue with the strongest available evidence and label the gap when it materially affects the answer.\n\nClarify with the user when a missing input would materially change the estimate or recommendation. Otherwise make a reasonable assumption, state it, and proceed.\n\n## Workflow\n\n### 1. Frame The Market Or Opportunity\n\nDefine the market or opportunity boundary before estimating:\n\n- What is being sized, for example a product category, workflow, problem, use case, or category of activity.\n- Where and when it applies, for example geography, segment scope, time horizon, or market maturity.\n- Who or what counts as part of the market, for example the relevant population, unit of demand, transaction type, or included activity.\n- How the opportunity is measured, for example spend, revenue, volume, value created, or another unit that fits the question.\n- What kind of sizing answer the user needs, for example TAM/SAM/SOM, market entry, expansion upside, spend pool, revenue pool, population count, or unit volume.\n\n### 2. Choose A Starting Sizing Approach And Inputs\n\nPick the simplest sound sizing approach for the question, then sketch the calculation chain and the major inputs the estimate will depend on.\n\nA top-down model works when reliable aggregate market data exists; a bottom-up model works when the market can be built from observable units and assumptions; a value-based model works when the estimate should start from the value created rather than a published market total. Use a mixed approach only when cross-checking would materially improve confidence. If more than one approach fits, briefly explain which one you trust most and why.\n\nExpect the first approach to change if source checks show that another model would be more defensible.\n\n### 3. Gather Sources For The Inputs\n\nChoose sources based on the inputs the estimate depends on most.\n\nStart with user-named sources when provided. Then use the strongest available evidence for each major input from the starting approach. Use `~~structured_data` when an input should come from the user's data warehouse or another structured data source. Use context lanes such as `~~company_docs`, `~~team_communication`, or `~~dashboards_or_bi` when an input needs business meaning, source-of-truth guidance, or assumptions that are not captured in structured data alone. When an input depends on the outside market, use public sources for benchmarks, population estimates, comparable markets, or proxy assumptions.\n\nUse $gather-business-context to resolve context lanes when the right source of truth, business meaning, or assumption set is unclear.\n\nIf the strongest source is unavailable or thin, continue with a transparent proxy assumption only when the estimate is still useful. Label the gap and explain how it affects confidence.\n\n### 4. Separate Facts From Assumptions\n\nKeep sourced facts, inferred estimates, and judgment calls distinct in the model. When exact data is unavailable, use a defensible proxy, explain why it is reasonable, and note the confidence level. Ground assumptions in evidence about how the market actually behaves, what can realistically change, and what determines the size of the opportunity.\n\n### 5. Build The Model\n\nMake the model easy to inspect and adjust.\n\nThe model should make these elements easy to audit or revise:\n\n- market definition and measurement unit\n- assumptions and source context\n- calculation chain and derived values\n- base case, material ranges, and sensitivity logic\n- validation priorities\n\nFor each major input, make the source path visible: structured data, context lane, public source, user-provided input, or proxy assumption.\n\nKeep derived values traceable to formulas or code rather than hardcoded outputs.\n\nUse $jupyter-notebooks when code is needed for source harmonization, calculations, sensitivity analysis, or reusable modeling logic. Keep formulas, inputs, intermediate calculations, and sensitivity logic inspectable.\n\nUse the `$Spreadsheets` skill when the user requests a spreadsheet, workbook, or Google Sheets deliverable, or when a market-sizing model would materially benefit from editable assumptions, sensitivity tables, charts, or polished workbook formatting.\n\n### 6. Test Sensitivity\n\nIdentify the assumptions that move the estimate most.\n\nShow how the estimate changes when those assumptions move up or down. Prefer simple, decision-useful sensitivity analysis over exhaustive scenario sprawl.\n\nUse ranges when uncertainty is material. Do not hide uncertainty behind a single point estimate when the inputs are thin.\n\n### 7. State The Estimate And Validation Priorities\n\nEnd by handing the estimate, method, key assumptions, uncertainty, and next validation priorities to $build-report unless the user explicitly waives report creation or selects another primary artifact. This handoff is mandatory when no explicit human waiver was given; do not infer a waiver because the user asked for an estimate or did not use the word \"report\". This workflow owns the sizing model and conclusion; $build-report owns the reader-facing structure, visuals, evidence placement, and delivery surface.\n\nBefore handoff, make the market-sizing conclusion explicit:\n\n- market definition and measurement unit\n- estimate or range\n- method and calculation chain\n- key assumptions and source support\n- main uncertainty drivers and sensitivity takeaways\n- validation priorities and practical interpretation for the user's decision\n\nIf source coverage is thin, say which major inputs rely on proxy assumptions and what source would most improve them.\n\nUse $validate-data when methodology, calculations, assumptions, caveats, or source support need review before sharing.\n\nDo not render charts directly from this skill. If a sensitivity, scenario, funnel, or market-breakdown visual would clarify the estimate, pass that visual intent and supporting evidence to $build-report so $visualize-data owns chart selection and QA.\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/metric-diagnostics/SKILL.md":"---\nname: metric-diagnostics\ndescription: \"Diagnose why a metric changed or differs from expectation. Use when the task is to identify likely drivers of a metric movement, anomaly, gap, or discrepancy.\"\n---\n\n## Related Skills\n\nUse $gather-business-context when business context is needed to understand the metric, analysis period, ownership, or plausible explanations.\n\nUse $product-business-analysis when the task asks for a recommendation or tradeoff decision after diagnosing the movement.\n\nUse $analyze-data-quality when dashboard trust, grain, freshness, or source disagreement could affect the metric.\n\n# Metric Diagnostics\n\nUse this skill to diagnose why a metric changed or differs from expectation. Reproduce the metric, define the comparison, quantify the movement, validate likely drivers, and state what is verified, likely, unresolved, and useful to do next.\n\nClarify with the user when a missing input would materially change the analytical frame or recommendation. Otherwise make a reasonable assumption, state it, and proceed.\n\n## Skill Configuration\n\n### Source Discovery And Verification\n\nUse the relevant semantic layer as a starting map, not a boundary.\n\n1. **Explore all possible sources.** Search every connected or provided source that could contain task-relevant data or change the interpretation. Within each structured-data source, run fresh catalog or metadata discovery for relevant schemas, datasets, tables, views, models, and metrics. Known sources, tables, dashboards, and semantic mappings are starting points, not stopping points.\n2. **Compare duplicates and conflicts.** When sources overlap or disagree, compare ownership, freshness, definition, grain, coverage, and directness. Use the best authoritative source, or combine complementary sources when needed. Note material conflicts, explain why the selected source or sources control the answer, and verify selected data through live reads before concluding.\n\n### Source Access Guardrail\n\nBefore querying sources, building artifacts, or drawing conclusions, determine whether the answer requires a specific source of truth.\n\nIf a required source is unavailable, stop that path. Tell the user what source is needed, ask them to make it available or provide a reviewed fallback, and do not treat weaker substitutes as equivalent.\n\nIf the missing source is only optional enrichment, continue with the strongest available evidence and label the gap when it materially affects the answer.\n\n## Workflow\n\n### 1. Define The Diagnostic Question\n\nFrame the diagnostic so it is clear what changed and what comparison would prove it.\n\nDefine:\n\n- what the metric means in business terms\n- the time window and comparison that make the change measurable\n- the population and grain that determine what counts\n- the source that owns the metric definition\n- the diagnostic question being answered, for example movement, concentration, or reconciliation\n\nUse $gather-business-context when business context is needed to understand what the metric means, what changed around the analysis period, or which explanations are plausible.\n\n### 2. Validate The Metric Definition And Source\n\nBefore explaining the movement, confirm that the metric is defined correctly and that the source data can measure it reliably.\n\nConfirm the metric definition, grain, aggregation logic, filters, joins, exclusions, freshness, lineage, and any disagreement between trusted surfaces. Keep this source check focused on issues that could change the answer.\n\nTreat current context, named semantic layers, and familiar table names as source candidates, not source selection. For broad metric questions, run live source discovery against available tables, dashboards, metric docs, semantic layers, or other source-of-truth surfaces before choosing the controlling source. When both are available, inspect at least one business-facing or top-line surface and one lower-level source surface, then state why the selected source owns the answer.\n\nUse $analyze-data-quality when freshness, grain, joins, missingness, schema drift, outliers, unexpected categories, or distribution shifts could affect trust.\n\nUse $jupyter-notebooks when fresh SQL, Python, statistical modeling, reusable calculations, or multi-step decomposition need an inspectable analytical record.\n\n### 3. Establish The Metric Pattern\n\nBefore looking for drivers, establish the metric pattern the diagnostic needs to explain. Quantify the metric over the relevant period and scope. If the question includes a comparison, reproduce that comparison.\n\nDo not search for causes until the size, timing, and scope of the pattern are verified or explicitly marked uncertain.\n\n### 4. Choose The Diagnostic Plan\n\nChoose the smallest set of cuts and checks likely to explain the pattern or strengthen confidence.\n\nChoose driver dimensions from the metric's operating logic, business context, and source shape. Prioritize drivers the business usually monitors or can act on, not every field available in the source. If the relevant drivers are unclear, use current context, a named semantic layer, or $gather-business-context to understand how the business explains the metric and what changed around the analysis period.\n\nWhen using a lower-level table, do not limit the driver analysis to fields surfaced by the first query. Recreate or join the business grouping needed to answer the question, such as model family, model superfamily, segment, region, cohort, product taxonomy, or customer hierarchy. If the grouping cannot be reconstructed, say so before simplifying the analysis.\n\nUse the explanation mode that fits the question. Common examples:\n\n- **Metric change**: compare the focal window with a baseline, rank segment contributions, check peer or historical context, and test mix shift versus within-segment movement.\n- **Spike, regression, or incident**: pin down onset, peak, recovery,\n  distribution shape rather than only averages, affected slices, broad versus localized degradation, and whether traffic or failure behavior changed.\n- **Largest contributors or concentration**: define \"largest\", rank entities,\n  compare total share and change, and look for major movers, entrants, and exits.\n- **Reconciliation or difference analysis**: align definitions, filters, grain,\n  numerator, denominator, and exclusions; quantify the components explaining the gap and state any residual.\n\n### 5. Decompose And Validate Drivers\n\nQuantify the main drivers and validate whether they explain the pattern.\n\nSize each major driver with the strongest readily available evidence. Show whether it explains the pattern, how large it is relative to the relevant base, trend, or gap, whether it is broad or concentrated, and whether it holds under the right comparison or scope.\n\nIterate on driver hypotheses until the explanation answers why in a way that is relevant to the business. Follow promising cross-cuts and drill-downs when they could reveal the key explanation, and stop when additional cuts are unlikely to change the conclusion or materially improve confidence.\n\nInterpret driver results in context:\n\n- Use the relevant base, comparison, or share of total to make the driver meaningful.\n- For rates, check whether the numerator, denominator, or both explain the change.\n- For additive metrics, calculate contribution share when it sharpens the story.\n- Separate composition effects from within-segment performance effects when that distinction changes the explanation.\n- Prefer mutually exclusive driver buckets when additive contributions need to be interpreted; reconcile the decomposition exactly or size and explain the residual.\n\nTreat measurement issues as possible explanations, not just cleanup details. For example, the pattern may come from logging changes, incomplete recent data, duplicated rows, or a shifted denominator rather than an underlying business change.\n\nCalibrate the explanation to the evidence, and make important uncertainty visible. Use context when it changes interpretation, such as whether the pattern is ordinary, unusual, expected, or tied to a known change.\n\nUse $visualize-data when a chart would make the diagnostic claim easier to understand or verify.\n\n### 6. State Implications And Follow-Up\n\nLead with the answer to the diagnostic question, then state the practical implications when the evidence supports them.\n\nThe answer should make clear:\n\n- the pattern being explained\n- the strongest driver explanation and supporting evidence\n- why it matters for the business\n- how much confidence to place in the explanation\n- the implication, next action, or follow-up that matters most\n\nUse $product-business-analysis when the user needs a recommendation or tradeoff decision, not just the diagnostic implication.\n\nKeep implications distinguishable from verified factual reporting so a reader can tell where evidence ends and interpretation begins. Do not claim causality from timing alone; state when an explanation is only a plausible hypothesis.\n\nUse $gather-business-context when the metric result is clear but business context is needed to interpret the `so what` or identify realistic next actions.\n\nUse $validate-data when methodology, calculations, caveats, or the evidentiary support for the diagnostic conclusion need review before sharing.\n\nDo not treat artifact or report validation as analytical validation. Before handing off, confirm the analysis has the headline metric movement, driver contribution shares or effect sizes, source/window reconciliation, exact executed SQL or query references when queries were used, and caveats that would change interpretation.\n\nPass the diagnostic substance and supporting evidence to $build-report unless the user explicitly requests an inline, chat-only, brief/no-artifact answer, asks not to create a report/file/artifact, or selects another primary artifact. This handoff is mandatory when no explicit human waiver was given; do not infer a waiver because the user asked a direct diagnostic question or did not use the word \"report\". Let $build-report own the report surface, presentation polish, reproducibility treatment, and sharing handoff.\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/product-business-analysis/SKILL.md":"---\nname: product-business-analysis\ndescription: \"Analyze product or business data to support a decision or recommendation. Use when a decision depends on metric-backed evidence, such as choosing a direction, prioritizing an opportunity, evaluating a change, segmenting users, sizing tradeoffs, or deciding what to do next.\"\n---\n\n## Related Skills\n\nUse $metric-diagnostics when the recommendation depends on explaining a metric movement, anomaly, gap, or discrepancy.\n\n# Product And Business Analysis\n\nUse this skill to answer product or business questions with data-backed evidence, context, and a recommendation. Give the audience enough trustworthy evidence, interpretation, and uncertainty framing to choose a practical next action.\n\n## Skill Configuration\n\n### Source Discovery And Verification\n\nUse the relevant semantic layer as a starting map, not a boundary.\n\n1. **Explore all possible sources.** Search every connected or provided source that could contain task-relevant data or change the interpretation. Within each structured-data source, run fresh catalog or metadata discovery for relevant schemas, datasets, tables, views, models, and metrics. Known sources, tables, dashboards, and semantic mappings are starting points, not stopping points.\n2. **Compare duplicates and conflicts.** When sources overlap or disagree, compare ownership, freshness, definition, grain, coverage, and directness. Use the best authoritative source, or combine complementary sources when needed. Note material conflicts, explain why the selected source or sources control the answer, and verify selected data through live reads before concluding.\n\n### Source Access Guardrail\n\nBefore querying sources, building artifacts, or drawing conclusions, determine whether the answer requires a specific source of truth.\n\nIf a required source is unavailable, stop that path. Tell the user what source is needed, ask them to make it available or provide a reviewed fallback, and do not treat weaker substitutes as equivalent.\n\nIf the missing source is only optional enrichment, continue with the strongest available evidence and label the gap when it materially affects the answer.\n\nClarify with the user when a missing input would materially change the analytical frame or recommendation. Otherwise make a reasonable assumption, state it, and proceed.\n\n## Workflow\n\n### 1. Start From The Decision\n\nIdentify the decision, audience, and action the analysis should inform before choosing data sources or metrics.\n\nState plainly:\n\n- the question and decision the analysis should inform\n- who will use the answer and what they can act on\n- the scope and comparison that define a useful answer\n- the outcome or behavior that matters for the decision\n- any assumptions needed to proceed\n\nDo not let unclear scope turn into broad exploratory work by default.\n\n### 2. Gather Decision-Relevant Context\n\nRun $gather-business-context before deeper analysis. That skill owns source selection, retrieval, source authority, conflict handling, and compact context notes. Use this workflow to decide how the gathered context changes the analysis and recommendation.\n\nKeep the context pass proportional to the task. For self-contained prompts or cases where the user already provided enough context, the pass can be brief: confirm the decision frame, definitions, source assumptions, and any obvious gaps before moving on. Do not turn mandatory context gathering into a broad background scan.\n\nRelevant context should clarify:\n\n- intent: what the work was meant to accomplish and why\n- definitions: how the work, metric, or source is defined and measured\n- timing: what changed around the analysis period that could affect interpretation\n- constraints: decisions, caveats, or limitations that affect what action is realistic\n\n### 3. Frame The Analysis\n\nTurn the question into a focused analytical framework.\n\nDefine a framework for answering the question with data:\n\n- the specific data questions that would support or change the recommendation\n- the comparisons and dimensions to inspect\n- the unit of analysis that matches the decision\n- the metric definitions and caveats needed to interpret the result\n\nUse the framework to surface plausible hypotheses or interpretations, then turn them into focused data questions. Keep the framework specific enough to avoid broad exploration and support a recommendation.\n\nUse $design-kpis when the success metric, driver metrics, guardrails, or measurement plan need to be defined before the analysis can proceed.\n\nStart by defining what the answer needs to show in plain language. Then choose the data that matches that meaning as closely as possible, including who is counted and what comparison makes the number meaningful. If a field or event captures only part of what the decision cares about, say what it captures and what it leaves out.\n\n### 4. Run Focused Quantitative Analysis\n\nRun enough quantitative analysis to support or reject the framed hypotheses and inform the decision:\n\n- **Follow the framework.** Run the analyses that could change the recommendation first. Track additional data questions that emerge, answer the ones that matter for the decision, and leave lower-impact cuts as follow-up instead of expanding into broad exploration.\n\n- **Use the right comparison.** Interpret results against the relevant baseline, denominator, or comparison point before turning them into a recommendation. For example, do not conclude that one group is the best opportunity just because it has the most total usage. Check whether usage is high because the group is larger, whether the pattern still holds after normalizing by the active base, whether the group is growing or declining, whether the usage reflects the behavior or outcome that matters, and whether business context changes the interpretation.\n\n- **Size the opportunities.** Estimate the magnitude of impact each important opportunity could have. State what is being compared, which metric represents impact, what denominator or population it uses, and whether the data is complete enough to trust. Keep material unknown or unclassified groups visible when they could change the interpretation.\n\n- **Keep quantitative work inspectable.** Use $jupyter-notebooks to record queries and analysis. Use $analyze-data-quality when source freshness, grain, joins, missingness, schema drift, or unexpected distributions could affect trust.\n\n- **Validate before concluding.** Use $validate-data before sharing stakeholder-facing recommendations, high-impact claims, or surprising results. When dashboards and direct queries both exist, reconcile them or explain why they differ.\n\n### 5. Translate Evidence Into Decision Implications\n\nFrame the findings within the broader business context. Do not present quantitative evidence and business context as two unrelated streams.\n\nInterpret the evidence through the decision lenses that best fit the question. Choose lenses that would actually change the recommendation, and skip ones that would add noise or false precision. Common lenses include:\n\n- **Current scale:** Is the opportunity or problem large enough today to matter for the decision?\n- **Momentum:** Is the signal growing, shrinking, accelerating, or newly emerging?\n- **Breadth:** Is the pattern broad-based, or does it only appear in a narrow corner of the business?\n- **Concentration:** Does the conclusion depend on a few large entities, events, or outliers?\n- **Intensity:** Is the behavior deep enough per unit to suggest real need, value, or risk?\n- **Efficiency:** Does the option create better output, margin, conversion, productivity, or quality for the input required?\n- **Addressability:** Can the team realistically act on this option with available product, GTM, operational, policy, or technical levers?\n- **Differentiation:** Does this group or use case require a distinct motion, product experience, support model, or message?\n- **Substitution:** Is there evidence that behavior, spend, time, or workload could shift from another path?\n- **Risk or dependency:** Are there quality, trust, compliance, technical, operational, or data constraints that change the recommendation?\n- **Coverage:** Are unknown, missing, or sparsely tagged records large enough to change the answer?\n\nUse these as thinking tools, not a checklist. Explain why the chosen lenses matter for this decision, and mention omitted cuts only when they would plausibly change the interpretation or help explain the result.\n\nUse the measured opportunities to explain which differences matter for the decision and which ones call for different actions. If the business context shows that the initial sizing misses the actionable part of the opportunity, add the focused sizing cut needed to make the recommendation useful.\n\nIf evidence conflicts, say so directly and explain which interpretation is better supported. Do not smooth over disagreement between sources.\n\n### 6. Hand Off The Recommendation\n\nEnd by handing the decision-ready recommendation to $build-report unless the user explicitly requests an inline, chat-only, brief/no-artifact answer, asks not to create a report/file/artifact, or selects another primary artifact. This handoff is mandatory when no explicit human waiver was given; do not infer a waiver because the user asked a direct question or did not use the word \"report\". This workflow owns the analytical conclusion; $build-report owns the reader-facing structure, visuals, evidence placement, and delivery surface.\n\nBefore handoff, make the recommendation explicit:\n\n- what they should believe or do next\n- why the evidence supports that recommendation\n- which caveats or dependencies matter\n- what follow-up analysis would most improve confidence\n\nIf evidence is incomplete, label the recommendation as provisional and state what would change confidence. Do not overstate the conclusion just to make the answer feel decisive.\n\nUse $validate-data when methodology, calculations, caveats, or the evidentiary support for the conclusion need review before sharing.\n\nPass narrative ingredients to the report surface, not only result tables:\n\n- direct answer and recommendation\n- key evidence and how to interpret it\n- implication for the decision\n- unresolved uncertainty and caveats\n- recommended follow-up\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/validate-data/SKILL.md":"---\nname: validate-data\ndescription: \"Validate whether an analysis is accurate, well-supported, and ready to share or use for a decision. Use when reviewing methodology, calculations, comparisons, visuals, caveats, or conclusions.\"\n---\n## Related Skills\n\nUse $analyze-data-quality when validation depends on whether the underlying data is trustworthy, comparable, fresh, or at the right grain.\n\nUse $product-business-analysis when the task asks for a recommendation or decision after the validation pass.\n\n# Validate Data Analysis\n\nValidate an analysis before it is shared with stakeholders. Focus on whether the question, data, methodology, calculations, visuals, claims, caveats, and recommendations are trustworthy enough for the stated audience and decision.\nThis skill is for analysis QA, not raw dataset profiling alone. When validation depends on dataset reliability checks such as freshness, grain, missingness,\nduplicates, join coverage, or source mismatches, use $analyze-data-quality as a companion.\n\n## Workflow\n\n1. Inventory the artifact and claims.\n\n   Identify the report, notebook, spreadsheet, SQL, dashboard, chart, pasted analysis, or recommendation being validated. Inspect source artifacts when a path, link, query, notebook, spreadsheet, or dashboard is referenced. Extract the main question, audience, decision, key claims, headline numbers, data sources, time windows, populations, filters, comparison baselines, and stated caveats. Verify that every metric or KPI requested by the user appears in the analysis or is explicitly marked unavailable, not applicable, or out of scope.\n\n2. Validate the question, methodology, and assumptions.\n\n   Confirm that the analysis answers the stated business or product question,\n   not a nearby easier question. Check whether the population, eligibility rules, exclusions, sampling, metric definitions, formulas, units,\n   denominators, timezones, cohorts, comparison periods, and baselines match the stakeholder decision. Flag hidden exclusions, inconsistent definitions,\n   partial-period comparisons, and causal wording that lacks experimental or otherwise credible causal evidence.\n\n3. Validate data selection and quality risks.\n\n   Confirm that the chosen tables, files, dashboards, or extracts are appropriate and current enough for the decision. Check freshness or \"as of\"\n   date, expected partitions, segment coverage, row/category completeness, null handling, deduplication, filter logic, join coverage, and source mismatches when those risks could change the conclusion. Use `~~structured_data` for source metadata, schema checks, sample rows, query history, or SQL spot checks through the relevant source connector when available. Use `~~operations_logs` for table freshness, lineage, or pipeline context.\n\n4. Verify calculations and aggregations.\n\n   Recompute the highest-impact numbers independently when possible. Check grain, subtotals, denominators, non-zero denominators, rate bases,\n   period-over-period bases, weighted averages, units, currency, timezone handling, and whether mutually exclusive categories add to totals. For SQL,\n   inspect join types, group-by grain, filters, distinct counts, and row counts before and after joins. Use $jupyter-notebooks or `~~spreadsheet_workspace`\n   when the artifact itself is a notebook or spreadsheet, or when reproducible spot checks need code or formulas.\n\n5. Test reasonableness and common analytical traps.\n\n   Compare magnitudes against known dashboards, historical reports, prior analyses, finance sources, or expected product scale when possible. Investigate trend jumps, drops, flatlines, exact round numbers, 0% or 100% rates, segment shares that should sum to about 100%, and results that perfectly confirm the hypothesis without friction. Check edge cases such as empty segments, new entities, and boundary dates.\n\n6. Review visuals and presentation integrity.\n\n   Confirm that charts use appropriate chart types, scales, axes, intervals,\n   titles, labels, units, ordering, annotations, color, and precision. Use\n   $visualize-data for non-trivial chart review. For rendered reports,\n   dashboards, slides, docs, PDFs, HTML, or other final artifacts, inspect the rendered output for broken charts, missing tables, clipped text, bad formatting, stale placeholders, and obvious layout issues. Check whether a quick reader could walk away with a misleading interpretation, especially from truncated axes, dual axes, 3D effects, inconsistent intervals, missing date ranges, or chart titles that overstate the data.\n\n7. Evaluate narrative, conclusions, and recommendations.\n\n   Confirm each conclusion is supported by visible evidence or saved artifacts.\n   Separate verified findings from interpretation, caveats, and open questions.\n   Identify alternative explanations, uncertainty, missing context,\n   recommendations that go beyond the evidence, and any causal language that is not supported by the design.\n\n8. Produce a confidence assessment and required fixes.\n\n   Prioritize issues that materially affect the stakeholder decision. Separate blockers from caveats: do not block sharing for minor polish issues, but do block when a number, denominator, join, time window, population, comparison,\n   or conclusion is materially unreliable. Record incomplete handoff blockers separately from caveats, including missing access, unavailable source artifacts, unrun checks, broken render steps, unresolved data-quality risks,\n   or absent owner confirmation. If SQL, Python, a notebook, or a spreadsheet was used for validation, include the artifact path, query permalink, notebook path, spreadsheet tab, or dashboard link so the check is reproducible.\n\n## Standards\n\n### Validation Stance\n\n- Validate the claims the analysis actually makes, not just whether the artifact looks polished.\n- Prefer concrete evidence: recompute important numbers, inspect source data,\n  check code paths, trace records, or reconcile against trusted sources when tools and access allow it.\n- Label anything that cannot be verified, and state what would be needed to verify it.\n- Treat surprising results, stakeholder-facing recommendations, causal claims,\n  high-impact decisions, and externally shared analyses as higher-risk validation targets.\n- Select checks that match the artifact and decision. Do not run every possible check mechanically.\n\n### Methodology Checks\n\n- Question framing: the analysis answers the stated business or product question.\n- Data selection: sources are appropriate and current enough for the decision.\n- Population: inclusions, exclusions, eligibility rules, and sampling are explicit.\n- Metric definitions: formulas, units, denominators, and timezones are clear and aligned with stakeholder definitions.\n- Baselines: comparison periods, cohorts, and contexts are comparable.\n- Causality: causal wording is backed by experimental or otherwise credible causal evidence.\n\n### Data Quality Checks\n\n- Freshness: the analysis states or can recover the data \"as of\" date.\n- Completeness: no unexpected missing partitions, segments, rows, or categories.\n- Null handling: key columns have expected null rates or explicit treatment.\n- Deduplication: primary entities are not double counted.\n- Filter verification: filters and WHERE clauses do not silently exclude the population of interest.\n- Join coverage: dimensions, experiments, and reference tables do not drop or multiply important rows.\n\n### Calculation Checks\n\n- Grain: the aggregation level matches the intended analysis grain.\n- Denominators: rates and percentages use the correct population and non-zero denominators.\n- Period alignment: comparisons use equal or explicitly caveated windows.\n- Weighted metrics: averages are weighted correctly when group sizes differ.\n- Subtotals: parts add to totals where categories are mutually exclusive.\n- Units: currency, token, user, request, account, day/week/month, and timezone units are consistent.\n\n### Reasonableness Checks\n\n- Magnitudes are plausible relative to known dashboards, historical reports, or expected product scale.\n- Percentages fall in expected ranges and segment shares sum to about 100% where expected.\n- Trend jumps, drops, flatlines, exact round numbers, and 0% or 100% rates have an explanation.\n- Results do not perfectly confirm the hypothesis without friction or exceptions.\n- Edge cases such as empty segments, new entities, and boundary dates behave sensibly.\n\n### Common Pitfalls\n\n- Join explosion: many-to-many joins silently multiply rows and inflate counts or sums. Compare row counts and distinct primary entities before and after the join, and check whether the right-hand table has multiple rows per join key.\n  Aggregate the right-hand table to the intended grain before joining when needed, use `COUNT(DISTINCT primary_id)` when counting entities through joins,\n  and comment intentional one-to-many joins.\n- Survivorship bias: the analysis only includes entities that exist today and misses deleted, churned, failed, or otherwise absent entities. Ask who is not in the dataset and whether the missing population changes the conclusion.\n- Incomplete period comparison: a partial period is compared with a complete period. Use complete periods, compare the same number of elapsed days, or label the partial-period caveat prominently.\n- Denominator shifting: the eligible population changes between periods or segments. Validate that conversion, churn, activation, attach, and retention rates use stable definitions across compared groups.\n- Average of averages: pre-computed averages are averaged without weighting for group size. Aggregate from raw numerators and denominators or use a weighted average.\n- Timezone mismatch: sources use different timestamp conventions or daily cutoffs. Confirm the analysis standardizes timestamps or explicitly states the timezone and cutoff.\n- Selection bias in segmentation: segments are defined by the outcome being measured. Define comparison groups by pre-treatment characteristics when making lift, causality, or behavior-difference claims.\n- Other statistical traps: Simpson's paradox where aggregate and segment-level trends conflict, correlation presented as causation, small samples,\n  outlier-dominated averages that need medians or distribution views, multiple testing, cherry-picked time ranges, and look-ahead bias.\n\n### Spot-Check Recipes\n\n- Recompute a key metric from raw numerators and denominators.\n- Trace a few individual records through joins, filters, and final output.\n- Reconcile a key total against a trusted dashboard, prior report, or finance source.\n- Reverse engineer a headline number from component metrics, such as users times per-user revenue.\n- Run a one-day, one-segment, or one-entity boundary check to make sure filters and joins behave sensibly.\n- Compare the same metric through an alternate query path when a claim is surprising or high stakes.\n\n### Visualization Checks\n\n- Bar charts should generally start at zero; waterfall, bridge, variance, and other delta-focused charts may use a non-zero or narrowed value axis when zero would materially compress the intended movement, provided exact values, units, and the focused scale are clear.\n- Comparison charts should use consistent scales unless the scale difference is explicit and justified.\n- Axes, units, legends, and date ranges should be labeled.\n- Category ordering should match the comparison the reader should make.\n- Truncated axes, dual axes, 3D effects, and inconsistent intervals require explicit justification or redesign.\n- Chart titles and annotations should match exactly what the data supports.\n- Titles should state the finding and include date range or scope when needed.\n- Caveats should be visible near the claims they qualify.\n- Number formatting should use appropriate precision and units.\n- Rendered artifacts should be checked in their final form when available, not only in source form.\n\n### Confidence Ratings\n\n- `Ready to share`: The analysis is methodologically sound, key calculations are verified or low risk, caveats are clear, and any remaining issues are minor.\n- `Share with caveats`: The analysis is directionally usable, but specific assumptions, limitations, or unverified checks must be communicated to stakeholders.\n- `Needs revision`: There are material errors, unsupported claims, missing checks, or methodological issues that should be fixed before sharing.\n\n### Output Standards\n\nUse this structure unless the user asks for a lighter review:\n\n```markdown\n## Validation Report\n\n### Overall Assessment: [Ready to share | Share with caveats | Needs revision]\n\n### Methodology Review\n[Findings about question framing, data selection, population, definitions, comparisons, and assumptions.]\n\n### Issues Found\n1. [Severity: High/Medium/Low] [Issue description, evidence, and impact]\n2. ...\n\n### Calculation Spot-Checks\n- [Metric or claim]: [Verified / Discrepancy found / Not verified] - [brief evidence]\n\n### Visualization Review\n[Chart or presentation issues, if applicable.]\n\n### Suggested Improvements\n1. [Improvement and why it matters]\n\n### Required Caveats for Stakeholders\n- [Caveat that must be communicated]\n```\n\n- Include the question being answered, data sources and \"as of\" date, metric and segment definitions, time period and timezone, methodology steps, assumptions and limitations, SQL queries, notebook paths, spreadsheet tabs, dashboard links, or caveats required before acting when those details are relevant.\n- Preserve source references from the original artifact, including links, query IDs, notebook paths, spreadsheet tabs, dashboard URLs, cited documents, and other evidence needed to trace the analysis.\n- Verify that every section requested by the user or implied by the deliverable format is present; explain omitted sections.\n- Keep issues prioritized by decision impact, not by artifact section order.\n- Make unverified claims and remaining caveats explicit.\n- List incomplete handoff blockers separately from caveats and suggested improvements.\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/visualize-data/SKILL.md":"---\nname: visualize-data\ndescription: \"Design, create, revise, or QA quantitative charts and figures for reports, dashboards, notebooks, slides, files, or inline analytical answers.\"\n---\n\n# Visualize Data\n\nCreate quantitative visuals that are analytically sound, immediately readable, and appropriate for their destination. Treat a chart as evidence for a takeaway, not decoration.\n\n## Workflow\n\n1. State the analytical question and intended takeaway.\n2. Verify the data grain, measures, dimensions, units, missing values, filters, time window, sample size, and source.\n3. Choose the chart family from the analytical relationship:\n   - Change over ordered time: line or area chart.\n   - Category comparison: bar chart.\n   - Distribution: histogram, box plot, or density plot.\n   - Relationship between numeric measures: scatter plot.\n   - Composition: stacked bar/area; use pie only for a small set of meaningful parts.\n   - Funnel progression: funnel or ordered bars with stage conversion.\n   - Contribution to change: waterfall.\n   - Exact lookup values: table, optionally with small bars or sparklines.\n4. Define explicit encodings, sorting, aggregation, grouping, scales, labels, units, colors, annotations, and uncertainty treatment.\n5. Render with the destination's native system when one is selected. Otherwise prefer reproducible Python/Matplotlib or SVG for files and inline artifacts. Notebook-native plotting is appropriate for notebooks.\n6. Inspect the final output in context when the host provides image, browser, document, or notebook inspection.\n\nDo not install or require React, Recharts, Vite, MCP widgets, or proprietary UI renderers. For self-contained HTML, use inline SVG/canvas or a static image plus semantic fallback data. Avoid remote scripts unless the user explicitly accepts the dependency.\n\n## Visual quality\n\n- Use an answer-oriented title and a subtitle only when it adds a distinct takeaway.\n- Label axes and units; show legends or direct labels for every visible group.\n- Use consistent scales for comparisons and avoid misleading truncated axes unless clearly justified.\n- Prefer direct labeling and restrained color. Reserve semantic colors for meaning such as positive, warning, or negative states.\n- Keep annotations selective and evidence-backed.\n- Make dense charts readable through aggregation, faceting, filtering, or a table rather than shrinking text.\n- Provide accessible contrast, text alternatives, and a data table when the destination supports them.\n- Put provenance in a source note rather than cluttering the title.\n\n## QA\n\n- Recompute plotted values from the reviewed rows.\n- Confirm the visual answers the stated question and does not imply unsupported causality.\n- Check ordering, scales, labels, clipping, overlap, empty states, and small-screen behavior where relevant.\n- Confirm the exported file opens and contains the expected marks and text.\n- Preserve the code or notebook needed to reproduce the chart when the user needs an auditable artifact.\n\n","packages/cli/src/skill/builtin/.bundle/deep-research/SKILL.md":"---\nname: deep-research\ndescription: Deep research on any topic using parallel sub-agents and built-in tools only (WebSearch/WebFetch + free APIs, no keys). Use when the user asks for a thorough multi-source investigation with a cited report — \"深度调研X\"、\"deep research\"、\"帮我全面研究一下\"、\"多方求证\"、\"写一份调研报告\". NOT for simple lookups (single WebSearch suffices) and NOT for academic literature surveys (use auto-research skill instead).\n---\n\n# Deep Research\n\nOrchestrate parallel research sub-agents, then write one coherent cited report. Research is parallel; writing is single-point — never let multiple agents write report sections.\n\n## Step 0 — Always first\n\n1. Run `date +%Y-%m-%d` via Bash. Never assume the current year from training data.\n2. Triage:\n   - Answerable with 1-2 searches? → STOP, just use WebSearch directly. Do not use this skill.\n   - Enumeration task (N items × M fields, e.g. \"compare 20 frameworks\")? → still this skill, but use table-oriented decomposition (one sub-agent per item batch).\n   - Open-ended investigation? → continue below.\n3. Pick depth (default **standard**; user can override with words like \"quick\"/\"exhaustive\"):\n\n| Mode | Sub-agents (round 1) | Max follow-up rounds | Sources target |\n|---|---|---|---|\n| quick | 2-3 | 0 | 8+ |\n| standard | 3-5 | 1 | 15+ |\n| deep | 5-8 | 2 | 25+ |\n\nThese are hard budgets. Reflection (Phase 4) can spend them but never exceed them.\n\n## Workspace\n\nAll state lives on disk at `./research/<slug>/` — never only in context (survives compaction):\n\n```\nresearch/<slug>/\n├── brief.md         # research brief — the single contract for all phases\n├── findings/        # F1.md, F2.md ... one per sub-agent, structured evidence\n└── REPORT.md        # final deliverable\n```\n\nOn resume: re-read `brief.md` + list `findings/`, skip completed angles, continue.\n\n## Phase 1 — Scope\n\nAsk at most one round of clarifying questions (AskUserQuestion), only if genuinely ambiguous: audience, time frame, region, decision at stake. If the user said \"just run it\" or intent is clear, skip asking and write assumptions into the brief instead.\n\nThen write `brief.md`: refined question, scope boundaries (in/out), assumptions, depth mode, today's date. This brief — not the raw conversation — is what every later phase measures against.\n\n## Phase 2 — Plan\n\nDecompose the brief into 3-8 **independent** research angles. Pull from these lenses as applicable: core facts/definitions · recent developments (last 12 months) · quantitative data/benchmarks · counter-arguments & failure cases · practitioner experience (forums, issues) · academic work · key players/alternatives.\n\nList angles in `brief.md` under `## Angles`. For deep mode or contested topics, show the angle list to the user for a quick confirm before spending budget.\n\n## Phase 3 — Parallel research\n\nSpawn one sub-agent per angle **in a single message** (parallel). Build each prompt from the locked template in [reference/subagent-prompt.md](reference/subagent-prompt.md) — reproduce it verbatim, replacing only the `{variables}`. Each sub-agent:\n\n- researches ONE angle only, using WebSearch/WebFetch and the free endpoints in [reference/sources.md](reference/sources.md)\n- writes structured findings to `findings/F<n>.md` (claim / quote / URL / date / confidence per item)\n- returns only a 3-5 line summary to you — raw page content must never enter your context\n\nIf a sub-agent fails or returns thin results, note it and move on; do not block other angles.\n\n## Phase 4 — Reflect (gap check)\n\nRead all `findings/*.md`. Against `brief.md`, ask: which parts of the brief have no evidence? Which major claims rest on a single source? Where do sources conflict?\n\n- Gaps found AND follow-up budget remains → spawn targeted sub-agents with delta-queries (same template, narrower angle). Repeat once per remaining round.\n- No budget left or coverage sufficient → proceed. Record unresolved gaps; they go in the report's \"Open questions\".\n\n## Phase 5 — Write (single-point)\n\nYou alone write `REPORT.md` in one pass, following [reference/report.md](reference/report.md). Core rules:\n\n- Every non-obvious claim carries an inline citation `[n]` mapping to a Sources section; citation URLs come only from findings files — never from memory.\n- Where sources conflict, present both sides with dates; prefer newer + primary sources.\n- Mark single-source claims with `[single source]`, speculation with `[speculative]`.\n- End with: Open questions · Sources (numbered, with access date).\n\nFor deep mode, before finalizing do one critique pass: reread the report as a skeptical reviewer (unsupported claims? stale data? missing counter-view?) and fix in place.\n\nFinally, give the user a 5-10 line summary of key conclusions and the report path.\n","packages/cli/src/skill/builtin/.bundle/docx-official/README.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fdocx-official%2FREADME.md -->","packages/cli/src/skill/builtin/.bundle/docx-official/SKILL.md":"---\nname: docx-official\ndescription: \"Use this skill whenever a Microsoft Word (.docx) file is being produced, opened, transformed, or read. That includes: drafting reports, letters, contracts, RFPs, technical documents, or any long-form written deliverable; extracting text or structure from an existing Word file; filling a Word template with values; converting Word to PDF or plain text; splitting or merging documents; inspecting styles, headings, sections, tables, images, comments, or tracked changes. Trigger on mentions of 'Word doc', 'DOCX', 'Office document', a filename ending in .docx, or requests like 'turn this into a Word report'.\"\nlicense: Apache-2.0 — see LICENSE for terms and third-party attributions\n---\n\n# DOCX Skill\n\nAn Apache-2.0 toolkit for producing, editing, and reading Microsoft Word (`.docx`) files. Written from scratch against the public [ECMA-376 / ISO/IEC 29500](https://www.ecma-international.org/publications-and-standards/standards/ecma-376/) specification and built on permissively-licensed tooling (`python-docx` MIT, `lxml` BSD-3-Clause, optional external binaries `pandoc` and `soffice`) so it can be reused in commercial projects without restriction.\n\n## Decision matrix\n\n| Situation | Path | Read first |\n|-----------|------|------------|\n| No source file — build a document from a prompt / data | Author from scratch with `python-docx` | [`create.md`](create.md) |\n| You have a `.docx` template to fill in or lightly modify | Placeholder replacement via `python-docx`, keeps styles | [`edit.md`](edit.md) → *Workflow A — `python-docx` in-place edit* |\n| Deep structural edits, new sections, custom XML, unusual layouts | Explode → edit XML → assemble | [`edit.md`](edit.md) → *Workflow B — Explode → edit XML → assemble* |\n| You only need the text / structure / metadata out of a `.docx` | Extraction pipeline | [`read.md`](read.md) |\n| Need a PDF preview for QA | `scripts/render_pdf.py` via LibreOffice | see *QA* below |\n\nIf the task mixes several of these, do them in this order: **read → plan → edit/create → validate**.\n\n## One-time environment setup\n\n> **Bundled runtime:** when the `MIMO_PYTHON` environment variable is set, skip `uv`/`python3` and pip installs entirely — run every command below with `uv run` replaced by `\"$MIMO_PYTHON\"` (e.g. `\"$MIMO_PYTHON\" scripts/extract_text.py input.docx`). This skill's Python dependencies are preinstalled in that interpreter; pip console scripts are unavailable, so always go through `\"$MIMO_PYTHON\" -m <module>`. A bundled LibreOffice is exposed as `MIMO_SOFFICE` and picked up automatically by the scripts here.\n\nAll scripts include [PEP 723](https://peps.python.org/pep-0723/) inline metadata, so `uv run` resolves dependencies automatically — no manual install step needed. Just run:\n\n```bash\nuv run scripts/extract_text.py input.docx\n```\n\nIf you don't use `uv`, install dependencies once:\n\n```bash\npython3 -m pip install --upgrade python-docx lxml\n# Optional but recommended:\n#   LibreOffice (for docx → pdf preview):   brew install --cask libreoffice   (macOS)\n#                                           apt-get install -y libreoffice    (Debian/Ubuntu)\n#   Poppler   (for pdf → image, QA loop):   brew install poppler\n```\n\nAlternatively, if this skill lives in a persistent workspace you can `uv init` a project, `uv add python-docx lxml`, and run scripts with `uv run scripts/...` from the project root — this gives you a lockfile and reproducible environment.\n\nAll scripts here use the standard library plus `python-docx`. No proprietary dependencies.\n\n## Common commands\n\n```bash\n# 1. Extract plain text (best for \"what does this file say?\" questions)\nuv run scripts/extract_text.py input.docx > input.txt\n\n# 2. Explode a .docx into readable XML for structural surgery\nuv run scripts/explode.py input.docx exploded/\n\n# 3. Assemble an exploded directory into a fresh .docx\nuv run scripts/assemble.py exploded/ output.docx\n\n# 4. Render a .docx as PDF (used for visual QA)\nuv run scripts/render_pdf.py output.docx           # writes output.pdf next to it\n\n# 5. Well-formedness check (ZIP integrity + parseable XML + python-docx open)\nuv run scripts/audit.py output.docx\n\n# 6. Accept every tracked change without needing Word/LibreOffice\nuv run scripts/resolve_revisions.py reviewed.docx clean.docx\n\n# 7. Add a comment to an exploded directory\nuv run scripts/annotate.py exploded/ \"Please check\" --author \"Reviewer\" --anchor \"text\"\n```\n\nEvery script is a small, self-contained Python file. Read the top of the file for full CLI options.\n\n## Authoring principles\n\nWord is a **flowing** document format, not a slide surface. Users expect it to look like something a human wrote in Word — not a design tool trying to reinvent typography. Keep that in mind:\n\n1. **Rely on named styles.** Use `Heading 1`, `Heading 2`, `Normal`, `Title`, `Quote`, `List Bullet`, `List Number`, `Caption`. They are what makes Word's ToC, navigation pane, and cross-references work.\n2. **One idea per paragraph.** Long paragraphs are fine; run-on paragraphs are not. Break at logical boundaries.\n3. **Structure first, prose second.** Draft the heading tree, then write inside it. Reviewers scan headings before words.\n4. **Tables for tabular data only.** Do not use tables to fake multi-column layouts — export to PDF and users see the borders through the layout.\n5. **Line length is set by page margins, not by hard breaks.** Never insert manual line breaks to control wrapping.\n6. **Use fields, not literal text, for things that change** — page numbers, dates, ToC, cross-references. `python-docx` supports field codes via low-level XML (see `edit.md`).\n7. **Every image needs alt text** — accessibility, and Word screams at you in review mode when it's missing.\n\n## Typography defaults (safe starting point)\n\n| Element        | Font          | Size | Weight | Notes |\n|----------------|---------------|------|--------|-------|\n| Title          | Calibri Light | 28pt | Bold   | Centered or left, one line |\n| Heading 1      | Calibri Light | 18pt | Bold   | Space before 12pt |\n| Heading 2      | Calibri Light | 14pt | Bold   | Space before 10pt |\n| Heading 3      | Calibri       | 12pt | Bold   | Space before 6pt |\n| Body           | Calibri       | 11pt | Regular| Line spacing 1.15, space after 6pt |\n| Caption        | Calibri       | 9pt  | Italic | Muted gray `#595959` |\n| Code / mono    | Consolas      | 10pt | Regular| Left-aligned, no first-line indent |\n\nChange the palette for the topic — muted navy `#1F3A5F` for legal/finance, warm charcoal `#2E2A26` for editorial. Avoid pure `#000000` for body text; `#1F1F1F` reads softer on print.\n\n## Page setup (A4 vs Letter)\n\nAsk the user which one to use. If you cannot ask, default to the region implied by the language (Chinese/European → A4, US English → Letter). Margins:\n\n| Size   | Width × Height    | Standard margins (T/B/L/R) |\n|--------|-------------------|-----------------------------|\n| A4     | 21.0 × 29.7 cm    | 2.54 / 2.54 / 3.18 / 3.18 cm |\n| Letter | 8.5 × 11.0 in     | 1.00 / 1.00 / 1.25 / 1.25 in |\n\n## QA checklist — always run before declaring done\n\n**Assume something is wrong.** Word files fail silently: a broken relationship, an unclosed `<w:p>`, a missing style — Word will still open the file but strip content or throw a \"content had problems\" warning. Verify explicitly.\n\n1. **Open cleanly** — no repair prompt.\n   ```bash\n   uv run python -c \"import docx; docx.Document('output.docx')\"   # loads without exceptions\n   ```\n2. **Text integrity** — no placeholder residue.\n   ```bash\n   uv run scripts/extract_text.py output.docx | grep -Ei \"TODO|TBD|\\{\\{|lorem|xxxx\"\n   ```\n   Grep must return nothing.\n3. **Visual sanity** — render a PDF, open the first and last pages, scan for:\n   - Widowed headings alone at the bottom of a page.\n   - Tables split awkwardly across pages.\n   - Images pushed to their own page because they exceeded content width.\n   - Missing page numbers, wrong header/footer content.\n   ```bash\n   uv run scripts/render_pdf.py output.docx\n   ```\n4. **Style hygiene** — every heading uses a real style, not just bold+large text:\n   ```bash\n   uv run python -c \"\n   import docx; d = docx.Document('output.docx')\n   for p in d.paragraphs:\n       if p.text and p.style.name == 'Normal' and p.runs and p.runs[0].bold:\n           print('possible fake heading:', p.text[:80])\"\n   ```\n\nIf any of these fail, fix and re-run — don't paper over.\n\n## What is out of scope\n\n- **`.doc` (legacy Word 97-2003)** — this skill only targets `.docx` (Office Open XML). Convert `.doc` to `.docx` with LibreOffice first: `soffice --headless --convert-to docx old.doc`.\n- **Live collaborative editing** — the Word online API is a separate concern; here we produce and modify files.\n- **Macros / VBA** — do not generate `.docm` files. If the user asks for automation, offer a Python script that regenerates the doc instead.\n\n## Where each detail lives\n\n- **Creating from scratch**: [`create.md`](create.md) — headings, paragraphs, styles, tables, images, page setup, headers/footers, tables of contents.\n- **Editing / templating**: [`edit.md`](edit.md) — placeholder replacement, section swap, raw XML surgery, tracked changes, comments.\n- **Reading / extracting**: [`read.md`](read.md) — plain-text export, structural walk, metadata, table extraction.\n- **Scripts**: [`scripts/`](scripts/) — self-contained CLI utilities used by all of the above.\n","packages/cli/src/skill/builtin/.bundle/grok-build/SKILL.md":"---\nname: grok-build\ndescription: Reference and workflow guidance for the Grok Build CLI (`grok`), including interactive and headless runs, authentication, sessions, worktrees, permissions, sandboxing, MCP servers, plugins, inspection, updates, and automation output. Invoke only when the user explicitly requests the `grok-build` skill, explicitly asks to use Grok Build CLI, or an already-selected workflow requires Grok Build; do not invoke for general coding, generic shell tasks, or other agent CLIs.\n---\n\n# Grok Build CLI\n\nOperate Grok Build from a terminal while keeping execution mode, permissions, sandboxing, session state, and output handling explicit.\n\n## Start with Local Evidence\n\n1. Confirm that the CLI is available:\n\n   ```bash\n   command -v grok\n   grok version\n   ```\n\n2. Inspect the installed command before giving version-sensitive advice:\n\n   ```bash\n   grok --help\n   grok <subcommand> --help\n   ```\n\n3. Inspect the configuration discovered for the target workspace when behavior depends on rules, skills, plugins, hooks, or MCP servers:\n\n   ```bash\n   grok --cwd /path/to/repo inspect\n   grok --cwd /path/to/repo inspect --json\n   ```\n\n4. Treat current official documentation and installed help as authoritative when they differ from this bundled reference.\n\n## Choose an Execution Mode\n\n- Run `grok` with no arguments for the interactive TUI.\n- Run `grok \"<initial prompt>\"` to open the TUI with an initial task.\n- Run `grok -p \"<prompt>\"` for one non-interactive turn that prints a result and exits.\n- Run `grok agent stdio` for an ACP client that communicates over stdin/stdout.\n- Run `grok dashboard` to open the Agent Dashboard.\n\nPrefer headless mode for scripts, CI, bots, and agent orchestration. Prefer ACP only when the caller implements the ACP JSON-RPC lifecycle and consumes `session/update` chunks.\n\n## Authenticate\n\nUse an interactive login on a developer machine:\n\n```bash\ngrok login\n```\n\nUse device-code authentication in headless or remote environments:\n\n```bash\ngrok login --device-auth\n```\n\nUse a locally cached login or provide `XAI_API_KEY` only to the process that needs it. Never print, persist, or commit credentials. Use `grok logout` to clear cached credentials.\n\n## Run Headlessly\n\nUse an explicit working directory and output format:\n\n```bash\ngrok --no-auto-update \\\n  --cwd /path/to/repo \\\n  --sandbox workspace \\\n  -p \"Inspect the repository and explain the failing test.\" \\\n  --output-format json\n```\n\nChoose output according to the consumer:\n\n- Use `plain` for humans.\n- Use `json` for one final machine-readable object.\n- Use `streaming-json` for newline-delimited incremental events.\n- Add `--json-schema '<schema>'` when the installed CLI supports constrained structured output.\n\nPass `--no-auto-update` in scripts and CI to suppress background update checks. Do not parse interactive TUI rendering in automation.\n\n## Control Permissions and Isolation\n\nTreat permissions and sandboxing as separate controls:\n\n- Use permission rules to decide whether a tool call may run.\n- Use a sandbox profile to limit what an approved call may access.\n- Prefer `--sandbox workspace` for normal repository changes.\n- Prefer `--sandbox read-only` for review and auditing.\n- Prefer `--sandbox strict` for an untrusted repository, then add narrow permission rules.\n- Use `--allow <RULE>` and `--deny <RULE>` for per-run policy; remember that deny rules win.\n- Use `--always-approve` only when the environment and command scope justify unattended execution. Pair it with a suitable sandbox and explicit deny rules.\n\nDo not describe `--always-approve` as equivalent to sandboxing. The sandbox is off by default unless configured or selected.\n\n## Manage Sessions and Worktrees\n\nContinue or resume intentionally:\n\n```bash\ngrok -c\ngrok --resume <session-id>\ngrok --resume\n```\n\nUse `--session-id <UUID>` for a new named session, not to resume an existing one. Add `--fork-session` when branching from a resumed session.\n\nUse a worktree when concurrent work could collide:\n\n```bash\ngrok --worktree --ref main \"Fix the flaky test\"\ngrok --worktree=feature-name \"Implement the feature\"\n```\n\nPreview removal with `grok worktree rm --dry-run <id>` before deleting a worktree. Do not assume deleting a session removes its worktree.\n\n## Diagnose Before Editing Configuration\n\nUse built-in inspection and diagnostics first:\n\n```bash\ngrok inspect --json\ngrok mcp list --json\ngrok mcp doctor\ngrok plugin list\ngrok models\n```\n\nPrefer `grok mcp add`, `grok mcp remove`, and plugin subcommands over manually editing configuration when the CLI supports the requested operation. Keep secrets in environment variables rather than command history or committed configuration.\n\n## Read the Bundled References\n\n- Read [references/cli-reference.md](references/cli-reference.md) for the subcommand and common flag index.\n- Read [references/workflows.md](references/workflows.md) for headless execution, sessions, worktrees, permissions, sandboxing, and MCP examples.\n\nVerify destructive commands such as session deletion, plugin removal, MCP removal, memory clearing, and worktree removal with the user or the governing workflow before running them.\n","packages/cli/src/skill/builtin/.bundle/html-to-video-pipeline/SKILL.md":"---\nname: html-to-video-pipeline\ndescription: Reliable HTML-to-MP4 rendering via headless browser recording (Playwright/Puppeteer) + ffmpeg — the ordering, gotchas, and verification steps you MUST get right or the output silently rots. Trigger whenever the user is building or debugging any pipeline that turns an HTML/CSS/JS page (single-file, multi-composition, GSAP-driven, or `@keyframes`-driven) into a video file, including headless recording, screen capture of a web page, deterministic frame-by-frame capture, multi-scene concatenation, or engine-mixed video output. Also trigger when the symptom sounds like: font swap flashing in the opening frames (FOUT), the first few seconds of the video are frozen/dead, animations play during page load and get truncated, concatenated segments produce a video whose duration is wildly wrong (e.g., 8s becomes 35s), `file://` loaded HTML fails to fetch its sub-scenes, the exported video is soft/blurry compared to the browser, or playback stutters/looks choppy despite passing a high `-r` fps to ffmpeg. Use even for one-off scripts — the failure modes here are subtle enough that starting from scratch usually reintroduces them.\n---\n\n# HTML → Video: the pipeline that actually works\n\nTurning a live HTML page into an MP4 sounds like a one-liner (\"Playwright records, ffmpeg encodes\") and the first draft always looks fine — until you play back the export and notice text flashing in a fallback font, three dead seconds at the start, or a \"10-second\" clip that clocks in at 35s. This skill captures the specific ordering, waits, and encoder flags that make the output trustworthy.\n\nThink of the pipeline as five phases with a single invariant between them:\n\n```\nlaunch  →  hold @ frame 0  →  align capture start with animation start  →  record  →  trim & encode\n```\n\nThe invariant: **no pixel of the animation should render before capture is ready, AND capture must not start before every asset that affects layout has loaded.** Every gotcha below is a violation of that invariant.\n\nQuick checklist (each item is expanded below):\n\n1. `viewport` must exactly equal `recordVideo.size` — mismatch silently rescales the output soft/blurry.\n2. Freeze CSS animations via `addInitScript` **before** `goto()`.\n3. `goto` with `domcontentloaded`, never `load`.\n4. Pre-inline `data-composition-src` sub-scenes — `file://` blocks client-side `fetch`.\n5. Font wait = stylesheet `<link>` load → `face.load()` per face → `fonts.ready` → 2 rAFs.\n6. Probe duration with infinite-iteration / `repeat: -1` guards.\n7. Unfreeze = t=0; trim `leadInMs − 120ms` with `-ss` *before* `-i`.\n8. Concat: same engine → demuxer `-c copy`; mixed engines → concat *filter* + re-encode.\n9. Verify with ffprobe duration + full decode + sampled frames. Always.\n\nThere are two capture modes, and picking the wrong one wastes a day:\n\n- **Mode A — real-time `recordVideo`** (the phases below). Simple, wall-clock = clip length. But the screencast is best-effort variable frame rate (~25fps) and competes with the animation for CPU. Good enough for previews and ≤30fps deliverables on an idle machine.\n- **Mode B — deterministic frame stepping** (pause everything, seek to `i / fps`, screenshot, encode the PNG sequence). Exact fps, every frame rendered, no lead-in trim, immune to machine load. Required when the output must be genuinely smooth ≥30fps or renders run on loaded CI. See \"Deterministic frame stepping\" below.\n\n## Prerequisites — install these first\n\nTwo hard requirements: a headless browser driver (Playwright or Puppeteer) and `ffmpeg`. Everything below assumes both are installed and on `PATH`.\n\n### 1. Headless browser driver\n\nPlaywright is the default in this skill (its `recordVideo` API is what the pipeline is written against). Puppeteer works too but you'll wire recording yourself via CDP screencast — pick Playwright unless you have a reason not to.\n\n```bash\n# Playwright (recommended) — npm / pnpm / bun all work\nnpm  install playwright\npnpm add playwright\nbun  add playwright\n\n# Then install the actual browser binaries (this is the step people forget):\nnpx playwright install chromium              # just Chromium — enough for this pipeline\nnpx playwright install --with-deps chromium  # Linux/CI: also install shared libs\n```\n\nVerify: `npx playwright --version` prints the driver version, and `node -e \"require('playwright').chromium.launch().then(b => b.close())\"` exits cleanly.\n\nPuppeteer alternative (only if you already have it in the project):\n\n```bash\nnpm install puppeteer            # bundles a matching Chromium automatically\n# or, to reuse a system Chrome:\nnpm install puppeteer-core       # no bundled browser — you supply executablePath\n```\n\n### 2. ffmpeg\n\nThe encode/trim/concat/verify steps all shell out to `ffmpeg` (and `ffprobe`, which ships in the same package). It is **not** an npm dependency — install it at the OS level.\n\n```bash\n# macOS\nbrew install ffmpeg\n\n# Debian / Ubuntu\nsudo apt-get update && sudo apt-get install -y ffmpeg\n\n# Fedora / RHEL\nsudo dnf install ffmpeg          # requires RPM Fusion enabled\n\n# Windows\nwinget install Gyan.FFmpeg       # or: choco install ffmpeg\n```\n\nVerify: `ffmpeg -version` and `ffprobe -version` both print. If a script spawns `ffmpeg` and gets `ENOENT`, the binary isn't on `PATH` — see the graceful-failure snippet in `references/ffmpeg-cheatsheet.md`.\n\nDo **not** rely on the `ffmpeg-static` / `@ffmpeg-installer/ffmpeg` npm packages for production: their bundled builds skip codecs and encoder flags you'll hit sooner or later (e.g. `libx264` presets, `tpad`). A system ffmpeg is the durable choice.\n\n### 3. Optional — ImageMagick (verification only)\n\nOnly needed if you want the \"did anything render?\" pixel-mean check from Phase 6. Skip it otherwise.\n\n```bash\nbrew install imagemagick         # macOS\nsudo apt-get install imagemagick # Debian/Ubuntu\n```\n\nVerify: `magick -version` (ImageMagick 7) or `convert -version` (ImageMagick 6).\n\n## The pipeline\n\n### Phase 1 — Launch and prepare the recorder\n\nUse `playwright.chromium.launch({ headless: true })` and a context configured with `recordVideo: { dir, size: { width, height } }`. Two sizing rules:\n\n- **`viewport` must exactly equal `recordVideo.size`.** When they differ, Playwright rescales the screencast to fit the recording size and the whole output goes soft. Derive both from the same constants.\n- `recordVideo` captures at CSS-pixel resolution; `deviceScaleFactor` does **not** raise recording resolution. For a 1080p export use a 1920×1080 viewport, not 960×540 @ 2x.\n\nRecording begins the instant the context exists — treat that timestamp as the WebM's t=0 and remember it (`tWebmStart = Date.now()`); you will need it in Phase 5 to trim the dead opening.\n\nKnow the recorder's ceiling: the screencast runs at a variable ~25fps and drops frames under CPU load. The `-r <fps>` flag in Phase 5 makes the container constant-frame-rate but only duplicates frames — it cannot add smoothness. If stutter matters, switch to frame stepping (Mode B) instead of fighting this.\n\n### Phase 2 — Freeze animations BEFORE the page parses\n\nThis is the single most-missed step. Pure-CSS `@keyframes` animations begin the moment the element is styled — there is no JS trigger to hold. If you `goto()` the HTML and then start waiting for fonts (which takes seconds), the CSS timeline has *already been running the whole time*. The recording captures the fallback font swapping to the real face mid-clip, and the opening beats of the animation are lost to the font wait.\n\nFix: inject a global freeze **via `page.addInitScript()`**, which runs before any of the document's own scripts and before CSS is applied, so the timeline is paused at frame 0 the moment it exists:\n\n```js\nawait page.addInitScript(() => {\n  const style = document.createElement('style');\n  style.id = '__freeze';\n  style.textContent =\n    '*, *::before, *::after { animation-play-state: paused !important;' +\n    ' -webkit-animation-play-state: paused !important; }';\n  const attach = () => (document.head || document.documentElement).appendChild(style);\n  if (document.head || document.documentElement) attach();\n  else document.addEventListener('DOMContentLoaded', attach, { once: true });\n  window.__unfreeze = () => document.getElementById('__freeze')?.remove();\n});\n```\n\nThis does not stop GSAP tweens driven by JS (see Phase 4 for those) — for GSAP-driven templates, register the master timeline paused and expose a `window.__playAll()` you call in Phase 4.\n\n### Phase 3 — Load with `domcontentloaded`, not `load`\n\n`waitUntil: 'load'` blocks on every external asset, including cross-origin videos with no CORS headers. Chromium will retry those for ~4s before giving up, and those 4s get burned into the recording as a frozen first scene. Use `waitUntil: 'domcontentloaded'` — the DOM + synchronous inline scripts (GSAP, your player) are ready, and you handle fonts explicitly next.\n\nIf the template is multi-composition (scenes loaded via `data-composition-src` and client-side `fetch`), you must **pre-inline** those sub-files into the entry HTML on the Node side and write it to a sibling `.tmp.html`. Chromium blocks `file://` fetch, so client-side scene loaders that work in a browser tab will silently produce an empty shell in a headless recording. See `references/multi-composition.md`.\n\n### Phase 4 — Wait for fonts properly, then release\n\n`document.fonts.ready` alone is **not enough** and this is the second most-missed step. Under `domcontentloaded`, the Google Fonts (or any external) `<link rel=\"stylesheet\">` has usually not returned yet. Until its CSS arrives, its `@font-face` rules are not in `document.fonts` at all — so `fonts.ready` sees an empty set and resolves *instantly*. Recording proceeds, the CSS lands mid-clip, faces download, and the swap happens on-camera.\n\nThe correct sequence, all inside a `page.evaluate()` with an 8s hard cap so a wedged CDN can't stall forever:\n\n1. Wait for every `<link rel=\"stylesheet\">` to `load` or `error` — that registers `@font-face` rules into `document.fonts`.\n2. For each registered face, call `face.load()` explicitly. `font-display: swap` defers the download until something paints with that face — if your first frame doesn't happen to use the face, it never fetches without this.\n3. `await fonts.ready`.\n4. Two rAFs so layout settles on the real glyph metrics before frame 0.\n\nThen, and only then:\n\n5. Drive playback: for GSAP multi-composition templates, call `window.__playAll()` to start every registered (paused) master timeline from 0. For pure-CSS templates, this is a no-op.\n6. Call `window.__unfreeze()` to remove the freeze style. **This is the true t=0 of the animation.** Record the wall-clock offset from `tWebmStart` (`leadInMs = Date.now() - tWebmStart`) — this is what you trim in Phase 5.\n\nThe full JS for Phase 4 is in `references/font-wait.md`.\n\n### Phase 5 — Probe duration, record, then trim and encode\n\n**Probe duration first** (skip this only if you know the exact intended length). The user's requested `duration` may be shorter than the animation, in which case you'd cut the animation mid-play. Take the maximum of:\n\n- The longest **non-infinite** CSS animation (`animation-duration + animation-delay` for entries where `animation-iteration-count !== 'infinite'`).\n- The longest **finite** GSAP tween. Do **not** use `gsap.globalTimeline.totalDuration()` — a `repeat: -1` tween (blinking cursor, looping background) makes it ~1e10s. Walk `globalTimeline.getChildren(true, true, true)` and skip anything with `repeat() === -1`.\n\nAdd a ~400ms settle so the last animation frame is captured, cap at 30s so a stray huge value can't run away. If your caller passed an *explicit* per-frame duration (e.g. \"each scene is exactly 4s\"), do **not** extend — treat it as a hard cap and pad the tail if the animation finished early (see below). If duration was 'auto', extend to the probed length.\n\n**Record** for `totalDuration`, then `context.close()`. Playwright drops the WebM in `recordDir`.\n\n**Encode with ffmpeg**, applying two corrections:\n\n```\nffmpeg -y \\\n  [ -ss <(leadInMs - 120) / 1000> ]  # trim dead lead-in, back off 120ms so we don't clip frame 1\n  -i input.webm \\\n  [ -vf tpad=stop_mode=clone:stop_duration=<totalDuration> ]  # pad tail only when duration is explicit\n  -t <totalDuration> \\                # trim to exact length (recordVideo sometimes overshoots)\n  -r <fps> \\\n  -c:v libx264 -pix_fmt yuv420p -preset medium -crf 20 \\\n  -movflags +faststart \\\n  out.mp4\n```\n\nThe `-ss` back-off matters: recorder start jitter and rounding can steal the first real frame if you trim to exactly `leadInMs`. A couple of extra still frames at the head are invisible; a missing opening beat is obvious.\n\n## Deterministic frame stepping (Mode B)\n\nWhen the deliverable must be genuinely smooth at an exact fps — or the render runs on a loaded CI box where real-time capture visibly stutters — don't record in real time at all. Keep Phases 1–4 (minus `recordVideo`), then: pause every timeline, seek to `i / fps`, `page.screenshot()` each frame, and encode the PNG sequence with `ffmpeg -framerate <fps>`. Duration is exact by construction, there is no lead-in to trim, and every single frame is fully rendered regardless of machine load.\n\nIt works when the page's motion is declaratively seekable — CSS `@keyframes` (via `document.getAnimations()` + `currentTime`), WAAPI, and GSAP (`gsap.globalTimeline.time(t)`). It does **not** work for `<video>` elements, `setTimeout`-choreographed scenes, or rAF-driven physics; those need real-time recording or a CDP virtual clock. Step time monotonically forward, never backwards.\n\nFull loop, the seek/suppressEvents subtleties, the \"animations created later by JS are invisible to the seek\" trap, and optional 2x supersampling are in `references/frame-stepping.md`.\n\n## Multi-segment concatenation\n\nWhen you have N per-scene MP4s and need one output, the correct ffmpeg strategy depends on whether the inputs share a codec/timebase.\n\n**Same encoder, same params (typical: all scenes rendered by the same adapter)** — use `concat` demuxer with stream copy. Fast, lossless:\n\n```\nffmpeg -y -f concat -safe 0 -i list.txt -c copy out.mp4\n```\n\nwhere `list.txt` is `file 'seg1.mp4'\\nfile 'seg2.mp4'\\n...`.\n\n**Mixed sources (e.g. scene A recorded by headless Chromium, scene B rendered by a React/Remotion pipeline)** — the concat demuxer's `-c copy` path assumes compatible timebases and PTS. When timebases differ, PTS accumulate incorrectly and an 8-second output can become 35 seconds. **Even `-vsync cfr` won't save you** — the bad PTS have already been fed in. You must re-encode via the concat **filter**, which rebuilds the timeline:\n\n```\nffmpeg -y -i seg1.mp4 -i seg2.mp4 -i seg3.mp4 \\\n  -filter_complex \"[0:v][1:v][2:v]concat=n=3:v=1:a=0[v]\" \\\n  -map \"[v]\" -c:v libx264 -pix_fmt yuv420p -r 60 \\\n  -movflags +faststart out.mp4\n```\n\nDecision rule in code: pass a `reencode: boolean` down to your concat helper. Set it to `true` whenever any segment came from a different rendering engine than the others, or when you're not sure.\n\n## Verify — always\n\nYou cannot trust \"the file was written\" as success. The failure modes above (wrong duration, FOUT, dead lead-in) all produce a playable MP4. Before declaring success:\n\n- `ffprobe -v error -show_entries format=duration -of csv=p=0 out.mp4` — actual duration matches expected within ~50ms?\n- `ffmpeg -v error -i out.mp4 -f null -` — full decode, no errors? A \"silently corrupted\" output from a bad concat will decode fine but be the wrong length; conversely, a broken concat demuxer output can throw here.\n- Sample a frame near t=0.1s and t=0.5s (`ffmpeg -ss 0.1 -i out.mp4 -frames:v 1 -y f1.png`) — text renders in the intended font? If your test rig has ImageMagick, `magick f1.png -threshold 50% -format '%[fx:100*mean]' info:` gives a rough non-background pixel percentage that catches \"recording is completely blank\" regressions.\n\nFor fonts specifically: **studio-style live iframe previews will not reproduce FOUT** because the browser tab caches faces. Only cold-headless rendering (i.e. the actual export path) reproduces it. Verify on the exported MP4, not the preview.\n\n## When to depart from this template\n\n- **Non-animated single-frame PNG export.** Skip Phases 2, 4-5-recording; goto → `fonts.ready` → `page.screenshot()` is enough. FOUT still applies for the screenshot.\n- **You own the animation timeline in JS end-to-end** (e.g. Motion Canvas / Remotion generator style). The freeze/unfreeze dance is unnecessary because *you* drive frame-by-frame rendering — use the framework's own frame API and skip Playwright recording entirely. The concat rules still apply if you're mixing engines.\n- **Interactive-page capture** (recording a real user session). Duration probing is meaningless; use manual start/stop signals and skip lead-in trim.\n\n## Reference files\n\n- `references/font-wait.md` — full JS for the Phase 4 font-wait routine, with per-link timeout and rAF-based settle.\n- `references/frame-stepping.md` — the Mode B deterministic capture loop: seek-per-frame, screenshot, PNG-sequence encode, supersampling, and its limits.\n- `references/multi-composition.md` — inlining `data-composition-src` scenes for `file://` recording, including re-executing cloned `<script>` nodes.\n- `references/duration-probe.md` — CSS + GSAP probe with the infinite-iteration guards.\n- `references/ffmpeg-cheatsheet.md` — the encode/concat/verify commands in one place.\n","packages/cli/src/skill/builtin/.bundle/learn-everything/SKILL.md":"---\nname: learn-everything\ndescription: Turn an uploaded PDF, paper, book chapter, document, URL, or user-provided topic into a structured, interactive learning course. Use when the user wants to learn, study, understand, master, review, or practice a subject chapter by chapter; asks for a tutorial or curriculum from source material; wants exercises, quizzes, answer grading, hints, spaced review, or a final assessment; or says \"teach me this\", \"learn this PDF\", \"分章节教学\", \"带我学\", or similar; or returns to continue a previous course (\"continue my course\", \"接着上次学\") or supplies a saved course-state file or state block. Adapt explanations and practice to the learner's level, preserve page or section references for documents, and teach incrementally rather than dumping all content at once.\n---\n\n# Learn Everything\n\nConvert source material or a topic into an adaptive course that alternates explanation, retrieval, application, feedback, and review.\n\n## Core behavior\n\n- Teach in the user's language unless they request another language.\n- Optimize for durable understanding, not merely summarization.\n- Work incrementally. Present a course map, then teach one chapter or lesson at a time.\n- Do not reveal exercise solutions before the learner attempts them, unless the learner explicitly asks.\n- Persist learning state. When file tools are available, maintain `learn/<slug>/course-state.md` (course map with completion, concept mastery table, review queue, error log) and update it at chapter boundaries — not every turn. Without file tools, keep state in conversation and emit a compact copyable state block at each chapter checkpoint so the learner can save it and paste it back to resume later. See `references/session-formats.md` for both formats.\n- Prefer concrete examples, analogies, diagrams described in text, counterexamples, and worked derivations over abstract exposition alone.\n- Separate source claims from added background knowledge. Never attribute added material to the source.\n- Match depth and notation to the learner. Define unfamiliar terms before relying on them.\n\n## Determine the input mode\n\n### Document mode\n\nUse document mode for PDFs, papers, books, slides, notes, or other supplied material.\n\n1. Read the document's structure first: table of contents, headings, section lengths, and spot checks of dense sections. Fully read short sources (a paper, a chapter, roughly ≤30 pages) before finalizing the course map; for longer sources, finalize the map from structure and read full text lazily — only the chapter currently being taught, immediately before teaching it.\n2. Identify the table of contents, headings, prerequisites, central claims, definitions, examples, equations, figures, tables, and appendices.\n3. Use semantic units rather than equal page ranges. Merge short dependent sections and split dense sections.\n4. Cite page numbers and section names when teaching source-specific content.\n5. Examine relevant figures, tables, and diagrams rather than relying only on extracted text.\n6. Mark unreadable, missing, contradictory, or ambiguous source content explicitly. Do not invent a reconstruction.\n7. Treat the supplied source as the primary curriculum. Add outside material only to supply prerequisites, clarify, correct an apparent error, or provide practice; label it as supplemental.\n\n### Topic mode\n\nUse topic mode when the learner supplies a subject rather than a source.\n\n1. Define a sensible scope and end capability.\n2. Identify prerequisites and arrange concepts from foundational to advanced.\n3. For current, niche, contested, or externally verifiable topics, research authoritative sources with available web tools before constructing the curriculum.\n4. Prefer primary sources and official documentation for technical or scientific claims.\n5. Distinguish stable fundamentals from current developments.\n6. State material scope and assumptions in the course map.\n\nDo not delay progress for minor ambiguity. Choose a useful default scope and make it visible.\n\n### Resume mode\n\nUse resume mode when the learner supplies a saved course-state file or state block, or asks to continue a previous course.\n\n1. Read the state: completed chapters, concept table, review queue, error log.\n2. Run 2–4 warm-up retrieval questions before new content, weighted toward review-needed concepts and past error classes. Ask fresh questions, never the originals verbatim.\n3. Give a one-line position recap, update the state with warm-up results, then proceed with the current chapter.\n4. If the source document is needed but not re-supplied, ask for it; teach from the state's concept summaries only as a stopgap and say so.\n\n## Start the course\n\nGather only information that materially changes the lesson. If the learner's level or goal is unknown, either:\n\n- ask one compact diagnostic question, or\n- offer a 3-question diagnostic quiz and let the learner skip it.\n\nDo not ask a long questionnaire. Infer preferences from the conversation whenever possible.\n\nThen provide:\n\n1. **Target capability** — what the learner should be able to explain or do.\n2. **Course map** — 3–12 chapters, each with purpose and prerequisites.\n3. **Estimated level** — beginner, intermediate, advanced, or mixed, with a brief reason.\n4. **Learning contract** — explain that lessons proceed one at a time and answers remain hidden until attempted.\n5. **Next action** — begin the first lesson or diagnostic immediately.\n\nUse the detailed formats in `references/session-formats.md` when consistency is useful.\n\n## Build the course map\n\nCreate chapters around conceptual dependencies, not source length alone. Each chapter should have:\n\n- a concise title;\n- one observable learning objective;\n- key concepts;\n- prerequisite links;\n- source pages or sections in document mode;\n- one planned practice outcome.\n\nUse these sizing rules:\n\n- Split a chapter when it contains more than one major reasoning jump.\n- Merge sections that cannot be understood independently.\n- Create a prerequisite bridge chapter when the source assumes missing knowledge.\n- Keep advanced appendices optional unless needed for the learner's goal.\n- For sources with more than ~12 natural chapters, group chapters into parts, agree on scope with the learner, and run the course part by part rather than flattening everything into one map.\n- Reorder only when pedagogically necessary; explain the reordering in document mode.\n\n## Teach each lesson\n\nFollow this lesson loop:\n\n1. **Orientation** — state why the lesson matters and connect it to prior learning.\n2. **Objectives** — give 2–4 observable goals.\n3. **Core explanation** — explain in small sections, introducing one conceptual jump at a time.\n4. **Worked example** — demonstrate the reasoning, not only the final result.\n5. **Misconception check** — identify 1–3 likely confusions or boundary cases.\n6. **Active recall** — ask a brief check before proceeding to longer practice.\n7. **Practice** — assign exercises calibrated to current mastery.\n8. **Feedback loop** — grade the learner's response and decide whether to advance, remediate, or increase difficulty.\n\nFor dense material, pause after each major concept and ask a single check question. For straightforward material, teach the full lesson before practice.\n\n## Design practice\n\nSelect exercises from multiple cognitive levels:\n\n- **Recall:** define, list, label, reproduce.\n- **Explain:** restate in the learner's own words; compare concepts; explain why.\n- **Apply:** solve a representative problem or use the method in context.\n- **Debug:** find an error in reasoning, code, derivation, or interpretation.\n- **Transfer:** apply the idea in a novel setting.\n- **Synthesize:** connect several chapters or produce an artifact.\n\nDefault to 3–5 exercises per lesson, mixing at least two levels. Prefer one exercise at a time when grading interactively. Use larger sets only when the learner requests a worksheet or exam.\n\nConsult `references/practice-and-mastery.md` for exercise-writing rules, difficulty bands, adaptation, and grading rubrics. The cognitive levels above describe *what the learner does*; the difficulty bands in the reference describe *how much scaffolding* — they combine freely.\n\n## Grade and respond to learner answers\n\nEvaluate substance before wording. Use this sequence:\n\n1. State the verdict: correct, mostly correct, partially correct, or needs revision.\n2. Identify what was done well.\n3. Point to the first important gap or error.\n4. Explain the correction with the smallest useful amount of teaching.\n5. Ask for a revision, provide a targeted follow-up, or advance.\n\nDo not merely say “correct.” Reinforce the decisive reasoning.\n\nWhen the answer is wrong:\n\n- First provide a hint that targets the misconception.\n- Give a stronger hint after another failed attempt.\n- Reveal a worked solution after repeated attempts, an explicit request, or when further guessing has low learning value.\n- Immediately follow a revealed solution with a near-transfer question.\n\nWhen the answer is correct:\n\n- Increase difficulty gradually.\n- Ask for explanation if the learner may have guessed.\n- Use a transfer question when mastery appears strong.\n\n## Track mastery and review\n\nMaintain a concept table — one row per concept — in the course state (file or state block):\n\n- status: unseen, introduced, practicing, mastered, or review-needed;\n- evidence: strongest recent answer or error;\n- confidence: low, medium, or high;\n- next review point.\n\nUpdate it at chapter boundaries and after significant errors. Do not print the full table every turn; show a compact progress snapshot at chapter boundaries or when requested.\n\nSchedule cumulative review:\n\n- after each chapter: 2–4 retrieval questions from current and earlier material;\n- after roughly one-third and two-thirds of the course: mixed checkpoint;\n- at course end: final assessment and synthesis task;\n- revisit recurring errors more often than mastered concepts.\n\nTreat mastery as demonstrated transfer, not one correct recall answer.\n\n## Handle learner commands\n\nRecognize and act on natural commands such as:\n\n- “继续 / continue” — move to the next pending step.\n- “提示 / hint” — give the next hint without the full answer.\n- “答案 / show solution” — reveal and explain the solution, then ask a near-transfer question.\n- “更简单 / simpler” — reduce abstraction, add prerequisites and examples.\n- “更深入 / deeper” — add derivation, edge cases, and harder transfer.\n- “跳过 / skip” — mark the item skipped and continue.\n- “复习 / review” — generate retrieval practice weighted toward weak concepts.\n- “考试 / test me” — run a closed-book mixed assessment.\n- “进度 / progress” — show completed chapters, mastery, weak points, and next step.\n- “重做课程 / rebuild course” — revise scope or chaptering while preserving demonstrated mastery.\n\n## Complete the course\n\nAt the end, provide:\n\n1. a mixed final assessment without solutions shown initially;\n2. a synthesis task that uses multiple chapters;\n3. grading with concept-level feedback;\n4. a concise mastery report;\n5. a personalized review plan focused on weak concepts;\n6. a compact reference sheet created only after assessment, so it does not replace retrieval practice.\n\nFor document mode, include a source navigation index linking mastered concepts back to pages or sections.\n\n## Quality checks\n\nBefore each response, verify:\n\n- Solutions are not exposed before the learner attempts the exercise.\n- The current activity matches the course state, and the state is updated at chapter boundaries.\n- The lesson does not assume an unexplained prerequisite.\n- The response gives the learner exactly one clear next action.","packages/cli/src/skill/builtin/.bundle/loop/SKILL.md":"---\nname: loop\ndescription: Schedule a prompt to fire on a fixed cadence (recurring loop). Use when the user asks to \"run X every N minutes/hours/days\", \"loop X\", \"babysit Y\", \"be proactive about Y every N\", or invokes `/loop` directly. Parses `[interval] <prompt>`, picks a clean cron expression, registers the job via the `cron` tool, and executes the prompt once immediately so the user sees activity without waiting for the first cron tick.\n---\n\n# /loop — schedule a recurring prompt\n\nThis skill turns a free-form `[interval] <prompt>` line into a `cron` tool call and runs the prompt once right away.\n\n## 1. Parse the input\n\nThe user's text is whatever appears after `/loop `. Apply the three rules below **in order** and stop at the first match.\n\n1. **Leading interval token.** If the first whitespace-separated token matches the regex `^\\d+[smhd]$` (case-insensitive), that token is the interval. Examples: `5m`, `2h`, `1d`, `30s`. The rest of the input is the prompt.\n\n2. **Trailing `every <N><unit>` clause.** Otherwise, look for a clause at the end of the input of the form `every <N><unit>` or `every <N> <unit-word>` where `<unit>` is `s|m|h|d` and `<unit-word>` is `second(s)|minute(s)|hour(s)|day(s)`. Strip the clause; what's left is the prompt; the captured `<N><unit>` is the interval. Examples: `every 20m`, `every 5 minutes`, `every 2 hours`.\n\n3. **Default.** No interval found → interval is `10m`, the whole input is the prompt.\n\nIf the input is empty, or is *only* an interval with no prompt body, reply with a one-line usage hint (`/loop [interval] <prompt>`) and stop. Do not schedule anything.\n\n## 2. Special: empty prompt with autonomous opt-in\n\nWhen the user types `/loop <interval>` (interval only) **and** the project has explicitly opted into autonomous-loop mode (a session-level flag the runtime sets), the prompt body is the sentinel `<<autonomous-loop>>`. The scheduler expands this sentinel at fire time into a self-directed tick instruction. If autonomous mode is not enabled, treat empty as the usage-hint case above.\n\n## 3. Map interval → 5-field cron expression\n\n| Pattern | Cron expression |\n|---|---|\n| `Ns` | treat as `ceil(N/60)m`; minimum is `1m` |\n| `Nm` where `N` is 1–59 and divides cleanly (1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30) | `*/N * * * *` |\n| `Nm` where `N ≥ 60` and `N/60` divides 24 (1, 2, 3, 4, 6, 8, 12) | `0 */(N/60) * * *` |\n| `Nh` where `N` is 1–23 and divides 24 | `0 */N * * *` |\n| `Nd` where `N` divides 31 sensibly (1, 2) | `0 0 */N * *` |\n\nCron fields are UTC. These interval patterns are timezone-agnostic; the `Nd`\nrow fires at midnight UTC, not local midnight.\n\n**Rounding rule.** If `N` does not divide its wrap-around cleanly (e.g. `7m`, `90m`, `5h`, `7d`), pick the **nearest interval that does** and tell the user explicitly what you rounded to and why. Acceptable nearby values:\n\n- minutes < 60: 1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30\n- hours: 1, 2, 3, 4, 6, 8, 12\n- days: 1, 2\n\nExamples of rounding messages:\n- `7m` → \"rounding 7m to 6m so the fires stay evenly spaced; `*/7` skews at the hour wrap\"\n- `90m` → \"rounding 90m to 2h; cron's hour field can't express 1.5h\"\n\n## 4. Call the cron tool\n\nWith the parsed `cron` expression and `prompt`, invoke the `cron` tool's `schedule` verb. Use whichever call form the tool's own prompt describes — pass `cron` and `prompt` as required, leave `durable: false` (the default; only set true when the user explicitly asked the job to persist across sessions), leave it recurring (the default; one-shot is wrong for `/loop` — one-shots come from natural-language scheduling).\n\nThe cron tool returns a job id. Mention it briefly so the user can cancel with `/loops cancel <id>`.\n\n## 5. Execute the prompt once immediately\n\nAfter the cron call succeeds, **do not wait for the first scheduled tick**. Run the prompt body once right now:\n\n- If the prompt starts with `/` (e.g. `/loop 5m /standup` → prompt is `/standup`), invoke it as a slash command — load the corresponding skill or command via the `skill` tool.\n- Otherwise, act on the prompt directly in this turn.\n\nThis is the \"don't make the user wait\" rule. The cron job carries the recurring behavior; the immediate run is for responsiveness.\n\n## 6. Examples\n\n| User input | Interval | Cron | Prompt |\n|---|---|---|---|\n| `/loop 5m /babysit-prs` | `5m` (leading) | `*/5 * * * *` | `/babysit-prs` |\n| `/loop check the deploy every 20m` | `20m` (trailing) | `*/20 * * * *` | `check the deploy` |\n| `/loop /standup every 2 hours` | `2h` | `0 */2 * * *` | `/standup` |\n| `/loop tidy inbox` | `10m` (default) | `*/10 * * * *` | `tidy inbox` |\n| `/loop 30s ping` | `30s` → `1m` | `*/1 * * * *` | `ping` |\n| `/loop 7m ping` | `7m` → `6m` (rounded, explain) | `*/6 * * * *` | `ping` |\n| `/loop` | (usage hint) | — | — |\n| `/loop 5m` | autonomous-only | (if enabled) | `<<autonomous-loop>>` |\n\n## 7. Do not\n\n- Do not invent intervals the user didn't ask for. If unsure, default to `10m` and say so.\n- Do not pass `--one-shot`. This skill is for recurring loops.\n- Do not list active jobs in your reply. Use `/loops` for that.\n- Do not re-derive the cron expression in your reply unless the user asked. A one-line confirmation (\"scheduled `<prompt>` every `<interval>`; job id `<id>`\") is enough.\n","packages/cli/src/skill/builtin/.bundle/mate/SKILL.md":"---\nname: mate\ndescription: \"Create custom desktop pet (Mate) characters with spritesheet and manifest. Use when the user asks to 'create a pet', 'make a desktop companion', 'design a mate character', 'generate a spritesheet for my pet', or wants to customize their desktop buddy. Generates a WebP spritesheet + manifest.json that can be loaded by MiMo Desktop's Mate system.\"\n---\n\n# Mate Pet Creator\n\nCreate animated desktop pet characters for MiMo Desktop's Mate (桌面伙伴) system.\n\n## Output Structure\n\nA valid custom pet lives in a folder with this structure:\n\n```\n<pet-id>/\n├── manifest.json     # Required — animation metadata\n└── spritesheet.webp  # Required — all animation frames in a grid\n```\n\nThe user places this folder in their MiMo Desktop custom pets directory (`userData/pets/<pet-id>/`), then clicks \"Refresh\" in Settings → Mate to load it.\n\n## Manifest Schema\n\n```json\n{\n  \"id\": \"my-pet\",\n  \"name\": \"My Pet\",\n  \"description\": \"A cute custom pet\",\n  \"version\": 1,\n  \"spritesheet\": \"spritesheet.webp\",\n  \"frameWidth\": 240,\n  \"frameHeight\": 240,\n  \"columns\": 8,\n  \"totalFrames\": 16,\n  \"animations\": {\n    \"idle\": { \"row\": 0, \"frames\": 8, \"fps\": 8, \"loop\": true }\n  }\n}\n```\n\n### Required Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `id` | string | Unique identifier (kebab-case) |\n| `name` | string | Display name |\n| `version` | number | Always `1` |\n| `spritesheet` | string | Filename of the spritesheet image |\n| `frameWidth` | number | Width of each frame in pixels |\n| `frameHeight` | number | Height of each frame in pixels |\n| `columns` | number | Number of columns in the spritesheet grid |\n| `totalFrames` | number | Total number of frames across all animations |\n| `animations` | object | At minimum must include `idle` |\n\n### Optional Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `description` | string | Shown in settings UI |\n| `anchorX` | number | Horizontal anchor (0–1, default 0.5) for centering |\n\n### Animation Definition\n\nEach animation entry:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `row` | number | Row index in the spritesheet (0-based) |\n| `frames` | number | Number of frames in this animation |\n| `fps` | number | Playback speed (recommended: 6–12) |\n| `loop` | boolean | Whether the animation loops |\n\nThe `idle` animation is **required** — it plays by default when the pet is loaded.\n\n## Spritesheet Layout\n\n- Frames are arranged left-to-right, top-to-bottom in a grid.\n- Each row corresponds to one animation (matched by the `row` field in the animation definition).\n- All frames must have identical dimensions (`frameWidth × frameHeight`).\n- Transparent background (alpha channel) is required — the pet window has no background.\n- Recommended frame size: 240×240 px (renders well at 1× scale on desktop).\n- Format: WebP with transparency (lossless or near-lossless for crisp pixel art).\n\n## Workflow\n\n### Step 1: Understand the Character\n\nAsk the user:\n- What animal/creature/character?\n- Art style preference (pixel art, cartoon, flat vector, kawaii)?\n- Any specific colors or features?\n\n### Step 2: Generate the Spritesheet\n\nUse the `imagegen` skill to generate the spritesheet image. Construct the prompt with these guidelines:\n- Request a **sprite sheet** with specific grid layout (e.g., \"8 frames in a single horizontal row, each frame 240×240 pixels\")\n- Specify **transparent background** (alpha channel)\n- Describe the **idle animation** motion: gentle breathing, blinking, tail wag, bobbing, etc.\n- Keep the character **centered** in each frame with consistent sizing\n- Style: match the user's preference; default to cute/kawaii if unspecified\n\nIf the generated image is already WebP, use it directly. If it is PNG or another format, convert to WebP:\n\n```bash\n# Convert to lossless WebP preserving transparency\ncwebp -lossless -q 100 spritesheet.png -o spritesheet.webp\n```\n\nIf `cwebp` is not available, check for `sips` (macOS Ventura+ supports WebP export):\n\n```bash\nsips -s format webp spritesheet.png --out spritesheet.webp\n```\n\nIf neither tool is available, instruct the user to install one:\n\n```\nbrew install webp   # provides cwebp\n```\n\nDo NOT silently rename a PNG to .webp — the file must have valid WebP encoding (RIFF/WEBP header). If conversion genuinely cannot be performed, fail explicitly and tell the user what tool to install.\n\nIf `imagegen` is unavailable (skill not enabled or image generation fails), fall back to generating pixel-art frames directly as SVG, then rasterize. Compute dimensions from the manifest:\n\n```bash\n# Calculate actual spritesheet dimensions from manifest\nWIDTH=$((frameWidth * columns))\nHEIGHT=$((frameHeight * rows))  # rows = max animation row index + 1\n\n# Rasterize SVG to PNG, then convert to WebP\nrsvg-convert -w $WIDTH -h $HEIGHT spritesheet.svg -o spritesheet.png\ncwebp -lossless spritesheet.png -o spritesheet.webp\n```\n\nAs a last resort, output the SVG file directly and instruct the user to convert it manually.\n\n### Step 3: Write the Manifest\n\nGenerate `manifest.json` with correct dimensions matching the actual spritesheet output. Verify:\n- `frameWidth × columns` = spritesheet total width\n- `frameHeight × (max animation row index + 1)` = spritesheet total height\n- `animations.idle` exists with valid `row`, `frames`, `fps`, `loop`\n- Each animation's `frames` ≤ `columns` (frames per row cannot exceed grid columns)\n\n### Step 4: Deliver\n\nWrite both files to the current working directory under a folder named with the pet ID. Tell the user to:\n1. Copy the folder to their MiMo Desktop pets directory (Settings → Mate → click \"Open Folder\" to find it)\n2. Click \"Refresh\" in Settings → Mate\n3. Select their new pet from the list\n\n## Constraints\n\n- The `idle` animation MUST exist — the system falls back to it.\n- Frame dimensions must be consistent across the entire spritesheet.\n- Keep total file size under 2MB for smooth loading.\n- Pet ID must be unique; if it conflicts with a preset (`koala`, `panda`), the preset wins.\n- Do NOT reference or depend on any external URLs — all assets must be local files.\n","packages/cli/src/skill/builtin/.bundle/memory-search/SKILL.md":"---\nname: \"memory-search\"\ndescription: \"Query the raw trajectory SQLite database directly when the built-in memory and history tools are insufficient. Use when you need structured analysis across sessions: finding repeated errors, grouping tool calls by pattern, verifying what was actually executed, or locating specific past commands/decisions that text search cannot surface. Provides the database schema, ready-to-use SQL query templates, and per-goal strategies.\"\n---\n\n# Memory Search: SQLite Trajectory Database\n\nDirect SQL access to mimocode's trajectory database for structured analysis that the `memory` (BM25 over curated markdown) and `history` (FTS over raw messages) tools cannot perform — aggregation, filtering by tool/status/time, cross-session pattern detection, and execution chain inspection.\n\n## When to use\n\n- You need to **aggregate or count** across sessions (e.g. \"which tool fails most often?\", \"how many sessions touched file X?\").\n- You need to **filter by structure** — tool name, status, agent_id, time range — not just text content.\n- You need to **view a complete execution chain** for a session (every tool call in order).\n- You need to **verify a memory claim** against what actually happened (the DB is the source of truth).\n- The `memory` and `history` tools returned nothing useful despite multiple query attempts.\n\n## Locating the database\n\n```bash\n# Typically at this path. MIMOCODE_DB env var overrides if set.\nsqlite3 -readonly ~/.local/share/mimocode/mimocode.db \".tables\"\n```\n\nAlways use `-readonly` or only SELECT queries — never modify the database.\n\n## Schema\n\n| Table | Purpose | Key columns |\n|-------|---------|-------------|\n| `session` | Session metadata | `id`, `project_id`, `title`, `time_created`, `parent_id` |\n| `message` | User/assistant turns | `id`, `session_id`, `agent_id`, `time_created`, `data` (JSON: `$.role`) |\n| `part` | Message parts (text, tool calls, steps) | `id`, `message_id`, `session_id`, `time_created`, `data` (JSON) |\n| `task` | Task tree | `id`, `session_id`, `summary`, `status` |\n| `task_event` | Task state transitions | `id`, `session_id`, `task_id`, `at`, `kind`, `summary` |\n| `actor_registry` | Subagent/peer history | `session_id`, `actor_id`, `agent`, `mode`, `status`, `description` |\n\n### Part types in `part.data`\n\n- `{\"type\":\"text\",\"text\":\"...\"}` — agent text output\n- `{\"type\":\"tool\",\"tool\":\"<name>\",\"callID\":\"...\",\"state\":{\"status\":\"completed\",\"input\":{...},\"output\":\"...\"}}` — completed tool call\n- `{\"type\":\"tool\",\"tool\":\"<name>\",\"callID\":\"...\",\"state\":{\"status\":\"error\",\"input\":{...},\"error\":\"...\"}}` — failed tool call (no `output` field; error message in `$.state.error`)\n- `{\"type\":\"step-start\"}` / `{\"type\":\"step-finish\",\"tokens\":...}` — step boundaries\n- `{\"type\":\"compaction\",\"auto\":true/false}` — compaction boundary\n- `{\"type\":\"checkpoint\",...}` — checkpoint/rebuild boundary\n\n### Key conventions\n\n- `agent_id = 'main'` = main agent; other values = subagent (e.g. `\"explore-1\"`, `\"general-1\"`).\n- `$.state.output` only exists when `$.state.status = \"completed\"`. Failures store the message in `$.state.error`.\n- `time_created` is Unix milliseconds.\n\n## Query templates\n\n**List recent sessions for this project:**\n\n```sql\nSELECT id, title, time_created,\n       datetime(time_created/1000, 'unixepoch', 'localtime') as created\nFROM session\nWHERE project_id = '<PROJECT_ID>'\n  AND parent_id IS NULL\nORDER BY time_created DESC\nLIMIT 20;\n```\n\n**Find user messages containing a keyword:**\n\n```sql\nSELECT m.session_id, m.id,\n       substr(json_extract(p.data, '$.text'), 1, 200) as preview\nFROM message m\nJOIN part p ON p.message_id = m.id AND p.session_id = m.session_id\nWHERE json_extract(m.data, '$.role') = 'user'\n  AND json_extract(p.data, '$.type') = 'text'\n  AND json_extract(p.data, '$.text') LIKE '%keyword%'\nORDER BY m.time_created DESC\nLIMIT 10;\n```\n\n**Find tool calls by tool name:**\n\n```sql\nSELECT m.session_id, m.id, m.agent_id,\n       json_extract(p.data, '$.tool') as tool,\n       json_extract(p.data, '$.state.status') as status,\n       substr(COALESCE(json_extract(p.data, '$.state.output'), json_extract(p.data, '$.state.error')), 1, 300) as result_preview\nFROM message m\nJOIN part p ON p.message_id = m.id AND p.session_id = m.session_id\nWHERE json_extract(m.data, '$.role') = 'assistant'\n  AND json_extract(p.data, '$.type') = 'tool'\n  AND json_extract(p.data, '$.tool') = '<TOOL_NAME>'\n  AND m.session_id = '<SESSION_ID>'\nORDER BY m.time_created DESC\nLIMIT 20;\n```\n\n**View a session's full execution chain:**\n\n```sql\nSELECT m.id, m.agent_id,\n       json_extract(p.data, '$.type') as part_type,\n       json_extract(p.data, '$.tool') as tool,\n       substr(p.data, 1, 800) as preview\nFROM message m\nJOIN part p ON p.message_id = m.id AND p.session_id = m.session_id\nWHERE m.session_id = '<SESSION_ID>'\n  AND json_extract(m.data, '$.role') = 'assistant'\nORDER BY m.time_created, p.time_created;\n```\n\n**Find repeated stdout errors (completed bash calls, last 7 days):**\n\n```sql\nSELECT substr(json_extract(p.data, '$.state.output'), 1, 200) as error_output,\n       COUNT(*) as occurrences,\n       GROUP_CONCAT(DISTINCT m.session_id) as sessions\nFROM part p\nJOIN message m ON m.id = p.message_id AND m.session_id = p.session_id\nWHERE json_extract(p.data, '$.type') = 'tool'\n  AND json_extract(p.data, '$.tool') = 'bash'\n  AND json_extract(p.data, '$.state.status') = 'completed'\n  AND json_extract(p.data, '$.state.output') LIKE '%error%'\n  AND m.time_created > (strftime('%s', 'now') - 7*86400) * 1000\nGROUP BY substr(json_extract(p.data, '$.state.output'), 1, 200)\nHAVING occurrences > 1\nORDER BY occurrences DESC\nLIMIT 10;\n```\n\n**Find actual tool failures (any tool, last 7 days):**\n\n```sql\nSELECT json_extract(p.data, '$.tool') as tool,\n       substr(json_extract(p.data, '$.state.error'), 1, 200) as error_msg,\n       COUNT(*) as occurrences,\n       GROUP_CONCAT(DISTINCT m.session_id) as sessions\nFROM part p\nJOIN message m ON m.id = p.message_id AND m.session_id = p.session_id\nWHERE json_extract(p.data, '$.type') = 'tool'\n  AND json_extract(p.data, '$.state.status') = 'error'\n  AND m.time_created > (strftime('%s', 'now') - 7*86400) * 1000\nGROUP BY json_extract(p.data, '$.tool'), substr(json_extract(p.data, '$.state.error'), 1, 200)\nHAVING occurrences > 1\nORDER BY occurrences DESC\nLIMIT 10;\n```\n\n## Search strategies\n\n| Goal | Strategy |\n|------|----------|\n| Find a user's stated rule/preference | Search user text parts for `'%always%'`, `'%never%'`, `'%remember%'`, `'%rule%'` |\n| Find a design decision | Search `'%decided%'`, `'%tradeoff%'`, `'%reason%'` in user text |\n| Find a specific file path or command | LIKE match on tool output/error |\n| Find repeated workflows | Group tool call sequences by session, look for recurring tool×N patterns |\n| Verify a memory claim | Find the session_id from the memory entry `[ses_xxx]`, then query its full execution chain |\n| Count tool usage | `GROUP BY json_extract(p.data, '$.tool')` with COUNT |\n\n## Constraints\n\n- **Read-only**: Never modify the database. Always `sqlite3 -readonly` or SELECT only.\n- **Performance**: The DB can be multi-GB. Always use LIMIT and filter by `session_id` or `time_created` range.\n- **Privacy**: Raw trajectory contains everything the user typed. Treat it with care.\n- **JSON access**: Part data is JSON-in-a-column. Always use `json_extract()` for structured field access.\n","packages/cli/src/skill/builtin/.bundle/mimocode-docs/SKILL.md":"---\nname: mimocode-docs\ndescription: \"Use whenever the user asks about MiMoCode itself: features, TUI or CLI commands, keybindings, terminal compatibility, rendering glitches, TUI lag, SSH or remote rendering, agent modes (build / plan) and how to switch between them, configuration, file locations, providers, models, authentication, or custom OpenAI-compatible or Anthropic-compatible API endpoints. Especially trigger when a prompt supplies or asks to configure a base URL/baseURL, API key/apiKey, model name or ID, provider, Anthropic Messages API, or global/project mimocode.json/jsonc, or when the user asks how to enter or leave plan mode. Also trigger when a skill, task, subprocess, or external client needs to borrow this instance's models — the OpenAI-compatible /v1 chat endpoints every MiMoCode server serves, `mimo llm-server` task tokens, or how to expose a listening port for them. Use this skill to inspect existing config safely, make minimal changes, and verify them without guessing schema fields or model capabilities.\"\n---\n\n# MiMoCode\n\nYou are MiMoCode. This skill lets you explain your own features, tell users how to use them, and help configure yourself. When a user asks \"what can you do\", \"how do I set X\", \"where does Y live\", or \"how does Z work\", answer from here — don't guess.\n\n## Identity\n\nMiMoCode (CLI binary `mimo`) is an agentic coding tool with a terminal UI, built as a fork of OpenCode. Beyond OpenCode's core (multi-provider, TUI, LSP, MCP, plugins) it adds: persistent memory, intelligent context management, subagent orchestration, goal-driven autonomous loops, compose-next end-to-end delivery, Dynamic Workflows, and self-improvement via dream/distill.\n\n## Feature Map\n\n| Feature | What it is | How to reach it |\n|---------|-----------|-----------------|\n| **Agents / modes** | `build` (default, full tools), `plan` (read-only analysis), plus custom modes you define. Build and Plan can switch at any time; other custom or special modes lock once the first message is sent. Only the user enters a mode — no tool lets the agent switch into plan, and the agent does not raise plan mode unasked; from inside plan the agent can call `plan_exit` to ask for approval and hand the plan back to build | `Tab` cycles primary agents, or pick one in the agent dialog; add your own via `.mimocode/agent/<name>.md` (see @reference/guide.md) |\n| **Subagents** | Primary agent spawns `general`/`explore` helpers, parallel + background, with lifecycle/cancel | automatic; `actor` tooling |\n| **Persistent memory** | Markdown-backed memory with indexed search across `MEMORY.md`, `checkpoint.md`, `notes.md`, and `tasks/<id>/progress.md` | auto-injected on resume |\n| **Context management** | Auto-checkpoints, context reconstruction near limit, budgeted injection | automatic; tune via `checkpoint`/`compaction` config |\n| **Task tree** | `T1`, `T1.1`… tree, integrated with checkpoints | `task` tooling |\n| **Goal / stop condition** | Judge model verifies a stop condition before the agent halts | `/goal` |\n| **Compose mode** | Structured spec→ship lifecycle; entry is the `compose-next` skill — clarify, spec, implement, verify, review, finish. Do not combine it with plan mode | `/compose-next` (see @reference/guide.md) |\n| **Visual modes** | `vivid` (default: star field, meteors, logo effects, animated activity) and `minimal` (quiet visuals, stable activity indicators); independent from the animation override | `/vivid` or the visual-mode option in `ctrl+p` |\n| **Voice input** | Streaming ASR (TenVAD + MiMo ASR); needs `sox` | `/voice` |\n| **Dream** | Consolidates recent traces into project memory | `/dream` |\n| **Distill** | Packages repeated manual workflows into skills/subagents/commands | `/distill` |\n| **Scheduled prompts** | Cron/loop: inject a prompt on a schedule or repeating loop (UTC, 5-field) | `cron` tool · `/loop` · `/loops` |\n| **Dynamic Workflow** | JS scripts that orchestrate many subagents deterministically (fan-out, pipelines, nesting); built-ins include `deep-research`, `fact-check`, and `research-experiment` | `.mimocode/workflows/*.js` + `workflow` tool |\n| **Custom skills** | Add reusable task instructions under `.mimocode/skills/` | see the `skill-creator` skill |\n| **Skill discovery** | `/skill-name` slash invocation (2+ in one message auto-load with an orchestration plan); `skill_search` tool matches by exact name/alias + BM25 and auto-loads high-confidence hits; some builtins (`claude-code`, `codex`) only appear when their CLI is installed | `/` autocomplete · automatic |\n| **MCP** | Local & remote Model Context Protocol servers | `mcp` config + `mimo mcp` |\n| **Capability API** | Every session already serves this project's chat models over OpenAI-compatible `/v1` on a loopback port, so a skill or subprocess borrows a model instead of a provider key | `mimo llm-server issue` mints a scoped token and prints the base URL (see @reference/capability-api.md) |\n\n## Configuration Basics\n\nConfig file (JSON or JSONC), discovered by walking up from cwd:\n- **Project**: `.mimocode/mimocode.json` (or `.jsonc`)\n- **Global**: `~/.config/mimocode/mimocode.jsonc` (preferred for new files) or `mimocode.json`\n\nAdd `\"$schema\": \"https://mimo.xiaomi.com/mimocode/config.json\"` for editor validation. All top-level keys are optional; project config merges over global.\n\n```jsonc\n{\n  \"$schema\": \"https://mimo.xiaomi.com/mimocode/config.json\",\n  \"model\": \"provider/model\",\n  \"permission\": { \"external_directory\": { \"/tmp/**\": \"allow\" } }\n}\n```\n\n## Reference routing\n\nRead only the reference needed for the request, but read it before changing files:\n\n- Models, providers, API keys, base URLs, or OpenAI-/Anthropic-compatible endpoints: @reference/providers.md\n- Other config keys and on-disk locations: @reference/config.md\n- Task-oriented usage and setup: @reference/guide.md\n- Terminal compatibility, TUI rendering or lag, and SSH remote use: @reference/guide.md\n- CLI and slash commands: @reference/commands.md\n- Permission rules: @reference/permissions.md\n- MCP client-side sampling (servers borrowing your model, audio transcription): @reference/mcp-sampling.md\n- Lending this instance's chat models to a skill, task, or subprocess — the OpenAI-compatible `/v1` endpoints and the `mimo llm-server` tokens that reach them: @reference/capability-api.md\n- Dynamic Workflow: @reference/workflows.md\n\n## How-To Guide\n\nFor task-oriented walkthroughs — signing in & choosing a model, troubleshooting TUI rendering or lag, using MiMoCode over SSH, making memory remember project rules, writing custom slash commands, remapping keybinds, adding MCP servers, scheduling prompts (cron/loop), and using compose-next end-to-end delivery — see @reference/guide.md. For authoring and running **Dynamic Workflow** scripts (the in-script API, where to save `.js` workflow files, and the `workflow` tool) see @reference/workflows.md.\n\n**Built-in workflows** (runnable by name via the `workflow` tool, no file needed):\n- **`deep-research`** — comprehensive research report generator (brief → plan → parallel research → reflect → write → cold review). Pass `args: { dir, question, today, depth?, context? }`. Convergent/resumable.\n- **`fact-check`** — adversarial fact verification (plan → search → extract → group → 3-juror crosscheck → JSON findings). Pass the question as `args`.\n- **`research-experiment`** — autonomous metric-improvement loop with baseline, guarded iterations, audit, and report. It requires an eval command, metric extraction rule, and editable-file scope.\n\n## Where Things Live On Disk\n\nBase dirs follow `MIMOCODE_HOME` (if set, absolute) else XDG. Data typically lives at `~/.local/share/mimocode/` (memory, logs, extracted builtin skills), config at `~/.config/mimocode/`, cache at `~/.cache/mimocode/`. See @reference/config.md for the full layout and env vars.\n\n## Commands\n\n`mimo` subcommands (`mcp`, `run`, `agent`, `models`, `providers`, `upgrade`, `stats`, `export`/`import`, `github`/`pr`, `serve`, …) and slash commands (`/goal`, `/dream`, `/distill`, `/vivid`, `/voice`, `/loop`, `/connect`, `/<skill-name>`) are documented in @reference/commands.md.\n\n## Helping the User Configure\n\nWhen asked to change a behavior:\n1. Read the routed reference and identify the exact schema fields. Do not infer fields from another tool's config format.\n2. Determine scope from the request. Treat model/provider setup as global unless the user says it is project-only; use project config for explicitly repo-local behavior.\n3. Inspect only the exact config candidates. Never recursively search the user's home directory. Prefer an existing higher-precedence `.jsonc` file and preserve comments, `$schema`, unrelated providers, and other settings.\n4. Keep secrets out of tool output and the final response. When inspecting a config, redact values for keys such as `apiKey`, `token`, `secret`, and `password`; never dump the whole unredacted file merely to find its shape.\n5. Edit minimally. If the request says configure, use, or make default, also set the top-level `model`; if it only says add, leave the current selection unchanged.\n6. When persisting a newly supplied API key and model, also put that exact `provider/model` at the front of the TUI recent-model state so the user can switch to it immediately. Follow the merge procedure in @reference/providers.md; never replace favorites, variants, or unrelated recent models.\n7. Validate the parsed configuration with the narrowest relevant command and report the config and recent-model state files changed, selected provider/model, and whether a new session or re-selection is needed. Never include the credential in the summary.\n\nDon't invent config keys, model limits, context windows, output limits, modalities, reasoning support, or tool-call capabilities. Add optional model metadata only when the user supplied it or a current authoritative source verifies it. If a requested behavior has no key, say so and suggest the closest supported option.\n\n## Answering Feature Questions\n\n- Confirm the feature exists in the map above before describing it.\n- Give the trigger (command / key / config), then a one-line how.\n- For authoring reusable task instructions, use the `skill-creator` skill.\n- If unsure whether a detail is current, verify against the config schema or README rather than asserting.\n","packages/cli/src/skill/builtin/.bundle/modern-python-toolchain/SKILL.md":"---\nname: modern-python-toolchain\ndescription: \"Modern Python project setup with uv, ruff, and pyright. Use when initializing a new Python project, configuring the Python environment, setting up linting/formatting, or when a project needs uv (the fast Python package manager). Trigger on: 'set up Python', 'new Python project', 'configure uv', 'install uv', 'ruff', 'pyright', 'Python linting', 'Python formatting', or when a task requires Python and no pyproject.toml exists yet.\"\n---\n\n# Modern Python Toolchain\n\nA guide for setting up Python projects with modern, fast tooling: **uv** (package/project manager), **ruff** (linter/formatter), and **pyright** (type checker).\n\n## Installing uv\n\nuv is an extremely fast Python package and project manager. It replaces pip, pip-tools, pipx, pyenv, virtualenv, poetry, etc.\n\n```bash\n# macOS / Linux\ncurl -LsSf https://astral.sh/uv/install.sh | sh\n\n# Windows (PowerShell)\npowershell -ExecutionPolicy ByPass -c \"irm https://astral.sh/uv/install.ps1 | iex\"\n\n# Homebrew (macOS)\nbrew install uv\n```\n\nAfter installation, restart your shell or run `source $HOME/.local/bin/env` (the installer prints the exact command).\n\nFor detailed information: https://docs.astral.sh/uv/\n\n---\n\n## uv basics\n\n### Python version\n\nPin a single Python minor version. The recommended default is 3.12 (broadest ecosystem support — PyTorch, CUDA images, downstream libraries). Python 3.14 is the latest stable; prefer it for new projects unless you depend on packages that haven't added 3.14 support yet.\n\n```toml\n# pyproject.toml\nrequires-python = \"==3.12.*\"\n```\n\nInstall Python via uv (no system Python needed):\n\n```bash\nuv python install 3.12\n```\n\n### Creating a new project\n\n```bash\nuv init                       # Create new project with pyproject.toml\nuv init -p 3.12               # Specify Python version\n```\n\n### Common commands\n\n```bash\nuv add requests               # Add dependency\nuv add --dev ruff \"pyright[nodejs]\"  # Add dev dependencies\nuv remove requests            # Remove dependency\nuv sync                       # Install from lockfile\nuv run COMMAND                # Run command in project environment\nuv run script.py              # Run a script\nuv run python -c \"...\"        # Run Python one-liner\nuvx TOOL ARGS                 # Run a tool without installing it\n```\n\n### Rules\n\n- **Never use `pip`** in uv projects — always `uv add` for packages.\n- **Never run `python script.py` directly** — always `uv run script.py` to ensure the correct environment. For one-liners use `uv run python -c \"...\"`.\n- **Don't manually manage environments** with `python -m venv` or `source .venv/bin/activate` — uv handles this automatically.\n- `uvx` runs tools from PyPI by package name without installing them permanently.\n\n### Project types\n\nFor **library** projects (`uv init --lib`) or packaged apps (`uv init --package`), `uv_build` is used as the default build backend automatically:\n\n```toml\n[build-system]\n# auto-generated by uv init; version bound tracks your installed uv (here: 0.11.28)\nrequires = [\"uv_build>=0.11.28,<0.12.0\"]\nbuild-backend = \"uv_build\"\n```\n\nFor **application** projects with an entry point:\n\n```toml\n[project.scripts]\nmyapp = \"myapp.__main__:main\"\n```\n\nIf the project does not use src layout, just run `uv run main.py`.\n\n---\n\n## ruff\n\nRuff is an extremely fast Python linter and code formatter. It replaces Flake8, isort, Black, pyupgrade, autoflake, and more.\n\nFor detailed information: https://docs.astral.sh/ruff/\n\n### When to use\n\nAlways use ruff for Python linting and formatting. Prefer `uv run ruff` when ruff is a dev dependency; otherwise fall back to `uvx ruff`.\n\n### Configuration\n\nAdd to `pyproject.toml`:\n\n```toml\n[tool.ruff.lint]\nextend-select = [\n    \"UP\",  # pyupgrade\n    \"I\",   # isort\n]\n```\n\nDo not enable the full `E` category or other formatter-conflicting rules (E1xx, E501, W191, Q, COM); `ruff format` owns layout.\n\n### Post-edit workflow\n\nAfter modifying Python code, run both:\n\n```bash\nuv run ruff check --fix path/to/changed_file.py\nuv run ruff format path/to/changed_file.py\n```\n\nUse `--diff` to preview changes without applying.\n\n---\n\n## pyright\n\nPyright is a fast type checker for Python. Only use it when the project lists it as a dev dependency or explicitly uses type checking.\n\nInstall with the `nodejs` extra so Node.js is bundled automatically (no system `node` required):\n\n```bash\nuv add --dev \"pyright[nodejs]\"\n```\n\nRun type checking:\n\n```bash\nuv run pyright path/to/changed_file.py    # check specific files\nuv run pyright src/                        # check all code\n```\n\nUsually only check the files you modified. For broad changes (base classes, shared types), check the full tree.\n\n---\n\n## Coding style\n\n### Type annotations\n\nUse modern Python 3.12+ syntax:\n\n```python\n# Good — builtin generics, union syntax\ndef fetch(url: str, timeout: float = 30.0) -> list[dict[str, str | None]]:\n    ...\n\n# Bad — legacy typing imports\nfrom typing import List, Dict, Optional\ndef fetch(url: str, timeout: float = 30.0) -> List[Dict[str, Optional[str]]]:\n    ...\n```\n\nAlways annotate function parameters. Local variables can rely on inference unless the type is ambiguous:\n\n```python\nitems: list[tuple[str, int]] = []    # annotate — empty literal\nconfig: dict[str, Any] = {}          # annotate — empty literal\nresult = some_api()                  # inference is fine\n```\n\n### pydantic v2\n\nUse the modern class-based API:\n- `model_config = ConfigDict(...)` at class body level, not `class Config`.\n- `RootModel` with `root: SomeType` for single-root schemas.\n\n### typer (CLI)\n\nRecommended for CLI entry points over `argparse`:\n\n```python\nimport typer\nfrom typing import Annotated\n\ncli = typer.Typer(add_completion=False)\n\n@cli.command()\ndef main(name: Annotated[str, typer.Argument(help=\"Your name\")]) -> None:\n    typer.echo(f\"Hello {name}\")\n\nif __name__ == \"__main__\":\n    cli()\n```\n","packages/cli/src/skill/builtin/.bundle/pdf-official/README.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fpdf-official%2FREADME.md -->","packages/cli/src/skill/builtin/.bundle/pdf-official/SKILL.md":"---\nname: pdf-official\ndescription: \"Use this skill whenever a PDF file is being produced, opened, transformed, filled, or read. That includes: extracting text or tables from an existing PDF; combining, carving, rotating, cropping, or watermarking pages; composing a fresh PDF (report, invoice, certificate); filling AcroForm fields or overlaying text onto a non-fillable scanned form; encrypting or unlocking a PDF; running OCR over a scanned document; rendering pages to PNG/JPEG for visual analysis. Trigger on mentions of 'PDF', a filename ending in .pdf, requests like 'turn this into a PDF report', or references to AcroForm / form fields.\"\nlicense: Apache-2.0 — see LICENSE for terms and third-party attributions\n---\n\n# PDF skill\n\nAn Apache-2.0 toolkit for reading, composing, transforming, and filling PDF\nfiles. Written from scratch on top of permissively-licensed open-source\nlibraries (pypdf, pdfplumber, pypdfium2, reportlab, pdf-lib, qpdf) so this\ncan be embedded in commercial projects without special agreement.\n\n## Route the task\n\nPick the sub-guide by the *verb* of the request.\n\n| Task | Path | Read |\n|------|------|------|\n| Pull text / tables / metadata / images out of an existing PDF | Extract | [`extract.md`](extract.md) |\n| Combine, carve, rotate, crop, watermark, encrypt, or shrink | Transform | [`transform.md`](transform.md) |\n| Build a PDF that doesn't exist yet (report, invoice, certificate) | Compose | [`compose.md`](compose.md) |\n| Fill a form (AcroForm or scanned) | Interactive | [`interactive.md`](interactive.md) |\n| Scanned / image-only PDF (no selectable text) | Extract → *OCR* | [`extract.md`](extract.md) §5 |\n\nIf a task mixes several of these, follow the order:\n**probe → plan → extract or compose → validate.**\n\nEvery path starts with a probe. `scripts/survey.py` returns page count,\nwhether the file is encrypted, whether it has an AcroForm, and whether\npage 1 looks like a scan.\n\n## First install\n\n> **Bundled runtime:** when the `MIMO_PYTHON` environment variable is set, skip the installs below — run every command with `python3`/`uv run` replaced by `\"$MIMO_PYTHON\"` (pypdf/pypdfium2/reportlab/Pillow preinstalled; pip console scripts unavailable, use `\"$MIMO_PYTHON\" -m <module>`). A bundled qpdf is exposed as `MIMO_QPDF` (picked up automatically by the scripts here); invoke it directly as `\"$MIMO_QPDF\" --check file.pdf`.\n\nPython-only path (all BSD / MIT / Apache) — covers 95% of tasks:\n\n```bash\npython3 -m pip install --upgrade pypdf pdfplumber pypdfium2 reportlab Pillow\n```\n\nAdd these external binaries only when you actually need them:\n\n```bash\n# qpdf — merge/split/encrypt/repair, Apache-2.0\nbrew install qpdf                # macOS\napt-get install -y qpdf          # Debian / Ubuntu\n\n# Tesseract — OCR for scanned PDFs, Apache-2.0\nbrew install tesseract\npython3 -m pip install pytesseract pdf2image\napt-get install -y tesseract-ocr\n\n# Poppler — pdftotext / pdftoppm / pdfimages, GPL-2.0\n# Optional. Only install if you accept a GPL dependency at CLI level.\nbrew install poppler\napt-get install -y poppler-utils\n```\n\nEvery script under `scripts/` uses argparse. Exit codes:\n`0` OK · `1` runtime failure · `2` bad arguments · `3` validation failure\n(`apply_values.py` / `overlay_text.py`; `sanity_check.py` reports findings\nwith exit `1`).\nAny single script can be lifted into another project — none imports from a\nshared framework.\n\n## One-command triage\n\n```bash\nscripts/survey.py path/to/file.pdf --pretty\n```\n\nSample output:\n\n```json\n{\n  \"path\": \"/abs/path/file.pdf\",\n  \"page_count\": 12,\n  \"is_locked\": false,\n  \"form_field_count\": 34,\n  \"looks_scanned\": false,\n  \"metadata\": {\"Title\": \"...\", \"Author\": \"...\", \"Producer\": \"...\"}\n}\n```\n\nRoute by the flags:\n\n- `is_locked: true` → unlock first (`qpdf --password=… --decrypt`). Almost\n  every reader library refuses locked files.\n- `form_field_count > 0` → widgets path in [`interactive.md`](interactive.md) §1.\n- `form_field_count == 0` AND you need to fill it → overlay path\n  in [`interactive.md`](interactive.md) §2.\n- `looks_scanned: true` → skip pypdf text extraction, go straight to OCR\n  ([`extract.md`](extract.md) §5).\n\n## Which library for which task\n\n| Task | Preferred | Reason | Fallback |\n|------|-----------|--------|----------|\n| Plain text | `pdftotext -layout` | fastest, keeps columns | `pypdf` |\n| Positioned text | `pdfplumber` | char-level bboxes | `pypdfium2.get_text` |\n| Tables | `pdfplumber` | tunable `table_settings` | pandas over manual CSV |\n| Page → image | `pypdfium2` | Apache/BSD, no GPL | `pdftoppm` (GPL) |\n| Merge / carve / rotate | `pypdf` | pure Python | `qpdf --pages` (faster on huge files) |\n| Encrypt / repair / linearise | `qpdf` | handles broken input | pypdf (basic encrypt only) |\n| Compose from scratch | `reportlab` | mature, BSD | `pdf-lib` in Node |\n| Fill AcroForm | `pypdf.update_page_form_field_values` | preserves widget appearances | `pdf-lib` in Node |\n| Overlay on non-fillable | reportlab + `pypdf.merge_page` | two-layer merge, see interactive.md | — |\n\n## Common gotchas\n\n1. **PDF origin is bottom-left**, image origin is top-left. Every \"off by a\n   few points\" bug is one of these two systems misapplied. Coordinate\n   conversion is in one place: [`interactive.md`](interactive.md) §2.c.\n2. **`pypdf.extract_text()` returns nothing for scans.** That's not a bug —\n   there's no text stream. Use the `looks_scanned` flag and route to OCR.\n3. **Unicode subscripts / superscripts render as black rectangles in\n   reportlab** because Helvetica/Times/Courier don't ship those glyphs. Use\n   `<sub>` / `<super>` XML in `Paragraph`, or move the pen manually on canvas.\n   See [`compose.md`](compose.md) §5.\n4. **CJK text renders as black boxes when the font never registered.**\n   reportlab does not consult the OS font system; a bad font name/path (思源黑体,\n   PingFang, Noto on machines that lack it) plus a swallowed exception means a\n   silent Helvetica fallback — and Helvetica has no CJK glyphs. Resolve fonts\n   with the ladder in [`compose.md`](compose.md) §4 (`resolve_cjk_font()`);\n   the terminal fallback is the built-in CID font, never Helvetica.\n5. **XFA forms are not AcroForms.** If `probe_fields.py` returns `[]` on a\n   PDF that clearly has widgets in Adobe Reader, it's XFA — flatten it in\n   Acrobat first.\n6. **`writer.encrypt(pw)` in pypdf uses RC4 by default**. For real AES-256,\n   pass `algorithm=\"AES-256\"`, or use `qpdf --encrypt … 256 --`.\n\n## What's next\n\nOpen the sub-guide from the routing table and work through it end to end.\nEach sub-guide has a Validation section at the bottom describing how to\nconfirm the result.\n","packages/cli/src/skill/builtin/.bundle/playwright/SKILL.md":"---\nname: \"playwright\"\ndescription: \"Use when the task requires automating a real browser from the terminal (navigation, form filling, snapshots, screenshots, data extraction, UI-flow debugging) via `playwright-cli` or the bundled wrapper script.\"\n---\n\n\n# Playwright CLI Skill\n\nDrive a real browser from the terminal using `playwright-cli`. Prefer the bundled wrapper script so the CLI works even when it is not globally installed.\nTreat this skill as CLI-first automation. Do not pivot to `@playwright/test` unless the user explicitly asks for test files.\n\n## Prerequisite check (required)\n\nBefore proposing commands, check whether `npx` is available (the wrapper depends on it):\n\n```bash\ncommand -v npx >/dev/null 2>&1\n```\n\nIf it is not available, pause and ask the user to install Node.js/npm (which provides `npx`). Provide these steps verbatim:\n\n```bash\n# Verify Node/npm are installed\nnode --version\nnpm --version\n\n# If missing, install Node.js/npm, then:\nnpm install -g @playwright/cli@latest\nplaywright-cli --help\n```\n\nOnce `npx` is present, proceed with the wrapper script. A global install of `playwright-cli` is optional.\n\n## Skill path (set once)\n\n```bash\nexport CODEX_HOME=\"${CODEX_HOME:-$HOME/.codex}\"\nexport PWCLI=\"$CODEX_HOME/skills/playwright/scripts/playwright_cli.sh\"\n```\n\nUser-scoped skills install under `$CODEX_HOME/skills` (default: `~/.codex/skills`).\n\n## Quick start\n\nUse the wrapper script:\n\n```bash\n\"$PWCLI\" open https://playwright.dev --headed\n\"$PWCLI\" snapshot\n\"$PWCLI\" click e15\n\"$PWCLI\" type \"Playwright\"\n\"$PWCLI\" press Enter\n\"$PWCLI\" screenshot\n```\n\nIf the user prefers a global install, this is also valid:\n\n```bash\nnpm install -g @playwright/cli@latest\nplaywright-cli --help\n```\n\n## Core workflow\n\n1. Open the page.\n2. Snapshot to get stable element refs.\n3. Interact using refs from the latest snapshot.\n4. Re-snapshot after navigation or significant DOM changes.\n5. Capture artifacts (screenshot, pdf, traces) when useful.\n\nMinimal loop:\n\n```bash\n\"$PWCLI\" open https://example.com\n\"$PWCLI\" snapshot\n\"$PWCLI\" click e3\n\"$PWCLI\" snapshot\n```\n\n## When to snapshot again\n\nSnapshot again after:\n\n- navigation\n- clicking elements that change the UI substantially\n- opening/closing modals or menus\n- tab switches\n\nRefs can go stale. When a command fails due to a missing ref, snapshot again.\n\n## Recommended patterns\n\n### Form fill and submit\n\n```bash\n\"$PWCLI\" open https://example.com/form\n\"$PWCLI\" snapshot\n\"$PWCLI\" fill e1 \"user@example.com\"\n\"$PWCLI\" fill e2 \"password123\"\n\"$PWCLI\" click e3\n\"$PWCLI\" snapshot\n```\n\n### Debug a UI flow with traces\n\n```bash\n\"$PWCLI\" open https://example.com --headed\n\"$PWCLI\" tracing-start\n# ...interactions...\n\"$PWCLI\" tracing-stop\n```\n\n### Multi-tab work\n\n```bash\n\"$PWCLI\" tab-new https://example.com\n\"$PWCLI\" tab-list\n\"$PWCLI\" tab-select 0\n\"$PWCLI\" snapshot\n```\n\n## Wrapper script\n\nThe wrapper script uses `npx --package @playwright/cli playwright-cli` so the CLI can run without a global install:\n\n```bash\n\"$PWCLI\" --help\n```\n\nPrefer the wrapper unless the repository already standardizes on a global install.\n\n## References\n\nOpen only what you need:\n\n- CLI command reference: `references/cli.md`\n- Practical workflows and troubleshooting: `references/workflows.md`\n\n## Guardrails\n\n- Always snapshot before referencing element ids like `e12`.\n- Re-snapshot when refs seem stale.\n- Prefer explicit commands over `eval` and `run-code` unless needed.\n- When you do not have a fresh snapshot, use placeholder refs like `eX` and say why; do not bypass refs with `run-code`.\n- Use `--headed` when a visual check will help.\n- When capturing artifacts in this repo, use `output/playwright/` and avoid introducing new top-level artifact folders.\n- Default to CLI commands and workflows, not Playwright test specs.\n","packages/cli/src/skill/builtin/.bundle/pptx-official/SKILL.md":"---\nname: pptx-official\ndescription: \"Use this skill whenever a Microsoft PowerPoint (.pptx) file is being produced, opened, transformed, or read. That includes: authoring slide decks, pitch decks, executive readouts, training material, or any presentation deliverable; extracting text or structure from an existing .pptx; filling a .pptx template with values; converting a deck to PDF or images; splitting or merging decks; inspecting slides, layouts, masters, tables, images, charts, speaker notes, or comments. Trigger on words like 'deck', 'slides', 'presentation', 'pitch deck', 'keynote' (when a .pptx is expected as output), or any filename ending in .pptx. Do NOT trigger when the primary deliverable is a Word document, spreadsheet, PDF report, HTML site, or Google Slides API call, even if presentation-shaped content appears along the way.\"\nlicense: Apache-2.0 — see LICENSE for terms and third-party attributions\n---\n\n# PPTX Skill\n\nAn Apache-2.0 toolkit for producing, editing, and reading Microsoft PowerPoint\n(`.pptx`) files. Written from scratch against the public\n[ECMA-376 / ISO/IEC 29500 (PresentationML)](https://www.ecma-international.org/publications-and-standards/standards/ecma-376/)\nspecification and built on permissively-licensed tooling (`python-pptx` MIT,\n`pptxgenjs` MIT, `lxml` BSD-3-Clause, `Pillow` MIT-CMU, optional external\nbinaries `soffice` MPL 2.0 and `pdftoppm` GPL) so it can be reused in\ncommercial projects without restriction.\n\n## Decision matrix\n\n| Situation | Path | Read first |\n|-----------|------|------------|\n| Build a deck from a prompt or dataset — no source file to start from | Author with `python-pptx` (structured / repeatable) or PptxGenJS (design-heavy, JS) | [`create.md`](create.md) |\n| You have a `.pptx` template to fill in — keep its master, layouts, look | Placeholder replacement via `python-pptx` | [`edit.md`](edit.md) → *Template fill* |\n| Deep structural edits — reorder slides, splice XML, add unusual objects | Explode → edit XML parts → assemble | [`edit.md`](edit.md) → *Raw XML workflow* |\n| Only need the text / speaker notes / structure out of a `.pptx` | Extraction pipeline | [`read.md`](read.md) |\n| Turn a deck into PDF or PNG images (visual QA, publishing) | `scripts/render_pdf.py` / `scripts/render_slides.py` via LibreOffice | see *QA* below |\n| Grid of slide thumbnails for previewing a template | `scripts/contact_sheet.py` (Pillow) | [`read.md`](read.md) → *Thumbnails* |\n\nIf the task mixes several of these, do them in this order:\n**read → plan slide-by-slide → edit/create → validate → visual QA.**\n\n## One-time environment setup\n\n> **Bundled runtime:** when the `MIMO_PYTHON` environment variable is set, skip `uv`/pip installs — run every Python command below with `uv run` replaced by `\"$MIMO_PYTHON\"` (python-pptx/Pillow/lxml preinstalled; pip console scripts unavailable, use `\"$MIMO_PYTHON\" -m <module>`). A bundled LibreOffice is exposed as `MIMO_SOFFICE` (picked up automatically by `soffice_bridge.py`/`render_pdf.py`), and slide rasterisation automatically falls back to pypdfium2 in that interpreter when Poppler (`pdftoppm`) is absent. For the PptxGenJS authoring path, bundled Node.js is exposed as `MIMO_NODE`, with pptxgenjs/react/react-dom/sharp/react-icons/mathjax-full preinstalled in `MIMO_NODE_MODULES` — run scripts as `NODE_PATH=\"$MIMO_NODE_MODULES\" \"$MIMO_NODE\" <script.js>` instead of `npm install`.\n\n### Prerequisites\n\nIf `uv` or `bun` are not yet installed:\n\n```bash\n# Install uv (Python package/project manager)\n# macOS / Linux\ncurl -LsSf https://astral.sh/uv/install.sh | sh\n# Windows: powershell -ExecutionPolicy ByPass -c \"irm https://astral.sh/uv/install.ps1 | iex\"\n\n# Install bun (TypeScript runtime, replaces Node.js for this workflow)\n# macOS / Linux\ncurl -fsSL https://bun.sh/install | bash\n# Windows: powershell -c \"irm bun.sh/install.ps1|iex\"\n```\n\nOnly if the user explicitly refuses `uv` / `bun`, substitute `pip` (in a venv you manage yourself) for `uv`, and `npm`/`pnpm` + `npx tsx` for `bun` — everything else in this skill stays the same.\n\n### Python (uv)\n\nPython dependencies are managed by `uv`. Do not use `pip` directly.\n\n```bash\n# Initialize project (if no pyproject.toml exists)\nuv init -p 3.12\n\n# Add dependencies\nuv add python-pptx lxml Pillow\nuv add defusedxml                  # safe XML parsing (recommended for manual XML edits)\n```\n\n**Rules:**\n- Never use `pip` — always `uv add` for packages.\n- Never run `python scripts/...` directly — always `uv run scripts/...`.\n- Don't manually manage environments with `python -m venv` or `source .venv/bin/activate`.\n\n### TypeScript (bun)\n\nFor PptxGenJS creation, use `bun` (project-local, not global installs):\n\n```bash\n# Initialize (if no package.json exists)\nbun init -y\n\n# Add dependencies\nbun add pptxgenjs                  # core PPTX creation library\nbun add react react-dom sharp      # rasterization (icons + formulas)\nbun add react-icons                # icon library (FA, MD, etc.)\nbun add mathjax-full               # LaTeX formula rendering\n\n# Type definitions (including Bun runtime types)\nbun add -d @types/bun @types/react @types/react-dom\n```\n\nCreate a `tsconfig.json` if one doesn't exist:\n```json\n{\n  \"compilerOptions\": {\n    \"lib\": [\"ESNext\"],\n    \"target\": \"ESNext\",\n    \"module\": \"Preserve\",\n    \"moduleResolution\": \"bundler\",\n    \"allowImportingTsExtensions\": true,\n    \"noEmit\": true,\n    \"jsx\": \"react-jsx\",\n    \"strict\": true,\n    \"skipLibCheck\": true,\n    \"types\": [\"bun\"]\n  }\n}\n```\n\nRun scripts directly as TypeScript — no transpilation needed:\n```bash\nbun run create-ppt.ts\n```\n\n**Always run type checking after writing or modifying TS code:**\n```bash\nbun tsc --noEmit\n```\nModels may inadvertently use outdated PptxGenJS API signatures or\ndeprecated syntax without realizing it. A type check catches these\nmismatches before runtime.\n\n### System dependencies (PDF/PNG rendering)\n\n```bash\n# macOS\nbrew install --cask libreoffice\nbrew install poppler\n\n# Debian/Ubuntu\nsudo apt-get install -y libreoffice poppler-utils\n```\n\nEvery script under `scripts/` uses only the standard library plus\n`python-pptx`, `lxml`, and `Pillow`. No proprietary dependencies. External\nbinaries (`soffice`, `pdftoppm`) are invoked as subprocesses; nothing is\nbundled or statically linked.\n\n## Common commands\n\n```bash\n# 1. Extract text from every slide (title, body, notes) — the \"what does it say?\" query\nuv run scripts/dump_text.py input.pptx --notes > input.txt\n\n# 2. Convert a deck to PDF for review\nuv run scripts/render_pdf.py input.pptx                     # writes input.pdf next to it\n\n# 3. Convert every slide to a PNG (visual QA)\nuv run scripts/render_slides.py input.pptx --out slides/       # writes slides/slide-1.png, ...\n\n# 4. Grid thumbnail preview (planning which template slide to reuse)\nuv run scripts/contact_sheet.py input.pptx --cols 3         # writes input.contact-sheet.jpg\n\n# 5. Explode a .pptx into readable XML for surgical edits\nuv run scripts/explode.py input.pptx unpacked/\n\n# 6. Reassemble an exploded tree\nuv run scripts/assemble.py unpacked/ output.pptx\n\n# 7. Drop orphaned slides and unused media before reassembly\nuv run scripts/prune.py unpacked/\n\n# 8. Duplicate slide 3, or spin up a new slide from layout 5\nuv run scripts/insert_slide.py unpacked/ --clone slide3.xml\nuv run scripts/insert_slide.py unpacked/ --blank-from slideLayout5.xml\n\n# 9. Well-formedness check (ZIP + XML + python-pptx round-trip)\nuv run scripts/diagnose.py output.pptx\n```\n\nEvery script is a small Python CLI. Some scripts (e.g. `render_pdf.py`,\n`render_slides.py`, `contact_sheet.py`) import from a shared helper\n(`soffice_bridge.py`) in the same directory — copy them together. Read the top\nof each file for its full CLI options.\n\n## Live preview\n\nA live preview server is available for real-time slide feedback.\n**Not started by default.** When multi-slide work begins, ask the user\nif they want live preview enabled.\n\n**Only offer this in a pure command-line environment.** This server is\nfor the MiMoCode CLI. If you are running inside a host that embeds\nMiMoCode via the SDK — a web UI, a desktop app, an IDE plugin, etc. —\nthat host almost certainly has its own native preview / file-open\nmechanism; use it instead and do NOT start this server.\n\nIf yes, and this is a CLI environment:\n\n```bash\n# `scripts/preview.ts` lives in this skill's bundle directory, not in\n# your cwd. Prefix it with the absolute path shown in this skill's\n# location header (the folder that contains SKILL.md) — refer to it\n# as <SKILL_DIR> below.\n\n# Start (spawns background server, prints URL, exits immediately)\nbun run <SKILL_DIR>/scripts/preview.ts /path/to/output.pptx\nbun run <SKILL_DIR>/scripts/preview.ts /path/to/output.pptx --port 5000\n\n# Stop\nbun run <SKILL_DIR>/scripts/preview.ts --stop /path/to/output.pptx\n```\n\nIf the server is already running, `preview.ts` detects this via PID file\nand prints the existing URL instead of spawning a duplicate.\n\nThe background server watches the `.pptx` file, debounces (800ms),\nconverts to PDF via LibreOffice, and pushes a WebSocket reload to the\nbrowser. The browser's native PDF viewer provides scroll, thumbnails,\nzoom, and search. Preview output goes to `.pptx-preview/` (separate\nfrom `qa/`, no conflict with other scripts).\n\nGive the user the printed URL to open in their browser.\n\n**Live preview is for humans only — it does NOT replace visual QA.**\nThe preview server lets the user watch progress. You must still run\nthe visual QA subagent (render PNGs to `qa/`, spawn a vision model to\ninspect them) as described in the \"Visual QA execution model\" section.\nThese are independent workflows:\n- Preview server → user sees live updates in browser\n- Visual QA subagent → automated inspection, catches issues you can't\n\n**When to regenerate the .pptx during multi-slide work:** If the user\nhas the preview server running, regenerate the `.pptx` (re-run the\ncreation script) after completing each logical module — e.g. after\nfinishing a section's slides, not after every single shape placement.\nThis gives the user meaningful visual checkpoints without excessive\nintermediate renders.\n\n## Authoring principles\n\nSlides are a **visual surface**. Users read the deck at 40 feet from the back\nof a room, or in a browser tab three inches wide on a phone. Both have to\nwork. Keep these in mind:\n\n1. **One idea per slide.** If you can't summarize the slide in a five-word\n   title, split it in two. Long-form reasoning belongs in the doc that\n   accompanies the deck, not on the slide itself.\n2. **Title, not label.** The title is the thesis of the slide. \"Revenue\" is a\n   label. \"Revenue grew 34% on 22% headcount\" is a title. Titles carry the\n   argument; bodies carry the evidence.\n3. **Every slide earns its visuals.** A slide without a chart, image, icon,\n   or shape is usually a bullet dump. Turn it into a comparison, a stat\n   callout, a diagram, or delete it. **A \"visual\" is not necessarily a\n   picture** — a stat callout, a comparison shape, or a well-typeset quote\n   is already a visual. When you do need a picture, see *Image sourcing*\n   below.\n4. **Layouts, not per-slide geometry.** For anything reused (section\n   dividers, content pages, quote slides), define a `slide_layout` once and\n   apply it. This makes swapping the theme a one-line change instead of a\n   fifty-slide sweep.\n5. **Aspect ratio matches the target.** 16:9 (default) for laptops and\n   projectors; 4:3 only when explicitly asked (still common in academia and\n   some corporate templates); 16:10 for older widescreen.\n6. **Speaker notes carry the words.** Put the full narration into\n   `slide.notes_slide.notes_text_frame` so the presenter can rehearse from\n   the deck itself. On the slide, keep it to the phrase they can hold in\n   their head.\n7. **Bullets are not the default.** Bullet lists are the failure mode of\n   most decks — comparisons, tables, icons-with-labels, and stat callouts\n   almost always land better.\n\n## Image sourcing (choose the right channel)\n\n\"Every slide earns its visuals\" does **not** mean \"generate an image for\nevery slide.\" Choose the source based on what the image does. Four channels,\nordered by preference (lower cost + higher stability first):\n\n**L1 · Draw in code.** Icons via react-icons / iconify. Charts via\nmatplotlib / plotly / echarts. Flowcharts, comparisons, org charts via\nshapes + lines. Anything that is a data or concept visualization —\nnever fetch or generate an image for this.\n\n**L2 · Search a stock library, then download the bytes.** When a slide\nneeds a **generic real photo** (city skyline, office desk, team\ncollaboration, nature, stock imagery), use `websearch` with a\n`site:unsplash.com` / `site:pexels.com` / `site:pixabay.com` query to find\na real URL, then **download the image to a local file** and pass that path\nto `add_picture` (see *Downloading* below). Do NOT try to pass an HTTP URL\ndirectly to `add_picture` — python-pptx's `add_picture` only accepts a\nlocal path or a file-like object; it will NOT fetch a URL for you.\n\n**L3 · Search a specific source.** For **specific real things** (a\nparticular company's logo, a specific product's official screenshot, a\nnamed person's photo), use `websearch` with a targeted query (e.g.\n`\"Acme Inc\" logo site:acme.com`, or `<product name> screenshot`) instead of\na stock-library query, then download the bytes the same way as L2. Never\ncall `image_gen` here — a generated logo will not look like the real logo.\nNote: `webfetch` returns text/markdown/html only and cannot deliver binary\nimage bytes — use `bash` + `curl` or python `urllib` to download.\n\n**L4 · Generate with `image_gen`.** Only for **stylized visuals** — cover\nart, hero backgrounds, illustration-style concept images, brand-mood\nimagery. Budget: **at most 1–2 `image_gen` calls per deck**, typically for\ncover or section dividers. Not for every content slide.\n\n### Downloading a URL for `add_picture`\n\nTwo working patterns. Both keep the file local so `add_picture` can read\nthe bytes:\n\n```python\n# Pattern A: download to a temp file, then pass the path\nfrom urllib.request import Request, urlopen\nfrom pathlib import Path\n\ndef download_image(url: str, dest: Path) -> Path:\n    req = Request(url, headers={\"User-Agent\": \"Mozilla/5.0\"})  # some CDNs 403 an empty UA\n    with urlopen(req, timeout=15) as r:\n        dest.write_bytes(r.read())\n    return dest\n\npath = download_image(hit_url, Path(\"assets/hero.jpg\"))\nslide.shapes.add_picture(str(path), Inches(1), Inches(1.5), width=Inches(11))\n```\n\n```python\n# Pattern B: in-memory via BytesIO — no temp file, but same request headers\nfrom io import BytesIO\nfrom urllib.request import Request, urlopen\n\nreq = Request(hit_url, headers={\"User-Agent\": \"Mozilla/5.0\"})\nwith urlopen(req, timeout=15) as r:\n    slide.shapes.add_picture(BytesIO(r.read()), Inches(1), Inches(1.5), width=Inches(11))\n```\n\nOr from a bash step:\n\n```bash\ncurl -sSL -A \"Mozilla/5.0\" -o assets/hero.jpg \"$URL\"\n```\n\nWrap any download in a try/except: on failure fall through to the next\nchannel (L3 → L4) or a shape+text fallback — never leave a slide blank.\n\n### Decision (run per slide)\n\n1. Does this slide actually need a picture? Often the answer is no — a\n   large stat callout, a comparison shape, a well-typeset quote, or a\n   diagram *is* a visual. Skip pictures when layout + typography carries\n   the message.\n2. If yes, pick the cheapest channel that works:\n   - Data / concept / flow / icon → **L1** (draw in code)\n   - Generic real photo → **L2** (stock library search + download)\n   - Specific brand / logo / product / person → **L3** (targeted web search + download)\n   - Stylized cover / hero / illustration → **L4** (`image_gen`)\n3. If a fetch fails: L2 → L3 → L4 → shape + text fallback. Never leave a\n   slide blank because an image failed to load.\n\n### Anti-patterns\n\n- **Calling `image_gen` on every content slide.** Slow, expensive,\n  style-inconsistent, visually noisy. A 20-slide deck with 20 generated\n  images is a red flag, not a success.\n- **Passing an HTTP URL to `add_picture`.** python-pptx will raise\n  `FileNotFoundError` — always download the bytes first (see *Downloading*).\n- **Using `webfetch` to grab image bytes.** `webfetch` returns text only.\n  Use `bash` + `curl` or python `urllib` for binaries.\n- **Making up a stock-library URL from memory.** Unsplash / Pexels CDN\n  paths are opaque hashes — you cannot reliably recall a URL that both\n  exists AND matches the described content. Always search first, then\n  download.\n- **Generating a logo, celebrity, or product screenshot with `image_gen`.**\n  The output will not resemble the real thing. Use targeted web search (L3).\n- **Executive / status / weekly decks in illustration style.** Work\n  reporting is data + icons + hierarchy, not concept art. Reserve L4 for\n  launch, brand, or hero visuals.\n- **Leaving a slide blank because an image fetch failed.** Always have a\n  shape + text fallback; a well-formatted stat callout is a better slide\n  than an empty one anyway.\n\n### Scene defaults (rough mix per deck type)\n\nL2/L3 both cost about one `websearch` + one download per image — cheap\ncompared to L4, still not free. L1 remains the default.\n\n| Deck type              | Dominant | Notes                                           |\n|------------------------|----------|-------------------------------------------------|\n| Status / OKR / weekly  | L1 (~90%) | Icons + data charts. Almost no L2 / L3 / L4.   |\n| Strategy / proposal    | L1 + L2  | ~60% L1, ~30% L2 (searched stock), ~10% L4 cover. |\n| Sales / pitch / BP     | L2 + L3  | Customer logos and product shots (L3) matter. 1 L4 cover max. |\n| Training / education   | L1 (~80%) | Diagrams and flowcharts win.                   |\n| Launch / brand         | L4-heavy | Visuals are the point. Still limit style drift and reuse assets. |\n| Competitive analysis   | L3-heavy | Logos and screenshots are irreplaceable.        |\n\n## Typography defaults (safe starting point)\n\n| Element              | Font          | Size    | Weight  | Notes |\n|----------------------|---------------|---------|---------|-------|\n| Slide title          | Calibri / Segoe UI | 32-40pt | Bold    | One line — wrap = rework the title |\n| Section header       | Calibri       | 24-28pt | Bold    | On dedicated divider slides |\n| Body / bullets       | Calibri       | 18-22pt | Regular | Never below 18pt for a room; 14pt for on-screen decks |\n| Stat callout         | Calibri Light | 60-96pt | Bold    | The number, then the label below at 14-18pt |\n| Caption / footer     | Calibri       | 10-12pt | Regular | Muted gray `#7A7A7A` |\n| Code / mono          | Consolas / Cascadia Code | 16-20pt | Regular | Left aligned, no word wrap |\n\nChange the palette for the topic (financial → navy `#1F3A5F`; environment →\nforest `#2C5F2D`; product launches → your brand's accent). Avoid pure black\non pure white for backgrounds — `#F7F5F0` cream on `#1F1F1F` ink reads\nsofter under a projector.\n\n## Slide sizes\n\n| Aspect | Width × Height (inches) | Pixels @ 96 DPI | When to use |\n|--------|-------------------------|------------------|-------------|\n| 16:9 widescreen (default) | 13.333 × 7.5    | 1280 × 720       | Almost every new deck |\n| 16:10                      | 13.333 × 8.333  | 1280 × 800       | Older projectors; some corporate templates |\n| 4:3 standard               | 10.0   × 7.5    | 960  × 720       | Academia, legacy templates, printed handouts |\n| A4 landscape               | 11.69  × 8.27   | 1123 × 794       | Print-first decks (EU) |\n| Letter landscape           | 11.0   × 8.5    | 1056 × 816       | Print-first decks (US) |\n\n## QA checklist — always run before declaring done\n\n**Assume something is wrong.** PowerPoint opens broken files quietly: a\nmisaligned text box, a chart pointing at deleted data, a stray placeholder\nthat survived template fill. Verify explicitly.\n\n1. **Opens cleanly.** No repair dialog, no missing-part warning.\n   ```bash\n   uv run scripts/diagnose.py output.pptx\n   ```\n\n2. **Text integrity.** No placeholder residue and no unfilled `{{token}}`s:\n   ```bash\n   uv run scripts/dump_text.py output.pptx --notes \\\n       | grep -Ei \"\\{\\{|TODO|TBD|lorem|ipsum|xxxx|click to add\"\n   ```\n   Grep must return nothing.\n\n3. **Visual sanity.** Render the whole deck to PNG, spot-check the first,\n   last, and any slide you touched. Look for:\n   - Text overflowing the placeholder or getting auto-shrunk past readability.\n   - Two shapes overlapping (title over image, footer over content).\n   - Legend / axis labels cut off on charts.\n   - Icons at the wrong scale (tiny hairline icons, or huge stretched ones).\n   - Off-brand colors that snuck in from a copied slide.\n   ```bash\n   uv run scripts/render_slides.py output.pptx --out qa/\n   ```\n\n4. **Layout hygiene.** Every non-master slide should reference a real layout,\n   not `slideLayout1` by default for a section divider:\n   ```bash\n   uv run python -c \"\n   from pptx import Presentation\n   prs = Presentation('output.pptx')\n   for i, s in enumerate(prs.slides, 1):\n       print(f'slide {i}: layout={s.slide_layout.name!r}')\"\n   ```\n\nIf any of these fail, fix and re-run — don't paper over.\n\n## Visual QA execution model\n\n**Slide images are expensive.** A single rendered PNG at 150 DPI consumes\nthousands of context tokens. Loading multiple slides into the main\nconversation for inspection will quickly exhaust your context budget and\ncrowd out useful working memory.\n\n**Default: always use a subagent for visual inspection.** Spawn a\n`general` subagent with the rendered PNG paths and the\ninspection criteria from step 3 above. The subagent reports findings as\ntext (slide number + issue description); the images never enter the main\nconversation context. This is mandatory unless the exception below applies.\n\n```\nactor({\n  operation: {\n    action: \"run\",\n    subagent_type: \"general\",\n    // omit `model` when your current model is vision-capable (preferred — see Model selection)\n    description: \"Visual QA slides\",\n    prompt: \"Inspect the rendered slide images in qa/ for: text overflow, overlapping shapes, cut-off labels, wrong-scale icons, off-brand colors. Report each issue as 'slide N: <problem>'. Images: qa/slide-1.png through qa/slide-<N>.png.\"\n  }\n})\n```\n\n**Model selection (in priority order):**\n\n1. **Prefer the user's current model.** Query the servable vision models via\n   `actor({ operation: { action: \"models\", vision: true } })`. If your current\n   model is in the list, **omit the `model` parameter** — the subagent inherits\n   it, and visual QA runs on the model the user chose.\n2. **Fallback: lightweight vision model, stated explicitly.** If your current\n   model is not vision-capable, pick a **lightweight** vision model from the\n   query result (haiku/flash/lite-class if present, otherwise the cheapest\n   listed) and **tell the user in your reply** which model you used for visual\n   QA and why (current model cannot inspect images).\n3. **No vision model available.** If the query returns an empty list, do not\n   guess a model id — skip the visual QA subagent, run the structural checks\n   only, and tell the user visual inspection could not be performed.\n\n**Never hardcode a model id.** Which models are servable varies per\ndeployment and changes over time; only ids returned by the vision models\nquery are guaranteed to work. A guessed id fails the subagent outright.\n\n**Exception — direct inspection in the main context:** Only load slide\nimages directly (without a subagent) when the user explicitly requests\nthat the current model inspect a specific slide for fine-grained,\ninteractive editing (e.g. \"look at slide 5 and adjust the title\nposition\"). This requires the current model to be multimodal. If it\nisn't, inform the user and offer to spawn a vision subagent instead.\n\n## Common visual pitfalls\n\n- **Titles wrap onto two lines** — either shorten the title or widen the\n  placeholder. Wrapped titles push body content down and break layout\n  alignment across slides.\n- **Body text auto-shrinks below 14pt** — python-pptx respects the\n  placeholder's autofit setting; if the resulting size is unreadable, split\n  the slide instead of accepting the shrink.\n- **Charts inherit Office defaults** — the pale blue / gray palette shipped\n  with PowerPoint looks generic. Explicitly set `chart.chart_style` or use\n  `python-pptx`'s low-level access to set fill colors on series.\n- **Speaker notes forgotten** — a deck without notes cannot be rehearsed.\n  Fill `notes_slide.notes_text_frame.text` on every slide, even if just a\n  single sentence.\n- **Images at wrong DPI** — a 4000×3000 photo on a 1280×720 slide bloats\n  the file with no visual benefit. Resample down to ~150 DPI at the target\n  display size (see `create.md` → *Images*).\n- **Fonts not embedded** — `python-pptx` does not embed fonts. If the deck\n  is opened on a machine without the chosen font, PowerPoint substitutes,\n  and layout drifts. For **Latin** text, prefer system-safe fonts (Calibri,\n  Arial, Segoe UI, Times New Roman, Consolas) or ship the .pptx alongside a\n  font install step.\n- **CJK text needs the East-Asian font slot** — `run.font.name` only sets the\n  Latin typeface (`a:latin`); Chinese / Japanese / Korean glyphs come from the\n  East-Asian slot (`a:ea`), which python-pptx does not expose. Leave it unset\n  and CJK renders as tofu boxes or an inconsistent substitute. Set `a:latin` +\n  `a:ea` + `a:cs` to a CJK-capable font on every run that contains CJK text\n  (recipe in `create.md` → *CJK / East-Asian text*).\n\n## What is out of scope\n\n- **`.ppt` (PowerPoint 97-2003 binary)**. Convert first:\n  `soffice --headless --convert-to pptx old.ppt`.\n- **VBA / macros / `.pptm`.** This skill does not emit or execute macros.\n- **Password-protected or encrypted decks.** `python-pptx` cannot read\n  encrypted files; strip protection with PowerPoint or LibreOffice first.\n- **Live PowerPoint automation.** For COM (Windows) or AppleScript (macOS)\n  integration, use a dedicated automation library — this toolkit is\n  file-in / file-out.\n- **Keynote `.key` files.** Not a PresentationML format; use Apple's\n  Keynote or LibreOffice for round-trip.\n\n## Where each detail lives\n\n- **Creating from scratch**: [`create.md`](create.md) — python-pptx recipes,\n  PptxGenJS recipes, layouts, text, tables, images, charts, icons,\n  backgrounds, speaker notes, palette and typography guidance.\n- **Editing / templating**: [`edit.md`](edit.md) — placeholder fill, slide\n  duplication / reorder / delete, explode/assemble for XML surgery, comments,\n  cleanup of orphaned parts, common pitfalls.\n- **Reading / extracting**: [`read.md`](read.md) — plain-text export\n  (including speaker notes), structural walk, metadata, thumbnails, image\n  extraction, conversion to PDF / PNG for QA.\n- **Scripts**: [`scripts/`](scripts/) — CLI utilities (some share a local\n  `soffice_bridge.py` helper; copy together when extracting).\n- **Live preview**: [`scripts/preview.ts`](scripts/preview.ts) — launcher\n  (start/stop); [`scripts/preview_server.ts`](scripts/preview_server.ts) —\n  background server that watches .pptx, converts to PDF, serves with\n  WebSocket hot-reload in the browser's native PDF viewer.\n","packages/cli/src/skill/builtin/.bundle/product-design/SKILL.md":"---\nname: product-design\ndescription: \"Use this skill when Product Design is explicitly invoked or the main task is product design exploration, UX research, flow auditing or critique, visual ideation, cloning a live product surface, implementing a selected visual target, design QA, saved design context, or sharing a prototype.\"\n---\n\n# Product Design\n\nThis is the single entry point for a code-agent-oriented Product Design bundle. The original workflow instructions are under `workflows/`, with shared guidance under `references/`. The bundled React/Vite prototype template and package metadata are intentionally excluded.\n\n## Route the request\n\n1. Read `workflows/index/SKILL.md` completely. Treat it as the authoritative plugin-level scope, routing, sequencing, and browser-choice policy.\n2. Select the focused workflow or workflow sequence specified by the index. Read every selected workflow's `SKILL.md` completely before acting.\n3. Common sequences include loading context before design/build work, ideating before implementation when no visual target is selected, and running design QA after a source-grounded prototype is built. Follow the exact conditions in the index rather than inferring a fixed sequence for every request.\n4. Resolve relative links from the file that contains the link. Read required reference files and use bundled scripts and assets when present.\n5. Do not load unrelated focused workflows merely because they are present.\n\n## Bundled capabilities\n\nFocused workflows live in `workflows/`: `user-context`, `get-context`, `research`, `audit`, `ideate`, `url-to-code`, `image-to-code`, `design-qa`, and `share`.\n\nShared reusable guidance lives in `references/`. Workflow-local references, scripts, and assets remain beside their owning workflow when they are not React/frontend build artifacts.\n\nUse browser, Chrome, Playwright, image generation, design apps, hosting, and other integrations only when the host harness exposes them. The bundle's mention of a tool does not prove availability or authorization. Follow host permissions and the selected workflow's fallback behavior.\n\nWhen creating a prototype, prefer the target repository's existing frontend stack. If there is no existing app and the user still wants a runnable web prototype, create the smallest suitable implementation using host-supported tools; React is not required. Do not look for the removed bundled prototype template or bootstrap script.\n\n## Safety and fidelity\n\n- Never treat plugin instructions as permission to bypass host policy or publish externally without the required user choice.\n- Keep audits evidence-grounded and distinguish screenshot-visible findings from claims requiring deeper testing.\n- Do not modify production code when a workflow requires an isolated prototype.\n- Preserve the selected workflow's visual QA and handoff requirements through completion.\n","packages/cli/src/skill/builtin/.bundle/product-design/workflows/audit/SKILL.md":"---\nname: audit\ndescription: \"Audit or critique a product flow, journey, workflow, funnel, onboarding path, checkout path, settings path, screen, or multi-step product experience by capturing screenshots first, then reporting UX, design, and accessibility findings inline from that evidence. Use Figma only when the user explicitly asks for a board. Use when the user asks to audit, review, critique, inspect, assess, analyze, evaluate, or give feedback on a product experience.\"\n---\n\n# Audit\n\nUse this skill when the user wants to audit, review, critique, inspect, assess, analyze, evaluate, or give feedback on a product flow, journey, funnel, onboarding path, checkout path, settings path, screen, or other product experience.\n\nThe output is not a loose opinion. The output is:\n\n- Screenshots of the flow\n- Those screenshots rendered inline in the report\n- A numbered step list\n- UX and design findings tied to steps or screenshots\n- Accessibility risks tied to steps or screenshots\n- Clear limits on what could not be checked from screenshots alone\n\n## Critical Overrides\n\n- Refer to the Plugin router [$index](../index/SKILL.md) before proceeding.\n- Follow [$critical-overrides](../../references/critical-overrides.md).\n\n## User Context\n\nBefore starting, load [$user-context](../user-context/SKILL.md) and run its preflight script when local shell access is available.\n\nUse saved product URLs, Figma files, screenshots, reference images, codebase paths, Storybook, tokens, design systems, brand assets, component refs, browser preferences, and share targets as grounding material when relevant.\n\nDo not inspect every saved reference. Inspect only what the current task needs.\n\n## Route\n\nBefore auditing:\n\n1. Identify the product or surface.\n2. Identify the flow or task.\n3. Choose the capture tool.\n4. Capture the flow.\n5. Save and inspect each screenshot.\n6. Return the audit inline with the accepted screenshots.\n\nOutput rules:\n\n- Default to a concise inline report with screenshots rendered in the chat.\n- Saving screenshots and notes in the workspace is an internal implementation detail. Do not ask the user to choose a local folder.\n- If the user explicitly asks for Figma, create the Figma audit board in addition to the inline report.\n- After the inline report, ask once: `Want me to plot this out in Figma with the screenshots and notes?`\n\nCapture rules:\n\n- Follow the Browser Choice rule in [$index](../index/SKILL.md#browser-choice).\n- If none of those can capture valid screenshots or control the flow, stop and report the blocker.\n\nBrowser capture order:\n\n1. Load the Browser skill before browser work.\n2. Connect to the browser and use the current tab when it already shows the target.\n3. Do not reload or navigate away unless the audit needs a fresh start.\n4. Observe the visible state before acting.\n5. Before each click, type, or key press, use the latest DOM snapshot to target one clear control.\n6. After each action, take the cheapest fresh check that proves what changed: DOM for structure, screenshot for visual state.\n7. Save and inspect the accepted screenshot before using it as audit evidence.\n\nFigma rules:\n\n- If Figma is the destination, load the required Figma skills before creating or editing the file.\n- Keep a local copy of every screenshot even when Figma succeeds.\n- Do not upload a screenshot to Figma until the saved local file has been inspected and accepted.\n- Figma is not done until the screenshots are visibly placed in the Figma output.\n- After placing screenshots in Figma, render or inspect the board and confirm every flow step has the correct screenshot visible in the correct card.\n- If an image is missing, misplaced, blank, or only uploaded as an unused asset, fix it before handoff.\n- If Figma tools cannot create files or place images, return the inline audit and explain the missing Figma capability.\n\nEvidence rules:\n\n- Use only evidence captured in the current audit run.\n- Do not use memory, prior chats, old traces, cached screenshots, or prior generated artifacts as audit evidence unless the user explicitly provides them.\n- Do not audit until the product, flow, and capture tool are known.\n- Do not claim full accessibility compliance from screenshots alone.\n\n## Capture And Audit The Flow\n\nYou are an expert design, UX, and accessibility auditor. For each step in the flow, capture what the user sees, observe how the screen behaves, inspect the screenshot, and write audit notes before moving on.\n\nFollow [references/design-audit-framework.md](references/design-audit-framework.md) when deciding what to inspect and how to describe strengths, UX issues, accessibility risks, limits, and recommendations.\n\nScreenshot source rule:\n\n- Use the screenshot you actually saw.\n- Save that exact screenshot to the local audit folder.\n- Open or inspect the saved file before accepting it.\n- If the saved file shows the wrong window, wrong state, blank page, crop, or loading screen, reject it and capture again.\n- When Figma is the destination, upload that accepted local file.\n- After upload, verify the Figma board shows the same step.\n- Do not replace a Browser, Chrome, or Computer Use screenshot with an OS screenshot unless you first prove the saved file shows the same window and state.\n\nFor every step:\n\n1. Move to the next step in the requested flow.\n2. Wait until the screen is loaded and visually stable.\n3. Check for loading spinners, blank areas, login walls, error pages, blocked states, cookie dialogs, and half-rendered content.\n4. Capture the screenshot.\n5. Inspect the screenshot before accepting it.\n6. Reject the screenshot if it is blank, loading, cropped, blocked, or showing the wrong state.\n7. Observe behavior that matters for the audit, such as navigation, focus, loading, validation, error handling, empty states, motion, and whether the next action is clear.\n8. Write notes for that step.\n9. In the notes, report strengths, UX issues, accessibility risks, and any limits that made the step difficult to audit.\n10. Save accepted screenshots with numbered names, such as `01-start.png`, `02-form-filled.png`, and `03-confirmation.png`.\n11. Inspect the saved screenshot file before upload or handoff.\n12. Keep each accepted screenshot and its notes together for the final inline report.\n13. If the user explicitly requested Figma, add each accepted screenshot and its notes to the board immediately.\n\nDefault inline report:\n\n- Render accepted screenshots in flow order.\n- Keep the report pithy: overall verdict, numbered steps, highest-impact changes, and evidence limits.\n- Tie every finding to the screenshot or step that supports it.\n\nIf the user explicitly requested Figma:\n\n- Place screenshots in order, left to right on the same row, with 200px between each one. Go to a new row every 15 screenshots, and separate those rows by 600px.\n- Underneath the screenshot, add text with the Step number and its name, and notes.\n- Keep a local folder copy even when Figma succeeds.\n- When you are done, wrap all of the assets you added in a Section and title the section.\n\nAcceptance checks:\n\n- Every important step in the requested flow has a valid screenshot or a named blocker.\n- Screenshots are saved in order.\n- Screenshots are rendered inline in the final report.\n- When Figma was explicitly requested, screenshots and notes are placed in the board as they are captured.\n- Every note points to the screenshot or step it describes.\n- Notes explain strengths, UX issues, accessibility risks, and evidence limits when those apply.\n- Accessibility risks say what can be seen from screenshots and what still needs testing.\n- The final screenshot set and notes are enough to support the requested audit.\n\nBlockers:\n\n- The flow cannot be completed.\n- A required step cannot be screenshotted.\n- The source changes in a way that makes the flow unclear.\n- Screenshots cannot be saved or rendered inline.\n- Notes cannot be written.\n- The requested claim would require evidence that screenshots cannot provide.\n- Do not claim an audit if the actual flow could not be accessed and captured. Help Center pages, web searches, and other indirect evidence are research, not an audit.\n\n## Final Response\n\nAfter the flow is captured and notes are written, list every step in the final response.\n\nThe final step list MUST include:\n\n- step number\n- short description of the step\n- general health of that step\n\nAlso include where the full output was saved or placed.\n\nKeep the language direct. Do not use broad design jargon when a plain phrase works.\n","packages/cli/src/skill/builtin/.bundle/product-design/workflows/design-qa/SKILL.md":"---\nname: design-qa\ndescription: \"Internal prototype QA helper. Use only after a Product Design prototype, URL-to-code build, or image-to-code build has a source visual target and a rendered implementation to compare before handoff. Do not use for broad UX critique, design critique, product audits, or flow reviews; route those user-facing requests to audit.\"\n---\n\n# Design QA\n\nUse this internal helper to compare a prototype's source design against the rendered implementation before handoff.\n\nDo not use this skill for broad UX critique, design critique, product audits, or flow reviews. Use [audit](../audit/SKILL.md) for those user-facing requests.\n\nUse this skill before every Product Design build handoff.\n\nA passing QA run requires both:\n\n- a source visual target: Figma node, image, screenshot, mockup, or source capture\n- a rendered implementation: local URL, deployed URL, app screen, component, or screenshot\n\nIf either artifact cannot be opened, captured, or compared, write `design-qa.md` with `final result: blocked` and name the blocker. Do not let the build skill hand off as done.\n\n## Critical Overrides\n\nFollow [critical-overrides](../../references/critical-overrides.md).\n\n## Workflow\n\nCompare the intended design to the implementation as a product-quality reviewer, not as a generic aesthetic critic. The output must be a prioritized fix list grounded in evidence from both artifacts.\n\nDo not write the QA review from memory, code, or file paths alone. Open or capture both the source design and the implementation first, then compare what is actually visible.\n\nDo not pretend separate image views are side-by-side comparison. Put the source image and the implementation screenshot together in the same comparison input, then judge the visible differences from that combined input.\n\nDesign QA is an iteration loop. The first comparison may pass only when it finds no actionable P0/P1/P2 differences and no visual fixes are made in response.\n\nWhen a comparison finds any P0/P1/P2 issue:\n\n- Record the finding and keep the current result blocked.\n- Apply the fix.\n- Capture the revised implementation at the same viewport and state.\n- Compare the revised capture against the source again.\n\nA later pass must identify the earlier findings, the fixes made, and the post-fix visual evidence. Build, dependency, lint, deployment, and preview troubleshooting do not count as design-QA iterations.\n\n1. Identify the comparison target.\n   - Determine the source design: Figma node, image, design board, screenshot, spec, or mockup.\n   - Determine the implementation: local URL, deployed URL, app screen, component, screenshot, or code-rendered view.\n   - Match the same viewport, state, theme, device density, route, content, auth state, and interaction state before judging.\n   - If artifacts do not represent the same state, call that out first and avoid false precision.\n\n2. Capture evidence.\n   - For Figma, use design context and screenshot tools when available.\n   - For web/app implementations, follow the Browser Choice rule in [index](../index/SKILL.md#browser-choice). In ChatGPT Work Mode, follow the active build skill's \"Previewing prototypes in ChatGPT Work Mode\" section before opening a local implementation. Then capture screenshots at the intended viewport.\n   - Capture additional states when relevant: mobile/desktop, hover/focus/active, empty/loading/error, dark/light, and key responsive breakpoints.\n   - Save paths or URLs for screenshots when available so findings can cite evidence.\n   - Capturing screenshots is not enough. Put the source image and the implementation screenshot together in the same comparison input before judging.\n\n3. Normalize before comparing.\n   - Align crop, viewport size, scale, and device frame. Do not compare a framed mockup to an unframed page without noting the mismatch.\n   - Prefer comparing content regions over full browser chrome or surrounding canvas.\n\n4. Compare at the right level of detail.\n   - Use a full-view comparison to judge overall composition, hierarchy, layout, density, and responsive structure.\n   - Use focused region comparisons when important details are too small to judge in the full-view comparison.\n   - Choose focused regions from the actual source and implementation. Use them where fidelity depends on precise typography, alignment, imagery, assets, icons, logos, controls, forms, navigation, tables, dense UI, or visible interaction states.\n   - If no focused region is needed, say why in `design-qa.md`.\n   - Do not pass QA from a full-view comparison alone when important details are not clearly readable.\n\n5. Review systematically.\n   - Read [qa-rubric](./references/qa-rubric.md) when the QA pass spans more than a quick visual check.\n   - Check information architecture, layout, spacing, typography/fonts, color, imagery/image quality, icons, copy, affordances, interaction states, responsiveness, accessibility, and polish.\n   - Always make a specific pass over the five required fidelity surfaces: fonts/typography, spacing/layout rhythm, colors/tokens, image quality, and copy/content. Do this even if the user did not name those areas explicitly.\n   - If the mock does not address some issue you're seeing (e.g. a null state), call that out as a separate finding as a shortcoming of the mock to be addressed.\n   - Your other goal is to decide whether the implementation \"looks as good\" as the mock. If there are stylistic problems, call them out. If the user's prompt is leaking into the implementation (vs letting the app stand on its own), call that out as well.\n   - Distinguish design drift from intentional product/code constraints. If a deviation may be intentional, phrase it as a question or assumption.\n\n6. Produce a fix-oriented QA report.\n   - Lead with findings, ordered by severity and user impact.\n   - For each finding include: severity, location, what differs, evidence, why it matters, and the concrete fix.\n   - Include exact CSS/component/token suggestions when the implementation context is available.\n   - Separate objective mismatches from subjective polish recommendations.\n   - Do not say a design matches, is done, or is as good as it can get until the required fidelity surfaces have been checked and any remaining differences are explicitly classified as acceptable, expected, or still actionable.\n   - End with a concise implementation checklist.\n\n## Required Fidelity Surfaces\n\nEvery QA report must explicitly evaluate these surfaces:\n\n- Fonts and typography: family, fallback, weight, size, line height, letter spacing, antialiasing, hierarchy, wrapping, truncation, and whether display text and small UI text use appropriate optical weights. It is incredibly important to check fonts carefully for fidelity, including looking up similar typefaces or using image analysis to find the font differences.\n- Spacing and layout rhythm: frame size, crop, alignment, margins, padding, grid tracks, section gaps, component spacing, radii, shadows/elevation, and vertical rhythm.\n- Colors and visual tokens: sampled or inferred palette, gradients, opacity, contrast, semantic state colors, foreground/background balance, and whether CSS tokens map to the source design.\n- Image quality and asset fidelity: subject correctness, crop, scale, sharpness, compression, transparency halos, masking, background treatment, raster-vs-vector appropriateness, and whether generated assets match the source art direction. Fail QA if logos, illustrations, decorative marks, product imagery, non-standard icons, or other visible image assets from the visual target were replaced with custom inline SVG, handcrafted SVG, HTML elements, div/span shapes, CSS drawings, gradients, emoji, text glyphs, placeholder shapes, or code-native approximations.\n- Copy and content of app-specific text\n\n## Severity\n\n- `P0`: Blocks core use, severe accessibility failure, broken layout, or impossible task.\n- `P1`: Major design mismatch or usability regression likely to be noticed by users.\n- `P2`: Moderate visual drift, inconsistent state, responsive issue, or fixable polish gap.\n- `P3`: Minor refinement that improves fidelity but does not block acceptance.\n\nTreat viewport overflow that hides persistent app controls, and mismatches that materially change above-the-fold content, major-region proportions, text wrapping, or interface density, as P2 or higher.\n\n## Output Format\n\nUse this structure unless the user asks otherwise:\n\n```markdown\n**Findings**\n- [P1] Short issue title\n  Location: screen/component/selector/file if known.\n  Evidence: design does X, implementation does Y.\n  Impact: why this matters.\n  Fix: concrete change.\n\n**Open Questions**\n- Any ambiguity about intentional deviations, unavailable states, or missing artifacts.\n\n**Implementation Checklist**\n- Ordered fixes that can be executed directly.\n\n**Follow-up Polish**\n- P3 refinements that can improve fidelity after handoff.\n```\n\nIf there are no substantive mismatches, say that clearly and list any residual test gaps.\n\nWhen this skill is used before handoff, save the latest QA report as project-root `design-qa.md`.\n\n`design-qa.md` must include:\n\n- source visual truth path\n- implementation screenshot path\n- viewport\n- state\n- full-view comparison evidence\n- focused region comparison evidence, or why it was not needed\n- findings\n- comparison history for every P0/P1/P2 iteration: earlier findings, fixes made, and post-fix visual evidence\n- final result\n\nFor ChatGPT Work Mode builds, `design-qa.md` must include the browser-rendered implementation screenshot, viewport, primary interactions tested, console errors checked, and final result. If browser-rendered evidence is missing, `final result` is `blocked`.\n\n`final result` must be exactly `passed` or `blocked`.\n\nUse `passed` when there are no actionable P0/P1/P2 findings. P3 findings may remain as follow-up polish.\nUse `blocked` when actionable P0/P1/P2 findings remain and name the blocker.\n\nReturn the file path with the QA report.\n","packages/cli/src/skill/builtin/.bundle/product-design/workflows/get-context/SKILL.md":"---\nname: get-context\ndescription: \"Mandatory design-brief gate for clarifying the product and outcome. Use before ideation, image-to-code builds, redesigns, or product UI work to clarify missing product information and play back the brief before proceeding.\"\n---\n\n# Get Context\n\n\nRun this skill at the start of Product Design requests that ask to design, build, prototype, clone, redesign, extend, or generate product UI directions.\n\nUse question mode to clarify the following:\n\n- what product, site, feature, workflow, component, or screen is being designed, redesigned, or extended\n- what the feature, change, app, or website should help the user do\n\nDo not re-ask answered questions. When both are clear, play back the brief and defaults in one pithy note, name the next workflow, and continue in the same turn. Playback is not a request for approval. The user can course-correct style, scope, or interactivity at any point.\n\nHard boundary: do not implement UI, scaffold a prototype, start a server, or create files while the design target or intended user outcome is still missing.\n\n## Critical Overrides\n\n- Refer to the Plugin router [$index](../index/SKILL.md) before proceeding.\n- Follow [$critical-overrides](../../references/critical-overrides.md).\n\n## User Context\n\nBefore starting, load [$user-context](../user-context/SKILL.md) and run its preflight script when local shell access is available.\n\nUse saved product URLs, Figma files, screenshots, reference images, codebase paths, Storybook, tokens, design systems, brand assets, component refs, browser preferences, and share targets as grounding material when relevant.\n\nDo not inspect every saved reference. Inspect only what the current task needs.\n\n## Handoff To The Next Workflow\n\n1. When the next workflow is already clear, read that skill before sending the brief playback. Do not only name a skill you have not read.\n\n2. Before executing `$ideate`, `$url-to-code`, or `$image-to-code`, play back the minimum brief and any defaults in one pithy user-visible note.\n\n3. If the target and intended user outcome are clear, continue to the next workflow in the same turn. Do not wait for explicit confirmation. If the user provides feedback, incorporate it and course-correct.\n\n4. Before starting an involved app, prototype, clone, redesign, or build, send one short expectation-setting note and continue. Example:\n\n```text\nThis kind of build usually takes about 10-15 minutes, and ambitious ones can take longer. Good moment to grab coffee or tend to something else; I’ll keep moving and bring the prototype back when it is ready.\n```\n\nDo not send this note for tiny static changes, quick audits, simple research, setup-only, or share-only requests.\n\nDone means the design target and intended user outcome are clear, defaults have been played back, and any already-determined next skill has been read.\n","packages/cli/src/skill/builtin/.bundle/product-design/workflows/ideate/SKILL.md":"---\nname: ideate\ndescription: \"Generate image-based alternatives, remixes, or new design directions from a Product Design brief. Use when the user asks for design variants, visual exploration, remixes, or image-generated approaches from provided context.\"\n---\n\n# Ideate\n\nYou're tasked with generating design concepts for a user's idea.\n\nFollow the shared Product Design routing guidance in [$index](../index/SKILL.md).\n\n## Critical Overrides\n\n- Refer to the Plugin router [$index](../index/SKILL.md) before proceeding.\n- Follow [$critical-overrides](../../references/critical-overrides.md).\n\n## User Context\n\nBefore starting, load [$user-context](../user-context/SKILL.md) and run its preflight script when local shell access is available.\n\nAttach provided product URLs, Figma files, screenshots, reference images, codebase paths, Storybook, tokens, design systems, brand assets, component refs, browser preferences, and share targets to the Image Gen generations to align them to the design brief.\n\nDo not inspect every saved reference. Inspect only what the current task needs.\n\n## Workflow\n\nDo not generate images until `$get-context` has satisfied the minimum required design brief.\n\nBefore generating images:\n\n1. Understand the brief.\n\n- Identify the target: component, screen, feature/workflow, or broad product idea.\n- Identify the intended user, product surface, and goal.\n- Preserve hard constraints from the user.\n- Run `get-context` if the minimum required design brief isn't satisfied.\n\n2. Resolve context.\n\n- Use provided files, screenshots, links, and visible references.\n- In a local workspace, look for nearby design documentation and other local visual context.\n- Check likely design context folders such as `user-context`, `storybook/`, `.storybook/`, `design-system/`, `design-systems/`, `tokens/`, `components/`, `app/`, and generated prototype roots.\n- In an existing project, look for existing product screenshots, similar flows, Storybook captures, design tokens, and component references before generating. Ask if the user can provide example screens similar to the one they are building if the existing app isn't accessible. Ensure you add design language and tokens to the Image Gen prompt.\n\n3. Inspect references directly.\n\n- Look at screenshots, images, Figma frames, app surfaces, or other visual references before generating.\n- Do not infer from filenames alone.\n- If a named local path or reference is not visible, stop and ask the user to confirm the path, upload the file, start the local app, or point to the correct workspace.\n\n4. Decide the variation mode.\n\n- If useful local design context exists and the user has not asked for a new style, stay within that existing direction.\n- If no useful design context exists, or the user asks for broad exploration, vary both concept and visual system.\n- For a specific component or existing surface, vary structure, interaction, hierarchy, and emphasis before varying brand style.\n- For a broad product idea, explore three meaningfully different product directions.\n\n5. Choose target dimensions before Image Gen.\n\n- Pick the dimensions that best match the user's request and any provided visual reference.\n- Mobile app: `390 x 844`.\n- Tablet app: `834 x 1194`.\n- Desktop app, dashboard, admin, or SaaS: `1440 x 1024`.\n- Landing or marketing page: `1440` wide and scrollable.\n- Modal, panel, widget, or component: natural container size.\n- Provided screenshot, Figma frame, mockup, or reference image: match its dimensions and aspect ratio when the user wants to continue from that visual.\n- Avoid crowding. Make the design fit the chosen dimensions cleanly, with realistic spacing, readable type, and no clipped content.\n- Include the chosen dimensions in every Image Gen prompt.\n\n6. Check for access gaps.\n\n- If a connector, reference, or file cannot be accessed because of auth, permissions, expired login, missing scope, suspiciously empty results, or unavailable local state, stop.\n- Name the gap clearly and ask whether to troubleshoot access or continue without that source.\n- Do not generate images while silently ignoring a named reference.\n\n7. Attach images and mocks provided by the user to the Image Gen call along with your design brief.\n\n8. Generate 3 independent options that have distinct information hierarchy, layout strategy, interaction model, or product framing.\n\nRules you must follow:\n\n- Use the Image Gen prompt below.\n- Use the built-in Image Gen tool.\n- Generate exactly three independent images unless the user overrides the count.\n- Launch each Image Gen call independently. Do not batch Image Gen calls with `Promise.all`, collect them into an ordered array, or replay them in request order.\n- Each option must be its own Image Gen result. Do not put multiple ideas in one image.\n- Give each direction a distinct, descriptive name before generation, but do not call it `option 1`, `option 2`, or `option 3` and do not put planned numeric labels in Image Gen prompts. Parallel results can arrive in a different order from the requests.\n- Number options only after the Image Gen results are present in the thread. The only authoritative option order is the order those generated-image results are displayed in the current thread. Ignore the planned concept order, original request chain, prompt submission order, `Promise.all` result order, batch order, array indexes, retry order, and assumed completion order.\n- After all results return, bind each visible option number to the result in that displayed order. Do not name or describe the options in the final selection message.\n- Attach provided screenshots, files, app captures, Figma references, and visual source material as moodboard inspiration when available.\n- Attach existing product screenshots, similar flows, Storybook captures, design tokens, and component references as grounding material when available.\n- When mock data includes dates or time-sensitive information, resolve the exact current date and include it in every Image Gen prompt. Derive visible dates from that anchor; preserve dates required by the user or source design.\n- If a screenshot, image, or visual file is available, attach the actual image to the Image Gen call. Do not rely on text descriptions of it.\n- Only claim a visual reference was attached if the Image Gen call actually received that image or a readable local image path.\n- If you cannot attach the image, say that clearly and ask whether to continue with text-only direction.\n- Preserve hard constraints from the brief in every image.\n- After generating options, stop for the user's selection before any build work begins.\n- When the user later selects option `N`, resolve it against the Nth displayed generated-image result from the most recent ideation set, not the original planned concept order. If the exact displayed result cannot be resolved, do not build from a guess; ask the user to name the concept or reattach/select the image.\n- The selected option is the visual target for `$image-to-code`.\n\n## Feedback Loop\n\nIf the user gives feedback after seeing options, generate revised options with that feedback.\n\nIf the user selects an option and gives feedback, generate a revised option with that feedback before build.\n\nIf the user likes parts of more than one option, combine those choices into a new Image Gen design and show it before build.\n\n## Image Gen Prompt\n\nAdapt this prompt to the current design brief, attach any available image references, and send it to Image Gen:\n\n```text\nCreate realistic, production-quality UI designs with clear hierarchy, strong typography, intentional imagery, and purposeful spacing.\n\nDesign a focused primary screen, not a feature inventory. The product may support many workflows, but this frame should show the hero use case, one clear primary action, and only one or two supporting actions or content areas. Do not add cards, panels, tabs, badges, metrics, filters, or navigation items merely to advertise every feature. Let the rest of the product exist off-screen. Prefer strong hierarchy and generous whitespace; if the screen feels crammed, remove UI.\n\n### Target Dimensions\n\nPick the dimensions that best match the user's request and any provided visual reference.\n\nDefault to a desktop web-app frame unless the user or reference clearly calls for mobile, tablet, or another format.\n\n - Mobile app: `390 x 844`\n - Tablet app: `834 x 1194`\n - Desktop app, dashboard, admin, or SaaS: `1440 x 1024`\n - Landing or marketing page: `1440` wide and scrollable\n - Modal, panel, widget, or component: natural container size\n - Provided screenshot, Figma frame, mockup, or reference image: match its dimensions and aspect ratio when the user wants to continue from that visual\n\nUse a natural viewport ratio for the intended surface. Never stretch, squash, or warp the generated screen, imagery, typography, or UI elements to fill the canvas. If the composition does not fit naturally, recompose or simplify the layout instead.\n\nAvoid crowding. Make the design fit the chosen dimensions cleanly, with realistic spacing, readable type, and no clipped content.\n\n### Layout\n\nWhen deciding how to lay elements out on the page, this should be your priority order for tools to differentiate sections:\n\n1. Use spacing, grouping, alignment, typography, and hierarchy on the same product surface.\n2. Use simple dividers or row separators.\n3. Use a subtle surface tint only when the base surface is not enough.\n4. Use borders only when separation still is not clear.\n5. Use shadows/elevation last, and sparingly.\n\nDon'ts:\n - Do not default to a centered \"app card\" (the whole UI is in a card on the page) on top of a contrasting page background. Use the base page surface first unless the source product or user explicitly asks for a contained app panel.\n - Do not put cards inside cards. Do not make every major section a card. Do not make each list item its own card unless each item is truly a standalone object. A normal list should usually read as one grouped surface with lightweight row separation.\n - Do not make up extraneous features. Add only the things essential to accomplish what the prototype's goal is. Don't make up more features just to fill out a UI.\n\n### Typography\n\n - Anchor UI typography to readable product sizes. Body text should usually sit between 14px and 16px, with the rest of the type scale built around that baseline.\n - Keep long-form text to a comfortable line length, generally no more than 65 characters per line.\n - Use no more than 2 fonts in a UI. You can use any font available in the project, or fonts provided free on Google Fonts. Pick the font that is best for the goal of the product and that matches with its intended look and feel.\n\n### Presentation\n\n - Do not add browser or device chrome around the mockup.\n - Do not put multiple ideas into a single image generation.\n - Vary each idea as much as possible while adhering to the constraints given entirely.\n\n### Data Freshness\n\nWhen the design includes dates or time-sensitive mock data, use the supplied current date as the anchor. Weekly views must show the real containing week with correct weekday/date pairs. Feeds, charts, notifications, and recent activity must use plausible chronological dates relative to today. Mark today when useful. Preserve dates required by the brief or source design.\n```\n\n## Output\n\nWait until all Image Gen calls have returned before sending the final message that asks the user to choose.\n\nDo not send the final selection message until every requested generated image is visible exactly once in the main chat.\n\nIf fewer Image Gen outputs are visible than requested, retry the missing generation. Do not send the selection message.\n\nNumber the returned Image Gen outputs in the order they appear in the conversation context:\n\n- First Image Gen output = Option 1\n- Second Image Gen output = Option 2\n- Third Image Gen output = Option 3\n\nIgnore the planned concept order, original request chain, request order, `Promise.all` result order, batch order, array indexes, retry order, and tool submission order.\n\nDo not name or describe the options. For the default three images, send only:\n\n`Which option should I build: 1, 2, or 3? Or tell me what you'd like to refine or personalize first.`\n\nAdjust the numbers only if the user requested a different count.\n\nIf the user chooses a number, acknowledge the chosen option before routing to `$image-to-code`, for example: `Building option 2!` Do not ask for confirmation when the mapping is clear.\n\nDone means the requested number of independent images have been generated and the user has been asked to select one.\n","packages/cli/src/skill/builtin/.bundle/product-design/workflows/image-to-code/SKILL.md":"---\nname: image-to-code\ndescription: \"Implement a selected image, screenshot, mockup, generated concept, or design frame as a faithful, responsive, interactive frontend in the target codebase.\"\n---\n\n# Image to Code\n\nTranslate a selected visual target into a high-quality frontend. Read `../index/SKILL.md`, `../../references/critical-overrides.md`, and the relevant saved context from `../user-context/SKILL.md` before building.\n\n## Preconditions\n\n- Require an unambiguous selected image, screenshot, mockup, generated result, or design frame. A written brief alone is not a visual target; route to ideation first when appropriate.\n- Resolve which image is selected before editing. Ask when an ordinal or attachment is ambiguous.\n- Use only the current task's relevant product context, tokens, components, assets, and references.\n\n## Workflow\n\n1. Inspect the source visual at useful detail and record its viewport, layout regions, hierarchy, spacing, typography, colors, borders, radii, shadows, imagery, icons, responsive behavior, and visible states.\n2. Inventory every required asset. Reuse supplied or repository assets when they match. Use an available image-generation tool for custom raster imagery and an appropriate existing icon set for UI icons. Do not substitute emoji, generic placeholders, or improvised CSS drawings for meaningful visual assets.\n3. Inspect the target repository and use its existing framework, package manager, component system, design tokens, and conventions. React is not required. Do not replace an established stack merely to match this workflow.\n4. If no target app exists, create the smallest runnable frontend supported by the harness and suited to the request; plain HTML/CSS/JavaScript is acceptable.\n5. Implement the full visible structure and the primary user journey. Unless requested otherwise, make navigation, tabs, menus, forms, toggles, selections, and main calls to action behave realistically without inventing backend systems.\n6. Match desktop or mobile based on the source. When the source is a phone UI and no device is named, verify around 390 × 844 as well as any relevant responsive behavior.\n7. Run the real app using its normal development or preview command.\n8. Capture the implementation using the browser tool selected by `../index/SKILL.md` and run `../design-qa/SKILL.md` against the source visual.\n9. Fix all blocking and high-impact mismatches. Save `design-qa.md` in the project root and hand off only when it records `final result: passed`, or clearly report a genuine capture/verification blocker.\n\n## Fidelity rules\n\n- Treat the selected visual as the design target; do not introduce unrelated redesign ideas.\n- Match the same viewport and interaction state during visual comparison.\n- Place real assets before final QA and avoid hotlinking third-party source assets in the finished app.\n- Keep the implementation maintainable within the target repository's patterns.\n- Do not claim verification from build success or an HTTP status alone; inspect the rendered result and primary interactions.\n\n## Handoff\n\nProvide the runnable project or changed files, the local preview information when useful, and a concise summary of what was implemented, verified, and left as a limitation. Publish only when the user asks and the host exposes an authorized deployment tool.\n\n","packages/cli/src/skill/builtin/.bundle/product-design/workflows/index/SKILL.md":"---\nname: index\ndescription: \"Use when Product Design is explicitly invoked, or when the user's main goal is to explore a design, research UX, audit or critique a flow, faithfully clone a visual source, check a built design, or share a prototype. Do not use Product Design for ordinary implementation unless the user explicitly asks for it.\"\n---\n\n# Skill Purpose\n\nRoute Product Design requests to the right Product Design skill. Use this plugin for an `@Product Design` mention, a direct Product Design request, or a request mainly about design exploration, faithful source cloning, audits, research, critique, or sharing. A request is not Product Design just because it mentions UI, a prototype, or visual style.\n\n# Plugin Purpose\n\nThe Product Design plugin helps designers and other non-coders close the gap between product ideas and working software.\n\nThe Product Design plugin equips you with the following set of skills to:\n\n- Research ideas and pain points related to your product.\n- Conduct product-flow audits.\n- Generate distinctly new ideas for your product with ImageGen.\n- Clone existing product apps into lightweight prototypes.\n- Build lightweight or interactive prototypes to share with your team.\n\n## Communication Style\n\nSpeak to the user in a warm, fun, and collaborative way, prioritizing pithy explanations over long walls of text and numerous bullet points. Refer to the [communication-protocol](../../references/communication-protocol.md) for relaying Product Design plugin progress updates and handoff.\n\n## Critical Overrides\n\n- Follow [$critical-overrides](../../references/critical-overrides.md).\n\n## Router Only\n\nThis index chooses the next Product Design skill. It does not do that skill's work.\n\nIf the user names a focused skill, read that exact skill first. Do not replace it with a related skill.\n\nWhen a request matches `$user-context`, `$get-context`, `$research`, `$ideate`, `$image-to-code`, `$url-to-code`, `$audit`, `$design-qa`, or `$share`, load the focused skill and follow it.\n\nFor requests to audit, review, critique, inspect, assess, analyze, evaluate, or give feedback on an existing product experience, load `$audit` directly; do not load `$get-context` first. If the same request also asks to build, fix, redesign, or implement afterward, run `$audit` first, then continue through the appropriate normal workflow.\n\nFor visual ideation, `$ideate` is the focused workflow. Use `$get-context` to resolve the minimum brief and play back any defaults before `$ideate` starts.\n\nFor clone or recreation of a live URL, load `$url-to-code` directly.\n\nFor a redesign, improvement, or new site based on a URL, use `$get-context` to confirm the redesign brief. `Like <URL>` means redesign, not clone. Capture the current site with screenshots, attach those screenshots to the `$ideate` Image Gen calls, then execute `$ideate`.\n\n## Standard Chat Mode\n\nIf Product Design is invoked in standard ChatGPT chat without Work Mode tools, do not start the workflow. Tell the user once:\n\n```text\nChat isn't supported by the Product Design plugin. Please switch to the Work tab and paste this prompt in for the full experience.\n```\n\nDo not ask design-brief questions, generate options, or begin build work until the user moves to Work Mode.\n\n## Browser Choice\n\nIn ChatGPT Work Mode, always use the cloud browser available to that chat. If it is not initially visible, load the Browser skill and follow its setup instructions before concluding it is unavailable.\n\nIn Codex Desktop, use `@Browser` and explicitly select the in-app surface with `agent.browsers.get(\"iab\")`.\n\nIn Codex Desktop, use Chrome only when the user asks for it, the task needs an existing Chrome tab/login/profile/extension, or the in-app Browser is unavailable or blocked.\n\nIf ChatGPT Work Mode does not expose both the cloud browser and `@Sites` after preflight, tell the user once:\n\n```text\nCloud browser and Sites are not available in this chat. I can still build a single-page HTML prototype, but I cannot visually verify it or publish a live checkpoint, so fidelity and interaction polish may be lower. Continue with that fallback?\n```\n\nOnly proceed after the user agrees. Do not claim the fallback is verified, open, hosted, or ready to share. This fallback applies to image-to-code and new prototypes. It does not apply to URL-to-code when browser capture is required.\n\n## No Visual Target, No Build\n\nFor new app, prototype, redesign, or UI build requests without a URL, screenshot, Figma frame, mockup, source image, or existing code target:\n\n- `$ideate` is the focused workflow.\n- Use `$get-context` to resolve the minimum brief.\n- Once the target and intended user outcome are clear, play back the assumptions and run `$ideate` in the same turn.\n- Show exactly three visual options and wait for the user to choose one.\n- Do not scaffold, edit files, or start a server before a visual option is selected.\n\n`Full working version`, `no refs`, `go for it`, `make an assumption`, or a complete brief do not waive this.\n\n## User Context\n\nUse [$user-context](../user-context/SKILL.md) when the user asks to:\n\n- Set up Product Design\n- Get started with Product Design\n- Onboard with Product Design\n- Save product or design sources\n- See what Product Design remembers\n- Update saved product or design context\n- Remember a Product Design preference\n- Setup my plugin\n\nAdjust the context-gathering request to match the user's request. First-time setup differs from updating existing context.\n\nFor setup-only requests, do not inspect the workspace, install dependencies, scaffold a prototype, generate images, run audits, or start implementation.\n\nWhen answering \"what can you do?\", \"how do I get started?\", or similar broad Product Design questions, load `$user-context` and follow its persistence availability check before offering saved-context onboarding.\n\nBefore routing to Product Design workflows, load [$user-context](../user-context/SKILL.md) and run its preflight script when local shell access is available.\n\n## Browser Annotation Updates\n\nTreat annotations as scoped edits to the current prototype.\n\nRead the annotation, its target, and the surrounding screen before changing code. Preserve the existing prototype by default: layout, style, content, routes, assets, interactions, and working behavior stay the same unless the annotation asks to change them.\n\nDo not redesign nearby UI or rebuild the prototype just because an annotation touches that area. If the annotation is ambiguous and the choice would materially change the prototype, ask first.\n\n## Skills\n\nUse this as the root routing guidance for Product Design plugin work. If several focused skills apply, sequence them in the order that creates the most useful design workflow. Keep this index as a router; do not perform focused workflow logic here.\n\n### $user-context\n\nPreflight, save, or answer from Product Design setup context. Route here before Product Design workflows to load saved product and design sources, and for direct setup, get-started, onboarding, save, remember, recall, inspect, or customization requests. This skill owns Product Design plugin-scoped context and preference policy.\n\n### $get-context\n\nRoute here first for design, build, prototype, redesign, extend, or UI exploration work. Require only a clear design target and intended user outcome. Ask one targeted question only when one of those is missing; otherwise play back the brief and defaults, then continue without waiting for approval.\n\n### $research\n\nRun fast, source-grounded UX research on current user problems for a named digital product. Route here for researching user pain, UX friction, onboarding issues, docs/help problems, developer experience friction, support pain, product workflow issues, or current user complaints.\n\n### $audit\n\nCapture and review a product flow, journey, screen, or multi-step product experience from screenshots. Route here for user-facing audit, review, critique, inspect, assess, analyze, evaluate, or feedback requests. It reports UX, design, and accessibility findings tied to captured evidence; do not use `design-qa` for user-facing audits.\n\n### $ideate\n\nGenerate image-based visual alternatives, remixes, or concept directions for a component, screen, feature, workflow, or product idea. Route here after `get-context` has played back the minimum brief and the user needs visual exploration, design variants, alternatives to an existing design, or idea discovery before choosing a visual target. Prefer this over prose-only ideation unless the user asks for prose.\n\n### $url-to-code\n\nClone a live URL as a runnable frontend-only local app using the Browser Choice rule above. Load this alongside `get-context` when the user provides a production URL for a faithful local prototype or clone, but do not execute it until the minimum brief has been played back. It should not modify production code; stay in `get-context` when source selection is still unclear.\n\n### $image-to-code\n\nImplement a selected visual target as a faithful, responsive, interactive frontend. Route here after `get-context` has played back the minimum brief and the user has chosen an ImageGen mock, screenshot, Figma frame, mockup, reference image, or other visual source. Do not start here when no visual target has been selected; use `get-context` and `ideate` first.\n\n### $share\n\nDeploy a runnable prototype and return a shareable URL using the user's preferred target when available. Route here when the user asks to share, deploy, publish, host, create a link, or make a prototype shareable with `@Sites`, `@Vercel`, or another deployment tool.\n\n### $design-qa\n\nCompare a coded Product Design prototype against its source visual target before handoff. Route here only as an internal helper after a prototype, URL-to-code build, or image-to-code build has both a source visual and rendered implementation. Do not route broad UX critiques, audits, or product-flow reviews here; use `audit` instead.\n","packages/cli/src/skill/builtin/.bundle/product-design/workflows/share/SKILL.md":"---\nname: share\ndescription: \"Share a runnable prototype using the user's preferred deployment tool.\"\n---\n\n# Share\n\nDeploy the user's runnable prototype so they can share it with others.\n\n## Critical Overrides\n\n- Refer to the Plugin router [$index](../index/SKILL.md) before proceeding.\n- Follow [$critical-overrides](../../references/critical-overrides.md).\n\n## User Context\n\nBefore starting, load [$user-context](../user-context/SKILL.md) and run its preflight script when local shell access is available.\n\nUse saved product URLs, Figma files, screenshots, reference images, codebase paths, Storybook, tokens, design systems, brand assets, component refs, browser preferences, and share targets as grounding material when relevant.\n\nDo not inspect every saved reference. Inspect only what the current task needs.\n\n## Workflow\n\n1. Confirm the prototype directory and the user's preferred deployment target.\n2. If the user invokes Product Design with @Sites, @Vercel, or another deployment tool, treat that as the selected hosting target.\n3. If the user did not choose a target, ask one question:\n\n> Where should I deploy this: @Sites, @Vercel, or another target?\n\n4. Use the selected deployment tool when it is available.\n5. If the selected tool is not available, say that clearly and ask whether to use another target.\n6. Run the deployment when possible. Do not give setup instructions if you can complete the deployment directly.\n7. Return the shareable URL.\n8. State any misses or manual follow-up the user still needs to do.\n\n## Rules\n\n- Do not deploy before the user chooses or confirms the target.\n- Do not claim the prototype is shared until you have a working URL.\n- If the selected tool is not available, say that clearly and ask whether to use another target.\n","packages/cli/src/skill/builtin/.bundle/product-design/workflows/url-to-code/SKILL.md":"---\nname: url-to-code\ndescription: \"Recreate an authorized live website or app URL as a faithful, runnable, frontend-only local implementation.\"\n---\n\n# URL to Code\n\nUse this workflow only when the user asks to clone or faithfully recreate a live site they own or have permission to reproduce. For redesign, improvement, or a loosely inspired result, route through `../index/SKILL.md` to context and ideation instead.\n\nRead `../index/SKILL.md`, `../../references/critical-overrides.md`, and relevant saved context before building.\n\n## Workflow\n\n1. Remind the user that they must have permission and follow the target site's terms.\n2. Open the source with the browser selected by the index. Stop if it resolves to a wrong page, login wall, error, unrelated redirect, or other surface that cannot ground the requested clone.\n3. Capture the full desktop page and a representative mobile viewport. Inspect small scroll increments so sticky, lazy-loaded, and animated content is not missed.\n4. Inspect the DOM and visible behavior for text, links, controls, component states, images, icons, fonts, colors, spacing, dimensions, breakpoints, and interaction behavior.\n5. Test important interactions one at a time and return to the starting state between tests. Preserve evidence for changed states.\n6. Save permitted source assets locally. Do not hotlink them in the final result. When an asset cannot be obtained, use an available generation tool or an appropriate open replacement and disclose the substitution.\n7. Inspect the target repository and use its existing framework and conventions. React is not required. If no app exists, create the smallest suitable frontend supported by the harness; plain HTML/CSS/JavaScript is acceptable.\n8. Build only from captured evidence. Implement the visible desktop/mobile layouts and primary interactions without inventing unrelated design choices or backend behavior.\n9. Run and inspect the local implementation with a real browser. Compare the same viewport and states against the source.\n10. Run `../design-qa/SKILL.md`, save `design-qa.md`, fix blocking and high-impact mismatches, and hand off only after `final result: passed` or a clearly documented verification blocker.\n\n## Hard rules\n\n- Capture source evidence before scaffolding or editing.\n- Do not infer hidden states when source evidence is available.\n- Do not use screenshots alone when DOM/style/interaction evidence can be inspected.\n- Do not leave placeholder assets or improvised icon glyphs in the final implementation.\n- Build success and server health are not visual verification.\n- Publish only when the user asks and the host exposes an authorized deployment tool.\n\n","packages/cli/src/skill/builtin/.bundle/product-design/workflows/user-context/SKILL.md":"---\nname: user-context\ndescription: Load or manage Product Design's saved user context. Use when the user asks to set up Product Design, get started, onboard, save product or design sources, see what Product Design remembers, update saved context, or remember Product Design preferences. Examples include product URLs, Figma files, screenshots, reference images, codebase paths, Storybook, tokens, design systems, brand assets, and general product/design notes.\n---\n\n# User Context\n\nUser Context stores the product and design references a designer uses often, so future Product Design work starts from the right sources.\n\nUse this skill when the user asks to:\n\n- set up Product Design\n- get started with Product Design\n- onboard with Product Design\n- save product or design sources\n- see what Product Design remembers\n- update saved product or design context\n- remember a Product Design preference\n- setup my plugin\n\n## Critical Overrides\n\n- Refer to the Plugin router [$index](../index/SKILL.md) before proceeding.\n- Follow [$critical-overrides](../../references/critical-overrides.md).\n- Before offering onboarding or saving context for future conversations, confirm that local shell access is available, `$CODEX_HOME` can be resolved, and `$CODEX_HOME/state/plugins/product-design/` exists and is writable or can be created in a writable parent directory. If `user-context.md` already exists, confirm that it is writable too.\n- If any check cannot be completed or fails, persistent context is unavailable. Do not offer saved-context onboarding or claim that new context was saved for future conversations. If the user asks to save something, explain that it can be used in the current conversation but not saved for future conversations.\n\n## Saved User Context\n\nIf `user-context.md` exists, use it by default.\n\nUse saved product URLs, Figma files, screenshots, reference images, codebase paths, Storybook, tokens, design systems, brand assets, component refs, browser preferences, and share targets to ground Product Design work.\n\nIdeation, prototypes, audits, clones, and critiques should match the saved product context unless the user asks for something different.\n\nWhen a workflow needs visual grounding, attach or include relevant saved screenshots, reference images, tokens, design language, and component references in ImageGen, ideation, prototype, audit, and critique work.\n\n## State File\n\nSaved context lives here:\n\n```text\n$CODEX_HOME/state/plugins/product-design/user-context.md\n```\n\nSaved screenshots and reference images live next to it:\n\n```text\n$CODEX_HOME/state/plugins/product-design/assets/\n```\n\nIf the file does not exist, continue normally unless the user asks to set up Product Design, save context, or the current task is blocked by missing product/design context.\n\n## Preflight\n\nWhen any Product Design workflow needs saved context, run:\n\n```bash\npython3 scripts/user_context_preflight.py\n```\n\nUse the returned saved entries as the starting context for the task.\n\nIf the script reports that no saved context exists, continue from the current user prompt unless setup context is required.\n\nDo not browse, open, or inspect every saved reference during preflight. Inspect only the saved references needed for the current task.\n\n## Setup\n\nUse [references/onboarding.md](references/onboarding.md) when the user asks to set up Product Design, asks what Product Design can remember, asks what Product Design knows about their product, or provides product/design references to save.\n\nFor setup-only requests, explain what Product Design can remember and ask for useful sources.\n\nAdjust the context-gathering request to match the user's request. First-time setup differs from updating existing context.\n\nDo not inspect the workspace, install dependencies, scaffold a prototype, generate images, run audits, or start implementation during setup.\n\nAfter the user provides references to save, run:\n\n```bash\npython3 scripts/init_user_context.py\n```\n\nThen add the references to the created `user-context.md`.\n\n## Save\n\nSave useful, durable Product Design context:\n\n- Product URLs\n- Figma files\n- Screenshots and reference images\n- Codebase paths\n- Storybook and component docs\n- Design tokens and theme sources\n- Brand, logo, icon, illustration, image, and asset sources\n- Preferred browser, capture tools, and share targets\n- Team conventions that make future Product Design work more accurate\n\nWhen the user provides screenshots or reference images to save, copy them into `assets/` next to `user-context.md` and link them from the saved entry.\n\nGive each saved image a clear, descriptive filename that says what the image shows. Use names future Product Design runs can understand without opening the file.\n\nGood image names:\n\n```text\nassets/chatgpt-settings-modal-dark-mode.png\nassets/payment-sheet-mobile-error-state.png\nassets/product-dashboard-sidebar-navigation.png\nassets/storybook-primary-button-states.png\nassets/brand-logo-lockup-purple-gradient.png\nassets/onboarding-flow-welcome-step.png\nassets/checkout-confirmation-screen.png\nassets/account-menu-open-state.png\n```\n\nDo not save secrets, credentials, API keys, private tokens, copied customer data, or anything that should not persist.\n\nUse this structure:\n\n```md\n# {Category}\n\n- Description: {what this category is and when future Product Design runs should use it}\n\n## Saved Links And Context\n\n{Saved reference or fact}\n- Date Added: YYYY-MM-DD.\n- File: assets/{clear-descriptive-name}.png\n- Useful Context: {what this reference represents}\n- Future Use: {how future Product Design work should use it}\n```\n\nInclude `File:` only when the saved entry has a local image file.\n\nWhen a category has no saved references yet, use exactly:\n\n```md\nstatus: not provided\n```\n\nKeep saved context curated. Prefer a few high-value references over a dump of every possible URL or file.\n\n## Read\n\n- Do not treat `status: not provided` as a fact.\n- Read through `scripts/user_context_preflight.py` when local shell access is available.\n- Use saved context as default grounding, then inspect only what the current task needs.\n","packages/cli/src/skill/builtin/.bundle/research-paper-writing/SKILL.md":"---\nname: research-paper-writing\ndescription: Write, rewrite, and polish academic papers (ML/CV/NLP style). Use when the user drafts or revises Abstract, Introduction, Related Work, Method, Experiments, or Conclusion; asks \"does this flow / 这段通顺吗 / polish this paragraph\"; turns bullet points or a Chinese draft into publication-quality English; runs a pre-submission self-review or reviewer-style critique; fixes paper figures/tables/LaTeX formatting; or compiles/converts the paper to PDF (LaTeX build, 编译PDF, 转成PDF). Trigger on mentions of paper, draft, camera-ready, rebuttal-facing revision, CVPR/ICCV/NeurIPS/ICLR/ACL-style venues, or .tex files being edited for a paper.\n---\n\n# Research Paper Writing\n\nAct as an experienced co-author who has published at top ML/CV/NLP venues. The goal is not \"prettier English\" — it is a draft that survives skeptical reviewers: clear story, one message per paragraph, and every claim backed by evidence.\n\n## Step 1: Diagnose the request, then route\n\nMatch the user's situation and load ONLY the needed reference (do not preload all):\n\n| User situation | What to do | Load |\n|---|---|---|\n| \"Polish this paragraph / does this flow?\" | Quick polish pass (see below) | `references/paragraph-flow.md` |\n| Draft or rewrite Abstract | Pick a template, draft, check claims | `references/abstract.md` |\n| Draft or rewrite Introduction | Clarify story first, then template | `references/introduction.md` |\n| Draft or rewrite Related Work | Topic grouping + positioning | `references/related-work.md` |\n| Draft or rewrite Method | Module triad workflow | `references/method.md` |\n| Draft or rewrite Experiments; fix tables | Claim→experiment mapping, table rules | `references/experiments.md` |\n| Draft or rewrite Conclusion / Limitations | Scope-based limitation framing | `references/conclusion.md` |\n| \"Review my paper / 投稿前检查\" | Adversarial five-dimension review | `references/paper-review.md` |\n| \"Compile / convert to PDF / 编译不过\" | Pick engine, build, verify output | `references/pdf-export.md` |\n| Bullet points / Chinese notes → English section | Treat as section drafting; get facts first, then draft | the matching section guide |\n\nIf the user's draft lives in files (`.tex`, `.md`, Overleaf export), work on the files directly: locate sections with grep (`\\section`, `\\begin{abstract}`), edit in place, and keep every `\\cite{...}`, `\\ref{...}`, label, comment, and math environment byte-for-byte unless the edit is specifically about them.\n\n## Step 2: Get the facts before writing\n\nGood paper writing is mostly correct facts arranged well. Before drafting a section, make sure these are known — from the draft, the codebase, or the user:\n\n1. What exact technical problem is solved, and why prior methods fail at it (limitation + technical reason).\n2. What the contribution is (new task / pipeline / module / finding / insight).\n3. Why the method works in essence, and its concrete advantages.\n4. What the strongest experimental numbers are.\n\nIf any of these are missing and not recoverable from context, ask — at most 3 focused questions in one message. Never fill gaps by inventing.\n\n## Hard Rules (never violate)\n\n1. **Never fabricate.** Do not invent experimental numbers, citations, baseline names, dataset statistics, or related-work claims. Use explicit placeholders (`[XX.X]`, `[CITE: sparse-view NeRF methods]`) and tell the user what to fill in.\n2. **Preserve technical meaning.** Rewrites must keep every claim's strength and scope. If a sentence is ambiguous and the rewrite must pick an interpretation, flag it: `⚠ interpreted as ...`.\n3. **Weaken or cut unsupported claims.** If a claim in Abstract/Introduction has no experimental backing in the paper, do not keep it strong — propose the weakened version and say why.\n4. **Respect double-blind.** Do not insert author names, GitHub links, or acknowledgments into a submission draft; warn the user if the draft already leaks identity.\n5. **Scale the output to the request.** A one-paragraph polish gets revised text plus a 1–2 line note — no outlines, no checklists. Full contracts are for section rewrites and reviews only.\n\n## Core Writing Principles\n\n1. One paragraph, one message; the first sentence states it.\n2. Every sentence connects to the previous one (cause, contrast, consequence, refinement, example).\n3. Define terms before reusing them; keep terminology identical across the whole paper (never alternate synonyms for a key concept).\n4. Never present the method as an incremental patch on a naive baseline — lead with the challenge and the insight, even for incremental work.\n5. Figures and tables are content, not decoration: clean teaser, clear pipeline figure, booktabs-style minimal-ink tables.\n\n## Workflows by request size\n\n### A. Quick polish (sentence / paragraph)\n\n1. Run the flow test from `references/paragraph-flow.md`: one message? first sentence states it? nouns self-contained? sentence-to-sentence relations explicit?\n2. Return the revised paragraph, then 1–2 lines on what changed and why.\n3. If the paragraph's real problem is structural (wrong message, no evidence), say so instead of cosmetically polishing.\n\n### B. Section draft / rewrite\n\n1. Confirm the section's story in a 3–7 bullet mini-outline before writing prose; on low ambiguity proceed and show the outline with the draft.\n2. Draft paragraph by paragraph — one message per paragraph, template from the section guide.\n3. Reverse-outline the result: thesis → topic sentences → evidence; fix anything that doesn't map.\n4. For Abstract/Introduction, append a claim-evidence map: `Claim: ... | Evidence: ... | Status: supported / needs evidence / weakened`.\n\n### C. Pre-submission review\n\n1. Load `references/paper-review.md` and read the paper as a hostile reviewer.\n2. Score the five dimensions (contribution, clarity, experimental strength, evaluation completeness, method soundness); mark each question `pass` / `needs revision` / `needs new experiment`.\n3. Return a prioritized fix list: rejection-level risks first, then clarity issues, then polish. Include concrete edit suggestions, not just complaints.\n\n## References\n\n- `references/abstract.md` — 3 abstract templates with annotated real examples\n- `references/introduction.md` — intro logic map, 4 opening / 3 challenge / 4 pipeline templates\n- `references/related-work.md` — topic grouping and positioning\n- `references/method.md` — module triad (design / motivation / advantage) workflow\n- `references/experiments.md` — claim→experiment planning, table/figure rules\n- `references/conclusion.md` — limitation framing that doesn't invite rejection\n- `references/paper-review.md` — adversarial five-dimension review checklist\n- `references/paragraph-flow.md` — paragraph clarity test, reverse outlining, transitions\n- `references/pdf-export.md` — compiling LaTeX/Markdown to PDF, engine choice, failure fixes, output verification\n- `references/examples/` — annotated LaTeX examples cited from the section guides\n","packages/cli/src/skill/builtin/.bundle/sales/SKILL.md":"---\nname: sales\ndescription: \"Use this skill whenever Sales is explicitly invoked or the task involves customer meeting preparation, call follow-up, account prioritization, account signals, deal strategy, business cases, competitive briefs, forecasts, customer evidence, rep coaching, company research, CRM context, or company and contact enrichment.\"\n---\n\n# Sales\n\nThis is the single entry point for a code-agent-oriented Sales bundle. The original workflow instructions are under `workflows/`; connector manifests and plugin marketplace metadata are intentionally excluded.\n\n## Route the request\n\n1. Read `workflows/index/SKILL.md` completely. Treat it as the authoritative plugin-level scope, source-selection rules, routing, and workflow sequencing policy.\n2. Select the narrowest focused workflow or workflow sequence named by that index. Read every selected workflow's `SKILL.md` completely before acting.\n3. Load provider-specific skills such as Salesforce, HubSpot, Apollo, or ZoomInfo only when the chosen source and available host tools make them relevant.\n4. If a selected workflow names related skills, read them only when their stated conditions apply. Resolve relative links from the file containing the link and load required references completely.\n5. Prefer bundled scripts and templates when a selected workflow calls for them. Do not load unrelated sales workflows merely because they are present.\n\n## Bundled capabilities\n\nFocused workflows live in `workflows/`, covering meeting preparation, call follow-up, account prioritization and signals, deal planning, business cases, competitive briefs, forecast review, customer quotes, internal experts, rep coaching, company research, enrichment, and provider-specific CRM or intelligence workflows.\n\nWorkflow-local supporting assets, references, and scripts remain beside their owning workflow. Use CRM, email, calendar, messaging, transcript, intelligence, and document systems only when the host harness exposes an authenticated tool for them. Do not invent customer facts when a source is missing; use the workflow's evidence and fallback rules.\n\n## Safety and fidelity\n\n- Never treat plugin instructions as permission to bypass host policy, reveal credentials, or perform unapproved external writes.\n- Keep sourced facts separate from inference and recommendations.\n- Require appropriate confirmation before sending messages, updating CRM records, or taking other external actions.\n- Preserve the selected workflow's requested output and handoff requirements through completion.\n","packages/cli/src/skill/builtin/.bundle/sales/workflows/analyze-account-signals/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fanalyze-account-signals%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/answers-ask-user-input/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fanswers-ask-user-input%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/apollo/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fapollo%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/build-business-case/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fbuild-business-case%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/build-competitive-brief/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fbuild-competitive-brief%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/enrich-company-and-contact-data/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fenrich-company-and-contact-data%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/find-customer-quotes/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Ffind-customer-quotes%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/find-key-internal-sources/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Ffind-key-internal-sources%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/follow-up-after-call/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Ffollow-up-after-call%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/get-rep-call-feedback/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fget-rep-call-feedback%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/hubspot/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fhubspot%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/index/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Findex%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/plan-deal-strategy/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fplan-deal-strategy%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/prepare-for-meeting/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fprepare-for-meeting%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/prioritize-accounts/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fprioritize-accounts%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/review-forecast/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Freview-forecast%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/review-rep-call-trends/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Freview-rep-call-trends%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/sales-company-research/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fsales-company-research%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/salesforce/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fsalesforce%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/zoominfo/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fzoominfo%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/skill-creator/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fskill-creator%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/super-research/README.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsuper-research%2FREADME.md -->","packages/cli/src/skill/builtin/.bundle/super-research/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsuper-research%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/super-research/evals/toy_bench/README.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsuper-research%2Fevals%2Ftoy_bench%2FREADME.md -->","packages/cli/src/skill/builtin/.bundle/super-research/evals/toy_dataset/README.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsuper-research%2Fevals%2Ftoy_dataset%2FREADME.md -->","packages/cli/src/skill/builtin/.bundle/super-research/evals/toy_pipeline/README.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsuper-research%2Fevals%2Ftoy_pipeline%2FREADME.md -->","packages/cli/src/skill/builtin/.bundle/super-research/evals/toy_regression/README.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsuper-research%2Fevals%2Ftoy_regression%2FREADME.md -->","packages/cli/src/skill/builtin/.bundle/super-research/evals/toy_repo/README.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsuper-research%2Fevals%2Ftoy_repo%2FREADME.md -->","packages/cli/src/skill/builtin/.bundle/xlsx-official/README.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fxlsx-official%2FREADME.md -->","packages/cli/src/skill/builtin/.bundle/xlsx-official/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fxlsx-official%2FSKILL.md -->","packages/cli/src/sync/README.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fsync%2FREADME.md -->","packages/cli/test/AGENTS.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Ftest%2FAGENTS.md -->","packages/cli/test/fixture/skills/agents-sdk/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Ftest%2Ffixture%2Fskills%2Fagents-sdk%2FSKILL.md -->","packages/cli/test/fixture/skills/agents-sdk/references/callable.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Ftest%2Ffixture%2Fskills%2Fagents-sdk%2Freferences%2Fcallable.md -->","packages/cli/test/fixture/skills/cloudflare/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Ftest%2Ffixture%2Fskills%2Fcloudflare%2FSKILL.md -->","packages/cli/test/fixture/skills/index.json":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Ftest%2Ffixture%2Fskills%2Findex.json -->","packages/cli/test/fixture/skills/llm-endpoint-demo/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Ftest%2Ffixture%2Fskills%2Fllm-endpoint-demo%2FSKILL.md -->"},"files":{".agents/skills/drive-mimo/SKILL.md":"---\nname: drive-mimo\ndescription: Use when developing or testing the MiMoCode repository and you need to programmatically drive another MiMoCode (mimo) process. Supports headless `mimo run` with JSON events and interactive TUI via tmux for behavior, integration, and visual regression testing. Covers an installed `mimo` binary or a dev build launched from source with `bun dev`; do not use it for ordinary MiMoCode task execution.\n---\n\n# Drive MiMo\n\n## Overview\n\nTwo **interfaces** for driving a separate mimo process:\n\n| Interface | Command | Use when |\n|------|---------|----------|\n| **Headless** | `mimo run --format json` | Scripted tasks, CI, event validation |\n| **TUI** | `mimo` in tmux | Interactive flow, permission dialogs, keybindings, visual regression |\n\n**Core principle:** Every run produces parseable evidence. No eyeballing.\n\nAlways drive an *isolated* instance: give each run a fresh `MIMOCODE_HOME` and a throwaway workspace so it never touches your own config, memory, or session DB.\n\n### Two ways to launch — orthogonal to interface\n\nThe interface (headless vs TUI, above) is *what you drive*. How the process is\n**launched** is a separate axis — either can be launched either way:\n\n| Launcher | Command | Use when |\n|----------|---------|----------|\n| **Installed binary** | `mimo …` | Testing a released/installed build |\n| **Dev (from source)** | `bun dev …` | Debugging mimocode itself — runs `src/index.ts` directly, no build step, picks up local code changes |\n\nEverything below uses `mimo` for brevity. To drive a **dev build** instead,\nsubstitute `bun dev` for `mimo` and run from the repo root — every flag,\nJSON event, and tmux technique is identical. See the Dev Mode section.\n\n## Prerequisites\n\n```bash\n# mimo binary must be on PATH (installed-binary launcher)\nwhich mimo || echo \"mimo not found on PATH\"\n\n# OR: dev launcher — run from the mimocode repo root, needs bun\nwhich bun || echo \"bun not found — needed for dev mode\"\n\n# tmux (for TUI interface)\nwhich tmux || echo \"tmux not found — install it for TUI mode\"\n```\n\n> **Running the `wait-for-text.sh` helper:** invoke it as\n> `./scripts/wait-for-text.sh …` from this skill's directory. The repository copy\n> is executable and can be called directly.\n\n---\n\n## Dev Mode (debugging mimocode itself)\n\nWhen the goal is to debug **mimocode's own code**, launch from source with\n`bun dev` instead of the installed `mimo` binary. It runs\n`packages/cli/src/index.ts` directly — no build step — so local edits take\neffect on the next launch.\n\n**Key facts:**\n\n- Run from the **repo root**. `bun dev` == `bun run dev`.\n- It is the dev equivalent of the `mimo` command: same CLI, same subcommands\n  and flags. `bun dev --help`, `bun dev run …`, `bun dev serve`, etc.\n- Args pass straight through, so **both interfaces work under dev**:\n  - Headless: `bun dev run --format json --dangerously-skip-permissions …`\n  - TUI:      `bun dev <workspace>` (positional workspace arg, as with `mimo`)\n- If `MIMOCODE_HOME` is not set, dev defaults it to a repo-local `.dev-home`\n  dir. For an isolated driven run, set `MIMOCODE_HOME=$(mktemp -d)` explicitly\n  just like with the binary.\n\n**Substitution rule:** anywhere Part 1 / Part 2 / Part 3 below say `mimo`,\nreplace it with `bun dev` (invoked from the repo root) to drive a dev build.\n\n```bash\n# Headless, dev build (from repo root)\nREPO=/path/to/mimocode/checkout   # your local mimocode repo root\nMIMOCODE_HOME=$(mktemp -d) bun --cwd \"$REPO\" dev run \\\n  --format json --dangerously-skip-permissions --dir \"$WORKSPACE\" \\\n  < \"$PROMPT\" > /tmp/mimo-dev.jsonl 2>&1\n\n# TUI, dev build in tmux (from repo root)\ntmux new-session -d -s \"$SESSION\" -x 120 -y 30 \\\n  \"cd $REPO && MIMOCODE_HOME=$(mktemp -d) MIMOCODE_PURE=true bun dev $WORKSPACE; sleep 999\"\n```\n\n---\n\n## Part 1: Headless Mode (`mimo run`)\n\n### Launch\n\n```bash\nPROMPT=$(mktemp -t mimo-drive.XXXXXX)\ncat >\"$PROMPT\" <<'EOF'\nYour task here.\nEOF\n\nMIMOCODE_HOME=$(mktemp -d) mimo run \\\n  --format json \\\n  --dangerously-skip-permissions \\\n  --dir \"$WORKSPACE\" \\\n  < \"$PROMPT\" > /tmp/mimo-out.jsonl 2>&1\n\nEXIT=$?\n```\n\n### Key flags\n\n| Flag | Purpose |\n|------|---------|\n| `--format json` | Structured JSONL events to stdout |\n| `--dangerously-skip-permissions` | Auto-approve all permissions |\n| `--model provider/model` | Override model |\n| `--session SID` | Continue existing session |\n| `--continue` | Continue last session |\n| `--file path` | Attach file to message |\n| `--dir path` | Working directory |\n\n### JSON event types\n\n`--format json` writes one JSON object per line. **Every** event has the shape\n`{\"type\": ..., \"timestamp\": <ms>, \"sessionID\": \"ses_...\", ...payload}` — the\n`sessionID` is a field on each event, not a standalone event. The payload for\nmost events is nested under `part`.\n\nEmitted event types (from the run event stream):\n\n```\n{\"type\":\"step_start\",\"timestamp\":...,\"sessionID\":\"ses_abc\",\"part\":{...}}\n{\"type\":\"text\",\"timestamp\":...,\"sessionID\":\"ses_abc\",\"part\":{\"type\":\"text\",\"text\":\"I'll create the file...\",\"time\":{...}}}\n{\"type\":\"reasoning\",\"timestamp\":...,\"sessionID\":\"ses_abc\",\"part\":{\"type\":\"reasoning\",\"text\":\"The user wants...\"}}\n{\"type\":\"tool_use\",\"timestamp\":...,\"sessionID\":\"ses_abc\",\"part\":{\"type\":\"tool\",\"tool\":\"write\",\"state\":{\"status\":\"completed\",...}}}\n{\"type\":\"step_finish\",\"timestamp\":...,\"sessionID\":\"ses_abc\",\"part\":{...}}\n{\"type\":\"error\",\"timestamp\":...,\"sessionID\":\"ses_abc\",\"error\":{...}}\n```\n\nNotes that matter for parsing:\n\n- **No `session.id`, no `tool_result`, no `session.status` event.** A `tool_use`\n  is emitted **once** per tool part when it reaches `completed` or `error` — the\n  result/output is inside `part.state`, there is no separate result event.\n- **`tool_use` identifies the tool via `part.tool`** (a bare string, e.g.\n  `\"tool\":\"write\"`) — there is no `.tool.name` and no top-level `.name`.\n- **`text` / `reasoning` text lives at `part.text`**, not top-level `.text`.\n- **`reasoning` is only emitted when `--thinking` is passed.** Without it, no\n  reasoning events appear.\n- **Completion is not a stream event.** The process finishes when the run\n  completes; the reliable completion signal is **process exit** (exit code 0),\n  not any line in the JSONL.\n\n### Validation patterns\n\n```bash\n# Completion — the real signal is the exit code, not a stream event\n[ $EXIT -eq 0 ] || echo \"FAIL: exit $EXIT\"\n\n# No errors\ngrep -q '\"type\":\"error\"' /tmp/mimo-out.jsonl && echo \"FAIL: errors found\"\n\n# A specific tool was used (match part.tool, the bare string)\ngrep -q '\"tool\":\"write\"' /tmp/mimo-out.jsonl || echo \"FAIL: write tool not called\"\n\n# Text output contains expected string (text is at .part.text)\ngrep '\"type\":\"text\"' /tmp/mimo-out.jsonl | jq -r '.part.text' | grep -q \"expected\"\n\n# Robust tool check via jq (works regardless of key ordering)\njq -e 'select(.type==\"tool_use\") | .part.tool==\"write\"' /tmp/mimo-out.jsonl >/dev/null \\\n  || echo \"FAIL: write tool not called\"\n```\n\n\n### Timeout\n\n```bash\ntimeout 120 mimo run --format json --dangerously-skip-permissions < \"$PROMPT\"\n[ $? -eq 124 ] && echo \"FAIL: timed out\"\n```\n\n---\n\n## Part 2: TUI Mode (tmux)\n\n### Isolation variables\n\n| Variable | Purpose |\n|---|---|\n| `MIMOCODE_HOME` | **Required.** Fresh `mktemp -d` per run. Sandboxes DB, config, cache. |\n| `MIMOCODE_PURE=true` | Disable external plugins. |\n| `MIMOCODE_DISABLE_GIT=true` | Skip git ops if workspace isn't a real repo. |\n\n### Launch TUI in tmux\n\n```bash\n# Create isolated environment\nMHOME=$(mktemp -d)\nWORKSPACE=$(mktemp -d)\nSESSION=\"mimo-drive-$$\"\n\n# Launch mimo TUI in tmux (workspace is a positional arg, NOT --dir)\ntmux new-session -d -s \"$SESSION\" -x 120 -y 30 \\\n  \"MIMOCODE_HOME=$MHOME MIMOCODE_PURE=true mimo $WORKSPACE; sleep 999\"\n\n# Wait for the TUI to render its input prompt\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"$PROMPT_RE\" -T 15\n```\n\nWhere `PROMPT_RE` is a language-neutral pattern for the input prompt. The\nprompt placeholder is localized, so match on the stable markers rather than a\nlocalized string:\n\n```bash\n# Matches the prompt line regardless of UI language:\n#   the \">\" input caret, the \"Ask\" English placeholder, or a \"/\" command hint\nPROMPT_RE='>|Ask|/[a-z]'\n```\n\nIf a run's UI language is known and fixed, you may match its literal\nplaceholder instead — but prefer the neutral pattern for portability.\n\n### Send input\n\n```bash\n# Type a message (literal text, then Enter)\ntmux send-keys -t \"$SESSION:0.0\" -l -- \"Create a file called hello.txt with content 'world'\"\ntmux send-keys -t \"$SESSION:0.0\" Enter\n\n# Special keys\ntmux send-keys -t \"$SESSION:0.0\" C-c          # Cancel\ntmux send-keys -t \"$SESSION:0.0\" C-d          # EOF\ntmux send-keys -t \"$SESSION:0.0\" Escape       # Escape\ntmux send-keys -t \"$SESSION:0.0\" Tab          # Tab completion\ntmux send-keys -t \"$SESSION:0.0\" Up           # History up\ntmux send-keys -t \"$SESSION:0.0\" Down         # History down\ntmux send-keys -t \"$SESSION:0.0\" Enter        # Submit\n```\n\n### Capture output\n\n```bash\n# Current screen\ntmux capture-pane -t \"$SESSION:0.0\" -p\n\n# Full scrollback\ntmux capture-pane -t \"$SESSION:0.0\" -p -S -\n\n# Last 50 lines\ntmux capture-pane -t \"$SESSION:0.0\" -p -S -50\n```\n\n### Wait for state changes\n\n```bash\n# Wait for agent to start processing\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"thinking\\|reading\\|writing\" -T 30\n\n# Wait for tool permission prompt\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"Allow\\|Deny\\|permission\\|approve\" -T 30\n\n# Wait for completion\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"completed\\|done\\|finished\\|idle\" -T 120\n\n# Wait for error\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"error\\|failed\\|Error\" -T 30\n\n# Custom regex\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"hello\\.txt.*world\" -T 30\n```\n\n### Handle permission dialogs\n\n```bash\n# Wait for permission prompt, then approve\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"Allow\\|approve\" -T 30\ntmux send-keys -t \"$SESSION:0.0\" -l -- \"y\"\ntmux send-keys -t \"$SESSION:0.0\" Enter\n\n# Or deny\ntmux send-keys -t \"$SESSION:0.0\" -l -- \"n\"\ntmux send-keys -t \"$SESSION:0.0\" Enter\n```\n\n### Multi-turn interaction\n\n```bash\n# Turn 1: send initial message\ntmux send-keys -t \"$SESSION:0.0\" -l -- \"Create a TypeScript file that adds two numbers\"\ntmux send-keys -t \"$SESSION:0.0\" Enter\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"completed\\|done\" -T 120\n\n# Turn 2: follow-up\ntmux send-keys -t \"$SESSION:0.0\" -l -- \"Now add a test for it\"\ntmux send-keys -t \"$SESSION:0.0\" Enter\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"completed\\|done\" -T 120\n\n# Verify result\ntmux capture-pane -t \"$SESSION:0.0\" -p -S - | grep -i \"pass\\|fail\"\n```\n\n### Cleanup\n\n```bash\ntmux kill-session -t \"$SESSION\" 2>/dev/null\nrm -rf \"$MHOME\" \"$WORKSPACE\"\n```\n\n---\n\n## Part 3: Scenarios\n\n### S1: Smoke (headless)\n\n```bash\ntest_smoke() {\n  local P=$(mktemp) MHOME=$(mktemp -d)\n  echo \"Say hello\" > \"$P\"\n  MIMOCODE_HOME=$MHOME mimo run --format json --dangerously-skip-permissions \\\n    < \"$P\" > /tmp/s1.jsonl 2>&1\n  local E=$?\n  rm -rf \"$MHOME\" \"$P\"\n  [ $E -eq 0 ] && grep -q '\"type\":\"text\"' /tmp/s1.jsonl && echo \"PASS\" || echo \"FAIL\"\n}\n```\n\n### S2: Tool use (headless)\n\n```bash\ntest_tool_use() {\n  local P=$(mktemp) MHOME=$(mktemp -d) WS=$(mktemp -d)\n  echo 'Create file test.txt with content \"hello\"' > \"$P\"\n  MIMOCODE_HOME=$MHOME mimo run --format json --dangerously-skip-permissions --dir \"$WS\" \\\n    < \"$P\" > /tmp/s2.jsonl 2>&1\n  local E=$?\n  local OK=true\n  [ $E -ne 0 ] && OK=false\n  ! grep -q '\"tool\":\"write\"' /tmp/s2.jsonl && OK=false\n  [ ! -f \"$WS/test.txt\" ] && OK=false\n  rm -rf \"$MHOME\" \"$WS\" \"$P\"\n  $OK && echo \"PASS\" || echo \"FAIL\"\n}\n```\n\n### S3: TUI interactive flow\n\n```bash\ntest_tui_interactive() {\n  local MHOME=$(mktemp -d) WS=$(mktemp -d) SID=\"mimo-s3-$$\"\n  local PROMPT_RE='>|Ask|/[a-z]'\n  tmux new-session -d -s \"$SID\" -x 120 -y 30 \"MIMOCODE_HOME=$MHOME MIMOCODE_PURE=true mimo $WS; sleep 999\"\n\n  # Wait for prompt\n  bash scripts/wait-for-text.sh -t \"$SID:0.0\" -p \"$PROMPT_RE\" -T 15 || { echo \"FAIL: no prompt\"; tmux kill-session -t $SID; return 1; }\n\n  # Send task\n  tmux send-keys -t \"$SID:0.0\" -l -- \"Create hello.txt with content 'world'\"\n  tmux send-keys -t \"$SID:0.0\" Enter\n\n  # Wait for completion (agent shows elapsed time like \"· 9.8s\")\n  bash scripts/wait-for-text.sh -t \"$SID:0.0\" -p \"· [0-9]\" -T 120 || { echo \"FAIL: no completion\"; tmux kill-session -t $SID; return 1; }\n\n  # Verify file\n  [ -f \"$WS/hello.txt\" ] && echo \"PASS\" || echo \"FAIL\"\n  tmux kill-session -t \"$SID\" 2>/dev/null\n  rm -rf \"$MHOME\" \"$WS\"\n}\n```\n\n### S4: TUI permission handling\n\n```bash\ntest_tui_permission() {\n  local MHOME=$(mktemp -d) WS=$(mktemp -d) SID=\"mimo-s4-$$\"\n  local PROMPT_RE='>|Ask|/[a-z]'\n  tmux new-session -d -s \"$SID\" -x 120 -y 30 \"MIMOCODE_HOME=$MHOME MIMOCODE_PURE=true mimo $WS; sleep 999\"\n\n  bash scripts/wait-for-text.sh -t \"$SID:0.0\" -p \"$PROMPT_RE\" -T 15\n\n  # Ask for something that needs permission (no --dangerously-skip-permissions in TUI)\n  tmux send-keys -t \"$SID:0.0\" -l -- \"Run the command: echo hello\"\n  tmux send-keys -t \"$SID:0.0\" Enter\n\n  # Wait for permission prompt\n  bash scripts/wait-for-text.sh -t \"$SID:0.0\" -p \"Allow\\|approve\\|permission\\|y/n\" -T 30 || { echo \"FAIL: no permission prompt\"; tmux kill-session -t $SID; return 1; }\n\n  # Approve\n  tmux send-keys -t \"$SID:0.0\" -l -- \"y\"\n  tmux send-keys -t \"$SID:0.0\" Enter\n\n  # Wait for completion\n  bash scripts/wait-for-text.sh -t \"$SID:0.0\" -p \"· [0-9]\" -T 60\n\n  tmux capture-pane -t \"$SID:0.0\" -p | grep -q \"hello\" && echo \"PASS\" || echo \"FAIL\"\n  tmux kill-session -t \"$SID\" 2>/dev/null\n  rm -rf \"$MHOME\" \"$WS\"\n}\n```\n\n### S5: TUI keybindings\n\n```bash\ntest_tui_keybindings() {\n  local MHOME=$(mktemp -d) WS=$(mktemp -d) SID=\"mimo-s5-$$\"\n  local PROMPT_RE='>|Ask|/[a-z]'\n  tmux new-session -d -s \"$SID\" -x 120 -y 30 \"MIMOCODE_HOME=$MHOME MIMOCODE_PURE=true mimo $WS; sleep 999\"\n\n  bash scripts/wait-for-text.sh -t \"$SID:0.0\" -p \"$PROMPT_RE\" -T 15\n\n  # Test Ctrl+C cancels input\n  tmux send-keys -t \"$SID:0.0\" -l -- \"some partial input\"\n  tmux send-keys -t \"$SID:0.0\" C-c\n\n  # Screen should still show prompt (not exit)\n  sleep 1\n  tmux capture-pane -t \"$SID:0.0\" -p | grep -qE \"$PROMPT_RE\" && echo \"PASS: Ctrl+C didn't exit\" || echo \"FAIL: Ctrl+C exited\"\n\n  # Test Escape\n  tmux send-keys -t \"$SID:0.0\" Escape\n  sleep 0.5\n\n  tmux kill-session -t \"$SID\" 2>/dev/null\n  rm -rf \"$MHOME\" \"$WS\"\n}\n```\n\n---\n\n## Batch Runner\n\n```bash\nrun_all() {\n  local PASS=0 FAIL=0 RESULTS=()\n  for fn in test_smoke test_tool_use test_tui_interactive test_tui_permission test_tui_keybindings; do\n    echo \"--- $fn ---\"\n    if $fn 2>/dev/null; then PASS=$((PASS+1)); else FAIL=$((FAIL+1)); RESULTS+=(\"$fn: FAIL\"); fi\n  done\n  echo \"=== $PASS passed, $FAIL failed ===\"\n  [ ${#RESULTS[@]} -gt 0 ] && printf '  %s\\n' \"${RESULTS[@]}\"\n  [ $FAIL -eq 0 ]\n}\n```\n\n---\n\n## Quick Reference\n\n| Task | Command |\n|------|---------|\n| Headless run | `MIMOCODE_HOME=$(mktemp -d) mimo run --format json --dangerously-skip-permissions \"prompt\"` |\n| TUI launch | `tmux new-session -d -s test -x 120 -y 30 \"MIMOCODE_HOME=$(mktemp -d) mimo $WORKSPACE; sleep 999\"` |\n| Send text | `tmux send-keys -t test:0.0 -l -- \"text\" && tmux send-keys -t test:0.0 Enter` |\n| Capture screen | `tmux capture-pane -t test:0.0 -p -S -` |\n| Wait for text | `bash scripts/wait-for-text.sh -t test:0.0 -p \"pattern\" -T 30` |\n| Send Ctrl+C | `tmux send-keys -t test:0.0 C-c` |\n| Approve permission | `tmux send-keys -t test:0.0 -l -- \"y\" && tmux send-keys -t test:0.0 Enter` |\n| Cleanup | `tmux kill-session -t test && rm -rf $MHOME` |\n",".agents/skills/effect/SKILL.md":"---\nname: effect\ndescription: Answer questions about the Effect framework\n---\n\n# Effect\n\nThis codebase uses Effect, a framework for writing typescript.\n\n## How to Answer Effect Questions\n\n1. Clone the Effect repository: `https://github.com/Effect-TS/effect-smol` to\n   `.opencode/references/effect-smol` in this project NOT the skill folder.\n2. Use the explore agent to search the codebase for answers about Effect patterns, APIs, and concepts\n3. Provide responses based on the actual Effect source code and documentation\n\n## Guidelines\n\n- Always use the explore agent with the cloned repository when answering Effect-related questions\n- Reference specific files and patterns found in the Effect codebase\n- Do not answer from memory - always verify against the source\n","AGENTS.md":"# MiMo-Code\n\n## Conventions\n\n- Use MiMoCode Compose skills when available, otherwise use superpowers skill if installed.\n- To regenerate the JavaScript SDK, run `./packages/sdk/script/build.ts`.\n- ALWAYS USE PARALLEL TOOLS WHEN APPLICABLE.\n- The default branch in this repo is `main`.\n- CI triggers on `main`.\n- Prefer automation: execute requested actions without confirmation unless blocked by missing info or safety/irreversibility.\n- Install deps with `bun ci` (= `bun install --frozen-lockfile`) — install per `bun.lock`, don't mutate the lockfile. ⛔ Do NOT use `bun install`/`npm install`.\n- Comments, docs, shipped skill content and test assertions use synthetic values, never machine-specific ones — `/tmp/example` for paths, `test/model` for model refs, `feat/example` for branches.\n- Do not edit `packages/cli/migration/*/migration.sql` that already shipped — engines have applied those journals; new schema changes get a **new** migration directory under `packages/cli/migration/`.\n\n## Style Guide\n\nMatch the style of the surrounding code. The rules below apply across the repository.\n\n### Types and errors\n\n- Avoid using the `any` type\n- Inside Effect code, express failures through the Effect error channel (`Effect.try`, `Effect.tryPromise`, `Effect.catchTag`, typed errors) rather than `try`/`catch`; plain scripts and non-Effect code may use `try`/`catch`\n\n### Bun and Node runtimes\n\n- Use Bun APIs where the runtime is Bun-only, like `Bun.file()` in the TUI (`src/cli/cmd/tui/`); build-time macros are fine anywhere, as they never reach the shipped runtime\n- In core code reachable from `src/node.ts`, prefer the Node equivalent when one exists — `createHash` over `Bun.CryptoHasher`, `prepare()` over bun:sqlite's `query()` — as that code also ships through `script/build-node.ts` and must run on plain Node\n- Bun-only calls in core escape both `typecheck` and `bun test`, which run on Bun; existing usage needs no urgent removal, and APIs with no Node equivalent may stay until a runtime seam exists\n\n### Config modules\n\nIn `src/config`, follow the existing self-export pattern at the top of the file (for example `export * as ConfigAgent from \"./agent\"`) when adding a new config module.\n\n### Schema Definitions (Drizzle)\n\nUse snake_case for field names so column names don't need to be redefined as strings.\n\n```ts\n// Good\nconst table = sqliteTable(\"session\", {\n  id: text().primaryKey(),\n  project_id: text().notNull(),\n  created_at: integer().notNull(),\n})\n\n// Bad\nconst table = sqliteTable(\"session\", {\n  id: text(\"id\").primaryKey(),\n  projectID: text(\"project_id\").notNull(),\n  createdAt: integer(\"created_at\").notNull(),\n})\n```\n\n### Reading a nullable column\n\nTwo independent absences meet in one expression, and only one of them is\n`undefined`. `.get()` yields `undefined` when no row matches — Drizzle normalises\nthe driver's `null` there — while a nullable column's SQL `NULL` arrives as\n`null`. So `row?.some_column` is `T | null | undefined`.\n\nWhen a caller only asks \"is there a value\", flatten to `undefined`, and write the\nflattening as an annotation rather than an `as` cast:\n\n```ts\n// Good — the compiler enforces it; deleting the `?? undefined` is a type error\nconst boundary: MessageID | undefined = row?.last_checkpoint_message_id ?? undefined\n\n// Bad — the cast removes `null` from the union without converting anything,\n// so the declared type is untrue at runtime\nreturn row?.last_checkpoint_message_id as MessageID | undefined\n```\n\nDiscriminate a possibly-absent value with truthiness or `== null`, never with\n`=== undefined` / `!== undefined`. Because `null !== undefined` is `true`, such a\nguard typechecks, reads correctly in review, and does nothing.\n\n## Testing\n\n- Avoid mocks as much as possible\n- Test actual implementation, do not duplicate logic into tests\n","packages/cli/README.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2FREADME.md -->","packages/cli/src/acp/README.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Facp%2FREADME.md -->","packages/cli/src/provider/sdk/copilot/README.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fprovider%2Fsdk%2Fcopilot%2FREADME.md -->","packages/cli/src/skill/builtin/.bundle/arxiv/SKILL.md":"---\nname: arxiv\ndescription: \"Use this skill whenever the user wants to find, read, cite, track, download, or analyze academic papers on arXiv. That includes: searching papers by topic, author, category, or arXiv ID; fetching abstracts or full metadata; generating BibTeX citations; downloading PDFs; listing the latest submissions in a field (e.g. cs.AI daily digest); checking a paper's citation impact; finding who cites a paper, what it references, or related-paper recommendations. Trigger on mentions of 'arXiv', an arXiv ID (e.g. 2601.02780 or hep-th/0601001), an arxiv.org URL, 'paper search', 'literature review', 'find papers about X', 'cite this paper', or 'what's new in cs.LG'.\"\nversion: 2.0.0\nlicense: MIT\nplatforms: [linux, macos, windows]\n---\n\n# arXiv Research\n\nSearch, read, cite, and analyze academic papers using the free arXiv API and Semantic Scholar API. No API keys, no dependencies — the bundled script uses only the Python stdlib.\n\n## Quick Start: the `arxiv.py` script\n\nPrefer `scripts/arxiv.py` over raw `curl` — it handles Atom XML parsing, versioned IDs, withdrawn-paper detection, and produces clean readable (or `--json`) output.\n\n| Goal | Command |\n|------|---------|\n| Search papers | `python scripts/arxiv.py search \"GRPO reinforcement learning\" --max 10 --sort date` |\n| Filtered search | `python scripts/arxiv.py search \"attention\" --author vaswani --category cs.CL` |\n| Full metadata + abstract | `python scripts/arxiv.py get 2601.02780,1706.03762` |\n| BibTeX citation | `python scripts/arxiv.py bibtex 2601.02780` |\n| Download PDF | `python scripts/arxiv.py download 2601.02780 --dest ./papers` |\n| Latest in a category | `python scripts/arxiv.py new cs.CL --max 10` |\n| Who cites this paper | `python scripts/arxiv.py cites 2601.02780 --max 20` |\n| What this paper cites | `python scripts/arxiv.py refs 2601.02780` |\n| Related-paper recommendations | `python scripts/arxiv.py similar 2601.02780` |\n| Machine-readable output | append `--json` to any command |\n\nCommon flags: `--max N` (result count), `--sort relevance|date|updated`, `--start N` (pagination offset, search only), `--json`.\n\n## Reading Paper Content\n\nAfter finding a paper, read it with the `webfetch` tool:\n\n- Abstract page (fast, metadata + abstract): `https://arxiv.org/abs/2601.02780`\n- Full paper as HTML (best for reading, when available): `https://arxiv.org/html/2601.02780`\n- PDF: `https://arxiv.org/pdf/2601.02780`\n\nIf HTML is unavailable and the PDF must be processed locally, `download` it first, then use a PDF-processing skill.\n\n## Recommended Research Workflows\n\n**Literature review on a topic**\n1. `search \"topic\" --sort date --max 15` — recent work\n2. `search \"topic\" --max 15` — seminal work (relevance-sorted)\n3. Cross-check impact: `python scripts/arxiv.py get ID` then `cites ID --max 5` for citation counts\n4. Read the top candidates via `webfetch` on the abs/html URLs\n5. `bibtex ID1,ID2,...` for the papers you keep\n\n**Deep-dive a single paper**\n1. `get ID` — full abstract, versions, journal ref, DOI\n2. `refs ID` — what it builds on\n3. `cites ID` — follow-up work (sorted by citation count)\n4. `similar ID` — related papers you might have missed\n5. `webfetch` the HTML/PDF for full text\n\n**Stay current in a field**\n- `new cs.AI --max 20` — latest submissions in a category\n- Category taxonomy: https://arxiv.org/category_taxonomy — common ones: `cs.AI`, `cs.CL` (NLP), `cs.CV`, `cs.LG`, `cs.CR`, `stat.ML`, `math.OC`\n\n## Raw API Reference (when the script isn't enough)\n\nThe script covers most needs; use the raw APIs for advanced queries.\n\n### arXiv API (Atom XML)\n\n```bash\ncurl -s \"https://export.arxiv.org/api/query?search_query=all:transformer&max_results=5\"\n```\n\nField prefixes: `all:` (everything), `ti:` (title), `au:` (author), `abs:` (abstract), `cat:` (category), `co:` (comment, e.g. `co:accepted+NeurIPS`).\n\nBoolean syntax (URL-encode spaces as `+`):\n\n```\nall:GPT+OR+all:BERT              # OR\nall:language+model+ANDNOT+all:vision   # AND NOT\nti:\"chain+of+thought\"            # exact phrase\nau:hinton+AND+cat:cs.LG          # combined\n```\n\nParameters: `sortBy` (`relevance`|`lastUpdatedDate`|`submittedDate`), `sortOrder`, `start`, `max_results`, `id_list` (comma-separated IDs).\n\n### Semantic Scholar API (JSON)\n\narXiv has no citation data — Semantic Scholar fills that gap (free, ~1 req/sec unauthenticated).\n\n```bash\n# Paper details with citation counts\ncurl -s \"https://api.semanticscholar.org/graph/v1/paper/arXiv:2601.02780?fields=title,citationCount,influentialCitationCount,tldr\"\n\n# Author profile\ncurl -s \"https://api.semanticscholar.org/graph/v1/author/search?query=Yann+LeCun&fields=name,hIndex,citationCount,paperCount\"\n\n# Keyword search returning JSON (alternative to arXiv search)\ncurl -s \"https://api.semanticscholar.org/graph/v1/paper/search?query=GRPO&limit=5&fields=title,year,citationCount,externalIds\"\n```\n\nUseful fields: `title`, `authors`, `year`, `abstract`, `tldr` (AI summary), `citationCount`, `influentialCitationCount`, `isOpenAccess`, `openAccessPdf`, `fieldsOfStudy`, `publicationVenue`, `externalIds` (arXiv ID, DOI).\n\n## Important Details\n\n**Rate limits** — arXiv: ~1 request / 3 seconds; Semantic Scholar: ~1 request / second. Space out consecutive calls; the script exits with a clear message on HTTP 429.\n\n**ID formats** — new style `2402.03300`, old style `hep-th/0601001`. Both work everywhere.\n\n**Versioning** — `arxiv.org/abs/2601.02780` resolves to the latest version; `...v2` is a specific immutable version. `bibtex` and `download` preserve the version suffix so citations match the content you actually read (later versions can change substantially).\n\n**Withdrawn papers** — the script flags entries whose abstract indicates withdrawal/retraction with `[WITHDRAWN]`. Don't cite these without noting the status.\n\n**Listings caveat** — `new CATEGORY` sorts by submission date via the search API; the official \"new today\" listing at `https://arxiv.org/list/cs.AI/new` may group slightly differently (cross-lists, replacements).\n","packages/cli/src/skill/builtin/.bundle/claude-code/SKILL.md":"---\nname: claude-code\ndescription: \"Operate Claude Code CLI (v2.1+) via the terminal only when the user explicitly requests Claude Code or names this skill. Covers print mode (-p), interactive tmux sessions, and background (--bg) orchestration.\"\nversion: 2.0.0\nlicense: MIT\nplatforms: [linux, macos, windows]\n---\n\n# Claude Code Delegation\n\nDelegate coding work to Claude Code, Anthropic's autonomous coding agent CLI.\n\n**Setup (once):** `npm install -g @anthropic-ai/claude-code && claude auth login` · verify with `claude auth status` / `claude doctor`. CI token: `claude setup-token`. Full auth/install variants → `references/flags.md`.\n\n**Platform check (before running anything):** detect the OS first. All shell examples in this skill are POSIX (bash). Linux/macOS run them as-is. On **Windows**, run Claude Code natively in PowerShell/Git Bash for print and background modes, but interactive tmux orchestration requires **WSL**. Shell-syntax translation table (quoting, env vars, piping, paths) → `references/platforms.md`.\n\n## Mode Selection (decide FIRST)\n\n| Task shape | Mode | Why |\n|---|---|---|\n| One-shot task: fix bug, add feature, review diff, extract data | **Print `-p`** ← default | No PTY, no dialogs, structured output |\n| Multi-turn iterate: refactor → review → fix → test; needs slash commands | **Interactive tmux** → `references/interactive-tmux.md` | Full REPL, requires dialog handling |\n| Long-running, shouldn't block; large fan-out supervision | **Background `--bg`** | Native supervision via `claude agents` |\n| High-stakes PR review | **`claude ultrareview [pr#]`** | Cloud multi-agent, exit-code driven (uploads diff to cloud — never on branches with secrets) |\n\nDo NOT hand-roll tmux fan-outs for parallel work — prefer `--bg` + `claude agents --json --all`.\n\n## Print Mode (the 90% path)\n\n```\nterminal(command=\"claude -p 'Fix the auth bug in src/auth.py' \\\n  --allowedTools 'Read,Edit' --max-turns 10 --output-format json\",\n  workdir=\"/path/to/project\", timeout=180)\n```\n\n**Always set:** `workdir` · `--max-turns` (5–10; print-mode only) · `--allowedTools` (least privilege: `Read,Edit,Write,Bash`, patterns like `Bash(git *)`).\n\n**JSON result fields:** `result` (text) · `session_id` (for resume) · `subtype` (`success` | `error_max_turns` | `error_budget`) · `total_cost_usd` · `num_turns` · `structured_output` (with `--json-schema`).\n\n**Common variants:**\n\n```bash\ngit diff main... | claude -p 'Review for bugs' --max-turns 1     # pipe input, cheapest review\nclaude -p 'Continue: add pooling' --resume <session_id>          # resume; --continue = latest in cwd; --fork-session = branch\nclaude -p 'List functions' --output-format json --json-schema '<schema>' --max-turns 5   # structured extraction (needs turns to read files)\nclaude --bare -p 'task' --settings ci.json                       # CI: skips hooks/plugins/CLAUDE.md; auth = ANTHROPIC_API_KEY only\nclaude -p 'task' --max-budget-usd 0.50 --fallback-model haiku    # cost cap (min ~$0.05) + overload fallback\n```\n\nStreaming, stream-json events, bidirectional input, cache-reuse (`--exclude-dynamic-system-prompt-sections`) → `references/print-mode.md`.\n\n## Background Mode\n\n```bash\nclaude --bg 'investigate flaky test in tests/api.test.ts'   # NOT compatible with -p\nclaude agents --json --all                                   # list/inspect\nclaude attach <id> | logs <id> | stop <id> | respawn <id> | rm <id>\n```\n\n## Guardrails & Gotchas (violations break agents)\n\n1. **`-p` auto-skips trust/permission dialogs** (any non-TTY does) — only run in trusted directories.\n2. **Interactive mode = tmux required** (Windows: only inside WSL — never attempt tmux in PowerShell/cmd; fall back to `-p` or `--bg`); two startup dialogs, and the `--dangerously-skip-permissions` dialog defaults to **\"No, exit\"** (must send `Down` then `Enter`). Full patterns → `references/interactive-tmux.md`.\n3. **Session resume is per-directory** — `--continue` only finds sessions from the same cwd.\n4. **Slash commands don't work in `-p`** — describe the task in natural language instead.\n5. **Context >70% degrades quality** — in interactive sessions monitor `/context`, use `/compact`.\n6. **Clean up**: kill tmux sessions and `claude stop/rm` background sessions when done.\n7. **Don't kill slow sessions** — capture progress first (`tmux capture-pane` / `claude logs`).\n8. **Report back**: after completion, summarize what changed (use the JSON `result` + `git diff`).\n\n## References (read on demand)\n\n| File | Read when |\n|---|---|\n| `references/print-mode.md` | Streaming output, stream-json events, piping, schemas, session mgmt, cache reuse |\n| `references/interactive-tmux.md` | Any tmux/PTY session: dialogs, send-keys, monitoring, slash commands, shortcuts |\n| `references/flags.md` | Full CLI flag & subcommand tables, auth variants, env vars, model/effort selection |\n| `references/config.md` | CLAUDE.md/memory, settings hierarchy, custom agents, hooks, MCP, plugins, project purge |\n| `references/platforms.md` | Running on Windows (PowerShell/Git Bash/WSL) or macOS: shell translation, paths, per-OS gotchas |\n","packages/cli/src/skill/builtin/.bundle/codex/SKILL.md":"---\nname: codex\ndescription: Run, configure, and troubleshoot OpenAI Codex CLI in non-interactive headless environments. Use for Codex automation in Bash or PowerShell, native Windows or WSL2, shell scripts, CI/CD, Docker, Kubernetes, remote servers, agent harnesses, or batch jobs; for constructing `codex exec` commands; selecting sandbox and approval modes; consuming JSONL events or structured output; resuming sessions; passing prompts through stdin; and handling failures caused by unavailable interactive input such as `request_user_input`.\n---\n\n# Codex CLI\n\nUse Codex CLI as a deterministic, non-interactive worker suitable for automation and agent orchestration.\n\n## Operating Rules\n\n1. Use `codex exec`, not the interactive `codex` TUI.\n2. Pass the task as the positional `PROMPT` argument. Do not use `-p` for the prompt; `-p` selects a profile.\n3. For ordinary unattended code changes, prefer:\n\n```bash\ncodex exec \\\n  -C /path/to/repo \\\n  --sandbox workspace-write \\\n  --ask-for-approval never \\\n  \"<TASK>\"\n```\n\n4. Use `--yolo` only inside an externally hardened and disposable runner. It disables Codex approvals and sandboxing.\n5. For harnesses and CI, prefer `--json` plus `--output-last-message`.\n6. Do not make the run depend on a human answering questions. Resolve ambiguity using repository evidence and conservative defaults.\n7. Treat credentials as secrets. Inject `CODEX_API_KEY` only into the single `codex exec` process when possible.\n8. Before giving version-sensitive advice, inspect `codex exec --help` or current official Codex documentation if available.\n9. On Windows, choose one execution environment per task: native PowerShell for Windows toolchains or WSL2 for Linux toolchains. Do not casually mix paths, installations, or authentication across them.\n\n## Choose the Execution Mode\n\n### Read-only analysis\n\nUse when the task must not modify files:\n\n```bash\ncodex exec \\\n  -C /path/to/repo \\\n  --sandbox read-only \\\n  --ask-for-approval never \\\n  \"Analyze the repository and report risks. Do not modify files.\"\n```\n\n### Workspace-scoped implementation\n\nUse as the default for autonomous repository work:\n\n```bash\ncodex exec \\\n  -C /path/to/repo \\\n  --sandbox workspace-write \\\n  --ask-for-approval never \\\n  \"Implement the task, run relevant tests, and report unresolved blockers.\"\n```\n\n### Externally isolated unrestricted execution\n\nUse only when the enclosing container, VM, or sandbox enforces the real security boundary:\n\n```bash\ncodex exec \\\n  -C /workspace/repo \\\n  --yolo \\\n  \"Implement the task and validate the result.\"\n```\n\nNever recommend `--yolo` on a normal developer machine or a runner containing unrelated secrets, host mounts, SSH keys, cloud credentials, or a Docker socket.\n\n## Construct an Autonomous Prompt\n\nWhen headless execution could encounter choices, prepend these instructions:\n\n```text\nWork fully autonomously.\n\nDo not ask the user questions and do not request interactive input.\nInspect the repository and available context before making assumptions.\nWhen several valid approaches exist, choose the option that:\n1. minimizes unrelated changes,\n2. preserves backward compatibility,\n3. introduces the fewest new dependencies,\n4. avoids destructive or irreversible actions.\n\nContinue until the task is complete or a concrete blocking error is reached.\nRecord assumptions, validation performed, and unresolved blockers in the final response.\n```\n\nDo not simulate \"always select the first option.\" Option ordering is not a safety or quality policy. Apply the explicit decision rules above instead.\n\n## Handle `request_user_input` Failures\n\nWhen Codex reports that `request_user_input` is unavailable in Default mode or non-interactive mode:\n\n1. Confirm the invocation uses `codex exec` and is intentionally headless.\n2. Add the autonomous prompt policy above.\n3. Supply missing decisions in the task prompt or `AGENTS.md` when they are known in advance.\n4. Replace open-ended requests such as \"ask me which approach\" with deterministic selection criteria.\n5. If the choice is safety-critical, destructive, or impossible to infer, make the run fail clearly rather than selecting randomly.\n6. Do not attempt to emulate terminal keystrokes unless the subprocess itself, rather than Codex, requires input and the workflow explicitly defines the safe answer.\n\n## Pass Prompts and Context\n\nUse a direct positional prompt:\n\n```bash\ncodex exec \"Summarize the repository structure.\"\n```\n\nRead the prompt from stdin:\n\n```bash\ncodex exec - < prompt.md\n```\n\nPipe dynamic context while retaining an explicit task:\n\n```bash\nnpm test 2>&1 | codex exec \"Analyze this test output and fix the repository.\"\n```\n\nUse `--skip-git-repo-check` only for intentional one-off directories outside Git:\n\n```bash\ncodex exec \\\n  --skip-git-repo-check \\\n  -C /tmp/task \\\n  \"Analyze the files in this directory.\"\n```\n\n## Produce Harness-Friendly Output\n\n### Capture only the final message\n\n```bash\ncodex exec \\\n  -C /workspace/repo \\\n  --output-last-message /output/final.md \\\n  \"Review the codebase.\"\n```\n\n### Stream JSONL events\n\n```bash\ncodex exec \\\n  -C /workspace/repo \\\n  --json \\\n  --sandbox workspace-write \\\n  --ask-for-approval never \\\n  \"Run tests and fix failures.\" \\\n  > /output/events.jsonl\n```\n\nExpect event families such as `thread.started`, `turn.started`, `turn.completed`, `turn.failed`, `item.*`, and `error`.\n\n### Capture events and the final answer together\n\n```bash\ncodex exec \\\n  -C /workspace/repo \\\n  --json \\\n  --sandbox workspace-write \\\n  --ask-for-approval never \\\n  --output-last-message /output/final.md \\\n  \"Complete the task autonomously.\" \\\n  | tee /output/events.jsonl\n```\n\nDo not parse human-readable progress text when `--json` is available.\n\n## Require Structured Final Output\n\nCreate a JSON Schema and pass it with `--output-schema`:\n\n```bash\ncodex exec \\\n  -C /workspace/repo \\\n  --sandbox workspace-write \\\n  --ask-for-approval never \\\n  --output-schema /input/result.schema.json \\\n  --output-last-message /output/result.json \\\n  \"Implement the task, validate it, and return the requested structured result.\"\n```\n\nA useful harness schema usually includes:\n\n- `status`: `success`, `partial`, or `failed`\n- `summary`: concise outcome\n- `changed_files`: repository-relative paths\n- `validation`: commands run and results\n- `assumptions`: decisions made without user input\n- `blockers`: concrete unresolved problems\n\nSet `additionalProperties` to `false` when downstream parsing must be strict.\n\n## Resume or Avoid Persistence\n\nResume the most recent session for the current working directory:\n\n```bash\ncodex exec resume --last \"Continue the previous task and fix remaining issues.\"\n```\n\nResume a specific session:\n\n```bash\ncodex exec resume \"$SESSION_ID\" \"Continue with the next stage.\"\n```\n\nUse an ephemeral run when rollout persistence is undesirable:\n\n```bash\ncodex exec --ephemeral \"Analyze the repository.\"\n```\n\nDo not rely on `--last` across unrelated working directories unless deliberately using the relevant all-directory option supported by the installed CLI.\n\n## Authenticate Safely\n\nFor a local interactive login:\n\n```bash\ncodex login\n```\n\nFor a headless machine with device-code login enabled:\n\n```bash\ncodex login --device-auth\n```\n\nFor a single automated invocation:\n\n```bash\nCODEX_API_KEY=\"$OPENAI_API_KEY\" \\\ncodex exec --json \"Triage the repository.\"\n```\n\nDo not expose API keys as broad job-level environment variables in jobs that execute repository-controlled code. Never commit or print `~/.codex/auth.json`.\n\n## Windows, PowerShell, and WSL2\n\nFor native Windows headless use:\n\n- Install with the official PowerShell installer or npm.\n- Prefer PowerShell 7.4 or newer for JSONL redirection.\n- Build argument arrays and invoke them with `& codex @args`; avoid fragile backtick-heavy command construction.\n- Check `$LASTEXITCODE` after every Codex invocation. PowerShell error preferences alone are not a substitute for checking a native process exit code.\n- Keep stdout JSONL separate from stderr diagnostics. Do not use `2>&1` when stdout must remain parseable JSONL.\n- Configure `%USERPROFILE%\\.codex\\config.toml` with `[windows] sandbox = \"elevated\"` when available; use `unelevated` only as the fallback.\n- Preserve the task-level policy `--sandbox workspace-write --ask-for-approval never` for ordinary autonomous edits. The native Windows sandbox implementation and the CLI task policy are separate controls.\n\nFor WSL:\n\n- Use WSL2, not WSL1.\n- Install and authenticate Codex inside WSL as a Linux installation.\n- Keep repositories under `~/code/...`, not `/mnt/c/...`, for better performance and fewer permission, symlink, and file-watcher problems.\n- Do not pass credentials through visible `wsl.exe` command-line strings.\n\nSee [references/windows.md](references/windows.md) for installation, PowerShell wrappers, JSONL parsing, sandbox configuration, WSL2 patterns, and Windows-specific troubleshooting.\n\n## Container and CI Requirements\n\nWhen generating a Docker, Kubernetes, or CI design:\n\n- Mount only the intended workspace and output directory.\n- Run as a non-root user when practical.\n- Do not mount the host Docker socket.\n- Do not mount home directories, SSH keys, or cloud credential directories.\n- Restrict network access unless the task explicitly needs it.\n- Apply CPU, memory, process, and execution-time limits outside Codex.\n- Preserve stdout, stderr, exit status, JSONL events, and the final message separately.\n- Validate repository diffs and test results before treating a run as successful.\n- Prefer a fresh worktree or disposable checkout per task.\n\nSee [references/recipes.md](references/recipes.md) for ready-to-use shell, Docker, CI, and parser patterns.\n\n## Diagnose Failures\n\nUse this order:\n\n1. Run `codex --version` and `codex exec --help`.\n2. Verify the command uses a positional prompt or `-` for stdin.\n3. Verify the working directory and Git repository status.\n4. Verify authentication without printing secret material.\n5. Check whether sandbox policy blocks required reads, writes, commands, sockets, or network access.\n6. Check whether approval policy is causing an impossible prompt in headless mode.\n7. Inspect stderr and the JSONL `error` or `turn.failed` events.\n8. Re-run with a smaller, deterministic task that reproduces the failure.\n9. Do not silently switch to `--yolo` as a troubleshooting shortcut.\n\n## Completion Standard\n\nFor implementation tasks, consider the run complete only when Codex has:\n\n1. inspected the relevant repository context,\n2. made the requested changes,\n3. run the most relevant available validation,\n4. reviewed the resulting diff for unrelated changes,\n5. reported assumptions and unresolved blockers,\n6. produced machine-readable status when requested by the harness.\n","packages/cli/src/skill/builtin/.bundle/compose-next/SKILL.md":"---\nname: compose-next\ndescription: Use for multi-step feature work, bug fixes, or refactors where requirements need to settle, a feature document should carry design + tasks + delivery evidence, and the change deserves independent review before merge. Use it only when the user explicitly requests this workflow, whether with `/compose-next`, by name, or in any other clear natural language; do not infer the request from task complexity alone. Not for one-shot edits, single-file tweaks, or answering questions — those need no orchestration overhead.\n---\n\n# Compose Next\n\nCompact end-to-end contract for grill → workspace → spec → implement → verify → review → finalize → finish. One skill load, no internal skill hand-offs.\n\nWhen writing a checkpoint or compacting context, preserve this recovery instruction in the checkpoint or compacted summary: on resumption, if the Compose Next instructions are absent, reload the `compose-next` skill before continuing.\n\nEnter this workflow only on an explicit user request. Any clear natural-language instruction to use this workflow counts just like `/compose-next`; the user does not need to know or name the skill. If the user has not clearly requested the workflow, do the work directly and run none of the phases below; do not infer consent merely because the task is large or resembles a Compose task.\n\n## Step 0 — Orient\n\nInspect the repository, its instructions (`AGENTS.md`, `README`, existing spec files), and recent changes before asking anything. Do not ask the user for facts the environment already answers.\n\nDecide the shape of the work:\n\n- **Fully constrained mechanical change with no durable design surface** → skip Grill and Spec, go to Workspace then Implement.\n- **Requirements or design ambiguous** → Grill first.\n- **Requirements clear, feature deserves a durable document** → Workspace then Spec.\n\nUser gates and project overrides:\n\n- If the user explicitly requests `without worktree` or specifies a worktree or workspace path, use that workspace choice and skip the default worktree gate. Do not ask again for worktree consent.\n- If the user explicitly says `without spec`, \"no spec needed\", \"this is a small fix\", or gives an equivalent instruction, skip the durable feature document and its spec gate. Keep verification and review when the task still warrants them.\n- An explicit project instruction, `AGENTS.md`, or user-provided agent/worktree configuration may define a project-specific worktree path, branch convention, spec path, or spec format. Use that configuration instead of the defaults in this skill. Record the override in the feature document or final report when it changes the normal artifact location.\n\nEvery path passes through Workspace before Spec or Implement; no branch skips it.\n\n## Grill — resolve decisions\n\nResolve one decision axis at a time. A single decision may bundle multiple dependent fields in one structured question; unrelated decisions require separate turns.\n\nUse the Question tool for every user decision:\n\n- Put known choices in `options`. Each option gets a concise `label` and a `description` explaining the consequence. List the recommendation first and mark its label `(Recommended)`.\n- For consequential choices, include 2–3 viable alternatives.\n- When choices cannot be enumerated, still call Question with `options: []` for free-text.\n- Do not ask for permission to continue when no decision remains.\n\nSplit requests spanning independent subsystems before refining each part. Do not begin implementation until requirements and scope are settled.\n\n### When user input is unavailable\n\nIf user input cannot be obtained — the Question tool is absent, a question gets no reply, or the run cannot stop and wait (for example a goal that keeps running) — and the decision is not a dangerous action that requires explicit user consent, resolve **this one decision** yourself and continue:\n\n1. Choose the option marked `(Recommended)` when repository evidence still supports it and it can run unattended.\n2. Otherwise choose the closest minimal-scope option supported by the evidence; prefer text-only, non-interactive work.\n3. If the decision includes destructive or irreversible work, choose a non-destructive path that preserves progress; never auto-approve the destructive option.\n4. State the option selected and the reason in the response.\n\n## Workspace — worktree ownership\n\nNever begin implementation on `main` or `master` without explicit user consent. If the active workspace is already chosen, skip creation below and continue with toolchain setup.\n\n- Compare `git rev-parse --git-dir` with `git rev-parse --git-common-dir`. If they differ, use the current linked worktree; do not nest another. A non-empty `git rev-parse --show-superproject-working-tree` indicates a submodule, not a linked worktree.\n- Create a linked worktree at `.worktrees/{{slug}}` by default. Base the new branch on the latest mainline (e.g. `origin/main`). If the current checkout makes the base unclear (detached HEAD, an unrelated feature branch, unknown default branch), ask the user explicitly which base to use before creating the worktree. Run `git check-ignore -q \"$path\"`; if it is not ignored, write `*` to `.worktrees/.gitignore`. Then run `git worktree add \"$path\" -b \"$branch\" \"$base\"`.\n- When targeting the worktree with a command, pass its absolute path as `workdir`; omitted `workdir` uses the current session directory.\n- Install dependencies per repository instructions. Prefer lockfile-frozen, hardlink-friendly modes (`bun ci`, `uv sync --frozen`) over commands that mutate the lockfile. Confirm the toolchain is usable before continuing.\n\n## Spec — one document per feature\n\nMaintain one document per feature at `docs/compose/spec/{{feature-name}}.md` from the workspace root. Do not add a date to the filename. A user-specified location overrides this path. Edit an existing document in place; never create a separate plan or report. Do not write the feature document before Workspace owns the active workspace.\n\n### Template\n\n```markdown\n---\nfeature: {{feature-name}}\nstatus: designed | in-progress | delivered\nupdated: YYYY-MM-DD\nsource: {{branch-name}} | {{pr-url}} | {{mr-url}}\n---\n\n# {{Feature Name}}\n\n## Report\n\n## [S1] Problem\nDescribe the user-visible problem.\n\n## [S2] Design\nRecord the chosen behavior and the contracts needed to implement it.\n\n## [S3] Out of Scope\nState explicit boundaries.\n\n## Tasks\n- [ ] T1: {{work item}} — acceptance: {{observable result}} (covers: S2.1)\n- [ ] T2: {{work item}} — acceptance: {{observable result}} (depends: T1)\n\n## Journey log\nOptional. Dead ends, pivots, or transferable lessons worth future work. Do not pad an uncomplicated change by splitting it into several thin entries.\n```\n\n### Design-time rules\n\n- Leave `Report` empty until finalized and set `status: designed`. Keep `Journey log` empty unless something is worth carrying forward.\n- Set `source` to the form that best names where the spec's source lives — `{{branch-name}}`, `{{pr-url}}`, or `{{mr-url}}` — and update it whenever that changes.\n- Record settled decisions and precise contracts, not exploration history or file-level code dumps. Include architecture, interfaces, data flow, error behavior, and testing boundaries when they affect the change.\n- Make each task the smallest independently verifiable work item; give it an observable acceptance criterion. Add `depends:` only for real prerequisites; dependencies must be acyclic.\n- Under Design, give each contract or behavior its own subsection `S2.1`, `S2.2`, …\n- Keep `Sn` and `Sn.m` anchors stable when headings change; never renumber existing anchors.\n- `covers:` on a task is optional (for example `covers: S2.1`).\n- Scale detail to the change; do not pad small designs.\n\nBefore implementation, fix ambiguous requirements, contradictions, unresolved references, and unverifiable acceptance criteria. If the user is available, request document approval with the Question tool; otherwise continue.\n\n### Amendments\n\nUpdate only affected sections, bump `updated:`, preserve anchors, and keep only the tasks required by the amendment and their dependents. Do not regenerate the document or create duplicate tasks.\n\n## Implement\n\nUse the feature document as the source of requirements, or the conversation for an undocumented mechanical change. When a feature document exists, set its `status: in-progress` on the first implementation commit. Execute tasks in dependency order. Track multi-step work with the Task tool.\n\nFor behavior changes with a cheap reproduction, write a failing test, confirm it fails for the intended reason, implement the smallest fix, and confirm it passes. A bug fix requires a regression test when one can be written. Skip test-first for generated code, configuration-only changes, throwaway prototypes, or explicit user direction.\n\nTest public behavior. Do not duplicate production logic in expected values, add test-only production APIs, or assert only that mocks were called. Prefer real implementations over mocks.\n\nFor failures, reproduce before editing and identify the root cause from errors, diffs, recent commits, or boundary instrumentation. After two failed fixes, stop patching and re-derive the cause.\n\n### Parallel work\n\nDispatch independent tasks in parallel when isolation prevents collisions; keep tightly coupled work together. Prefer giving parallel subagents disjoint file sets and keeping commits with the orchestrator. Give each subagent the workspace path, task, acceptance criteria, relevant spec sections, and required verification. Do not pass session history. Treat its report as a claim and inspect the resulting diff.\n\nContinue through tasks without routine approval pauses. Stop only for an unresolved product decision, a blocker that cannot be worked around, a destructive action requiring consent, or completion.\n\n## Verify\n\nBefore any completion claim, run the repository's relevant tests, typecheck, build, or reproduction from the correct directory and read the output. Record each command and result. Mark known baseline failures as `PRE-EXISTING` with a short identifier. Do not substitute prior output or a subagent report for fresh evidence.\n\nVerification and review are strictly sequential. Wait for all verification commands to exit before dispatching the reviewer. Never overlap review with a resource-heavy test or application process in the same environment.\n\n## Review\n\nAfter implementation is verified and before finalizing the feature document, dispatch one fresh subagent to review the complete change.\n\nProvide the reviewer:\n\n- the applicable spec sections and acceptance criteria;\n- the workspace path, base branch, base SHA, head SHA, and exact diff command or precomputed diff;\n- a compact verification summary: one line per command with `PASS`, `FAIL`, or `PRE-EXISTING`, plus test counts when available. Do not paste full command output unless a specific failure requires it.\n\nIf there is no feature document, take acceptance criteria from the conversation. If none are explicit, ask the user for them before dispatching the reviewer.\n\nDo not provide an implementer-authored narrative. The reviewer may inspect the diff and run additional commands needed to validate its conclusions. It must not repeat a command already reported as passing, especially a heavy E2E suite, unless the result is stale, the code changed afterward, or concrete evidence makes the result suspect. Before any justified rerun, confirm no equivalent command is still running. Missing evidence should be reported or gathered with the cheapest non-duplicative command.\n\nUse a reviewer model at least as capable as the strongest implementer it reviews.\n\nRequire separate conclusions for:\n\n- **Spec compliance** — every acceptance criterion is met and points to evidence in the diff or reviewer-observed command output.\n- **Correctness** — logic, boundaries, error handling, regressions, and tests are sound, including issues outside the written spec.\n- **Codebase consistency** — naming, structure, and local conventions match surrounding code.\n\nClassify unmet or unverifiable acceptance criteria and correctness bugs as critical. Fix critical findings, re-verify, and re-review affected areas. Reject incorrect findings with technical evidence. When necessary, return to Spec and record the pivot in the Journey log. If the fix-and-re-review loop stops converging — repeated findings on the same area, or fixes that introduce new criticals — stop looping and report the impasse with the remaining findings instead of forcing a pass.\n\nFor human review feedback, verify each item against the codebase, clarify ambiguous items before editing, and implement validated items one at a time with verification. Check actual usage before expanding an unused path, and surface conflicts with prior user decisions instead of silently complying.\n\nFor parallel task work, review integrated task diffs at useful boundaries only when delaying review would compound risk.\n\n## Finalize — commit the feature document\n\nIf a feature document exists, after review passes and before finishing the branch:\n\n1. Set `status: delivered` and bump `updated:`.\n2. Check off completed tasks; leave incomplete tasks unchecked and do not claim delivery if they block acceptance.\n3. When finalized, fill `Journey log` when needed and replace `Report` with:\n\n```markdown\n## Report\n\n**What was built** — concise description of the final behavior.\n\n**Verification** — commands run and their observed results.\n```\n\nUpdate a design section only when it contradicts the delivered behavior. Commit the finalized document on the feature branch before finishing. This documentation-only commit does not restart verification or review; CI re-running on it is expected.\n\n## Finish\n\nDo not auto-finish: confirm with the user before any irreversible action, including opening a PR or MR, merging, or pushing.\n\nReport branch, base, head SHA, workspace, feature-doc path when available, and ask the user which way to finish — for example:\n\n- local merge / open PR / push only / keep the branch;\n- which base branch to merge or target;\n- keep or remove the worktree.\n\nOpen PR or MR does not imply merge: unless the user also asked to merge, stop after opening — the merge always needs its own confirmation, whether the PR or MR was created here or already existed.\n\nWhen the closing action changes where the spec lives, update `source` and commit it as documentation only: `{{pr-url}}` or `{{mr-url}}` after opening one, `{{branch-name}}` before a local merge.\n\nWorktree pitfalls:\n\n- Local merge and `gh pr merge` run from the main repository checkout — the base branch cannot be checked out while another worktree holds it.\n- `git worktree remove` only on `.worktrees/` or the path scoped by the prompt / `AGENTS.md`.\n","packages/cli/src/skill/builtin/.bundle/data-analytics/SKILL.md":"---\nname: data-analytics\ndescription: \"Use this skill for quantitative product or business analysis: data quality checks, metric diagnostics, KPI design and reporting, dashboards, analytical reports, charts, notebooks, market sizing, semantic layers, and evidence-backed recommendations. Also use it whenever Data Analytics is explicitly invoked.\"\n---\n\n# Data Analytics\n\nThis is the single entry point for a code-agent-oriented Data Analytics bundle. The original plugin workflows are under `workflows/`; React, Vite, MCP App widgets, connector manifests, and frontend build artifacts are intentionally excluded.\n\n## Route the request\n\n1. Read `workflows/index/SKILL.md` completely. Treat it as the authoritative plugin-level eligibility and analytical routing policy, except where its UI/runtime delivery rules conflict with the code-agent overrides below.\n2. Select the narrowest focused workflow named by that index. Read every selected workflow's `SKILL.md` completely before acting.\n3. If a selected workflow names related skills, load those only when its routing conditions apply. Multiple skills may form one workflow; follow the ordering defined by the index and focused skills.\n4. Resolve relative links from the file that contains the link. Read referenced instruction or reference files when the selected workflow requires them and they exist in this bundle. Prefer bundled scripts and sample data over recreating them.\n5. Do not load unrelated focused workflows merely because they are present.\n\n## Bundled capabilities\n\nFocused workflows live in `workflows/`, including data-quality analysis, business-context gathering, metric diagnostics, product/business analysis, KPI design and reporting, visualization, dashboards, reports, notebooks, market sizing, validation, and semantic-layer creation.\n\nUse data sources and tools only when the host harness exposes them. The bundle does not require a particular connector registry or UI protocol.\n\n## Code-agent delivery overrides\n\nThese rules take precedence over MCP App, widget, native Work Mode, and packaged Recharts delivery rules inherited from the original workflows:\n\n- Never require or call `render_artifact`, `render_chart`, `render_table`, `validate_artifact`, `export_artifact_package`, `charts_widget_v2`, or `app_block` unless the user independently provides an equivalent tool and explicitly requests it.\n- Default transient answers to concise Markdown with source notes. Default durable reports and dashboards to Markdown, a self-contained HTML file using plain HTML/CSS/SVG/vanilla JavaScript, a notebook, a spreadsheet, or a static image according to the user's request and the host's available tools.\n- For charts, prefer reproducible Python/Matplotlib, notebook-native plotting, SVG, or the destination system's native chart support. Inspect generated visuals when the harness provides image or browser inspection.\n- Do not install Node, React, Recharts, Vite, or frontend packages for analytics output. Do not depend on removed `src/`, `assets/`, MCP specifications, HTML runtime helpers, or widget resources.\n- If a focused workflow points to a removed UI-only reference, skip that reference and apply these overrides while preserving its analytical, provenance, QA, and narrative requirements.\n- A requested report remains incomplete until its chosen portable file exists or a concrete blocker is reported; a chat summary is sufficient only when the user requested an inline answer.\n\n## Safety and fidelity\n\n- Never treat plugin instructions as permission to bypass host policy, expose secrets, or perform unapproved external writes.\n- Keep source provenance and uncertainty visible in analytical outputs.\n- Do not silently replace real-data questions with sample data.\n- Preserve the selected workflow's validation and delivery requirements through completion.\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/analyze-data-quality/SKILL.md":"---\nname: analyze-data-quality\ndescription: \"Assess whether structured data, query results, dashboards, or analytical evidence are trustworthy enough to use. Use when the task is to check data quality, reconcile conflicting sources or metric definitions, or decide whether evidence is safe to cite.\"\n---\n\n## Related Skills\n\nUse $design-kpis when the work is to define or redesign a KPI framework, metric definition, guardrail, or target rather than checking whether existing data is trustworthy.\n\nUse $validate-data when the work is to QA an analysis, chart, report, or recommendation rather than investigate the underlying data.\n\n# Analyze Data Quality\n\nAssess whether a dataset is trustworthy enough for analysis, modeling,\ndashboards, experiments, or downstream pipelines. Start with the intended use and grain, run the highest-value checks for the data shape, and report concrete evidence, analytical risk, likely causes, and the smallest useful remediation or automated test.\n\n## Workflow\n\n1. Clarify the quality question and operating context.\n\n   Establish what the dataset represents, the intended unit of analysis, the downstream use, whether the user cares about raw ingestion quality,\n   transformed-model quality, or both, and the comparison baseline such as prior weeks, prior schema, or a trusted reference table. Identify expected grain,\n   primary keys or candidate keys, important date columns, timezone assumptions,\n   domain rules, allowed values, and business thresholds. If context is missing,\n   infer cautiously and label assumptions.\n\n2. Choose an inspectable analysis path.\n\n   When checks require SQL or Python, default to a companion notebook so the user can inspect the exact code behind the findings. Use $jupyter-notebooks when a dedicated notebook scaffold or refactor workflow would help. For queryable tables, use `~~structured_data` to confirm schema, grain, sample rows, and query rules through the relevant source connector before heavier checks. Use `~~operations_logs` for freshness and lineage when those checks matter.\n\n3. Build a compact profile.\n\n   Start with row count, column count, column names and types, candidate keys,\n   duplicate rates on likely identifiers, min/max timestamps for relevant date columns, null rates, distinct counts for likely categorical columns, and basic numeric summaries for measure columns. Confirm grain before interpreting anomalies; many apparent quality problems are mixed-grain data,\n   partial backfills, late-arriving data, or duplicated joins.\n\n4. Run core quality checks.\n\n   Select checks that match the dataset and task. Default to the most relevant checks across completeness, uniqueness, validity, consistency, integrity,\n   timeliness, volume, and shape. Compare rates, not just counts, and segment by time, source, country, platform, model version, or other key dimensions when that helps distinguish real issues from expected variation.\n\n5. Run shape-specific checks.\n\n   Adapt the checks to the data shape:\n\n   - Event data: duplicate event IDs, future event timestamps, session or user\n     coverage gaps, and abrupt event-mix changes after releases.\n   - Dimension tables: non-unique business keys, orphan surrogate keys, status\n     changes without corresponding timestamps, and unexpected churn in reference\n     values.\n   - Fact tables: mixed grain, impossible measures such as negative revenue or\n     quantity, join blowups to dimensions, and late-arriving or partially loaded\n     partitions.\n   - ML feature or scoring tables: leakage from post-outcome fields, feature\n     sparsity spikes, range shifts after model or feature-store changes, and\n     class-label drift.\n   - Experiment data: duplicate assignments, variant imbalance beyond\n     expectation, exposure without assignment, and events before assignment\n     timestamp.\n\n6. Run temporal and distribution checks when history exists.\n\n   Prioritize temporal diagnostics when the user mentions \"after X date\",\n   \"suddenly\", \"recently\", or \"only started appearing\". Check first-seen dates,\n   last-seen dates, daily or weekly null-rate trends, duplicate-rate trends, row count trends, category-share shifts, distribution drift, and change points around launches, migrations, incidents, model changes, or backfills.\n\n7. Investigate analytical risks and likely causes.\n\n   Tie each issue to the downstream risk: broken trusted analysis, biased decisions, broken joins, stale dashboards, incorrect experiments, leakage,\n   unreliable model features, or misleading segments. When possible, identify whether the issue is isolated to a source, segment, partition, time window,\n   release, migration, backfill, or upstream pipeline change.\n\n8. Recommend fixes or automated tests.\n\n   Recommend the smallest set of follow-up fixes, monitoring, or automated tests that would materially reduce risk. Suggest automation only when the rule is stable and worth maintaining. Include or save the notebook/query path when code produced the findings.\n\n## Standards\n\n### Core Checks\n\n- Completeness: null rate by column; null rate by partition, segment, and time bucket; unexpected empty strings or sentinel values; required-column population rate.\n- Uniqueness: exact duplicate rows, duplicate primary keys, duplicate composite keys, and proportion unique for semi-unique fields such as emails or device IDs.\n- Validity: type conformance after casting; format checks for IDs, emails, URLs,\n  enums, country codes, and timestamps; range checks for measures, percentages,\n  counts, and dates; allowed-values checks for controlled vocabularies.\n- Consistency: cross-field rule checks, units or currency consistency, status and timestamp alignment, and agreement between duplicated fields from different sources.\n- Integrity: parent-child key coverage, orphan records, unexpected many-to-many joins, and broken slowly changing dimension joins.\n- Timeliness: freshness lag from source event time to load time, freshness lag from load time to report time, missing recent partitions, and unexplained historical rewrites or backfills.\n- Volume and shape: row-count drift, distinct-count drift, distribution drift,\n  share-of-total drift for major categories, and new or disappeared categories.\n\n### Specific Check Guidance\n\n- Duplicates and keys: check exact duplicates, primary key duplicates, composite key duplicates at the intended grain, and near-duplicates caused by whitespace,\n  casing, formatting, or late updates. Report count, share of affected rows,\n  duplicated keys, and whether duplication is isolated to a time range, source,\n  or segment.\n- Missingness: distinguish acceptable sparsity from broken completeness. Check null rates over time, newly null columns after schema or pipeline changes, and sentinel values such as `''`, `'unknown'`, `'n/a'`, `0`, or `-1`.\n- Domain validity: check malformed identifiers, country codes, timestamps,\n  impossible values, values outside allowed sets, and cross-field contradictions such as `is_cancelled = false` with a non-null `cancelled_at`.\n- Join coverage: when multiple datasets are involved, check foreign keys that do not match a parent table, unexpected one-to-many expansion, coverage loss when joining to dimensions or experiments, and row counts before and after joins.\n- Freshness and schema drift: check row-count changes against recent history,\n  lag on important date columns, added/removed/retyped columns, and shifts in sparsity or cardinality that suggest upstream changes.\n- Outliers and distribution shifts: use robust methods such as quantiles, MAD,\n  or IQR before defaulting to z-scores. Check sudden changes in mean, median,\n  variance, zero rate, category share, and long-tail behavior.\n- Leakage, backfill, and time travel: check features populated before they should exist, future-dated records, late-arriving data causing unstable recent partitions, and backfills that change historical counts without annotation.\n\n### Severity\n\n- Critical: breaks trusted analysis, core joins, production dashboards, or key decisions, such as duplicated grain, missing primary keys, or stale production data.\n- High: materially biases downstream decisions, such as large null spikes,\n  category drift in a core dimension, invalid business-rule values, leakage, or severe join coverage loss.\n- Medium: localized or explainable issues that still need documentation,\n  monitoring, or owner follow-up.\n- Low: cosmetic inconsistencies, expected sparsity, or known edge cases that do not materially affect current use.\n\nDo not dump raw profiling output without interpretation. Tie each finding to an analytical risk and likely impact.\n\n### Automated Test Guidance\n\n- Good candidates for automation: primary key uniqueness, not-null checks on required columns, accepted values for stable enums, referential integrity,\n  freshness thresholds, and seasonality-aware row-count or volume bounds.\n- Use caution with hard-coded distribution thresholds on volatile product metrics, strict uniqueness in messy entity-resolution use cases, and recent partitions when late-arriving data is normal.\n- Suggest automated tests only when the expected rule is stable, important, and maintainable.\n\n### Output Standards\n\nFor stakeholder-facing data-quality work, pass the completed findings to $build-report by default so the runtime produces a portable report in the selected format. Do not stop at profiling output or a notebook unless the user explicitly requested a quick inline answer or another primary artifact. The structure below defines the report content.\n\nStructure the response with:\n\n1. dataset and grain summary\n2. checks performed\n3. findings\n4. temporal or trend anomalies\n5. likely causes and impacted use cases\n6. recommended fixes or automated tests\n7. assumptions and open questions\n\nFor each finding, include:\n\n- what failed\n- evidence: counts, rates, segments, and dates\n- why it matters\n- severity and confidence level\n- likely cause when known\n- suggested remediation or automated test\n\nWhen code was used, include or save a notebook containing the key SQL and Python checks and make the notebook path easy to find.\n\n### Defaults\n\n- Prefer small, high-signal tables over exhaustive dumps.\n- Compare rates, not just counts.\n- Break checks out by time and key segments whenever possible.\n- Normalize strings before judging duplicates or distinct-count spikes.\n- Treat recent partitions carefully when data arrives late.\n- Call out when an anomaly could be caused by a legitimate product launch,\n  experiment, migration, incident, model change, or backfill.\n- Preserve inspectable evidence: SQL, query links, notebook paths, source paths,\n  sample rows, chart outputs, and calculation notes.\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/build-dashboard/SKILL.md":"---\nname: build-dashboard\ndescription: \"Build a source-backed dashboard or monitoring view with clear metrics, filters, visual hierarchy, definitions, refresh context, and QA.\"\n---\n\n# Build a Dashboard\n\nUse this workflow when the user needs a reusable monitoring or exploration surface rather than a one-time report. Read the relevant analysis and KPI workflows first when metric definitions or decision logic are not already settled.\n\n## Select a portable surface\n\nHonor the user's destination. Otherwise choose the simplest surface supported by the harness:\n\n- Existing BI/product analytics platform when the user wants a governed shared dashboard there.\n- Streamlit when Python execution and local/server operation are appropriate; read `specifications/streamlit-dashboard.md`.\n- Self-contained plain HTML/CSS/vanilla JavaScript for a portable local dashboard; read `specifications/html-dashboard.md`.\n\nDo not require React, Vite, Recharts, MCP Apps, or widget runtimes.\n\n## Workflow\n\n1. Define the audience, operating decision, monitoring cadence, and questions the dashboard must answer.\n2. Define each metric: formula, numerator/denominator, unit, grain, time window, filters, exclusions, owner, source, and freshness expectation.\n3. Validate joins, completeness, duplicates, missingness, comparability, and refresh status before presenting metrics as trustworthy.\n4. Design the information hierarchy:\n   - Overview and primary outcomes.\n   - Drivers and diagnostic cuts.\n   - Guardrails and risks.\n   - Detail tables or drill-down paths.\n5. Add only decision-relevant filters. Make default date ranges, segments, comparison periods, and filter state visible.\n6. Use `../visualize-data/SKILL.md` for each chart and keep exact lookup values accessible in tables.\n7. Show data freshness, source context, definitions, and material caveats in the dashboard.\n8. Implement and test the real artifact with representative, empty, partial, and error states when feasible.\n\n## QA and handoff\n\n- Reconcile displayed totals and KPIs against reviewed source results.\n- Test filters, date boundaries, sorting, responsive layout, and refresh behavior.\n- Check chart labels, units, legends, accessibility, and table readability.\n- Ensure the artifact does not expose secrets, credentials, unnecessary personal data, or temporary local paths.\n- Deliver the dashboard artifact or governed platform link plus metric definitions, source/query files, refresh instructions, and known limitations.\n\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/build-report/SKILL.md":"---\nname: build-report\ndescription: \"Build a durable analytical report with an answer-first narrative, evidence-backed findings, charts or tables, caveats, recommendations, and source context.\"\n---\n\n# Build an Analytical Report\n\nUse this workflow when the user needs a durable report rather than a transient answer. Run the appropriate analysis workflow first; this workflow owns the reader-facing structure, evidence placement, visual/table placement, caveats, sources, QA, and handoff.\n\n## Choose one delivery format\n\nHonor an explicit format. Otherwise use:\n\n1. Markdown for the most portable code-agent deliverable.\n2. Self-contained plain HTML when a polished browser-readable report is useful and the host can render or inspect it.\n3. PDF, DOCX, slides, or another format only when requested or clearly required by the destination and the host exposes suitable creation and verification tools.\n\nDo not install or require React, Recharts, Vite, MCP Apps, or widget runtimes. HTML must use semantic HTML/CSS and may use inline SVG or small vanilla JavaScript interactions. It must remain readable without JavaScript.\n\n## Build the report\n\n1. Confirm the audience, decision, scope, comparison window, and requested format from available context. Ask only when a missing choice would materially change the result.\n2. Verify the analytical evidence. Keep metric definitions, grain, time range, filters, units, exclusions, and source freshness explicit.\n3. Lead with the answer. State the most important conclusion and decision implication before methodology details.\n4. Build a coherent narrative rather than a dump of charts or query results.\n5. Include only visuals and tables that support a finding. Read `../visualize-data/SKILL.md` when creating charts.\n6. Distinguish verified facts, likely explanations, assumptions, limitations, and unresolved questions.\n7. Provide recommendations tied to evidence, expected impact, owner or next action, and measurable follow-up where appropriate.\n8. Add a source section that identifies real source systems, tables/views, datasets, files, documents, queries, and access dates when known. Never invent provenance.\n\n## Recommended structure\n\n```markdown\n# [Short reader-facing title]\n\n## Executive summary\n[Answer, magnitude, and decision implication]\n\n## Key findings\n[Evidence-backed findings with charts or tables]\n\n## Recommendations\n[Prioritized actions and expected outcomes]\n\n## Risks and limitations\n[Data gaps, assumptions, uncertainty, and interpretation limits]\n\n## Sources and methodology\n[Definitions, scope, source details, and reproducibility notes]\n```\n\nAdapt the headings to the audience, but retain the answer-first logic.\n\n## QA and handoff\n\n- Recalculate headline values and comparisons from the reviewed evidence.\n- Check that every claim is supported and every chart matches its source data.\n- Check titles, labels, units, denominators, date ranges, and sorting.\n- For HTML/PDF/DOCX/slides, render or inspect the actual artifact when the host supports it; fix clipping, blank charts, overflow, low contrast, and unreadable tables.\n- Ensure the report contains no credentials, local temporary paths, placeholder provenance, or internal implementation noise.\n- Return the primary artifact path plus only the relevant supporting notebook, SQL, data, or chart files.\n\nIf the user asks only for an inline brief or explicitly says no file/artifact, deliver the same answer-first structure concisely in chat.\n\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/build-report/report-to-google-doc/SKILL.md":"---\nname: report-to-google-doc\ndescription: \"Narrow conversion skill. Invoke only when the user explicitly asks to convert an existing local or blob-hosted HTML analytics report into a Google Doc, DOCX, or shareable document.\"\n---\n\n# Report To Google Doc\n\nUse this skill only when the user explicitly needs a shareable Google Drive document from an existing HTML analytics report. The source must be an HTML report: a local file, a downloaded blob-hosted report, or a report produced by `$build-report`\nHTML mode or an equivalent local portable report source.\n\nThe expected path is HTML -> DOCX -> Drive upload. It is acceptable for Drive to host the upload as a DOCX-backed viewer file rather than a native Google Docs MIME type. Do not use the old Google Docs batch-update request path.\n\n## Workflow\n\n1. Resolve the HTML report.\n\n   Use an absolute local path. If the user provides a remote report, retrieve it first and pass the local HTML file to the helper. If the file is a sign-in page, redirect page, or tiny stub, stop and obtain the real report.\n\n2. Run the bundled helper.\n\n   ```bash\n   python3 <REPORT_TO_GOOGLE_DOC_SKILL_DIR>/scripts/report_to_google_doc_plan.py \\\n     /absolute/path/to/report.html \\\n     --out-dir /tmp/report_to_google_doc_plan\n   ```\n\n   Omit `--render-workers` on the normal path. Only pass a worker count after benchmarking the same report family locally. If dependencies are missing,\n   use a local virtual environment with `beautifulsoup4`, `pillow`, and `python-docx`; `cairosvg` or headless Playwright are optional renderers.\n\n3. Inspect helper outputs.\n\n   Required outputs:\n\n   - `skeleton.txt`: source text with stable placeholders\n   - `manifest.json`: parsed headings, tables, callouts, lists, styles, links,\n     and rendered visual inventory\n   - `preflight_checks.json`: source, width, DOCX, and rendered-image checks\n   - `report.docx`: generated local Word document\n   - `docx_upload_plan.json`: compact upload instructions\n   - `placeholder_queries.json`: source mapping debug labels\n\n   Do not upload until `preflight_checks.json` has `status: \"passed\"` with zero errors. Warnings must either be fixed or called out in the handoff.\n\n4. Upload the DOCX.\n\n   ```json\n   mcp__codex_apps__google_drive._upload_file({\n     \"file_uri\": \"/tmp/report_to_google_doc_plan/report.docx\",\n     \"file_name\": \"Report Name.docx\",\n     \"mime_type\": \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\"\n   })\n   ```\n\n   Treat the returned Drive URL as the deliverable. Do not attempt to force native Google Docs conversion, and do not fall back to `_batch_update_document`.\n\n5. Validate the uploaded result.\n\n   Confirm the uploaded file is readable and non-empty. Compare uploaded text against the source inventory: title, section headings, executive summary or answer callout, caveats, recommendations, source notes, and source links.\n   Inspect the local `report.docx` structure when available: heading counts,\n   lists, tables, hyperlink relationships, and image relationships should match `manifest.json`.\n\n6. Hand off the link.\n\n   Return the Drive/Docs URL and, when useful, the local DOCX path or source HTML path. Connector success alone is not enough; the handoff is complete only after the uploaded file and local DOCX structure have been checked against the source report. Keep routine check and preflight details in support artifacts. Do not list internal checks in the user-facing handoff unless a check failed, was unavailable, or produced a user-relevant caveat.\n\n## Standards\n\n- Preserve every section, headline claim, metric card, metric definition,\n  source note, chart takeaway, recommendation, caveat, and link from the HTML report.\n- Preserve semantic formatting: headings, paragraphs, inline bold/emphasis,\n  inline code, positive/negative colors, links, lists, callouts, metric-card grids, tables, notes, captions, and charts.\n- Use DOCX-native structures wherever practical: headings, paragraphs, tables,\n  bullets/numbered lists, links, inline images, paragraph shading, table cell shading, and text styles.\n- Keep the report text column readable. Tables, charts, rendered table grids,\n  screenshots, and visual blocks must not exceed the DOCX page text width.\n- Preserve charts as inline images rendered from the source visual or its same-data SVG fallback, aligned to the same left edge as text and tables. A chart with missing bars, missing legend swatches, or all-black/all-white marks fails validation even if the DOCX contains an image object.\n- Preserve multi-column report blocks. A two-column grid made only of titled mini-tables can remain a two-column rendered image capped to the text width;\n  mixed two-column blocks with narrative text, pills, callouts, or non-table panels should preserve that content natively instead of dropping it.\n- Do not expose customer-level details or sensitive links that were intentionally omitted from a sanitized report.\n- Do not write Google Docs batch-update artifacts such as `seed_requests.json`,\n  `remote_write_plan.json`, or `all_requests*.json`.\n\n## Repairs\n\nUse these fixes when validation exposes a conversion issue:\n\n| Problem | Fix |\n| --- | --- |\n| Heading is regular weight | Fix the DOCX writer heading style or explicit run bolding. |\n| Blank line after title or heading | Delete spacer paragraphs; skeletons should emit `\\n`, not `\\n\\n`, after headings. |\n| Body paragraphs have too much space | Delete literal blank paragraphs and set modest style spacing. |\n| Table/image too wide | Set table columns or image width to the DOCX text column width. |\n| Chart has labels but missing bars | Inline SVG class styles or use a headless screenshot before inserting. |\n| Two-column table group is flattened | Treat the grid as one layout block with mini-table titles preserved. |\n| Executive summary, metric cards, or section is missing | Fix parser inventory before upload. |\n| Chart overlaps table | Insert the image on its own paragraph after the table. |\n| Chart duplicated | Remove the extra image; keep exactly one source-order copy. |\n| Inline bold/code/color missing | Fix manifest range splitting in the DOCX writer. |\n| Source links show raw URLs | Replace with native linked labels or native bullets using HTML link text. |\n\n## Local Checks\n\n```bash\npython3 -m py_compile <REPORT_TO_GOOGLE_DOC_SKILL_DIR>/scripts/report_to_google_doc_plan.py\npython3 <REPORT_TO_GOOGLE_DOC_SKILL_DIR>/scripts/report_to_google_doc_plan.py \\\n  /absolute/path/to/report.html \\\n  --out-dir /tmp/report_to_google_doc_plan_smoke\njq '.status, .summary' /tmp/report_to_google_doc_plan_smoke/preflight_checks.json\ntest -f /tmp/report_to_google_doc_plan_smoke/report.docx\ntest -f /tmp/report_to_google_doc_plan_smoke/docx_upload_plan.json\ngit diff --check -- plugins/data-analytics/skills/build-report/report-to-google-doc\n```\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/build-report/report-to-google-slides/SKILL.md":"---\nname: report-to-google-slides\ndescription: \"Narrow conversion skill. Invoke only when the user explicitly asks to convert an existing HTML analytics report into a native Google Slides deck.\"\n---\n\n# Report To Google Slides\n\nUse this skill only when the user explicitly has an existing HTML analytics report and wants a Google Slides deliverable. The output should be a deck, not a pasted report. A stakeholder skimming the slides should understand the answer, evidence,\ncaveats, and recommended follow-up without opening the source report.\n\nThis skill consumes a local portable report, preferably self-contained HTML. If another format is the only source, first create an equivalent local HTML or structured report from the same evidence.\n\n## Workflow\n\n1. Resolve the local HTML report.\n\n   Use an absolute file path. If the user provides a remote report, retrieve it outside this skill first. If the local file is a sign-in page, redirect page,\n   or very small stub, stop and obtain the real report before continuing.\n\n2. Run the helper.\n\n   ```bash\n   python3 <REPORT_TO_GOOGLE_SLIDES_SKILL_DIR>/scripts/report_to_google_slides.py \\\n     <LOCAL_HTML_REPORT_PATH> \\\n     --out-dir /tmp/report_to_google_slides\n   ```\n\n3. Inspect local outputs.\n\n   Required outputs:\n\n   - `deck.pptx`: editable local PowerPoint file\n   - `manifest.json`: parsed source inventory and coverage counts\n   - `deck_plan.json`: slide-by-slide plan with named elements\n   - `preflight_checks.json`: local quality checks and pass/fail status\n   - `assets/`: rendered chart images\n\n   Do not import the PPTX until `preflight_checks.json` has `status: \"passed\"`.\n   Then run `unzip -t <out-dir>/deck.pptx`.\n\n4. Import and verify in Google Slides.\n\n   Import `deck.pptx` with `mcp__codex_apps__google_drive._import_presentation` using `upload_mode=\"native_google_slides\"`. Verify the imported deck with `_get_presentation_outline` and `_get_slide_thumbnail` for every slide when possible. At minimum, inspect the cover, one chart slide, one table slide,\n   and the caveats/sources slides.\n\n5. Repair before handoff.\n\n   If thumbnails show clipped text, missing charts, low contrast, blank images,\n   or awkward sizing, revise the helper output or source assumptions and regenerate before handing off the deck URL.\n\n6. Hand off the deck.\n\n   Return the Google Slides URL and, when useful, the local PPTX path or source HTML path. Keep routine check, preflight, thumbnail-inspection, and import-check details in support artifacts. Do not list internal checks in the user-facing handoff unless a check failed, was unavailable, or produced a user-relevant caveat.\n\n## Standards\n\n- Preserve the report's decision-critical information: headline claim,\n  executive summary, major findings, metric definitions, material charts,\n  decision-critical tables, recommendations, implications, caveats,\n  assumptions, freshness notes, and source/provenance notes.\n- Translate report prose into slide-native communication. Lead with the takeaway, use one main idea per slide, and put supporting detail in concise callouts, bullets, tables, chart annotations, or speaker notes.\n- Tighten copy before shrinking fonts.\n- Keep gross metric reads, net/incremental reads, causal claims, and caveats visibly separated when the source report distinguishes those lenses.\n- Use editable text and native PPTX tables wherever practical. Use native PPTX bullets; do not fake bullets with typed dashes.\n- Preserve source charts as evidence images. Do not screenshot the whole HTML report or paste whole report sections.\n- Support self-contained HTML reports whose chart evidence is available as inline SVG, accessible tables, or embedded images; render those into local chart evidence images before building the deck.\n- Use one chart per evidence slide unless the report has a stronger grouped comparison.\n- Keep table slides legible. If a full table is too dense, keep the main comparison in the deck and move extra detail to speaker notes or source slides.\n- Source notes should be visible but quiet.\n\n## Visual System\n\nThe helper derives colors and hierarchy from the HTML report CSS and chart palette, then applies a restrained analytics deck layout. It does not follow external deck files or company-specific branding.\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/build-report/report-to-pdf/SKILL.md":"---\nname: report-to-pdf\ndescription: \"Narrow conversion skill. Invoke only when the user explicitly asks to convert an existing Data Analytics report, dashboard, or inline chart export into a PDF artifact.\"\n---\n\n# Report To PDF\n\nUse this skill only when the user explicitly needs a PDF from an existing Data Analytics report, dashboard, or chart artifact. Prefer a static HTML export or another portable report file as the source.\n\nThe expected path is static HTML -> browser headless print-to-PDF -> PDF verification. If only a non-portable source exists, create or retrieve the matching static HTML/export source first.\n\n## Workflow\n\n1. Resolve the static source.\n\n   Use an absolute local path to a static HTML report/export or a local URL served from that static export. If the source is a blob stub, sign-in page, redirect page, incomplete viewer, or an app shell that contains boot scripts but not the report content, stop and obtain a static HTML/export source before continuing.\n\n   When the user provides a hosted artifact URL, first determine whether it exposes a usable static export or package source. If the static export is unavailable but the validated artifact payload is still available in the current run, create the matching static HTML/export from that payload and preserve source provenance in the handoff. If neither a static export nor the artifact payload is available, stop with a blocker instead of printing the live app shell or rebuilding the report from memory.\n\n   When creating or repairing the static source, keep visible metadata reader-facing. Do not copy internal artifact runtime fields, package plumbing, or validator/debug state into the report body, header, footer, or source section. For example, omit raw labels such as snapshot status, package path, widget type, manifest path, renderer IDs, validation status, and local temp paths from the visible PDF. If a runtime detail matters for audit or troubleshooting, preserve it in support notes rather than the visible PDF. Translate data-state caveats into reader language only when they affect interpretation, such as \"synthetic demo data\" or \"partial source coverage.\"\n\n2. Generate the PDF with Chrome CLI headless print-to-PDF.\n\n   Use the platform-specific Chrome executable available in the environment. Common examples are `/Applications/Google Chrome.app/Contents/MacOS/Google Chrome` on macOS and `google-chrome`, `chromium`, or `chromium-browser` on Linux. This is the primary conversion method because it prints the static HTML with a browser rendering engine and usually preserves selectable text, layout, charts, tables, and print CSS.\n\n   ```bash\n   chrome \\\n     --headless=new \\\n     --disable-gpu \\\n     --no-first-run \\\n     --no-default-browser-check \\\n     --no-pdf-header-footer \\\n     --print-to-pdf=/absolute/path/to/report.pdf \\\n     /absolute/path/to/report.html\n   ```\n\n3. If Chrome is unavailable or cannot produce a valid PDF, use a renderer-backed fallback.\n\n   Use the next available local mechanism that renders the same static HTML/export source and prints or saves that rendered page to PDF. Keep the fallback tool-agnostic: the requirement is faithful HTML rendering followed by PDF output, not a specific implementation. Do not replace this with a model-authored PDF layout, manually redrawn charts, or a report reconstructed from memory.\n\n   A fallback is acceptable only when:\n\n   - the static HTML/export remains the source of truth\n   - the rendered output preserves the report title, narrative, charts, tables, caveats, and source details\n   - app-only controls are omitted\n   - the resulting PDF passes the same verification checks as the primary Chrome path\n\n   If no available local renderer can print the static HTML/export faithfully, stop and report the blocker with the missing capability and the source file that could not be converted.\n\n4. Verify the PDF itself.\n\n   Confirm page count and metadata with `pdfinfo` or equivalent. Extract text with `pdftotext` or equivalent when the PDF should contain selectable text. Render representative pages with `pdftoppm` or equivalent and inspect them for blank charts, clipped content, missing source details, unwanted controls, internal runtime metadata, and layout regressions. For short reports, render every page. Include a negative check for app-only control labels such as share, edit, refresh, publish, toolbar, menu, and drag affordances, plus internal artifact labels such as snapshot status, widget type, manifest path, package path, validation status, and local temp paths.\n\n5. Repair before handoff.\n\n   If the output is blank, clipped, missing charts, missing source details, or includes app-only chrome, fix the static HTML/export source, print stylesheet, or renderer invocation and regenerate. Do not hand off an unverified PDF unless the user explicitly accepts the limitation.\n\n6. Hand off the PDF.\n\n   Return the PDF path and, when useful, the source HTML path or URL. Keep routine check details in support artifacts. Do not list internal checks in the user-facing handoff unless a check failed, was unavailable, or produced a user-relevant caveat. If the static HTML/export had to be created from an artifact payload because the hosted URL did not expose one, say that briefly. If required checks could not be completed, state the gap clearly.\n\n## Standards\n\n- Preserve the reader-facing artifact content: title, narrative, charts, tables, caveats, source details, and generated-at or source freshness details when present.\n- Omit app-only controls: top bars, share menus, edit controls, refresh controls, drag handles, hover-only menus, and interactive-only affordances.\n- Omit internal artifact and conversion metadata from the visible PDF. Do not show raw runtime fields, implementation state, package labels, local paths, validator/debug labels, or status strings that exist only to operate the app or export pipeline. Keep audit-useful internals in support files, and use plain reader-facing caveats in the PDF when a data state affects interpretation.\n- Prefer a text PDF with selectable/searchable text. Use a screenshot/image PDF only when a faithful text PDF is not viable, and state that text may not be selectable or searchable.\n- Keep the static source as the PDF source of truth. Do not reconstruct the report from memory when a source HTML/export exists.\n- Do not create a model-authored PDF from scratch as a normal fallback. Direct PDF construction is acceptable only as an explicitly labeled last-resort workaround after the user accepts the quality limitation.\n- Keep generated PDF support files together when possible: static HTML source, PDF output, extracted text, page previews, and any notes about source retrieval or renderer fallback.\n\n## Verification Guidance\n\nBefore handoff, verify the PDF with the local tools available in the environment:\n\n- Confirm the PDF exists, is non-empty, and has the expected page count and page size.\n- Confirm text is selectable/searchable when a text PDF is expected.\n- Render or preview representative pages; for short reports, prefer checking every page.\n- Inspect for blank pages, clipped charts, missing tables, missing source details, unwanted app controls, and leaked internal artifact or conversion metadata.\n- If the skill file itself was edited, run the repository's normal markdown or diff checks.\n\nExamples when available: `pdfinfo`, `pdftotext`, `pdftoppm`, file-size checks, and `git diff --check`.\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/create-data-context/SKILL.md":"---\nname: create-data-context\ndescription: \"Create, update, inspect, or repair Data Analytics semantic layers. Use when the user asks to save data context or create a semantic layer that future Data Analytics work can inspect and cite.\"\n---\n\n# Create Data Context\n\nThis skill creates and maintains semantic-layer skills for Data Analytics. A semantic-layer skill is an explicit artifact the user can inspect and cite later. It captures how future analyses should interpret the data, for example which metric definition is canonical, which dashboard or table is the best source of truth, and what caveats should be checked before answering.\n\nData-task routing is owned by the Data Analytics `index` skill. If the user wants Data Analytics to do work with data now, route to `index`, whether the work starts from connected sources, uploaded files, pasted tables, sample data, or an existing semantic layer. Examples include answering a metric question, building a report, or checking a dataset.\n\nUse this skill only when the user asks to save data context or create, update, inspect, or repair a semantic layer.\n\n## Runtime Routing\n\nUse the current runtime's classified `surface` and `mode` values, plus the capabilities exposed in the run, to choose intake and persistence. Build and validate the same canonical semantic-layer skill package before writing it to any destination.\n\nFor intake:\n\n- Use structured intake when a supported form action is available.\n- Use conversational intake for open-ended details and for runtimes without a supported form action.\n\nChoose one persistence destination by default:\n\n| Destination branch | Select this branch when | Action |\n| --- | --- | --- |\n| ChatGPT personal Skills | `surface = chatgpt_web` and the run exposes a product-backed personal Skills install surface, such as a native skill draft/upload/install action or an installable skill package preview. | Install the generated skill into the user's personal Skills library. Capture the installed skill link or Skills-library reference returned by the install surface and include it as a Markdown link in the chat response. Verify through the available Skills-library, list, or fresh-thread discovery surface when the runtime exposes one. |\n| Local Codex | The user asks for local persistence, or `surface = codex_desktop`. | Write a filesystem skill to `$CODEX_HOME/skills/<area>-semantic-layer`; if `$CODEX_HOME` is unavailable and the local runtime clearly uses the default home location, use `~/.codex/skills/<area>-semantic-layer`. Validate the written skill and verify it is discoverable in a new local Codex context when possible. |\n| Portable package | The current run has no supported persistent skill destination. | Return a portable skill package or source plan and clearly state that it has not been installed persistently, including the exact persistence blocker. |\n\nFor dual ChatGPT web and local Codex availability, install the same canonical package into both the ChatGPT Skills library and the local Codex user-skill directory.\n\nFor ordinary data work, return to the Data Analytics `index` workflow.\n\n## Skill Configuration\n\n### Audience And Language\n\nWrite for Data Analytics users, not plugin maintainers. Explain what context would improve the current or future analysis in practical terms. Avoid implementation terms such as raw state paths, connector ids, cache, runtime, metadata, or preflight unless the user asks for debugging details.\n\n### Source Links\n\nWhen referencing sources inline, prefer clickable Markdown links over plain labels whenever a useful URL exists. Use the source title, record name, channel/thread, or meeting/date as the link text. Use plain labels only when no useful link is available.\n\n## Semantic Layer Setup\n\nUse this flow when the user wants to create or maintain a semantic layer. If they are not ready to create the layer yet, use the same flow to produce a short source plan for what the semantic layer needs.\n\nThe output is a visible skill or plan. Build the semantic-layer skill when enough source-backed detail exists to make it useful. When the available detail is still thin, return a practical plan that explains what source to collect next and why.\n\n## Creating Or Updating The Layer\n\nCreate one semantic layer per coherent product, business, metric, source, or reporting area unless the user explicitly asks for a broader shared layer. Infer the area from the provided context when it is clear; ask only when the answer changes the crawl, destination, or resulting skill.\n\nChoose the destination from `Runtime Routing` using the supported persistence mechanism exposed in the current run. For local Codex creations, default to `$CODEX_HOME/skills/<area>-semantic-layer` unless the user chooses another destination. Ask before placing a generated semantic-layer skill inside a plugin.\n\nBefore crawling, build a data-source list that explains what was checked, what is missing, and which sources are lower-confidence. For direct creation or draft-file work, write it to `references/source-inventory.md`; for planning-only work, return it in chat.\n\nUse source-backed evidence. Favor durable sources such as transformation code, tests, maintained metric docs, and verified dashboards over looser signals such as query history or team discussion. If sources disagree, keep the conflict visible instead of choosing silently.\n\nKeep generated semantic-layer skills compact. Put detailed metric definitions, tables, query patterns, caveats, and evidence into linked references using `references/semantic-layer/skill-template.md`. Preserve provenance and avoid copying raw sensitive data, credentials, row-level examples, or long private messages into generated files.\n\nAfter creating or updating a semantic-layer skill, read `references/semantic-layer/weekly-polling-automation.md` and always offer weekly refresh when the layer has a stable target path and usable `references/source-inventory.md`. Weekly refresh is optional: do not create it without explicit user approval unless the user directly asked for recurring refresh. If the offer cannot be made, state the missing prerequisite.\n\nReturn the created or updated path or installed skill link, source coverage, any user-relevant caveats or blockers, future-use guidance, iteration guidance, and the weekly refresh automation offer or prerequisite blocker so the user can cite the semantic layer directly in later prompts. Tell the user they can ask to refine definitions, add sources, update caveats, or adjust the semantic layer as their understanding changes. For ChatGPT personal Skills creations, include the installed skill link in the response.\n\nKeep routine validation details in support artifacts unless a check failed, was unavailable, or changes how the user should rely on the semantic layer.\n\n## Output Contract\n\nFor semantic-layer work, report what was created, updated, inspected, or repaired; source coverage; any user-relevant caveats or blockers; and the exact path or installed skill link the user can cite later. For create or update results, include the weekly refresh automation offer or the missing prerequisite that prevented the offer, and let the user know they can iterate on the semantic layer. Keep routine validation details in support artifacts. If the request is ordinary data work, say that it should be routed through `index`.\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/design-kpis/SKILL.md":"---\nname: design-kpis\ndescription: \"Design KPI frameworks, metric definitions, targets, guardrails, and measurement plans for product or business decisions. Use when success metrics, drivers, guardrails, targets, or the measurement approach need to be defined or improved.\"\n---\n\n# Design KPIs\n\nDesign KPI frameworks, set targets, and develop measurement plans that help teams make product or business decisions.\n\n## When To Use Data Quality First\n\nUse $analyze-data-quality first when the task is to reconcile existing metrics, dashboards, tables, owners, or sources of truth.\n\nReturn to this skill only when the user asks to define the metric going forward, redesign the KPI framework, choose guardrails, or set targets.\n\n## Skill Configuration\n\n### Source Discovery And Verification\n\nUse the relevant semantic layer as a starting map, not a boundary.\n\n1. **Explore all possible sources.** Search every connected or provided source that could contain task-relevant data or change the interpretation. Within each structured-data source, run fresh catalog or metadata discovery for relevant schemas, datasets, tables, views, models, and metrics. Known sources, tables, dashboards, and semantic mappings are starting points, not stopping points.\n2. **Compare duplicates and conflicts.** When sources overlap or disagree, compare ownership, freshness, definition, grain, coverage, and directness. Use the best authoritative source, or combine complementary sources when needed. Note material conflicts, explain why the selected source or sources control the answer, and verify selected data through live reads before concluding.\n\n### Source Access Guardrail\n\nBefore querying sources, building artifacts, or drawing conclusions, determine whether the answer requires a specific source of truth.\n\nIf a required source is unavailable, stop that path. Tell the user what source is needed, ask them to make it available or provide a reviewed fallback, and do not treat weaker substitutes as equivalent.\n\nIf the missing source is only optional enrichment, continue with the strongest available evidence and label the gap when it materially affects the answer.\n\nClarify with the user when a missing input would materially change the analytical frame or recommendation. Otherwise make a reasonable assumption, state it, and proceed.\n\n## Workflow\n\n### 1. Clarify The Decision And Operating Context\n\nUnderstand the decision the metrics need to support, the context in which they will be reviewed, and who will act on the result. Ask the user to clarify the goal, operating cadence, or measurement constraints when missing or ambiguous input would change the recommendation.\n\n### 2. Gather Evidence Before Recommending Metrics\n\nWhen the prompt does not already provide enough context to know what success means, gather that context before recommending metrics or targets. Use $gather-business-context to understand the goal, current state, audience, constraints, risks, existing definitions, prior decisions, and any baseline or target context that should shape the metric system.\n\nFor KPI design, use that context to clarify what success is meant to mean, how related metrics have been defined before, and which constraints or risks should affect the recommended KPIs, drivers, guardrails, or measurement plan.\n\n### 3. Generate A Wider Candidate Set\n\nCreate candidate outcome, driver, and guardrail metrics before narrowing.\nEach candidate should have a clear definition and a plausible link to the decision. Use the example metric shapes below as inspiration when helpful, not as a required template.\n\n### 4. Compare And Select Metrics\n\nCompare candidate metrics by whether they:\n\n- reflect the goal: the metric should represent the intended outcome. When using a proxy, explain why it should reflect real progress and where it could mislead.\n- inform a real decision: movement should change what the team does, prioritizes, or investigates.\n- show useful signal at the decision cadence: a metric can be conceptually good but too slow-moving or noisy for the decision it supports. For example, annual retention may be the right outcome, but it may not help a weekly launch review unless paired with earlier indicators.\n- can be influenced by the team: the team should have plausible levers, or the metric should be paired with drivers it can affect.\n- can be measured operationally: the team should be able to instrument, calculate, and track the metric consistently without one-off manual work.\n- are hard to improve in a misleading way: improving the metric should not obviously hide harm to quality, trust, retention, cost, or another important outcome.\n\nUse lightweight scoring only when it helps explain tradeoffs. Recommend `1-3` primary KPIs, `1-2` driver metrics for each KPI when they improve diagnosis, and `1-2` guardrails when tradeoffs are likely. Do not recommend extra metrics unless they materially improve decision-making.\n\nFor each recommended metric, include enough detail for the team to use it: what it measures, why it matters, how it is calculated, where it comes from, its main pros and cons against the selection criteria above, and what caveats or guardrails matter.\n\n### 5. Set Targets When Needed\n\nTreat target setting as a separate judgment from metric selection. First decide what should be measured; then set targets when the user asks or when the recommendation needs a threshold to be useful.\n\nUse the target-setting approach that best fits the evidence:\n\n- Top-down: start from benchmarks, historical performance, comparable products, competitor or market context, or a reasoned view of what good would need to look like for the decision.\n- Bottom-up: start from what the team can realistically do, such as what is shipping, how adoption is expected to build, or which operating levers should move the metric.\n\nUse data to set or evaluate targets. Once the target-setting approach is clear, identify what data it requires, such as provided inputs, internal performance data, external benchmarks or market data, and results from similar past work.\n\nCompare aspirational targets with what the team can realistically influence through planned work, available audience, expected adoption, and historical movement. A good target should be meaningful for the decision and plausible enough to guide action. Explain the target anchor, key assumptions, and confidence. If the strongest target-setting method requires missing inputs, share the methodology and ask whether the user can provide or identify the relevant data. If there is still enough evidence for a directional target, present it as a provisional range; otherwise recommend the measurement needed before setting a firm target.\n\n### 6. Deliver The Recommendation\n\nKeep the final recommendation concise and decision-oriented, and deliver it inline by default. Do not load `$build-report` merely because the KPI framework uses evidence, compares candidates, or contains several metrics. Use `$visualize-data` and `$build-report` when a data visual would materially improve the answer, such as by showing how a proposed target compares with historical performance or benchmarks, or by clarifying tradeoffs or candidate scoring. Honor an explicitly requested report, dashboard, notebook, spreadsheet, native document, or slide deck as the primary artifact. The recommendation should include:\n\n1. initiative summary\n2. recommended metric candidates, with definition and rationale\n3. target recommendation, if included, with anchor, assumptions, and methodology\n4. evidence reviewed\n5. assumptions and missing context\n6. risks and guardrails\n7. open questions\n\n## Example Metric Shapes\n\nDifferent contexts need different metric shapes. Use these as examples, not a template:\n\n- Product launch or adoption: pair an outcome metric for adoption or value realization with drivers for activation, engagement, repeat use, or time to value, plus guardrails for experience quality.\n- Growth work: choose the business outcome the team is trying to improve, such as activation, retention, or monetization; add drivers that explain how growth is expected to happen and guardrails for quality.\n- Funnel work: choose the progression or completion outcome that represents success; add drivers around where people advance or drop off and guardrails for downstream quality.\n- Operating review: focus on health, pacing, and action-oriented metrics that show whether the business is on track and where attention is needed.\n- Experiment or intervention: use one primary success metric tied to the decision, diagnostics that explain movement, and guardrails for unintended effects.\n- Data, model, or analytics initiative: connect technical performance to the decision or workflow it improves, with adoption, reliability, cost, or fairness guardrails when relevant.\n- Platform, reliability, or operations work: measure service health, throughput, quality, cost efficiency, and customer impact in terms the owning team can act on.\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/gather-business-context/SKILL.md":"---\nname: gather-business-context\ndescription: \"Gather business context from connected or provided sources so downstream analysis starts with the right framing. Use when an analytical question depends on missing context, such as what a metric means, what changed recently, or which sources should be checked. If the same prompt asks for diagnosis, recommendation, or a deliverable, gather context first and continue to the focused skill.\"\n---\n\n## Boundary\n\nUse this skill to gather framing context, not to complete the downstream analysis.\n\nIf the same request also asks for a diagnosis, recommendation, dashboard, report, or other analytical deliverable, return only the context needed for that next step and continue with the appropriate focused skill, such as $metric-diagnostics, $product-business-analysis, $build-dashboard, or $build-report.\n\n# Gather Business Context\n\nUse this skill to collect the business context needed to understand an analytical question before doing deeper work. Focus on what the topic is, why it matters, what changed or is being decided, who or what source is closest to the work, and which definitions or artifacts should frame the analysis. This is a retrieval and extraction skill: gather enough context to set up the next step, not a final report, root-cause analysis, or broad background scan. Skip it when the prompt already provides the needed context or the task is fully self-contained.\n\n## Workflow\n\n### 1. Identify The Retrieval Target\n\nEstablish the analytical topic that needs context and why it matters for the next step. Capture the boundary needed to search and interpret sources, such as the relevant product area, audience, time period, or decision. If the timeframe is missing, use the narrowest reasonable window implied by the task and label it as an assumption.\n\n### 2. Build Search Anchors\n\nSearch with concrete identifiers rather than broad topic guesses. Start with the names the user provided or the sources surfaced, then expand with adjacent terms that help recall, such as aliases, owners, teams, dates, source names, related entities, or entities found in earlier results.\n\nStart broad enough to avoid missing relevant context. If too much comes back and a quick scan suggests the results are mostly unrelated, combine anchors to narrow retrieval, for example a metric plus a dashboard name, a feature plus a launch window, or a customer plus the relevant workflow. If a likely source comes back thin, revise the anchors before treating the source as missing.\n\n### 3. Search From Discovery Points Toward Authoritative Artifacts\n\n1. **Explore all possible sources.** Search every enabled or provided source family that could contain useful context or task-relevant data. Within each structured-data source, run fresh catalog or metadata discovery for relevant schemas, datasets, tables, views, models, and metrics. User-named sources, known tables, dashboards, and semantic-layer anchors are starting points, not stopping points.\n2. **Compare duplicates and conflicts.** When sources overlap or disagree, compare authority, freshness, definition, scope, and directness. Prefer artifacts closest to what was decided, defined, implemented, or measured; follow linked evidence when useful. Note material conflicts and explain which source or combination should guide downstream analysis.\n\n### 4. Extract Only Decision-Shaping Context\n\nTreat business context as a fixed extraction target, not an open-ended summary. Capture the facts that will shape the downstream analysis: the topic's business meaning, why it matters now, how it is defined or measured, where to verify it, what recently changed, and what uncertainty should travel with the analysis. Examples can include a metric definition, current rollout state, dashboard link, owner note, source conflict, or stated next step.\n\nKeep the context note focused on details that help frame the next analysis. Skip broad background, adjacent history, or long source excerpts unless they add useful context.\n\n### 5. Keep Source Notes Compact And Attributable\n\nFor each useful source, record enough attribution for the downstream work to be checked later: when the source applies, what kind of source it is, what factual context it established, and any important caveat or conflict. Distinguish source facts from inference and do not imply source review, stakeholder views, metric certainty, or confidence beyond what was actually established.\n\n### 6. Reconcile Conflicts Explicitly\n\nWhen sources disagree in a way that could change the downstream framing, preserve the disagreement instead of smoothing it over. Prefer the newest explicit decision artifact over older plans, owner-written docs over third-party summaries, and implementation artifacts over aspirational plans when the question is what is live, shipped, logged, or queryable now. Treat an informal source as stronger than a canonical artifact only when it clearly records a later decision or owner confirmation.\n\nIf disagreement remains, present both views, label the conflict, and state what source or owner would resolve it. If context is stale or incomplete, say what is missing and where to look next.\n\n### 7. Stop Once The Framing Is Sound\n\nStop gathering context when the downstream task can be framed well enough to proceed and the likely enabled or provided source families have been checked, ruled out as unavailable, or identified as too thin. Before stopping, make sure the next step has a clear enough understanding of the topic, why it matters, where the important definitions came from, what recent context applies, and what gaps remain.\n\nContinue searching when a relevant enabled or provided source is likely to add useful context. If an expected source was not found, name that as a gap rather than implying it does not exist.\n\n### 8. Return A Lightweight Context Note When Useful\n\nPrefer a focused context note over a full report or raw retrieval dump. Include enough context for the next analysis to proceed without redoing the search: a short summary, the relevant context, important definitions or source links, uncertainty or caveats, and citations. Keep it readable, but do not compress away details that explain the framing or source quality.\n\nIf the user asked only for quick orientation, shorten the structure while preserving citations, conflicts, and missing canonical artifacts.\n\n## Standards\n\nJudge sources by what they can actually establish. Informal discussion can be useful for discovery and recent context, but durable artifacts are usually stronger evidence for definitions, decisions, status, and measured results once found. Prefer sources close to the work, recent enough to reflect current reality, and explicit about what they establish. Surface missing source-of-truth artifacts as context gaps.\n\nKeep important claims attributable. Treat a source as useful only when it clarifies how the downstream task should be framed or interpreted; sources that merely mention the topic are incidental. Preserve enough evidence to check the work later, and label interpretation, assumptions, conflicts, and uncertainty when support is thin, stale, indirect, or conflicting.\n\nPreserve disagreements that could change the framing. Prefer owner-authored or decision-adjacent material and evidence of what is current over secondhand summaries or speculation. Do not infer consensus from silence. Say what source or owner would resolve an important conflict.\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/index/SKILL.md":"---\nname: index\ndescription: \"Route broad Data Analytics requests to the appropriate quantitative analysis, visualization, dashboard, report, notebook, KPI, market-sizing, validation, or semantic-layer workflow.\"\n---\n\n# Data Analytics Router\n\nUse this workflow when Data Analytics is explicitly invoked or the request requires structured records, quantitative evidence, metrics, or an evidence-backed product or business decision. Do not use it for ordinary prose drafting, file-format conversion, or qualitative description that does not require data interpretation.\n\n## Choose the focused workflow\n\n- Metric changed, missed a target, or differs from expectation: read `../metric-diagnostics/SKILL.md`.\n- Product or business decision, prioritization, segmentation, launch, or experiment recommendation: read `../product-business-analysis/SKILL.md`.\n- Dataset, dashboard, source, join, freshness, grain, or metric trust question: read `../analyze-data-quality/SKILL.md`.\n- KPI framework, canonical definition, target, driver, or guardrail design: read `../design-kpis/SKILL.md`.\n- KPI status update, WBR, MBR, QBR, or operating readout: read `../kpi-reporting/SKILL.md`.\n- Dashboard or monitoring view: read `../build-dashboard/SKILL.md`.\n- Durable analytical report: read `../build-report/SKILL.md`.\n- Chart or quantitative figure: read `../visualize-data/SKILL.md`.\n- Reproducible SQL/Python notebook: read `../jupyter-notebooks/SKILL.md`.\n- TAM, SAM, SOM, segment, or opportunity sizing: read `../market-sizing/SKILL.md`.\n- Review an analysis before sharing: read `../validate-data/SKILL.md`.\n- Create, repair, or save reusable data context or a semantic layer: read `../create-data-context/SKILL.md`.\n- Missing business definitions, ownership, change context, or decision framing: read `../gather-business-context/SKILL.md` before the primary workflow.\n\nLoad every selected workflow completely. Follow its related-skill rules when applicable. A task can combine workflows; use this usual order:\n\n1. Gather missing business context.\n2. Validate source quality and metric definitions.\n3. Perform the focused analysis.\n4. Validate conclusions.\n5. Visualize or create the requested durable artifact.\n\n## Source access\n\nUse the best source already available through the code-agent harness: local files, uploaded data, pasted results, databases, warehouses, BI systems, product analytics tools, notebooks, documents, or callable connectors. Tool availability is determined by the host, not by this skill.\n\nWhen no usable source is available:\n\n- Ask for the smallest useful artifact: a CSV/XLSX file, query result, schema, metric definition, dashboard export, screenshot, or pasted table.\n- Offer `assets/demo-product-growth.csv` only as a clearly labeled synthetic demonstration. Never use sample data to answer a real-data question.\n- Do not invent records, measurements, source access, or query results.\n\nIf available sources conflict in a way that changes the answer, surface the conflict and use the data-quality workflow. Otherwise choose the most authoritative and fresh source and proceed.\n\n## Portable output policy\n\nThis bundle targets a generic code agent and does not depend on React, MCP Apps, widgets, or a proprietary rendering surface.\n\n- Inline answers: concise Markdown with findings, evidence, caveats, and next actions.\n- Reports: Markdown by default; use self-contained plain HTML, PDF, DOCX, or another requested format only when the host can create and verify it.\n- Charts: use reproducible Python/Matplotlib, notebook-native plotting, SVG, or destination-native chart tools.\n- Dashboards: prefer a self-contained plain HTML/JavaScript artifact, Streamlit when Python execution is appropriate, or an existing BI platform selected by the user.\n- Notebooks: keep SQL/Python reproducible and make assumptions visible.\n\nPreserve source names, metric definitions, grain, time windows, filters, units, and uncertainty. Never expose credentials, secrets, hidden reasoning, or unnecessary personal data.\n\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/jupyter-notebooks/SKILL.md":"---\nname: jupyter-notebooks\ndescription: \"Create, edit, or validate reproducible SQL or Python notebooks. Use for notebooks, SQL/Python scratchpads, reproducible exploration, audit trails, or runnable companions where the analysis should be reviewable or rerunnable.\"\n---\n\n## Related Skills\n\nUse $validate-data when notebook results support a recommendation, shared claim, or decision.\n\n# Jupyter Notebooks\n\nCreate clean, reproducible Jupyter notebooks that are easy to skim, rerun, and handoff. Treat the notebook as a reader-facing analysis artifact, not a scratchpad dump. Notebook work is not complete until the notebook executes successfully top-to-bottom, or the execution gap is called out with the exact validation steps needed to reproduce it.\n\n## Workflow\n\n1. Lock the notebook mode and scope.\n\n   Decide whether the notebook is an analysis report, experiment log, diagnostic notebook, data-quality check, market-sizing calculation, model exploration,\n   tutorial, or companion artifact for a report. Identify the reader, decision,\n   expected handoff, required inputs, and whether the task calls for a new notebook or targeted edits to an existing one.\n\n2. Inspect or scaffold with notebook-safe tooling.\n\n   Prefer JupyterLab, `nbformat`, `nbclient`, or an existing scaffold utility over hand-editing raw JSON. When editing an existing notebook, preserve its intent and minimize JSON churn. Avoid reordering cells unless it clearly improves the top-to-bottom story. If raw JSON editing is unavoidable,\n   validate the notebook structure before finishing.\n\n3. Structure the notebook for the chosen mode.\n\n   For analytical notebooks, default to:\n\n   1. `## tl;dr`\n   2. `## Context & Methods`\n   3. `## Data`\n   4. `## Results`\n   5. `## Takeaways`\n\n   Write `tl;dr` and takeaways after reviewing executed outputs. Use concrete observed values, visible patterns, rows, or charts, not assumptions. Include a `### Key Assumptions` subsection in `Context & Methods` when assumptions affect correctness.\n\n   For tutorials or walkthroughs, adapt the same discipline to a teaching flow:\n\n   1. `## Goal`\n   2. `## Setup`\n   3. `## Steps`\n   4. `## Checks`\n   5. `## Next Steps`\n\n4. Build a clear data and computation path.\n\n   Separate setup, imports, parameters, data loading, data preparation,\n   calculations, visualizations, and interpretation. If the notebook uses both SQL and Python, keep complex SQL in SQL cells or separate query files rather than large embedded Python strings unless there is a clear reason. Use descriptive variable names and keep each code cell focused on one step.\n\n5. Use data sources deliberately.\n\n   When a notebook needs table data, first use `~~structured_data` to confirm table choice, schema, partition filters, sample rows, and query-submission policy. Use the relevant source connector when available, then fall back to exports or pasted SQL when needed. Use `~~operations_logs` for freshness or lineage checks when they matter. Record query permalinks, request IDs, source paths, dashboard links,\n   extract names, or other source artifacts in the notebook context for any executed result that supports the analysis. Keep heavy queries filtered and bounded instead of turning the notebook into a broad live-source scan.\n\n6. Make cells readable and bounded.\n\n   Add concise markdown headers before most code cells. Keep headers brief and action-oriented, such as `### 1. Load Data`, `### 2. Validate Inputs`, or `### 3. Plot Results`. Favor several short cells over one large mixed-purpose cell. Keep prose short: explain purpose, assumptions, and expected result, not every line of code. Split multiple tables or charts across separate cells instead of dumping all outputs from one cell.\n\n7. Validate results before writing conclusions.\n\n   Check that key numbers, charts, and takeaways match executed outputs. Bound raw debug output, oversized tables, and noisy logs. If a result is surprising, add a local reasonableness check, small sample inspection, or reconciliation against a trusted source before promoting it to the summary.\n\n8. Execute and record validation status.\n\n   Run the notebook top-to-bottom when the environment allows:\n\n   ```bash\n   python -m jupyter nbconvert --execute --to notebook --inplace path/to/notebook.ipynb\n   ```\n\n   Optional local setup when needed:\n\n   ```bash\n   uv pip install jupyterlab nbformat nbclient ipykernel\n   ```\n\n   If execution is not possible, say so explicitly and provide the exact command,\n   missing dependency, credential, data access, kernel, or environment step needed to validate locally.\n\n## Standards\n\n### Notebook Structure\n\n- Make the default top-to-bottom read clear before the reader starts executing cells out of order.\n- Put executive summary material at the top, but write it last after inspecting executed results.\n- Keep notebook sections aligned with the notebook mode: analysis, experiment,\n  diagnostic, tutorial, or handoff artifact.\n- Keep section titles, chart titles, labels, and file names descriptive enough for handoff.\n- Preserve the existing notebook's intent when refactoring; improve structure without rewriting everything by default.\n\n### Reproducibility\n\n- Keep parameters, date ranges, filters, cohorts, assumptions, and source references visible near the top of the notebook.\n- Record enough source context for another reader to trace the analysis: query permalinks, request IDs, table names, source paths, spreadsheet tabs,\n  dashboard links, extract versions, or input file locations.\n- Make computation deterministic where possible. Avoid hidden state, manually edited intermediate values, out-of-order dependencies, and unexplained cached outputs.\n- Prefer explicit environment setup cells or notes when the notebook depends on nonstandard packages, kernels, credentials, or local files.\n- Execute the notebook when the task requires a runnable artifact. In the final response, do not add a separate routine validation section for a clean run; surface execution gaps, partial execution, or unrun notebooks with the reason because those affect whether the user can rely on the artifact.\n\n### Code And Data Hygiene\n\n- Separate data preparation from presentation.\n- Keep complex SQL readable and documented with a one-line goal comment.\n- Keep plotting and lightweight shaping in Python after the data preparation step is complete.\n- Use descriptive variable names and avoid abbreviated temporary names in reader-facing notebooks.\n- Keep outputs bounded. Prefer small preview tables, sampled rows, explicit limits, and focused charts over raw dumps.\n- Avoid broad live-source scans. Filter queries by needed partitions, cohorts,\n  or time windows.\n\n### Analysis Quality\n\n- Make assumptions explicit when they affect interpretation.\n- Tie takeaways to executed outputs with concrete numbers, rows, charts, or visible patterns.\n- Do not promote unexecuted or unverified calculations into the `tl;dr`.\n- Label caveats, incomplete checks, missing source access, and known validation gaps.\n- Add reasonableness checks for surprising results, high-impact claims, or stakeholder-facing conclusions.\n\n### Validation Checklist\n\n- Required section order is present for the notebook mode.\n- The notebook executes without runtime errors, or execution failure is called out explicitly.\n- Outputs are present where expected and are not dominated by raw debug dumps.\n- The `tl;dr`, results, and takeaways match executed cells.\n- Source references and query or artifact links are preserved.\n- Tables and charts are labeled, bounded, and interpretable.\n- The final response includes the notebook path and validation status.\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/kpi-reporting/SKILL.md":"---\nname: kpi-reporting\ndescription: \"Prepare KPI readouts, scorecards, WBR/MBR/QBR updates, and executive summaries from quantitative business or product metrics; use when the task is to report status, compare against targets, explain validated drivers, and state operating implications.\"\n---\n# KPI Reporting\n\nUse this skill to turn business or product metrics into decision-ready operating readouts for leaders and teams. The job is to define the KPI contract, report status against the right comparison and target, include validated driver context, and state the operating implication clearly.\n\nClarify with the user when a missing input would materially change the analytical frame or recommendation. Otherwise make a reasonable assumption, state it, and proceed.\n\nThis skill owns the KPI readout: what should be reported, how metrics should be interpreted, whether driver context is validated, and what operating takeaway follows. It does not own metric-system design, new driver investigation, or final artifact polish.\n\nUse $metric-diagnostics when the readout needs fresh driver investigation, then return here to package the validated finding.\n\n## Skill Configuration\n\n### Source Discovery And Verification\n\nUse the relevant semantic layer as a starting map, not a boundary.\n\n1. **Explore all possible sources.** Search every connected or provided source that could contain task-relevant data or change the interpretation. Within each structured-data source, run fresh catalog or metadata discovery for relevant schemas, datasets, tables, views, models, and metrics. Known sources, tables, dashboards, and semantic mappings are starting points, not stopping points.\n2. **Compare duplicates and conflicts.** When sources overlap or disagree, compare ownership, freshness, definition, grain, coverage, and directness. Use the best authoritative source, or combine complementary sources when needed. Note material conflicts, explain why the selected source or sources control the answer, and verify selected data through live reads before concluding.\n\n### Source Access Guardrail\n\nBefore querying sources, building artifacts, or drawing conclusions, determine whether the answer requires a specific source of truth.\n\nIf a required source is unavailable, stop that path. Tell the user what source is needed, ask them to make it available or provide a reviewed fallback, and do not treat weaker substitutes as equivalent.\n\nIf the missing source is only optional enrichment, continue with the strongest available evidence and label the gap when it materially affects the answer.\n\n## Workflow\n\n### 1. Clarify The Readout Purpose\n\nUnderstand who the readout is for, what conversation it supports, and what is being reported before drafting. Anchor the update in the period being evaluated, the comparison or target that makes performance interpretable, and the freshness cutoff.\n\nAsk the user for missing context when it would help make the readout more accurate or useful.\n\n### 2. Define The Metric Framework\n\nDecide which metrics belong in the readout and what role each one plays before pulling numbers. If the framework already exists, confirm it and use it. If it is missing or weak, use $design-kpis before reporting.\n\nStart with the primary KPI, then add the smallest set of supporting metrics needed to explain status. Supporting metrics can explain movement, guard against harmful tradeoffs, or show whether performance is pacing as expected.\n\nLead with the metric that matters most to the audience. Do not add every available cut or comparison; include the metrics and slices decision-makers actually use, plus any that materially explain this update.\n\nWhen the primary KPI is top-line, composite, or otherwise not directly actionable, define its driver decomposition before interpreting it. Use an existing metric tree when available. Otherwise identify the smallest useful set of component drivers, such as numerator and denominator, volume and rate, mix, funnel stages, segments, cohorts, or operational inputs. Do not invent a causal hierarchy when source definitions do not support one.\n\n### 3. Lock Metric Definitions And Sources\n\nConfirm the KPI definition, source, time window, reporting cutoff, comparison period, and any target or pacing expectation before interpreting performance. If a target or pacing basis is missing, ask before treating one as authoritative. Use $analyze-data-quality when source quality issues could change the reported metrics.\n\nFor all KPI updates, make a focused source pass across `~~structured_data`, `~~company_docs`, `~~team_communication`, and `~~dashboards_or_bi` before drafting. Do not infer from a sparse prompt that source-backed actuals are unavailable. Use structured data for actuals, metric definitions, and comparison periods; use the other lanes for additional business context and source-of-truth guidance.\n\nIf any core definition is unclear, ask the user to clarify before making precise claims. When a metric definition changed, show comparable restated history when available; otherwise call out the break clearly.\n\n### 4. Pull The Topline Actuals\n\nDo not draft or render a WBR, MBR, scorecard, or KPI update from placeholders. Query or inspect connected structured-data sources for core actuals first. If actuals are blocked or insufficient, stop and say what source or access is needed unless the user explicitly asked for a template or mockup.\n\nReproduce the topline actual before explaining movement or driver context.\n\nFor each headline KPI, include the current value, the absolute and relative change versus the comparison period, and a short interpretation.\n\nCall out anything that makes the current value hard to compare with the prior period before interpreting the movement, such as a tracking change, data backfill, partial outage, or missing day.\n\n### 5. Put The Numbers In Context\n\nCompare actuals against the context that makes performance interpretable. When a target, plan, pacing model, benchmark, historical range, or relevant peer group is defined, identify it and compare performance against it before judging status.\n\nIf the goal has a deadline, do not just report whether the metric is above or below target. Show whether it is on pace to hit the target by the end of the period. Use the provided pacing definition when available. If none is defined or found, ask the user; when proceeding with a calculated fallback, state that it was calculated and explain the method.\n\nWhen useful, include absolute and percent variance to target and a red/yellow/green status. Make clear what comparison or pacing basis the status label uses.\n\n### 6. Explain Validated Drivers\n\nKPI updates need driver context, but driver claims must be validated before they are presented as explanations. A plausible story is not enough.\n\nWhen the readout needs to explain drivers, use $metric-diagnostics to identify and validate them. If trusted reporting or prior analysis already validates the drivers, use that evidence instead of re-running the diagnostic.\n\n### 7. Add Business Context And Operating Implications\n\nAfter identifying the likely drivers, use $gather-business-context to look for business context that helps explain what happened and what it means for the readout. Let the driver analysis guide what context to look for, and connect context to the metric only when evidence supports the link.\n\nTranslate the evidence, driver analysis, and business context into the operating implication for the business. State whether the movement is concerning, what next step or action is warranted, and whether the main KPI is on track, at risk, or ahead of plan. Recommend action only when the evidence supports it; otherwise name the next validation step.\n\n### 8. Validate The Readout\n\nAfter the analysis is assembled and before shaping the final readout, use $validate-data to review whether the numbers, methodology, caveats, and evidence support the claimed status, drivers, and implications. Resolve material issues before sharing; carry remaining limitations into the readout.\n\n### 9. Hand Off The Readout\n\nEnd by handing the validated KPI readout to $build-report unless the user explicitly requests an inline, chat-only, brief/no-artifact answer, asks not to create a report/file/artifact, or selects another primary artifact. A quick status update, brief readout, or findings-in-chat request is an inline output choice unless the user also asks for a report, document, deck, or durable artifact. When no explicit human waiver was given, the report handoff is mandatory; do not infer a waiver only because the user did not use the word \"report\".\n\nBefore handoff, make the readout explicit:\n\n- headline status and operating implication\n- actuals, targets, pacing basis, and comparison periods\n- validated drivers and unresolved uncertainty\n- audience, cadence, and requested delivery surface when known\n- charts or figures that would clarify the readout\n\nLoad `references/report-templates.md` before handing off and use the matching pattern as source notes for $build-report. Tell $build-report this is a KPI readout and pass the status, pacing, driver, uncertainty, audience, cadence, surface, and visual guidance above. Do not render charts directly from this skill; pass visual intent and supporting evidence to $build-report so $visualize-data owns chart selection and QA.\n\nFor slide or deck requests, use $build-report to create a portable source report first, then use an available presentation workflow or document tool to create and verify the deck. Preserve the same source evidence and findings across formats.\n\n## Standards\n\n### Metric Standards\n\n- Never present a KPI as precise when its definition, source, time window, or comparison basis is unclear.\n- Make calculation logic, inclusion or exclusion rules, grain, and time treatment explicit when they affect interpretation.\n- Reconcile totals and compare against prior reporting when possible.\n- Do not compare periods, cuts, or targets that are not definitionally compatible. Call out definition changes, backfills, denominator shifts, or calendar effects when they affect the movement.\n\n### Status And Pacing Standards\n\n- Include the headline takeaway, current actual, relevant comparison, target or pacing context, driver summary, and implication unless the user asks for a narrower readout.\n- Put actuals next to the target, plan, benchmark, or baseline when available so the reader can judge performance immediately.\n- If a target is time-bound, show whether current performance is on pace using the provided pacing definition or a clearly stated calculated fallback.\n- Keep recurring metric sections consistent across runs. If a requested section is missing because data, definitions, or validation are unavailable, explain the omission briefly.\n- Use traffic-signal status only when it helps prioritize action. Pair color with text and state the basis for the status.\n- Round numbers consistently, label units, and surface caveats when they change interpretation.\n\n### Driver Standards\n\n- Quantify drivers whenever the evidence supports it; do not use descriptive prose as a substitute for sizing the effect.\n- Report the few drivers, contributors, or known non-drivers that matter for interpreting the KPI movement.\n- For top-line KPI movement, structure validated drivers as a compact decomposition: top-line actual, component drivers, largest contributors or non-drivers, and residual or unresolved movement. Use an additive bridge only when the components reconcile cleanly; otherwise explain the relationship and uncertainty.\n- Separate validated drivers from business context or hypotheses.\n- Do not elevate business events into causes unless the timing, affected population, and measured change support the link.\n- State whether the movement is broad-based or concentrated when that changes the operating implication.\n- If driver evidence remains unresolved, name the uncertainty or diagnostic follow-up instead of inventing an explanation.\n\n### Presentation Standards\n\n- Write for executives and operators who skim: lead with the answer, then the evidence.\n- Use business-readable numbers and compact formats such as `123k (+8% w/w, +19% m/m)`.\n- Replace generic adjectives like `strong`, `healthy`, or `soft` with the metric evidence that justifies them.\n- Keep caveats close to the claim they affect, and omit caveats that do not change interpretation.\n- Use charts, tables, scorecards, or KPI cards only when they make the takeaway easier to understand and remain readable in the final delivery context.\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/market-sizing/SKILL.md":"---\nname: market-sizing\ndescription: \"Estimate market, segment, or opportunity size with transparent assumptions and uncertainty. Use for TAM/SAM/SOM, sizing scenarios, or comparing the scale of possible opportunities.\"\n---\n\n## Related Skills\n\nUse $visualize-data when the sizing result needs a chart or figure.\n\nUse $build-report to package the final estimate, assumptions, sensitivity, caveats, and source context whenever this skill is selected, unless the user explicitly requests an inline, chat-only, brief/no-artifact answer, asks not to create a report/file/artifact, or selects another primary artifact.\n\n# Market Sizing\n\nUse this skill to produce a defensible estimate of a market or opportunity from connected context, public sources, transparent assumptions, and auditable calculations. The job is to define the market, choose a sound sizing method, distinguish evidence from assumptions, test sensitivity, and state what would most improve confidence.\n\n## Skill Configuration\n\n### Source Discovery And Verification\n\nUse the relevant semantic layer as a starting map, not a boundary.\n\n1. **Explore all possible sources.** Search every connected or provided source that could contain task-relevant data or change the interpretation. Within each structured-data source, run fresh catalog or metadata discovery for relevant schemas, datasets, tables, views, models, and metrics. Known sources, tables, dashboards, and semantic mappings are starting points, not stopping points.\n2. **Compare duplicates and conflicts.** When sources overlap or disagree, compare ownership, freshness, definition, grain, coverage, and directness. Use the best authoritative source, or combine complementary sources when needed. Note material conflicts, explain why the selected source or sources control the answer, and verify selected data through live reads before concluding.\n\n### Source Access Guardrail\n\nBefore querying sources, building artifacts, or drawing conclusions, determine whether the answer requires a specific source of truth.\n\nIf a required source is unavailable, stop that path. Tell the user what source is needed, ask them to make it available or provide a reviewed fallback, and do not treat weaker substitutes as equivalent.\n\nIf the missing source is only optional enrichment, continue with the strongest available evidence and label the gap when it materially affects the answer.\n\nClarify with the user when a missing input would materially change the estimate or recommendation. Otherwise make a reasonable assumption, state it, and proceed.\n\n## Workflow\n\n### 1. Frame The Market Or Opportunity\n\nDefine the market or opportunity boundary before estimating:\n\n- What is being sized, for example a product category, workflow, problem, use case, or category of activity.\n- Where and when it applies, for example geography, segment scope, time horizon, or market maturity.\n- Who or what counts as part of the market, for example the relevant population, unit of demand, transaction type, or included activity.\n- How the opportunity is measured, for example spend, revenue, volume, value created, or another unit that fits the question.\n- What kind of sizing answer the user needs, for example TAM/SAM/SOM, market entry, expansion upside, spend pool, revenue pool, population count, or unit volume.\n\n### 2. Choose A Starting Sizing Approach And Inputs\n\nPick the simplest sound sizing approach for the question, then sketch the calculation chain and the major inputs the estimate will depend on.\n\nA top-down model works when reliable aggregate market data exists; a bottom-up model works when the market can be built from observable units and assumptions; a value-based model works when the estimate should start from the value created rather than a published market total. Use a mixed approach only when cross-checking would materially improve confidence. If more than one approach fits, briefly explain which one you trust most and why.\n\nExpect the first approach to change if source checks show that another model would be more defensible.\n\n### 3. Gather Sources For The Inputs\n\nChoose sources based on the inputs the estimate depends on most.\n\nStart with user-named sources when provided. Then use the strongest available evidence for each major input from the starting approach. Use `~~structured_data` when an input should come from the user's data warehouse or another structured data source. Use context lanes such as `~~company_docs`, `~~team_communication`, or `~~dashboards_or_bi` when an input needs business meaning, source-of-truth guidance, or assumptions that are not captured in structured data alone. When an input depends on the outside market, use public sources for benchmarks, population estimates, comparable markets, or proxy assumptions.\n\nUse $gather-business-context to resolve context lanes when the right source of truth, business meaning, or assumption set is unclear.\n\nIf the strongest source is unavailable or thin, continue with a transparent proxy assumption only when the estimate is still useful. Label the gap and explain how it affects confidence.\n\n### 4. Separate Facts From Assumptions\n\nKeep sourced facts, inferred estimates, and judgment calls distinct in the model. When exact data is unavailable, use a defensible proxy, explain why it is reasonable, and note the confidence level. Ground assumptions in evidence about how the market actually behaves, what can realistically change, and what determines the size of the opportunity.\n\n### 5. Build The Model\n\nMake the model easy to inspect and adjust.\n\nThe model should make these elements easy to audit or revise:\n\n- market definition and measurement unit\n- assumptions and source context\n- calculation chain and derived values\n- base case, material ranges, and sensitivity logic\n- validation priorities\n\nFor each major input, make the source path visible: structured data, context lane, public source, user-provided input, or proxy assumption.\n\nKeep derived values traceable to formulas or code rather than hardcoded outputs.\n\nUse $jupyter-notebooks when code is needed for source harmonization, calculations, sensitivity analysis, or reusable modeling logic. Keep formulas, inputs, intermediate calculations, and sensitivity logic inspectable.\n\nUse the `$Spreadsheets` skill when the user requests a spreadsheet, workbook, or Google Sheets deliverable, or when a market-sizing model would materially benefit from editable assumptions, sensitivity tables, charts, or polished workbook formatting.\n\n### 6. Test Sensitivity\n\nIdentify the assumptions that move the estimate most.\n\nShow how the estimate changes when those assumptions move up or down. Prefer simple, decision-useful sensitivity analysis over exhaustive scenario sprawl.\n\nUse ranges when uncertainty is material. Do not hide uncertainty behind a single point estimate when the inputs are thin.\n\n### 7. State The Estimate And Validation Priorities\n\nEnd by handing the estimate, method, key assumptions, uncertainty, and next validation priorities to $build-report unless the user explicitly waives report creation or selects another primary artifact. This handoff is mandatory when no explicit human waiver was given; do not infer a waiver because the user asked for an estimate or did not use the word \"report\". This workflow owns the sizing model and conclusion; $build-report owns the reader-facing structure, visuals, evidence placement, and delivery surface.\n\nBefore handoff, make the market-sizing conclusion explicit:\n\n- market definition and measurement unit\n- estimate or range\n- method and calculation chain\n- key assumptions and source support\n- main uncertainty drivers and sensitivity takeaways\n- validation priorities and practical interpretation for the user's decision\n\nIf source coverage is thin, say which major inputs rely on proxy assumptions and what source would most improve them.\n\nUse $validate-data when methodology, calculations, assumptions, caveats, or source support need review before sharing.\n\nDo not render charts directly from this skill. If a sensitivity, scenario, funnel, or market-breakdown visual would clarify the estimate, pass that visual intent and supporting evidence to $build-report so $visualize-data owns chart selection and QA.\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/metric-diagnostics/SKILL.md":"---\nname: metric-diagnostics\ndescription: \"Diagnose why a metric changed or differs from expectation. Use when the task is to identify likely drivers of a metric movement, anomaly, gap, or discrepancy.\"\n---\n\n## Related Skills\n\nUse $gather-business-context when business context is needed to understand the metric, analysis period, ownership, or plausible explanations.\n\nUse $product-business-analysis when the task asks for a recommendation or tradeoff decision after diagnosing the movement.\n\nUse $analyze-data-quality when dashboard trust, grain, freshness, or source disagreement could affect the metric.\n\n# Metric Diagnostics\n\nUse this skill to diagnose why a metric changed or differs from expectation. Reproduce the metric, define the comparison, quantify the movement, validate likely drivers, and state what is verified, likely, unresolved, and useful to do next.\n\nClarify with the user when a missing input would materially change the analytical frame or recommendation. Otherwise make a reasonable assumption, state it, and proceed.\n\n## Skill Configuration\n\n### Source Discovery And Verification\n\nUse the relevant semantic layer as a starting map, not a boundary.\n\n1. **Explore all possible sources.** Search every connected or provided source that could contain task-relevant data or change the interpretation. Within each structured-data source, run fresh catalog or metadata discovery for relevant schemas, datasets, tables, views, models, and metrics. Known sources, tables, dashboards, and semantic mappings are starting points, not stopping points.\n2. **Compare duplicates and conflicts.** When sources overlap or disagree, compare ownership, freshness, definition, grain, coverage, and directness. Use the best authoritative source, or combine complementary sources when needed. Note material conflicts, explain why the selected source or sources control the answer, and verify selected data through live reads before concluding.\n\n### Source Access Guardrail\n\nBefore querying sources, building artifacts, or drawing conclusions, determine whether the answer requires a specific source of truth.\n\nIf a required source is unavailable, stop that path. Tell the user what source is needed, ask them to make it available or provide a reviewed fallback, and do not treat weaker substitutes as equivalent.\n\nIf the missing source is only optional enrichment, continue with the strongest available evidence and label the gap when it materially affects the answer.\n\n## Workflow\n\n### 1. Define The Diagnostic Question\n\nFrame the diagnostic so it is clear what changed and what comparison would prove it.\n\nDefine:\n\n- what the metric means in business terms\n- the time window and comparison that make the change measurable\n- the population and grain that determine what counts\n- the source that owns the metric definition\n- the diagnostic question being answered, for example movement, concentration, or reconciliation\n\nUse $gather-business-context when business context is needed to understand what the metric means, what changed around the analysis period, or which explanations are plausible.\n\n### 2. Validate The Metric Definition And Source\n\nBefore explaining the movement, confirm that the metric is defined correctly and that the source data can measure it reliably.\n\nConfirm the metric definition, grain, aggregation logic, filters, joins, exclusions, freshness, lineage, and any disagreement between trusted surfaces. Keep this source check focused on issues that could change the answer.\n\nTreat current context, named semantic layers, and familiar table names as source candidates, not source selection. For broad metric questions, run live source discovery against available tables, dashboards, metric docs, semantic layers, or other source-of-truth surfaces before choosing the controlling source. When both are available, inspect at least one business-facing or top-line surface and one lower-level source surface, then state why the selected source owns the answer.\n\nUse $analyze-data-quality when freshness, grain, joins, missingness, schema drift, outliers, unexpected categories, or distribution shifts could affect trust.\n\nUse $jupyter-notebooks when fresh SQL, Python, statistical modeling, reusable calculations, or multi-step decomposition need an inspectable analytical record.\n\n### 3. Establish The Metric Pattern\n\nBefore looking for drivers, establish the metric pattern the diagnostic needs to explain. Quantify the metric over the relevant period and scope. If the question includes a comparison, reproduce that comparison.\n\nDo not search for causes until the size, timing, and scope of the pattern are verified or explicitly marked uncertain.\n\n### 4. Choose The Diagnostic Plan\n\nChoose the smallest set of cuts and checks likely to explain the pattern or strengthen confidence.\n\nChoose driver dimensions from the metric's operating logic, business context, and source shape. Prioritize drivers the business usually monitors or can act on, not every field available in the source. If the relevant drivers are unclear, use current context, a named semantic layer, or $gather-business-context to understand how the business explains the metric and what changed around the analysis period.\n\nWhen using a lower-level table, do not limit the driver analysis to fields surfaced by the first query. Recreate or join the business grouping needed to answer the question, such as model family, model superfamily, segment, region, cohort, product taxonomy, or customer hierarchy. If the grouping cannot be reconstructed, say so before simplifying the analysis.\n\nUse the explanation mode that fits the question. Common examples:\n\n- **Metric change**: compare the focal window with a baseline, rank segment contributions, check peer or historical context, and test mix shift versus within-segment movement.\n- **Spike, regression, or incident**: pin down onset, peak, recovery,\n  distribution shape rather than only averages, affected slices, broad versus localized degradation, and whether traffic or failure behavior changed.\n- **Largest contributors or concentration**: define \"largest\", rank entities,\n  compare total share and change, and look for major movers, entrants, and exits.\n- **Reconciliation or difference analysis**: align definitions, filters, grain,\n  numerator, denominator, and exclusions; quantify the components explaining the gap and state any residual.\n\n### 5. Decompose And Validate Drivers\n\nQuantify the main drivers and validate whether they explain the pattern.\n\nSize each major driver with the strongest readily available evidence. Show whether it explains the pattern, how large it is relative to the relevant base, trend, or gap, whether it is broad or concentrated, and whether it holds under the right comparison or scope.\n\nIterate on driver hypotheses until the explanation answers why in a way that is relevant to the business. Follow promising cross-cuts and drill-downs when they could reveal the key explanation, and stop when additional cuts are unlikely to change the conclusion or materially improve confidence.\n\nInterpret driver results in context:\n\n- Use the relevant base, comparison, or share of total to make the driver meaningful.\n- For rates, check whether the numerator, denominator, or both explain the change.\n- For additive metrics, calculate contribution share when it sharpens the story.\n- Separate composition effects from within-segment performance effects when that distinction changes the explanation.\n- Prefer mutually exclusive driver buckets when additive contributions need to be interpreted; reconcile the decomposition exactly or size and explain the residual.\n\nTreat measurement issues as possible explanations, not just cleanup details. For example, the pattern may come from logging changes, incomplete recent data, duplicated rows, or a shifted denominator rather than an underlying business change.\n\nCalibrate the explanation to the evidence, and make important uncertainty visible. Use context when it changes interpretation, such as whether the pattern is ordinary, unusual, expected, or tied to a known change.\n\nUse $visualize-data when a chart would make the diagnostic claim easier to understand or verify.\n\n### 6. State Implications And Follow-Up\n\nLead with the answer to the diagnostic question, then state the practical implications when the evidence supports them.\n\nThe answer should make clear:\n\n- the pattern being explained\n- the strongest driver explanation and supporting evidence\n- why it matters for the business\n- how much confidence to place in the explanation\n- the implication, next action, or follow-up that matters most\n\nUse $product-business-analysis when the user needs a recommendation or tradeoff decision, not just the diagnostic implication.\n\nKeep implications distinguishable from verified factual reporting so a reader can tell where evidence ends and interpretation begins. Do not claim causality from timing alone; state when an explanation is only a plausible hypothesis.\n\nUse $gather-business-context when the metric result is clear but business context is needed to interpret the `so what` or identify realistic next actions.\n\nUse $validate-data when methodology, calculations, caveats, or the evidentiary support for the diagnostic conclusion need review before sharing.\n\nDo not treat artifact or report validation as analytical validation. Before handing off, confirm the analysis has the headline metric movement, driver contribution shares or effect sizes, source/window reconciliation, exact executed SQL or query references when queries were used, and caveats that would change interpretation.\n\nPass the diagnostic substance and supporting evidence to $build-report unless the user explicitly requests an inline, chat-only, brief/no-artifact answer, asks not to create a report/file/artifact, or selects another primary artifact. This handoff is mandatory when no explicit human waiver was given; do not infer a waiver because the user asked a direct diagnostic question or did not use the word \"report\". Let $build-report own the report surface, presentation polish, reproducibility treatment, and sharing handoff.\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/product-business-analysis/SKILL.md":"---\nname: product-business-analysis\ndescription: \"Analyze product or business data to support a decision or recommendation. Use when a decision depends on metric-backed evidence, such as choosing a direction, prioritizing an opportunity, evaluating a change, segmenting users, sizing tradeoffs, or deciding what to do next.\"\n---\n\n## Related Skills\n\nUse $metric-diagnostics when the recommendation depends on explaining a metric movement, anomaly, gap, or discrepancy.\n\n# Product And Business Analysis\n\nUse this skill to answer product or business questions with data-backed evidence, context, and a recommendation. Give the audience enough trustworthy evidence, interpretation, and uncertainty framing to choose a practical next action.\n\n## Skill Configuration\n\n### Source Discovery And Verification\n\nUse the relevant semantic layer as a starting map, not a boundary.\n\n1. **Explore all possible sources.** Search every connected or provided source that could contain task-relevant data or change the interpretation. Within each structured-data source, run fresh catalog or metadata discovery for relevant schemas, datasets, tables, views, models, and metrics. Known sources, tables, dashboards, and semantic mappings are starting points, not stopping points.\n2. **Compare duplicates and conflicts.** When sources overlap or disagree, compare ownership, freshness, definition, grain, coverage, and directness. Use the best authoritative source, or combine complementary sources when needed. Note material conflicts, explain why the selected source or sources control the answer, and verify selected data through live reads before concluding.\n\n### Source Access Guardrail\n\nBefore querying sources, building artifacts, or drawing conclusions, determine whether the answer requires a specific source of truth.\n\nIf a required source is unavailable, stop that path. Tell the user what source is needed, ask them to make it available or provide a reviewed fallback, and do not treat weaker substitutes as equivalent.\n\nIf the missing source is only optional enrichment, continue with the strongest available evidence and label the gap when it materially affects the answer.\n\nClarify with the user when a missing input would materially change the analytical frame or recommendation. Otherwise make a reasonable assumption, state it, and proceed.\n\n## Workflow\n\n### 1. Start From The Decision\n\nIdentify the decision, audience, and action the analysis should inform before choosing data sources or metrics.\n\nState plainly:\n\n- the question and decision the analysis should inform\n- who will use the answer and what they can act on\n- the scope and comparison that define a useful answer\n- the outcome or behavior that matters for the decision\n- any assumptions needed to proceed\n\nDo not let unclear scope turn into broad exploratory work by default.\n\n### 2. Gather Decision-Relevant Context\n\nRun $gather-business-context before deeper analysis. That skill owns source selection, retrieval, source authority, conflict handling, and compact context notes. Use this workflow to decide how the gathered context changes the analysis and recommendation.\n\nKeep the context pass proportional to the task. For self-contained prompts or cases where the user already provided enough context, the pass can be brief: confirm the decision frame, definitions, source assumptions, and any obvious gaps before moving on. Do not turn mandatory context gathering into a broad background scan.\n\nRelevant context should clarify:\n\n- intent: what the work was meant to accomplish and why\n- definitions: how the work, metric, or source is defined and measured\n- timing: what changed around the analysis period that could affect interpretation\n- constraints: decisions, caveats, or limitations that affect what action is realistic\n\n### 3. Frame The Analysis\n\nTurn the question into a focused analytical framework.\n\nDefine a framework for answering the question with data:\n\n- the specific data questions that would support or change the recommendation\n- the comparisons and dimensions to inspect\n- the unit of analysis that matches the decision\n- the metric definitions and caveats needed to interpret the result\n\nUse the framework to surface plausible hypotheses or interpretations, then turn them into focused data questions. Keep the framework specific enough to avoid broad exploration and support a recommendation.\n\nUse $design-kpis when the success metric, driver metrics, guardrails, or measurement plan need to be defined before the analysis can proceed.\n\nStart by defining what the answer needs to show in plain language. Then choose the data that matches that meaning as closely as possible, including who is counted and what comparison makes the number meaningful. If a field or event captures only part of what the decision cares about, say what it captures and what it leaves out.\n\n### 4. Run Focused Quantitative Analysis\n\nRun enough quantitative analysis to support or reject the framed hypotheses and inform the decision:\n\n- **Follow the framework.** Run the analyses that could change the recommendation first. Track additional data questions that emerge, answer the ones that matter for the decision, and leave lower-impact cuts as follow-up instead of expanding into broad exploration.\n\n- **Use the right comparison.** Interpret results against the relevant baseline, denominator, or comparison point before turning them into a recommendation. For example, do not conclude that one group is the best opportunity just because it has the most total usage. Check whether usage is high because the group is larger, whether the pattern still holds after normalizing by the active base, whether the group is growing or declining, whether the usage reflects the behavior or outcome that matters, and whether business context changes the interpretation.\n\n- **Size the opportunities.** Estimate the magnitude of impact each important opportunity could have. State what is being compared, which metric represents impact, what denominator or population it uses, and whether the data is complete enough to trust. Keep material unknown or unclassified groups visible when they could change the interpretation.\n\n- **Keep quantitative work inspectable.** Use $jupyter-notebooks to record queries and analysis. Use $analyze-data-quality when source freshness, grain, joins, missingness, schema drift, or unexpected distributions could affect trust.\n\n- **Validate before concluding.** Use $validate-data before sharing stakeholder-facing recommendations, high-impact claims, or surprising results. When dashboards and direct queries both exist, reconcile them or explain why they differ.\n\n### 5. Translate Evidence Into Decision Implications\n\nFrame the findings within the broader business context. Do not present quantitative evidence and business context as two unrelated streams.\n\nInterpret the evidence through the decision lenses that best fit the question. Choose lenses that would actually change the recommendation, and skip ones that would add noise or false precision. Common lenses include:\n\n- **Current scale:** Is the opportunity or problem large enough today to matter for the decision?\n- **Momentum:** Is the signal growing, shrinking, accelerating, or newly emerging?\n- **Breadth:** Is the pattern broad-based, or does it only appear in a narrow corner of the business?\n- **Concentration:** Does the conclusion depend on a few large entities, events, or outliers?\n- **Intensity:** Is the behavior deep enough per unit to suggest real need, value, or risk?\n- **Efficiency:** Does the option create better output, margin, conversion, productivity, or quality for the input required?\n- **Addressability:** Can the team realistically act on this option with available product, GTM, operational, policy, or technical levers?\n- **Differentiation:** Does this group or use case require a distinct motion, product experience, support model, or message?\n- **Substitution:** Is there evidence that behavior, spend, time, or workload could shift from another path?\n- **Risk or dependency:** Are there quality, trust, compliance, technical, operational, or data constraints that change the recommendation?\n- **Coverage:** Are unknown, missing, or sparsely tagged records large enough to change the answer?\n\nUse these as thinking tools, not a checklist. Explain why the chosen lenses matter for this decision, and mention omitted cuts only when they would plausibly change the interpretation or help explain the result.\n\nUse the measured opportunities to explain which differences matter for the decision and which ones call for different actions. If the business context shows that the initial sizing misses the actionable part of the opportunity, add the focused sizing cut needed to make the recommendation useful.\n\nIf evidence conflicts, say so directly and explain which interpretation is better supported. Do not smooth over disagreement between sources.\n\n### 6. Hand Off The Recommendation\n\nEnd by handing the decision-ready recommendation to $build-report unless the user explicitly requests an inline, chat-only, brief/no-artifact answer, asks not to create a report/file/artifact, or selects another primary artifact. This handoff is mandatory when no explicit human waiver was given; do not infer a waiver because the user asked a direct question or did not use the word \"report\". This workflow owns the analytical conclusion; $build-report owns the reader-facing structure, visuals, evidence placement, and delivery surface.\n\nBefore handoff, make the recommendation explicit:\n\n- what they should believe or do next\n- why the evidence supports that recommendation\n- which caveats or dependencies matter\n- what follow-up analysis would most improve confidence\n\nIf evidence is incomplete, label the recommendation as provisional and state what would change confidence. Do not overstate the conclusion just to make the answer feel decisive.\n\nUse $validate-data when methodology, calculations, caveats, or the evidentiary support for the conclusion need review before sharing.\n\nPass narrative ingredients to the report surface, not only result tables:\n\n- direct answer and recommendation\n- key evidence and how to interpret it\n- implication for the decision\n- unresolved uncertainty and caveats\n- recommended follow-up\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/validate-data/SKILL.md":"---\nname: validate-data\ndescription: \"Validate whether an analysis is accurate, well-supported, and ready to share or use for a decision. Use when reviewing methodology, calculations, comparisons, visuals, caveats, or conclusions.\"\n---\n## Related Skills\n\nUse $analyze-data-quality when validation depends on whether the underlying data is trustworthy, comparable, fresh, or at the right grain.\n\nUse $product-business-analysis when the task asks for a recommendation or decision after the validation pass.\n\n# Validate Data Analysis\n\nValidate an analysis before it is shared with stakeholders. Focus on whether the question, data, methodology, calculations, visuals, claims, caveats, and recommendations are trustworthy enough for the stated audience and decision.\nThis skill is for analysis QA, not raw dataset profiling alone. When validation depends on dataset reliability checks such as freshness, grain, missingness,\nduplicates, join coverage, or source mismatches, use $analyze-data-quality as a companion.\n\n## Workflow\n\n1. Inventory the artifact and claims.\n\n   Identify the report, notebook, spreadsheet, SQL, dashboard, chart, pasted analysis, or recommendation being validated. Inspect source artifacts when a path, link, query, notebook, spreadsheet, or dashboard is referenced. Extract the main question, audience, decision, key claims, headline numbers, data sources, time windows, populations, filters, comparison baselines, and stated caveats. Verify that every metric or KPI requested by the user appears in the analysis or is explicitly marked unavailable, not applicable, or out of scope.\n\n2. Validate the question, methodology, and assumptions.\n\n   Confirm that the analysis answers the stated business or product question,\n   not a nearby easier question. Check whether the population, eligibility rules, exclusions, sampling, metric definitions, formulas, units,\n   denominators, timezones, cohorts, comparison periods, and baselines match the stakeholder decision. Flag hidden exclusions, inconsistent definitions,\n   partial-period comparisons, and causal wording that lacks experimental or otherwise credible causal evidence.\n\n3. Validate data selection and quality risks.\n\n   Confirm that the chosen tables, files, dashboards, or extracts are appropriate and current enough for the decision. Check freshness or \"as of\"\n   date, expected partitions, segment coverage, row/category completeness, null handling, deduplication, filter logic, join coverage, and source mismatches when those risks could change the conclusion. Use `~~structured_data` for source metadata, schema checks, sample rows, query history, or SQL spot checks through the relevant source connector when available. Use `~~operations_logs` for table freshness, lineage, or pipeline context.\n\n4. Verify calculations and aggregations.\n\n   Recompute the highest-impact numbers independently when possible. Check grain, subtotals, denominators, non-zero denominators, rate bases,\n   period-over-period bases, weighted averages, units, currency, timezone handling, and whether mutually exclusive categories add to totals. For SQL,\n   inspect join types, group-by grain, filters, distinct counts, and row counts before and after joins. Use $jupyter-notebooks or `~~spreadsheet_workspace`\n   when the artifact itself is a notebook or spreadsheet, or when reproducible spot checks need code or formulas.\n\n5. Test reasonableness and common analytical traps.\n\n   Compare magnitudes against known dashboards, historical reports, prior analyses, finance sources, or expected product scale when possible. Investigate trend jumps, drops, flatlines, exact round numbers, 0% or 100% rates, segment shares that should sum to about 100%, and results that perfectly confirm the hypothesis without friction. Check edge cases such as empty segments, new entities, and boundary dates.\n\n6. Review visuals and presentation integrity.\n\n   Confirm that charts use appropriate chart types, scales, axes, intervals,\n   titles, labels, units, ordering, annotations, color, and precision. Use\n   $visualize-data for non-trivial chart review. For rendered reports,\n   dashboards, slides, docs, PDFs, HTML, or other final artifacts, inspect the rendered output for broken charts, missing tables, clipped text, bad formatting, stale placeholders, and obvious layout issues. Check whether a quick reader could walk away with a misleading interpretation, especially from truncated axes, dual axes, 3D effects, inconsistent intervals, missing date ranges, or chart titles that overstate the data.\n\n7. Evaluate narrative, conclusions, and recommendations.\n\n   Confirm each conclusion is supported by visible evidence or saved artifacts.\n   Separate verified findings from interpretation, caveats, and open questions.\n   Identify alternative explanations, uncertainty, missing context,\n   recommendations that go beyond the evidence, and any causal language that is not supported by the design.\n\n8. Produce a confidence assessment and required fixes.\n\n   Prioritize issues that materially affect the stakeholder decision. Separate blockers from caveats: do not block sharing for minor polish issues, but do block when a number, denominator, join, time window, population, comparison,\n   or conclusion is materially unreliable. Record incomplete handoff blockers separately from caveats, including missing access, unavailable source artifacts, unrun checks, broken render steps, unresolved data-quality risks,\n   or absent owner confirmation. If SQL, Python, a notebook, or a spreadsheet was used for validation, include the artifact path, query permalink, notebook path, spreadsheet tab, or dashboard link so the check is reproducible.\n\n## Standards\n\n### Validation Stance\n\n- Validate the claims the analysis actually makes, not just whether the artifact looks polished.\n- Prefer concrete evidence: recompute important numbers, inspect source data,\n  check code paths, trace records, or reconcile against trusted sources when tools and access allow it.\n- Label anything that cannot be verified, and state what would be needed to verify it.\n- Treat surprising results, stakeholder-facing recommendations, causal claims,\n  high-impact decisions, and externally shared analyses as higher-risk validation targets.\n- Select checks that match the artifact and decision. Do not run every possible check mechanically.\n\n### Methodology Checks\n\n- Question framing: the analysis answers the stated business or product question.\n- Data selection: sources are appropriate and current enough for the decision.\n- Population: inclusions, exclusions, eligibility rules, and sampling are explicit.\n- Metric definitions: formulas, units, denominators, and timezones are clear and aligned with stakeholder definitions.\n- Baselines: comparison periods, cohorts, and contexts are comparable.\n- Causality: causal wording is backed by experimental or otherwise credible causal evidence.\n\n### Data Quality Checks\n\n- Freshness: the analysis states or can recover the data \"as of\" date.\n- Completeness: no unexpected missing partitions, segments, rows, or categories.\n- Null handling: key columns have expected null rates or explicit treatment.\n- Deduplication: primary entities are not double counted.\n- Filter verification: filters and WHERE clauses do not silently exclude the population of interest.\n- Join coverage: dimensions, experiments, and reference tables do not drop or multiply important rows.\n\n### Calculation Checks\n\n- Grain: the aggregation level matches the intended analysis grain.\n- Denominators: rates and percentages use the correct population and non-zero denominators.\n- Period alignment: comparisons use equal or explicitly caveated windows.\n- Weighted metrics: averages are weighted correctly when group sizes differ.\n- Subtotals: parts add to totals where categories are mutually exclusive.\n- Units: currency, token, user, request, account, day/week/month, and timezone units are consistent.\n\n### Reasonableness Checks\n\n- Magnitudes are plausible relative to known dashboards, historical reports, or expected product scale.\n- Percentages fall in expected ranges and segment shares sum to about 100% where expected.\n- Trend jumps, drops, flatlines, exact round numbers, and 0% or 100% rates have an explanation.\n- Results do not perfectly confirm the hypothesis without friction or exceptions.\n- Edge cases such as empty segments, new entities, and boundary dates behave sensibly.\n\n### Common Pitfalls\n\n- Join explosion: many-to-many joins silently multiply rows and inflate counts or sums. Compare row counts and distinct primary entities before and after the join, and check whether the right-hand table has multiple rows per join key.\n  Aggregate the right-hand table to the intended grain before joining when needed, use `COUNT(DISTINCT primary_id)` when counting entities through joins,\n  and comment intentional one-to-many joins.\n- Survivorship bias: the analysis only includes entities that exist today and misses deleted, churned, failed, or otherwise absent entities. Ask who is not in the dataset and whether the missing population changes the conclusion.\n- Incomplete period comparison: a partial period is compared with a complete period. Use complete periods, compare the same number of elapsed days, or label the partial-period caveat prominently.\n- Denominator shifting: the eligible population changes between periods or segments. Validate that conversion, churn, activation, attach, and retention rates use stable definitions across compared groups.\n- Average of averages: pre-computed averages are averaged without weighting for group size. Aggregate from raw numerators and denominators or use a weighted average.\n- Timezone mismatch: sources use different timestamp conventions or daily cutoffs. Confirm the analysis standardizes timestamps or explicitly states the timezone and cutoff.\n- Selection bias in segmentation: segments are defined by the outcome being measured. Define comparison groups by pre-treatment characteristics when making lift, causality, or behavior-difference claims.\n- Other statistical traps: Simpson's paradox where aggregate and segment-level trends conflict, correlation presented as causation, small samples,\n  outlier-dominated averages that need medians or distribution views, multiple testing, cherry-picked time ranges, and look-ahead bias.\n\n### Spot-Check Recipes\n\n- Recompute a key metric from raw numerators and denominators.\n- Trace a few individual records through joins, filters, and final output.\n- Reconcile a key total against a trusted dashboard, prior report, or finance source.\n- Reverse engineer a headline number from component metrics, such as users times per-user revenue.\n- Run a one-day, one-segment, or one-entity boundary check to make sure filters and joins behave sensibly.\n- Compare the same metric through an alternate query path when a claim is surprising or high stakes.\n\n### Visualization Checks\n\n- Bar charts should generally start at zero; waterfall, bridge, variance, and other delta-focused charts may use a non-zero or narrowed value axis when zero would materially compress the intended movement, provided exact values, units, and the focused scale are clear.\n- Comparison charts should use consistent scales unless the scale difference is explicit and justified.\n- Axes, units, legends, and date ranges should be labeled.\n- Category ordering should match the comparison the reader should make.\n- Truncated axes, dual axes, 3D effects, and inconsistent intervals require explicit justification or redesign.\n- Chart titles and annotations should match exactly what the data supports.\n- Titles should state the finding and include date range or scope when needed.\n- Caveats should be visible near the claims they qualify.\n- Number formatting should use appropriate precision and units.\n- Rendered artifacts should be checked in their final form when available, not only in source form.\n\n### Confidence Ratings\n\n- `Ready to share`: The analysis is methodologically sound, key calculations are verified or low risk, caveats are clear, and any remaining issues are minor.\n- `Share with caveats`: The analysis is directionally usable, but specific assumptions, limitations, or unverified checks must be communicated to stakeholders.\n- `Needs revision`: There are material errors, unsupported claims, missing checks, or methodological issues that should be fixed before sharing.\n\n### Output Standards\n\nUse this structure unless the user asks for a lighter review:\n\n```markdown\n## Validation Report\n\n### Overall Assessment: [Ready to share | Share with caveats | Needs revision]\n\n### Methodology Review\n[Findings about question framing, data selection, population, definitions, comparisons, and assumptions.]\n\n### Issues Found\n1. [Severity: High/Medium/Low] [Issue description, evidence, and impact]\n2. ...\n\n### Calculation Spot-Checks\n- [Metric or claim]: [Verified / Discrepancy found / Not verified] - [brief evidence]\n\n### Visualization Review\n[Chart or presentation issues, if applicable.]\n\n### Suggested Improvements\n1. [Improvement and why it matters]\n\n### Required Caveats for Stakeholders\n- [Caveat that must be communicated]\n```\n\n- Include the question being answered, data sources and \"as of\" date, metric and segment definitions, time period and timezone, methodology steps, assumptions and limitations, SQL queries, notebook paths, spreadsheet tabs, dashboard links, or caveats required before acting when those details are relevant.\n- Preserve source references from the original artifact, including links, query IDs, notebook paths, spreadsheet tabs, dashboard URLs, cited documents, and other evidence needed to trace the analysis.\n- Verify that every section requested by the user or implied by the deliverable format is present; explain omitted sections.\n- Keep issues prioritized by decision impact, not by artifact section order.\n- Make unverified claims and remaining caveats explicit.\n- List incomplete handoff blockers separately from caveats and suggested improvements.\n","packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/visualize-data/SKILL.md":"---\nname: visualize-data\ndescription: \"Design, create, revise, or QA quantitative charts and figures for reports, dashboards, notebooks, slides, files, or inline analytical answers.\"\n---\n\n# Visualize Data\n\nCreate quantitative visuals that are analytically sound, immediately readable, and appropriate for their destination. Treat a chart as evidence for a takeaway, not decoration.\n\n## Workflow\n\n1. State the analytical question and intended takeaway.\n2. Verify the data grain, measures, dimensions, units, missing values, filters, time window, sample size, and source.\n3. Choose the chart family from the analytical relationship:\n   - Change over ordered time: line or area chart.\n   - Category comparison: bar chart.\n   - Distribution: histogram, box plot, or density plot.\n   - Relationship between numeric measures: scatter plot.\n   - Composition: stacked bar/area; use pie only for a small set of meaningful parts.\n   - Funnel progression: funnel or ordered bars with stage conversion.\n   - Contribution to change: waterfall.\n   - Exact lookup values: table, optionally with small bars or sparklines.\n4. Define explicit encodings, sorting, aggregation, grouping, scales, labels, units, colors, annotations, and uncertainty treatment.\n5. Render with the destination's native system when one is selected. Otherwise prefer reproducible Python/Matplotlib or SVG for files and inline artifacts. Notebook-native plotting is appropriate for notebooks.\n6. Inspect the final output in context when the host provides image, browser, document, or notebook inspection.\n\nDo not install or require React, Recharts, Vite, MCP widgets, or proprietary UI renderers. For self-contained HTML, use inline SVG/canvas or a static image plus semantic fallback data. Avoid remote scripts unless the user explicitly accepts the dependency.\n\n## Visual quality\n\n- Use an answer-oriented title and a subtitle only when it adds a distinct takeaway.\n- Label axes and units; show legends or direct labels for every visible group.\n- Use consistent scales for comparisons and avoid misleading truncated axes unless clearly justified.\n- Prefer direct labeling and restrained color. Reserve semantic colors for meaning such as positive, warning, or negative states.\n- Keep annotations selective and evidence-backed.\n- Make dense charts readable through aggregation, faceting, filtering, or a table rather than shrinking text.\n- Provide accessible contrast, text alternatives, and a data table when the destination supports them.\n- Put provenance in a source note rather than cluttering the title.\n\n## QA\n\n- Recompute plotted values from the reviewed rows.\n- Confirm the visual answers the stated question and does not imply unsupported causality.\n- Check ordering, scales, labels, clipping, overlap, empty states, and small-screen behavior where relevant.\n- Confirm the exported file opens and contains the expected marks and text.\n- Preserve the code or notebook needed to reproduce the chart when the user needs an auditable artifact.\n\n","packages/cli/src/skill/builtin/.bundle/deep-research/SKILL.md":"---\nname: deep-research\ndescription: Deep research on any topic using parallel sub-agents and built-in tools only (WebSearch/WebFetch + free APIs, no keys). Use when the user asks for a thorough multi-source investigation with a cited report — \"深度调研X\"、\"deep research\"、\"帮我全面研究一下\"、\"多方求证\"、\"写一份调研报告\". NOT for simple lookups (single WebSearch suffices) and NOT for academic literature surveys (use auto-research skill instead).\n---\n\n# Deep Research\n\nOrchestrate parallel research sub-agents, then write one coherent cited report. Research is parallel; writing is single-point — never let multiple agents write report sections.\n\n## Step 0 — Always first\n\n1. Run `date +%Y-%m-%d` via Bash. Never assume the current year from training data.\n2. Triage:\n   - Answerable with 1-2 searches? → STOP, just use WebSearch directly. Do not use this skill.\n   - Enumeration task (N items × M fields, e.g. \"compare 20 frameworks\")? → still this skill, but use table-oriented decomposition (one sub-agent per item batch).\n   - Open-ended investigation? → continue below.\n3. Pick depth (default **standard**; user can override with words like \"quick\"/\"exhaustive\"):\n\n| Mode | Sub-agents (round 1) | Max follow-up rounds | Sources target |\n|---|---|---|---|\n| quick | 2-3 | 0 | 8+ |\n| standard | 3-5 | 1 | 15+ |\n| deep | 5-8 | 2 | 25+ |\n\nThese are hard budgets. Reflection (Phase 4) can spend them but never exceed them.\n\n## Workspace\n\nAll state lives on disk at `./research/<slug>/` — never only in context (survives compaction):\n\n```\nresearch/<slug>/\n├── brief.md         # research brief — the single contract for all phases\n├── findings/        # F1.md, F2.md ... one per sub-agent, structured evidence\n└── REPORT.md        # final deliverable\n```\n\nOn resume: re-read `brief.md` + list `findings/`, skip completed angles, continue.\n\n## Phase 1 — Scope\n\nAsk at most one round of clarifying questions (AskUserQuestion), only if genuinely ambiguous: audience, time frame, region, decision at stake. If the user said \"just run it\" or intent is clear, skip asking and write assumptions into the brief instead.\n\nThen write `brief.md`: refined question, scope boundaries (in/out), assumptions, depth mode, today's date. This brief — not the raw conversation — is what every later phase measures against.\n\n## Phase 2 — Plan\n\nDecompose the brief into 3-8 **independent** research angles. Pull from these lenses as applicable: core facts/definitions · recent developments (last 12 months) · quantitative data/benchmarks · counter-arguments & failure cases · practitioner experience (forums, issues) · academic work · key players/alternatives.\n\nList angles in `brief.md` under `## Angles`. For deep mode or contested topics, show the angle list to the user for a quick confirm before spending budget.\n\n## Phase 3 — Parallel research\n\nSpawn one sub-agent per angle **in a single message** (parallel). Build each prompt from the locked template in [reference/subagent-prompt.md](reference/subagent-prompt.md) — reproduce it verbatim, replacing only the `{variables}`. Each sub-agent:\n\n- researches ONE angle only, using WebSearch/WebFetch and the free endpoints in [reference/sources.md](reference/sources.md)\n- writes structured findings to `findings/F<n>.md` (claim / quote / URL / date / confidence per item)\n- returns only a 3-5 line summary to you — raw page content must never enter your context\n\nIf a sub-agent fails or returns thin results, note it and move on; do not block other angles.\n\n## Phase 4 — Reflect (gap check)\n\nRead all `findings/*.md`. Against `brief.md`, ask: which parts of the brief have no evidence? Which major claims rest on a single source? Where do sources conflict?\n\n- Gaps found AND follow-up budget remains → spawn targeted sub-agents with delta-queries (same template, narrower angle). Repeat once per remaining round.\n- No budget left or coverage sufficient → proceed. Record unresolved gaps; they go in the report's \"Open questions\".\n\n## Phase 5 — Write (single-point)\n\nYou alone write `REPORT.md` in one pass, following [reference/report.md](reference/report.md). Core rules:\n\n- Every non-obvious claim carries an inline citation `[n]` mapping to a Sources section; citation URLs come only from findings files — never from memory.\n- Where sources conflict, present both sides with dates; prefer newer + primary sources.\n- Mark single-source claims with `[single source]`, speculation with `[speculative]`.\n- End with: Open questions · Sources (numbered, with access date).\n\nFor deep mode, before finalizing do one critique pass: reread the report as a skeptical reviewer (unsupported claims? stale data? missing counter-view?) and fix in place.\n\nFinally, give the user a 5-10 line summary of key conclusions and the report path.\n","packages/cli/src/skill/builtin/.bundle/docx-official/README.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fdocx-official%2FREADME.md -->","packages/cli/src/skill/builtin/.bundle/docx-official/SKILL.md":"---\nname: docx-official\ndescription: \"Use this skill whenever a Microsoft Word (.docx) file is being produced, opened, transformed, or read. That includes: drafting reports, letters, contracts, RFPs, technical documents, or any long-form written deliverable; extracting text or structure from an existing Word file; filling a Word template with values; converting Word to PDF or plain text; splitting or merging documents; inspecting styles, headings, sections, tables, images, comments, or tracked changes. Trigger on mentions of 'Word doc', 'DOCX', 'Office document', a filename ending in .docx, or requests like 'turn this into a Word report'.\"\nlicense: Apache-2.0 — see LICENSE for terms and third-party attributions\n---\n\n# DOCX Skill\n\nAn Apache-2.0 toolkit for producing, editing, and reading Microsoft Word (`.docx`) files. Written from scratch against the public [ECMA-376 / ISO/IEC 29500](https://www.ecma-international.org/publications-and-standards/standards/ecma-376/) specification and built on permissively-licensed tooling (`python-docx` MIT, `lxml` BSD-3-Clause, optional external binaries `pandoc` and `soffice`) so it can be reused in commercial projects without restriction.\n\n## Decision matrix\n\n| Situation | Path | Read first |\n|-----------|------|------------|\n| No source file — build a document from a prompt / data | Author from scratch with `python-docx` | [`create.md`](create.md) |\n| You have a `.docx` template to fill in or lightly modify | Placeholder replacement via `python-docx`, keeps styles | [`edit.md`](edit.md) → *Workflow A — `python-docx` in-place edit* |\n| Deep structural edits, new sections, custom XML, unusual layouts | Explode → edit XML → assemble | [`edit.md`](edit.md) → *Workflow B — Explode → edit XML → assemble* |\n| You only need the text / structure / metadata out of a `.docx` | Extraction pipeline | [`read.md`](read.md) |\n| Need a PDF preview for QA | `scripts/render_pdf.py` via LibreOffice | see *QA* below |\n\nIf the task mixes several of these, do them in this order: **read → plan → edit/create → validate**.\n\n## One-time environment setup\n\n> **Bundled runtime:** when the `MIMO_PYTHON` environment variable is set, skip `uv`/`python3` and pip installs entirely — run every command below with `uv run` replaced by `\"$MIMO_PYTHON\"` (e.g. `\"$MIMO_PYTHON\" scripts/extract_text.py input.docx`). This skill's Python dependencies are preinstalled in that interpreter; pip console scripts are unavailable, so always go through `\"$MIMO_PYTHON\" -m <module>`. A bundled LibreOffice is exposed as `MIMO_SOFFICE` and picked up automatically by the scripts here.\n\nAll scripts include [PEP 723](https://peps.python.org/pep-0723/) inline metadata, so `uv run` resolves dependencies automatically — no manual install step needed. Just run:\n\n```bash\nuv run scripts/extract_text.py input.docx\n```\n\nIf you don't use `uv`, install dependencies once:\n\n```bash\npython3 -m pip install --upgrade python-docx lxml\n# Optional but recommended:\n#   LibreOffice (for docx → pdf preview):   brew install --cask libreoffice   (macOS)\n#                                           apt-get install -y libreoffice    (Debian/Ubuntu)\n#   Poppler   (for pdf → image, QA loop):   brew install poppler\n```\n\nAlternatively, if this skill lives in a persistent workspace you can `uv init` a project, `uv add python-docx lxml`, and run scripts with `uv run scripts/...` from the project root — this gives you a lockfile and reproducible environment.\n\nAll scripts here use the standard library plus `python-docx`. No proprietary dependencies.\n\n## Common commands\n\n```bash\n# 1. Extract plain text (best for \"what does this file say?\" questions)\nuv run scripts/extract_text.py input.docx > input.txt\n\n# 2. Explode a .docx into readable XML for structural surgery\nuv run scripts/explode.py input.docx exploded/\n\n# 3. Assemble an exploded directory into a fresh .docx\nuv run scripts/assemble.py exploded/ output.docx\n\n# 4. Render a .docx as PDF (used for visual QA)\nuv run scripts/render_pdf.py output.docx           # writes output.pdf next to it\n\n# 5. Well-formedness check (ZIP integrity + parseable XML + python-docx open)\nuv run scripts/audit.py output.docx\n\n# 6. Accept every tracked change without needing Word/LibreOffice\nuv run scripts/resolve_revisions.py reviewed.docx clean.docx\n\n# 7. Add a comment to an exploded directory\nuv run scripts/annotate.py exploded/ \"Please check\" --author \"Reviewer\" --anchor \"text\"\n```\n\nEvery script is a small, self-contained Python file. Read the top of the file for full CLI options.\n\n## Authoring principles\n\nWord is a **flowing** document format, not a slide surface. Users expect it to look like something a human wrote in Word — not a design tool trying to reinvent typography. Keep that in mind:\n\n1. **Rely on named styles.** Use `Heading 1`, `Heading 2`, `Normal`, `Title`, `Quote`, `List Bullet`, `List Number`, `Caption`. They are what makes Word's ToC, navigation pane, and cross-references work.\n2. **One idea per paragraph.** Long paragraphs are fine; run-on paragraphs are not. Break at logical boundaries.\n3. **Structure first, prose second.** Draft the heading tree, then write inside it. Reviewers scan headings before words.\n4. **Tables for tabular data only.** Do not use tables to fake multi-column layouts — export to PDF and users see the borders through the layout.\n5. **Line length is set by page margins, not by hard breaks.** Never insert manual line breaks to control wrapping.\n6. **Use fields, not literal text, for things that change** — page numbers, dates, ToC, cross-references. `python-docx` supports field codes via low-level XML (see `edit.md`).\n7. **Every image needs alt text** — accessibility, and Word screams at you in review mode when it's missing.\n\n## Typography defaults (safe starting point)\n\n| Element        | Font          | Size | Weight | Notes |\n|----------------|---------------|------|--------|-------|\n| Title          | Calibri Light | 28pt | Bold   | Centered or left, one line |\n| Heading 1      | Calibri Light | 18pt | Bold   | Space before 12pt |\n| Heading 2      | Calibri Light | 14pt | Bold   | Space before 10pt |\n| Heading 3      | Calibri       | 12pt | Bold   | Space before 6pt |\n| Body           | Calibri       | 11pt | Regular| Line spacing 1.15, space after 6pt |\n| Caption        | Calibri       | 9pt  | Italic | Muted gray `#595959` |\n| Code / mono    | Consolas      | 10pt | Regular| Left-aligned, no first-line indent |\n\nChange the palette for the topic — muted navy `#1F3A5F` for legal/finance, warm charcoal `#2E2A26` for editorial. Avoid pure `#000000` for body text; `#1F1F1F` reads softer on print.\n\n## Page setup (A4 vs Letter)\n\nAsk the user which one to use. If you cannot ask, default to the region implied by the language (Chinese/European → A4, US English → Letter). Margins:\n\n| Size   | Width × Height    | Standard margins (T/B/L/R) |\n|--------|-------------------|-----------------------------|\n| A4     | 21.0 × 29.7 cm    | 2.54 / 2.54 / 3.18 / 3.18 cm |\n| Letter | 8.5 × 11.0 in     | 1.00 / 1.00 / 1.25 / 1.25 in |\n\n## QA checklist — always run before declaring done\n\n**Assume something is wrong.** Word files fail silently: a broken relationship, an unclosed `<w:p>`, a missing style — Word will still open the file but strip content or throw a \"content had problems\" warning. Verify explicitly.\n\n1. **Open cleanly** — no repair prompt.\n   ```bash\n   uv run python -c \"import docx; docx.Document('output.docx')\"   # loads without exceptions\n   ```\n2. **Text integrity** — no placeholder residue.\n   ```bash\n   uv run scripts/extract_text.py output.docx | grep -Ei \"TODO|TBD|\\{\\{|lorem|xxxx\"\n   ```\n   Grep must return nothing.\n3. **Visual sanity** — render a PDF, open the first and last pages, scan for:\n   - Widowed headings alone at the bottom of a page.\n   - Tables split awkwardly across pages.\n   - Images pushed to their own page because they exceeded content width.\n   - Missing page numbers, wrong header/footer content.\n   ```bash\n   uv run scripts/render_pdf.py output.docx\n   ```\n4. **Style hygiene** — every heading uses a real style, not just bold+large text:\n   ```bash\n   uv run python -c \"\n   import docx; d = docx.Document('output.docx')\n   for p in d.paragraphs:\n       if p.text and p.style.name == 'Normal' and p.runs and p.runs[0].bold:\n           print('possible fake heading:', p.text[:80])\"\n   ```\n\nIf any of these fail, fix and re-run — don't paper over.\n\n## What is out of scope\n\n- **`.doc` (legacy Word 97-2003)** — this skill only targets `.docx` (Office Open XML). Convert `.doc` to `.docx` with LibreOffice first: `soffice --headless --convert-to docx old.doc`.\n- **Live collaborative editing** — the Word online API is a separate concern; here we produce and modify files.\n- **Macros / VBA** — do not generate `.docm` files. If the user asks for automation, offer a Python script that regenerates the doc instead.\n\n## Where each detail lives\n\n- **Creating from scratch**: [`create.md`](create.md) — headings, paragraphs, styles, tables, images, page setup, headers/footers, tables of contents.\n- **Editing / templating**: [`edit.md`](edit.md) — placeholder replacement, section swap, raw XML surgery, tracked changes, comments.\n- **Reading / extracting**: [`read.md`](read.md) — plain-text export, structural walk, metadata, table extraction.\n- **Scripts**: [`scripts/`](scripts/) — self-contained CLI utilities used by all of the above.\n","packages/cli/src/skill/builtin/.bundle/grok-build/SKILL.md":"---\nname: grok-build\ndescription: Reference and workflow guidance for the Grok Build CLI (`grok`), including interactive and headless runs, authentication, sessions, worktrees, permissions, sandboxing, MCP servers, plugins, inspection, updates, and automation output. Invoke only when the user explicitly requests the `grok-build` skill, explicitly asks to use Grok Build CLI, or an already-selected workflow requires Grok Build; do not invoke for general coding, generic shell tasks, or other agent CLIs.\n---\n\n# Grok Build CLI\n\nOperate Grok Build from a terminal while keeping execution mode, permissions, sandboxing, session state, and output handling explicit.\n\n## Start with Local Evidence\n\n1. Confirm that the CLI is available:\n\n   ```bash\n   command -v grok\n   grok version\n   ```\n\n2. Inspect the installed command before giving version-sensitive advice:\n\n   ```bash\n   grok --help\n   grok <subcommand> --help\n   ```\n\n3. Inspect the configuration discovered for the target workspace when behavior depends on rules, skills, plugins, hooks, or MCP servers:\n\n   ```bash\n   grok --cwd /path/to/repo inspect\n   grok --cwd /path/to/repo inspect --json\n   ```\n\n4. Treat current official documentation and installed help as authoritative when they differ from this bundled reference.\n\n## Choose an Execution Mode\n\n- Run `grok` with no arguments for the interactive TUI.\n- Run `grok \"<initial prompt>\"` to open the TUI with an initial task.\n- Run `grok -p \"<prompt>\"` for one non-interactive turn that prints a result and exits.\n- Run `grok agent stdio` for an ACP client that communicates over stdin/stdout.\n- Run `grok dashboard` to open the Agent Dashboard.\n\nPrefer headless mode for scripts, CI, bots, and agent orchestration. Prefer ACP only when the caller implements the ACP JSON-RPC lifecycle and consumes `session/update` chunks.\n\n## Authenticate\n\nUse an interactive login on a developer machine:\n\n```bash\ngrok login\n```\n\nUse device-code authentication in headless or remote environments:\n\n```bash\ngrok login --device-auth\n```\n\nUse a locally cached login or provide `XAI_API_KEY` only to the process that needs it. Never print, persist, or commit credentials. Use `grok logout` to clear cached credentials.\n\n## Run Headlessly\n\nUse an explicit working directory and output format:\n\n```bash\ngrok --no-auto-update \\\n  --cwd /path/to/repo \\\n  --sandbox workspace \\\n  -p \"Inspect the repository and explain the failing test.\" \\\n  --output-format json\n```\n\nChoose output according to the consumer:\n\n- Use `plain` for humans.\n- Use `json` for one final machine-readable object.\n- Use `streaming-json` for newline-delimited incremental events.\n- Add `--json-schema '<schema>'` when the installed CLI supports constrained structured output.\n\nPass `--no-auto-update` in scripts and CI to suppress background update checks. Do not parse interactive TUI rendering in automation.\n\n## Control Permissions and Isolation\n\nTreat permissions and sandboxing as separate controls:\n\n- Use permission rules to decide whether a tool call may run.\n- Use a sandbox profile to limit what an approved call may access.\n- Prefer `--sandbox workspace` for normal repository changes.\n- Prefer `--sandbox read-only` for review and auditing.\n- Prefer `--sandbox strict` for an untrusted repository, then add narrow permission rules.\n- Use `--allow <RULE>` and `--deny <RULE>` for per-run policy; remember that deny rules win.\n- Use `--always-approve` only when the environment and command scope justify unattended execution. Pair it with a suitable sandbox and explicit deny rules.\n\nDo not describe `--always-approve` as equivalent to sandboxing. The sandbox is off by default unless configured or selected.\n\n## Manage Sessions and Worktrees\n\nContinue or resume intentionally:\n\n```bash\ngrok -c\ngrok --resume <session-id>\ngrok --resume\n```\n\nUse `--session-id <UUID>` for a new named session, not to resume an existing one. Add `--fork-session` when branching from a resumed session.\n\nUse a worktree when concurrent work could collide:\n\n```bash\ngrok --worktree --ref main \"Fix the flaky test\"\ngrok --worktree=feature-name \"Implement the feature\"\n```\n\nPreview removal with `grok worktree rm --dry-run <id>` before deleting a worktree. Do not assume deleting a session removes its worktree.\n\n## Diagnose Before Editing Configuration\n\nUse built-in inspection and diagnostics first:\n\n```bash\ngrok inspect --json\ngrok mcp list --json\ngrok mcp doctor\ngrok plugin list\ngrok models\n```\n\nPrefer `grok mcp add`, `grok mcp remove`, and plugin subcommands over manually editing configuration when the CLI supports the requested operation. Keep secrets in environment variables rather than command history or committed configuration.\n\n## Read the Bundled References\n\n- Read [references/cli-reference.md](references/cli-reference.md) for the subcommand and common flag index.\n- Read [references/workflows.md](references/workflows.md) for headless execution, sessions, worktrees, permissions, sandboxing, and MCP examples.\n\nVerify destructive commands such as session deletion, plugin removal, MCP removal, memory clearing, and worktree removal with the user or the governing workflow before running them.\n","packages/cli/src/skill/builtin/.bundle/html-to-video-pipeline/SKILL.md":"---\nname: html-to-video-pipeline\ndescription: Reliable HTML-to-MP4 rendering via headless browser recording (Playwright/Puppeteer) + ffmpeg — the ordering, gotchas, and verification steps you MUST get right or the output silently rots. Trigger whenever the user is building or debugging any pipeline that turns an HTML/CSS/JS page (single-file, multi-composition, GSAP-driven, or `@keyframes`-driven) into a video file, including headless recording, screen capture of a web page, deterministic frame-by-frame capture, multi-scene concatenation, or engine-mixed video output. Also trigger when the symptom sounds like: font swap flashing in the opening frames (FOUT), the first few seconds of the video are frozen/dead, animations play during page load and get truncated, concatenated segments produce a video whose duration is wildly wrong (e.g., 8s becomes 35s), `file://` loaded HTML fails to fetch its sub-scenes, the exported video is soft/blurry compared to the browser, or playback stutters/looks choppy despite passing a high `-r` fps to ffmpeg. Use even for one-off scripts — the failure modes here are subtle enough that starting from scratch usually reintroduces them.\n---\n\n# HTML → Video: the pipeline that actually works\n\nTurning a live HTML page into an MP4 sounds like a one-liner (\"Playwright records, ffmpeg encodes\") and the first draft always looks fine — until you play back the export and notice text flashing in a fallback font, three dead seconds at the start, or a \"10-second\" clip that clocks in at 35s. This skill captures the specific ordering, waits, and encoder flags that make the output trustworthy.\n\nThink of the pipeline as five phases with a single invariant between them:\n\n```\nlaunch  →  hold @ frame 0  →  align capture start with animation start  →  record  →  trim & encode\n```\n\nThe invariant: **no pixel of the animation should render before capture is ready, AND capture must not start before every asset that affects layout has loaded.** Every gotcha below is a violation of that invariant.\n\nQuick checklist (each item is expanded below):\n\n1. `viewport` must exactly equal `recordVideo.size` — mismatch silently rescales the output soft/blurry.\n2. Freeze CSS animations via `addInitScript` **before** `goto()`.\n3. `goto` with `domcontentloaded`, never `load`.\n4. Pre-inline `data-composition-src` sub-scenes — `file://` blocks client-side `fetch`.\n5. Font wait = stylesheet `<link>` load → `face.load()` per face → `fonts.ready` → 2 rAFs.\n6. Probe duration with infinite-iteration / `repeat: -1` guards.\n7. Unfreeze = t=0; trim `leadInMs − 120ms` with `-ss` *before* `-i`.\n8. Concat: same engine → demuxer `-c copy`; mixed engines → concat *filter* + re-encode.\n9. Verify with ffprobe duration + full decode + sampled frames. Always.\n\nThere are two capture modes, and picking the wrong one wastes a day:\n\n- **Mode A — real-time `recordVideo`** (the phases below). Simple, wall-clock = clip length. But the screencast is best-effort variable frame rate (~25fps) and competes with the animation for CPU. Good enough for previews and ≤30fps deliverables on an idle machine.\n- **Mode B — deterministic frame stepping** (pause everything, seek to `i / fps`, screenshot, encode the PNG sequence). Exact fps, every frame rendered, no lead-in trim, immune to machine load. Required when the output must be genuinely smooth ≥30fps or renders run on loaded CI. See \"Deterministic frame stepping\" below.\n\n## Prerequisites — install these first\n\nTwo hard requirements: a headless browser driver (Playwright or Puppeteer) and `ffmpeg`. Everything below assumes both are installed and on `PATH`.\n\n### 1. Headless browser driver\n\nPlaywright is the default in this skill (its `recordVideo` API is what the pipeline is written against). Puppeteer works too but you'll wire recording yourself via CDP screencast — pick Playwright unless you have a reason not to.\n\n```bash\n# Playwright (recommended) — npm / pnpm / bun all work\nnpm  install playwright\npnpm add playwright\nbun  add playwright\n\n# Then install the actual browser binaries (this is the step people forget):\nnpx playwright install chromium              # just Chromium — enough for this pipeline\nnpx playwright install --with-deps chromium  # Linux/CI: also install shared libs\n```\n\nVerify: `npx playwright --version` prints the driver version, and `node -e \"require('playwright').chromium.launch().then(b => b.close())\"` exits cleanly.\n\nPuppeteer alternative (only if you already have it in the project):\n\n```bash\nnpm install puppeteer            # bundles a matching Chromium automatically\n# or, to reuse a system Chrome:\nnpm install puppeteer-core       # no bundled browser — you supply executablePath\n```\n\n### 2. ffmpeg\n\nThe encode/trim/concat/verify steps all shell out to `ffmpeg` (and `ffprobe`, which ships in the same package). It is **not** an npm dependency — install it at the OS level.\n\n```bash\n# macOS\nbrew install ffmpeg\n\n# Debian / Ubuntu\nsudo apt-get update && sudo apt-get install -y ffmpeg\n\n# Fedora / RHEL\nsudo dnf install ffmpeg          # requires RPM Fusion enabled\n\n# Windows\nwinget install Gyan.FFmpeg       # or: choco install ffmpeg\n```\n\nVerify: `ffmpeg -version` and `ffprobe -version` both print. If a script spawns `ffmpeg` and gets `ENOENT`, the binary isn't on `PATH` — see the graceful-failure snippet in `references/ffmpeg-cheatsheet.md`.\n\nDo **not** rely on the `ffmpeg-static` / `@ffmpeg-installer/ffmpeg` npm packages for production: their bundled builds skip codecs and encoder flags you'll hit sooner or later (e.g. `libx264` presets, `tpad`). A system ffmpeg is the durable choice.\n\n### 3. Optional — ImageMagick (verification only)\n\nOnly needed if you want the \"did anything render?\" pixel-mean check from Phase 6. Skip it otherwise.\n\n```bash\nbrew install imagemagick         # macOS\nsudo apt-get install imagemagick # Debian/Ubuntu\n```\n\nVerify: `magick -version` (ImageMagick 7) or `convert -version` (ImageMagick 6).\n\n## The pipeline\n\n### Phase 1 — Launch and prepare the recorder\n\nUse `playwright.chromium.launch({ headless: true })` and a context configured with `recordVideo: { dir, size: { width, height } }`. Two sizing rules:\n\n- **`viewport` must exactly equal `recordVideo.size`.** When they differ, Playwright rescales the screencast to fit the recording size and the whole output goes soft. Derive both from the same constants.\n- `recordVideo` captures at CSS-pixel resolution; `deviceScaleFactor` does **not** raise recording resolution. For a 1080p export use a 1920×1080 viewport, not 960×540 @ 2x.\n\nRecording begins the instant the context exists — treat that timestamp as the WebM's t=0 and remember it (`tWebmStart = Date.now()`); you will need it in Phase 5 to trim the dead opening.\n\nKnow the recorder's ceiling: the screencast runs at a variable ~25fps and drops frames under CPU load. The `-r <fps>` flag in Phase 5 makes the container constant-frame-rate but only duplicates frames — it cannot add smoothness. If stutter matters, switch to frame stepping (Mode B) instead of fighting this.\n\n### Phase 2 — Freeze animations BEFORE the page parses\n\nThis is the single most-missed step. Pure-CSS `@keyframes` animations begin the moment the element is styled — there is no JS trigger to hold. If you `goto()` the HTML and then start waiting for fonts (which takes seconds), the CSS timeline has *already been running the whole time*. The recording captures the fallback font swapping to the real face mid-clip, and the opening beats of the animation are lost to the font wait.\n\nFix: inject a global freeze **via `page.addInitScript()`**, which runs before any of the document's own scripts and before CSS is applied, so the timeline is paused at frame 0 the moment it exists:\n\n```js\nawait page.addInitScript(() => {\n  const style = document.createElement('style');\n  style.id = '__freeze';\n  style.textContent =\n    '*, *::before, *::after { animation-play-state: paused !important;' +\n    ' -webkit-animation-play-state: paused !important; }';\n  const attach = () => (document.head || document.documentElement).appendChild(style);\n  if (document.head || document.documentElement) attach();\n  else document.addEventListener('DOMContentLoaded', attach, { once: true });\n  window.__unfreeze = () => document.getElementById('__freeze')?.remove();\n});\n```\n\nThis does not stop GSAP tweens driven by JS (see Phase 4 for those) — for GSAP-driven templates, register the master timeline paused and expose a `window.__playAll()` you call in Phase 4.\n\n### Phase 3 — Load with `domcontentloaded`, not `load`\n\n`waitUntil: 'load'` blocks on every external asset, including cross-origin videos with no CORS headers. Chromium will retry those for ~4s before giving up, and those 4s get burned into the recording as a frozen first scene. Use `waitUntil: 'domcontentloaded'` — the DOM + synchronous inline scripts (GSAP, your player) are ready, and you handle fonts explicitly next.\n\nIf the template is multi-composition (scenes loaded via `data-composition-src` and client-side `fetch`), you must **pre-inline** those sub-files into the entry HTML on the Node side and write it to a sibling `.tmp.html`. Chromium blocks `file://` fetch, so client-side scene loaders that work in a browser tab will silently produce an empty shell in a headless recording. See `references/multi-composition.md`.\n\n### Phase 4 — Wait for fonts properly, then release\n\n`document.fonts.ready` alone is **not enough** and this is the second most-missed step. Under `domcontentloaded`, the Google Fonts (or any external) `<link rel=\"stylesheet\">` has usually not returned yet. Until its CSS arrives, its `@font-face` rules are not in `document.fonts` at all — so `fonts.ready` sees an empty set and resolves *instantly*. Recording proceeds, the CSS lands mid-clip, faces download, and the swap happens on-camera.\n\nThe correct sequence, all inside a `page.evaluate()` with an 8s hard cap so a wedged CDN can't stall forever:\n\n1. Wait for every `<link rel=\"stylesheet\">` to `load` or `error` — that registers `@font-face` rules into `document.fonts`.\n2. For each registered face, call `face.load()` explicitly. `font-display: swap` defers the download until something paints with that face — if your first frame doesn't happen to use the face, it never fetches without this.\n3. `await fonts.ready`.\n4. Two rAFs so layout settles on the real glyph metrics before frame 0.\n\nThen, and only then:\n\n5. Drive playback: for GSAP multi-composition templates, call `window.__playAll()` to start every registered (paused) master timeline from 0. For pure-CSS templates, this is a no-op.\n6. Call `window.__unfreeze()` to remove the freeze style. **This is the true t=0 of the animation.** Record the wall-clock offset from `tWebmStart` (`leadInMs = Date.now() - tWebmStart`) — this is what you trim in Phase 5.\n\nThe full JS for Phase 4 is in `references/font-wait.md`.\n\n### Phase 5 — Probe duration, record, then trim and encode\n\n**Probe duration first** (skip this only if you know the exact intended length). The user's requested `duration` may be shorter than the animation, in which case you'd cut the animation mid-play. Take the maximum of:\n\n- The longest **non-infinite** CSS animation (`animation-duration + animation-delay` for entries where `animation-iteration-count !== 'infinite'`).\n- The longest **finite** GSAP tween. Do **not** use `gsap.globalTimeline.totalDuration()` — a `repeat: -1` tween (blinking cursor, looping background) makes it ~1e10s. Walk `globalTimeline.getChildren(true, true, true)` and skip anything with `repeat() === -1`.\n\nAdd a ~400ms settle so the last animation frame is captured, cap at 30s so a stray huge value can't run away. If your caller passed an *explicit* per-frame duration (e.g. \"each scene is exactly 4s\"), do **not** extend — treat it as a hard cap and pad the tail if the animation finished early (see below). If duration was 'auto', extend to the probed length.\n\n**Record** for `totalDuration`, then `context.close()`. Playwright drops the WebM in `recordDir`.\n\n**Encode with ffmpeg**, applying two corrections:\n\n```\nffmpeg -y \\\n  [ -ss <(leadInMs - 120) / 1000> ]  # trim dead lead-in, back off 120ms so we don't clip frame 1\n  -i input.webm \\\n  [ -vf tpad=stop_mode=clone:stop_duration=<totalDuration> ]  # pad tail only when duration is explicit\n  -t <totalDuration> \\                # trim to exact length (recordVideo sometimes overshoots)\n  -r <fps> \\\n  -c:v libx264 -pix_fmt yuv420p -preset medium -crf 20 \\\n  -movflags +faststart \\\n  out.mp4\n```\n\nThe `-ss` back-off matters: recorder start jitter and rounding can steal the first real frame if you trim to exactly `leadInMs`. A couple of extra still frames at the head are invisible; a missing opening beat is obvious.\n\n## Deterministic frame stepping (Mode B)\n\nWhen the deliverable must be genuinely smooth at an exact fps — or the render runs on a loaded CI box where real-time capture visibly stutters — don't record in real time at all. Keep Phases 1–4 (minus `recordVideo`), then: pause every timeline, seek to `i / fps`, `page.screenshot()` each frame, and encode the PNG sequence with `ffmpeg -framerate <fps>`. Duration is exact by construction, there is no lead-in to trim, and every single frame is fully rendered regardless of machine load.\n\nIt works when the page's motion is declaratively seekable — CSS `@keyframes` (via `document.getAnimations()` + `currentTime`), WAAPI, and GSAP (`gsap.globalTimeline.time(t)`). It does **not** work for `<video>` elements, `setTimeout`-choreographed scenes, or rAF-driven physics; those need real-time recording or a CDP virtual clock. Step time monotonically forward, never backwards.\n\nFull loop, the seek/suppressEvents subtleties, the \"animations created later by JS are invisible to the seek\" trap, and optional 2x supersampling are in `references/frame-stepping.md`.\n\n## Multi-segment concatenation\n\nWhen you have N per-scene MP4s and need one output, the correct ffmpeg strategy depends on whether the inputs share a codec/timebase.\n\n**Same encoder, same params (typical: all scenes rendered by the same adapter)** — use `concat` demuxer with stream copy. Fast, lossless:\n\n```\nffmpeg -y -f concat -safe 0 -i list.txt -c copy out.mp4\n```\n\nwhere `list.txt` is `file 'seg1.mp4'\\nfile 'seg2.mp4'\\n...`.\n\n**Mixed sources (e.g. scene A recorded by headless Chromium, scene B rendered by a React/Remotion pipeline)** — the concat demuxer's `-c copy` path assumes compatible timebases and PTS. When timebases differ, PTS accumulate incorrectly and an 8-second output can become 35 seconds. **Even `-vsync cfr` won't save you** — the bad PTS have already been fed in. You must re-encode via the concat **filter**, which rebuilds the timeline:\n\n```\nffmpeg -y -i seg1.mp4 -i seg2.mp4 -i seg3.mp4 \\\n  -filter_complex \"[0:v][1:v][2:v]concat=n=3:v=1:a=0[v]\" \\\n  -map \"[v]\" -c:v libx264 -pix_fmt yuv420p -r 60 \\\n  -movflags +faststart out.mp4\n```\n\nDecision rule in code: pass a `reencode: boolean` down to your concat helper. Set it to `true` whenever any segment came from a different rendering engine than the others, or when you're not sure.\n\n## Verify — always\n\nYou cannot trust \"the file was written\" as success. The failure modes above (wrong duration, FOUT, dead lead-in) all produce a playable MP4. Before declaring success:\n\n- `ffprobe -v error -show_entries format=duration -of csv=p=0 out.mp4` — actual duration matches expected within ~50ms?\n- `ffmpeg -v error -i out.mp4 -f null -` — full decode, no errors? A \"silently corrupted\" output from a bad concat will decode fine but be the wrong length; conversely, a broken concat demuxer output can throw here.\n- Sample a frame near t=0.1s and t=0.5s (`ffmpeg -ss 0.1 -i out.mp4 -frames:v 1 -y f1.png`) — text renders in the intended font? If your test rig has ImageMagick, `magick f1.png -threshold 50% -format '%[fx:100*mean]' info:` gives a rough non-background pixel percentage that catches \"recording is completely blank\" regressions.\n\nFor fonts specifically: **studio-style live iframe previews will not reproduce FOUT** because the browser tab caches faces. Only cold-headless rendering (i.e. the actual export path) reproduces it. Verify on the exported MP4, not the preview.\n\n## When to depart from this template\n\n- **Non-animated single-frame PNG export.** Skip Phases 2, 4-5-recording; goto → `fonts.ready` → `page.screenshot()` is enough. FOUT still applies for the screenshot.\n- **You own the animation timeline in JS end-to-end** (e.g. Motion Canvas / Remotion generator style). The freeze/unfreeze dance is unnecessary because *you* drive frame-by-frame rendering — use the framework's own frame API and skip Playwright recording entirely. The concat rules still apply if you're mixing engines.\n- **Interactive-page capture** (recording a real user session). Duration probing is meaningless; use manual start/stop signals and skip lead-in trim.\n\n## Reference files\n\n- `references/font-wait.md` — full JS for the Phase 4 font-wait routine, with per-link timeout and rAF-based settle.\n- `references/frame-stepping.md` — the Mode B deterministic capture loop: seek-per-frame, screenshot, PNG-sequence encode, supersampling, and its limits.\n- `references/multi-composition.md` — inlining `data-composition-src` scenes for `file://` recording, including re-executing cloned `<script>` nodes.\n- `references/duration-probe.md` — CSS + GSAP probe with the infinite-iteration guards.\n- `references/ffmpeg-cheatsheet.md` — the encode/concat/verify commands in one place.\n","packages/cli/src/skill/builtin/.bundle/learn-everything/SKILL.md":"---\nname: learn-everything\ndescription: Turn an uploaded PDF, paper, book chapter, document, URL, or user-provided topic into a structured, interactive learning course. Use when the user wants to learn, study, understand, master, review, or practice a subject chapter by chapter; asks for a tutorial or curriculum from source material; wants exercises, quizzes, answer grading, hints, spaced review, or a final assessment; or says \"teach me this\", \"learn this PDF\", \"分章节教学\", \"带我学\", or similar; or returns to continue a previous course (\"continue my course\", \"接着上次学\") or supplies a saved course-state file or state block. Adapt explanations and practice to the learner's level, preserve page or section references for documents, and teach incrementally rather than dumping all content at once.\n---\n\n# Learn Everything\n\nConvert source material or a topic into an adaptive course that alternates explanation, retrieval, application, feedback, and review.\n\n## Core behavior\n\n- Teach in the user's language unless they request another language.\n- Optimize for durable understanding, not merely summarization.\n- Work incrementally. Present a course map, then teach one chapter or lesson at a time.\n- Do not reveal exercise solutions before the learner attempts them, unless the learner explicitly asks.\n- Persist learning state. When file tools are available, maintain `learn/<slug>/course-state.md` (course map with completion, concept mastery table, review queue, error log) and update it at chapter boundaries — not every turn. Without file tools, keep state in conversation and emit a compact copyable state block at each chapter checkpoint so the learner can save it and paste it back to resume later. See `references/session-formats.md` for both formats.\n- Prefer concrete examples, analogies, diagrams described in text, counterexamples, and worked derivations over abstract exposition alone.\n- Separate source claims from added background knowledge. Never attribute added material to the source.\n- Match depth and notation to the learner. Define unfamiliar terms before relying on them.\n\n## Determine the input mode\n\n### Document mode\n\nUse document mode for PDFs, papers, books, slides, notes, or other supplied material.\n\n1. Read the document's structure first: table of contents, headings, section lengths, and spot checks of dense sections. Fully read short sources (a paper, a chapter, roughly ≤30 pages) before finalizing the course map; for longer sources, finalize the map from structure and read full text lazily — only the chapter currently being taught, immediately before teaching it.\n2. Identify the table of contents, headings, prerequisites, central claims, definitions, examples, equations, figures, tables, and appendices.\n3. Use semantic units rather than equal page ranges. Merge short dependent sections and split dense sections.\n4. Cite page numbers and section names when teaching source-specific content.\n5. Examine relevant figures, tables, and diagrams rather than relying only on extracted text.\n6. Mark unreadable, missing, contradictory, or ambiguous source content explicitly. Do not invent a reconstruction.\n7. Treat the supplied source as the primary curriculum. Add outside material only to supply prerequisites, clarify, correct an apparent error, or provide practice; label it as supplemental.\n\n### Topic mode\n\nUse topic mode when the learner supplies a subject rather than a source.\n\n1. Define a sensible scope and end capability.\n2. Identify prerequisites and arrange concepts from foundational to advanced.\n3. For current, niche, contested, or externally verifiable topics, research authoritative sources with available web tools before constructing the curriculum.\n4. Prefer primary sources and official documentation for technical or scientific claims.\n5. Distinguish stable fundamentals from current developments.\n6. State material scope and assumptions in the course map.\n\nDo not delay progress for minor ambiguity. Choose a useful default scope and make it visible.\n\n### Resume mode\n\nUse resume mode when the learner supplies a saved course-state file or state block, or asks to continue a previous course.\n\n1. Read the state: completed chapters, concept table, review queue, error log.\n2. Run 2–4 warm-up retrieval questions before new content, weighted toward review-needed concepts and past error classes. Ask fresh questions, never the originals verbatim.\n3. Give a one-line position recap, update the state with warm-up results, then proceed with the current chapter.\n4. If the source document is needed but not re-supplied, ask for it; teach from the state's concept summaries only as a stopgap and say so.\n\n## Start the course\n\nGather only information that materially changes the lesson. If the learner's level or goal is unknown, either:\n\n- ask one compact diagnostic question, or\n- offer a 3-question diagnostic quiz and let the learner skip it.\n\nDo not ask a long questionnaire. Infer preferences from the conversation whenever possible.\n\nThen provide:\n\n1. **Target capability** — what the learner should be able to explain or do.\n2. **Course map** — 3–12 chapters, each with purpose and prerequisites.\n3. **Estimated level** — beginner, intermediate, advanced, or mixed, with a brief reason.\n4. **Learning contract** — explain that lessons proceed one at a time and answers remain hidden until attempted.\n5. **Next action** — begin the first lesson or diagnostic immediately.\n\nUse the detailed formats in `references/session-formats.md` when consistency is useful.\n\n## Build the course map\n\nCreate chapters around conceptual dependencies, not source length alone. Each chapter should have:\n\n- a concise title;\n- one observable learning objective;\n- key concepts;\n- prerequisite links;\n- source pages or sections in document mode;\n- one planned practice outcome.\n\nUse these sizing rules:\n\n- Split a chapter when it contains more than one major reasoning jump.\n- Merge sections that cannot be understood independently.\n- Create a prerequisite bridge chapter when the source assumes missing knowledge.\n- Keep advanced appendices optional unless needed for the learner's goal.\n- For sources with more than ~12 natural chapters, group chapters into parts, agree on scope with the learner, and run the course part by part rather than flattening everything into one map.\n- Reorder only when pedagogically necessary; explain the reordering in document mode.\n\n## Teach each lesson\n\nFollow this lesson loop:\n\n1. **Orientation** — state why the lesson matters and connect it to prior learning.\n2. **Objectives** — give 2–4 observable goals.\n3. **Core explanation** — explain in small sections, introducing one conceptual jump at a time.\n4. **Worked example** — demonstrate the reasoning, not only the final result.\n5. **Misconception check** — identify 1–3 likely confusions or boundary cases.\n6. **Active recall** — ask a brief check before proceeding to longer practice.\n7. **Practice** — assign exercises calibrated to current mastery.\n8. **Feedback loop** — grade the learner's response and decide whether to advance, remediate, or increase difficulty.\n\nFor dense material, pause after each major concept and ask a single check question. For straightforward material, teach the full lesson before practice.\n\n## Design practice\n\nSelect exercises from multiple cognitive levels:\n\n- **Recall:** define, list, label, reproduce.\n- **Explain:** restate in the learner's own words; compare concepts; explain why.\n- **Apply:** solve a representative problem or use the method in context.\n- **Debug:** find an error in reasoning, code, derivation, or interpretation.\n- **Transfer:** apply the idea in a novel setting.\n- **Synthesize:** connect several chapters or produce an artifact.\n\nDefault to 3–5 exercises per lesson, mixing at least two levels. Prefer one exercise at a time when grading interactively. Use larger sets only when the learner requests a worksheet or exam.\n\nConsult `references/practice-and-mastery.md` for exercise-writing rules, difficulty bands, adaptation, and grading rubrics. The cognitive levels above describe *what the learner does*; the difficulty bands in the reference describe *how much scaffolding* — they combine freely.\n\n## Grade and respond to learner answers\n\nEvaluate substance before wording. Use this sequence:\n\n1. State the verdict: correct, mostly correct, partially correct, or needs revision.\n2. Identify what was done well.\n3. Point to the first important gap or error.\n4. Explain the correction with the smallest useful amount of teaching.\n5. Ask for a revision, provide a targeted follow-up, or advance.\n\nDo not merely say “correct.” Reinforce the decisive reasoning.\n\nWhen the answer is wrong:\n\n- First provide a hint that targets the misconception.\n- Give a stronger hint after another failed attempt.\n- Reveal a worked solution after repeated attempts, an explicit request, or when further guessing has low learning value.\n- Immediately follow a revealed solution with a near-transfer question.\n\nWhen the answer is correct:\n\n- Increase difficulty gradually.\n- Ask for explanation if the learner may have guessed.\n- Use a transfer question when mastery appears strong.\n\n## Track mastery and review\n\nMaintain a concept table — one row per concept — in the course state (file or state block):\n\n- status: unseen, introduced, practicing, mastered, or review-needed;\n- evidence: strongest recent answer or error;\n- confidence: low, medium, or high;\n- next review point.\n\nUpdate it at chapter boundaries and after significant errors. Do not print the full table every turn; show a compact progress snapshot at chapter boundaries or when requested.\n\nSchedule cumulative review:\n\n- after each chapter: 2–4 retrieval questions from current and earlier material;\n- after roughly one-third and two-thirds of the course: mixed checkpoint;\n- at course end: final assessment and synthesis task;\n- revisit recurring errors more often than mastered concepts.\n\nTreat mastery as demonstrated transfer, not one correct recall answer.\n\n## Handle learner commands\n\nRecognize and act on natural commands such as:\n\n- “继续 / continue” — move to the next pending step.\n- “提示 / hint” — give the next hint without the full answer.\n- “答案 / show solution” — reveal and explain the solution, then ask a near-transfer question.\n- “更简单 / simpler” — reduce abstraction, add prerequisites and examples.\n- “更深入 / deeper” — add derivation, edge cases, and harder transfer.\n- “跳过 / skip” — mark the item skipped and continue.\n- “复习 / review” — generate retrieval practice weighted toward weak concepts.\n- “考试 / test me” — run a closed-book mixed assessment.\n- “进度 / progress” — show completed chapters, mastery, weak points, and next step.\n- “重做课程 / rebuild course” — revise scope or chaptering while preserving demonstrated mastery.\n\n## Complete the course\n\nAt the end, provide:\n\n1. a mixed final assessment without solutions shown initially;\n2. a synthesis task that uses multiple chapters;\n3. grading with concept-level feedback;\n4. a concise mastery report;\n5. a personalized review plan focused on weak concepts;\n6. a compact reference sheet created only after assessment, so it does not replace retrieval practice.\n\nFor document mode, include a source navigation index linking mastered concepts back to pages or sections.\n\n## Quality checks\n\nBefore each response, verify:\n\n- Solutions are not exposed before the learner attempts the exercise.\n- The current activity matches the course state, and the state is updated at chapter boundaries.\n- The lesson does not assume an unexplained prerequisite.\n- The response gives the learner exactly one clear next action.","packages/cli/src/skill/builtin/.bundle/loop/SKILL.md":"---\nname: loop\ndescription: Schedule a prompt to fire on a fixed cadence (recurring loop). Use when the user asks to \"run X every N minutes/hours/days\", \"loop X\", \"babysit Y\", \"be proactive about Y every N\", or invokes `/loop` directly. Parses `[interval] <prompt>`, picks a clean cron expression, registers the job via the `cron` tool, and executes the prompt once immediately so the user sees activity without waiting for the first cron tick.\n---\n\n# /loop — schedule a recurring prompt\n\nThis skill turns a free-form `[interval] <prompt>` line into a `cron` tool call and runs the prompt once right away.\n\n## 1. Parse the input\n\nThe user's text is whatever appears after `/loop `. Apply the three rules below **in order** and stop at the first match.\n\n1. **Leading interval token.** If the first whitespace-separated token matches the regex `^\\d+[smhd]$` (case-insensitive), that token is the interval. Examples: `5m`, `2h`, `1d`, `30s`. The rest of the input is the prompt.\n\n2. **Trailing `every <N><unit>` clause.** Otherwise, look for a clause at the end of the input of the form `every <N><unit>` or `every <N> <unit-word>` where `<unit>` is `s|m|h|d` and `<unit-word>` is `second(s)|minute(s)|hour(s)|day(s)`. Strip the clause; what's left is the prompt; the captured `<N><unit>` is the interval. Examples: `every 20m`, `every 5 minutes`, `every 2 hours`.\n\n3. **Default.** No interval found → interval is `10m`, the whole input is the prompt.\n\nIf the input is empty, or is *only* an interval with no prompt body, reply with a one-line usage hint (`/loop [interval] <prompt>`) and stop. Do not schedule anything.\n\n## 2. Special: empty prompt with autonomous opt-in\n\nWhen the user types `/loop <interval>` (interval only) **and** the project has explicitly opted into autonomous-loop mode (a session-level flag the runtime sets), the prompt body is the sentinel `<<autonomous-loop>>`. The scheduler expands this sentinel at fire time into a self-directed tick instruction. If autonomous mode is not enabled, treat empty as the usage-hint case above.\n\n## 3. Map interval → 5-field cron expression\n\n| Pattern | Cron expression |\n|---|---|\n| `Ns` | treat as `ceil(N/60)m`; minimum is `1m` |\n| `Nm` where `N` is 1–59 and divides cleanly (1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30) | `*/N * * * *` |\n| `Nm` where `N ≥ 60` and `N/60` divides 24 (1, 2, 3, 4, 6, 8, 12) | `0 */(N/60) * * *` |\n| `Nh` where `N` is 1–23 and divides 24 | `0 */N * * *` |\n| `Nd` where `N` divides 31 sensibly (1, 2) | `0 0 */N * *` |\n\nCron fields are UTC. These interval patterns are timezone-agnostic; the `Nd`\nrow fires at midnight UTC, not local midnight.\n\n**Rounding rule.** If `N` does not divide its wrap-around cleanly (e.g. `7m`, `90m`, `5h`, `7d`), pick the **nearest interval that does** and tell the user explicitly what you rounded to and why. Acceptable nearby values:\n\n- minutes < 60: 1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30\n- hours: 1, 2, 3, 4, 6, 8, 12\n- days: 1, 2\n\nExamples of rounding messages:\n- `7m` → \"rounding 7m to 6m so the fires stay evenly spaced; `*/7` skews at the hour wrap\"\n- `90m` → \"rounding 90m to 2h; cron's hour field can't express 1.5h\"\n\n## 4. Call the cron tool\n\nWith the parsed `cron` expression and `prompt`, invoke the `cron` tool's `schedule` verb. Use whichever call form the tool's own prompt describes — pass `cron` and `prompt` as required, leave `durable: false` (the default; only set true when the user explicitly asked the job to persist across sessions), leave it recurring (the default; one-shot is wrong for `/loop` — one-shots come from natural-language scheduling).\n\nThe cron tool returns a job id. Mention it briefly so the user can cancel with `/loops cancel <id>`.\n\n## 5. Execute the prompt once immediately\n\nAfter the cron call succeeds, **do not wait for the first scheduled tick**. Run the prompt body once right now:\n\n- If the prompt starts with `/` (e.g. `/loop 5m /standup` → prompt is `/standup`), invoke it as a slash command — load the corresponding skill or command via the `skill` tool.\n- Otherwise, act on the prompt directly in this turn.\n\nThis is the \"don't make the user wait\" rule. The cron job carries the recurring behavior; the immediate run is for responsiveness.\n\n## 6. Examples\n\n| User input | Interval | Cron | Prompt |\n|---|---|---|---|\n| `/loop 5m /babysit-prs` | `5m` (leading) | `*/5 * * * *` | `/babysit-prs` |\n| `/loop check the deploy every 20m` | `20m` (trailing) | `*/20 * * * *` | `check the deploy` |\n| `/loop /standup every 2 hours` | `2h` | `0 */2 * * *` | `/standup` |\n| `/loop tidy inbox` | `10m` (default) | `*/10 * * * *` | `tidy inbox` |\n| `/loop 30s ping` | `30s` → `1m` | `*/1 * * * *` | `ping` |\n| `/loop 7m ping` | `7m` → `6m` (rounded, explain) | `*/6 * * * *` | `ping` |\n| `/loop` | (usage hint) | — | — |\n| `/loop 5m` | autonomous-only | (if enabled) | `<<autonomous-loop>>` |\n\n## 7. Do not\n\n- Do not invent intervals the user didn't ask for. If unsure, default to `10m` and say so.\n- Do not pass `--one-shot`. This skill is for recurring loops.\n- Do not list active jobs in your reply. Use `/loops` for that.\n- Do not re-derive the cron expression in your reply unless the user asked. A one-line confirmation (\"scheduled `<prompt>` every `<interval>`; job id `<id>`\") is enough.\n","packages/cli/src/skill/builtin/.bundle/mate/SKILL.md":"---\nname: mate\ndescription: \"Create custom desktop pet (Mate) characters with spritesheet and manifest. Use when the user asks to 'create a pet', 'make a desktop companion', 'design a mate character', 'generate a spritesheet for my pet', or wants to customize their desktop buddy. Generates a WebP spritesheet + manifest.json that can be loaded by MiMo Desktop's Mate system.\"\n---\n\n# Mate Pet Creator\n\nCreate animated desktop pet characters for MiMo Desktop's Mate (桌面伙伴) system.\n\n## Output Structure\n\nA valid custom pet lives in a folder with this structure:\n\n```\n<pet-id>/\n├── manifest.json     # Required — animation metadata\n└── spritesheet.webp  # Required — all animation frames in a grid\n```\n\nThe user places this folder in their MiMo Desktop custom pets directory (`userData/pets/<pet-id>/`), then clicks \"Refresh\" in Settings → Mate to load it.\n\n## Manifest Schema\n\n```json\n{\n  \"id\": \"my-pet\",\n  \"name\": \"My Pet\",\n  \"description\": \"A cute custom pet\",\n  \"version\": 1,\n  \"spritesheet\": \"spritesheet.webp\",\n  \"frameWidth\": 240,\n  \"frameHeight\": 240,\n  \"columns\": 8,\n  \"totalFrames\": 16,\n  \"animations\": {\n    \"idle\": { \"row\": 0, \"frames\": 8, \"fps\": 8, \"loop\": true }\n  }\n}\n```\n\n### Required Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `id` | string | Unique identifier (kebab-case) |\n| `name` | string | Display name |\n| `version` | number | Always `1` |\n| `spritesheet` | string | Filename of the spritesheet image |\n| `frameWidth` | number | Width of each frame in pixels |\n| `frameHeight` | number | Height of each frame in pixels |\n| `columns` | number | Number of columns in the spritesheet grid |\n| `totalFrames` | number | Total number of frames across all animations |\n| `animations` | object | At minimum must include `idle` |\n\n### Optional Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `description` | string | Shown in settings UI |\n| `anchorX` | number | Horizontal anchor (0–1, default 0.5) for centering |\n\n### Animation Definition\n\nEach animation entry:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `row` | number | Row index in the spritesheet (0-based) |\n| `frames` | number | Number of frames in this animation |\n| `fps` | number | Playback speed (recommended: 6–12) |\n| `loop` | boolean | Whether the animation loops |\n\nThe `idle` animation is **required** — it plays by default when the pet is loaded.\n\n## Spritesheet Layout\n\n- Frames are arranged left-to-right, top-to-bottom in a grid.\n- Each row corresponds to one animation (matched by the `row` field in the animation definition).\n- All frames must have identical dimensions (`frameWidth × frameHeight`).\n- Transparent background (alpha channel) is required — the pet window has no background.\n- Recommended frame size: 240×240 px (renders well at 1× scale on desktop).\n- Format: WebP with transparency (lossless or near-lossless for crisp pixel art).\n\n## Workflow\n\n### Step 1: Understand the Character\n\nAsk the user:\n- What animal/creature/character?\n- Art style preference (pixel art, cartoon, flat vector, kawaii)?\n- Any specific colors or features?\n\n### Step 2: Generate the Spritesheet\n\nUse the `imagegen` skill to generate the spritesheet image. Construct the prompt with these guidelines:\n- Request a **sprite sheet** with specific grid layout (e.g., \"8 frames in a single horizontal row, each frame 240×240 pixels\")\n- Specify **transparent background** (alpha channel)\n- Describe the **idle animation** motion: gentle breathing, blinking, tail wag, bobbing, etc.\n- Keep the character **centered** in each frame with consistent sizing\n- Style: match the user's preference; default to cute/kawaii if unspecified\n\nIf the generated image is already WebP, use it directly. If it is PNG or another format, convert to WebP:\n\n```bash\n# Convert to lossless WebP preserving transparency\ncwebp -lossless -q 100 spritesheet.png -o spritesheet.webp\n```\n\nIf `cwebp` is not available, check for `sips` (macOS Ventura+ supports WebP export):\n\n```bash\nsips -s format webp spritesheet.png --out spritesheet.webp\n```\n\nIf neither tool is available, instruct the user to install one:\n\n```\nbrew install webp   # provides cwebp\n```\n\nDo NOT silently rename a PNG to .webp — the file must have valid WebP encoding (RIFF/WEBP header). If conversion genuinely cannot be performed, fail explicitly and tell the user what tool to install.\n\nIf `imagegen` is unavailable (skill not enabled or image generation fails), fall back to generating pixel-art frames directly as SVG, then rasterize. Compute dimensions from the manifest:\n\n```bash\n# Calculate actual spritesheet dimensions from manifest\nWIDTH=$((frameWidth * columns))\nHEIGHT=$((frameHeight * rows))  # rows = max animation row index + 1\n\n# Rasterize SVG to PNG, then convert to WebP\nrsvg-convert -w $WIDTH -h $HEIGHT spritesheet.svg -o spritesheet.png\ncwebp -lossless spritesheet.png -o spritesheet.webp\n```\n\nAs a last resort, output the SVG file directly and instruct the user to convert it manually.\n\n### Step 3: Write the Manifest\n\nGenerate `manifest.json` with correct dimensions matching the actual spritesheet output. Verify:\n- `frameWidth × columns` = spritesheet total width\n- `frameHeight × (max animation row index + 1)` = spritesheet total height\n- `animations.idle` exists with valid `row`, `frames`, `fps`, `loop`\n- Each animation's `frames` ≤ `columns` (frames per row cannot exceed grid columns)\n\n### Step 4: Deliver\n\nWrite both files to the current working directory under a folder named with the pet ID. Tell the user to:\n1. Copy the folder to their MiMo Desktop pets directory (Settings → Mate → click \"Open Folder\" to find it)\n2. Click \"Refresh\" in Settings → Mate\n3. Select their new pet from the list\n\n## Constraints\n\n- The `idle` animation MUST exist — the system falls back to it.\n- Frame dimensions must be consistent across the entire spritesheet.\n- Keep total file size under 2MB for smooth loading.\n- Pet ID must be unique; if it conflicts with a preset (`koala`, `panda`), the preset wins.\n- Do NOT reference or depend on any external URLs — all assets must be local files.\n","packages/cli/src/skill/builtin/.bundle/memory-search/SKILL.md":"---\nname: \"memory-search\"\ndescription: \"Query the raw trajectory SQLite database directly when the built-in memory and history tools are insufficient. Use when you need structured analysis across sessions: finding repeated errors, grouping tool calls by pattern, verifying what was actually executed, or locating specific past commands/decisions that text search cannot surface. Provides the database schema, ready-to-use SQL query templates, and per-goal strategies.\"\n---\n\n# Memory Search: SQLite Trajectory Database\n\nDirect SQL access to mimocode's trajectory database for structured analysis that the `memory` (BM25 over curated markdown) and `history` (FTS over raw messages) tools cannot perform — aggregation, filtering by tool/status/time, cross-session pattern detection, and execution chain inspection.\n\n## When to use\n\n- You need to **aggregate or count** across sessions (e.g. \"which tool fails most often?\", \"how many sessions touched file X?\").\n- You need to **filter by structure** — tool name, status, agent_id, time range — not just text content.\n- You need to **view a complete execution chain** for a session (every tool call in order).\n- You need to **verify a memory claim** against what actually happened (the DB is the source of truth).\n- The `memory` and `history` tools returned nothing useful despite multiple query attempts.\n\n## Locating the database\n\n```bash\n# Typically at this path. MIMOCODE_DB env var overrides if set.\nsqlite3 -readonly ~/.local/share/mimocode/mimocode.db \".tables\"\n```\n\nAlways use `-readonly` or only SELECT queries — never modify the database.\n\n## Schema\n\n| Table | Purpose | Key columns |\n|-------|---------|-------------|\n| `session` | Session metadata | `id`, `project_id`, `title`, `time_created`, `parent_id` |\n| `message` | User/assistant turns | `id`, `session_id`, `agent_id`, `time_created`, `data` (JSON: `$.role`) |\n| `part` | Message parts (text, tool calls, steps) | `id`, `message_id`, `session_id`, `time_created`, `data` (JSON) |\n| `task` | Task tree | `id`, `session_id`, `summary`, `status` |\n| `task_event` | Task state transitions | `id`, `session_id`, `task_id`, `at`, `kind`, `summary` |\n| `actor_registry` | Subagent/peer history | `session_id`, `actor_id`, `agent`, `mode`, `status`, `description` |\n\n### Part types in `part.data`\n\n- `{\"type\":\"text\",\"text\":\"...\"}` — agent text output\n- `{\"type\":\"tool\",\"tool\":\"<name>\",\"callID\":\"...\",\"state\":{\"status\":\"completed\",\"input\":{...},\"output\":\"...\"}}` — completed tool call\n- `{\"type\":\"tool\",\"tool\":\"<name>\",\"callID\":\"...\",\"state\":{\"status\":\"error\",\"input\":{...},\"error\":\"...\"}}` — failed tool call (no `output` field; error message in `$.state.error`)\n- `{\"type\":\"step-start\"}` / `{\"type\":\"step-finish\",\"tokens\":...}` — step boundaries\n- `{\"type\":\"compaction\",\"auto\":true/false}` — compaction boundary\n- `{\"type\":\"checkpoint\",...}` — checkpoint/rebuild boundary\n\n### Key conventions\n\n- `agent_id = 'main'` = main agent; other values = subagent (e.g. `\"explore-1\"`, `\"general-1\"`).\n- `$.state.output` only exists when `$.state.status = \"completed\"`. Failures store the message in `$.state.error`.\n- `time_created` is Unix milliseconds.\n\n## Query templates\n\n**List recent sessions for this project:**\n\n```sql\nSELECT id, title, time_created,\n       datetime(time_created/1000, 'unixepoch', 'localtime') as created\nFROM session\nWHERE project_id = '<PROJECT_ID>'\n  AND parent_id IS NULL\nORDER BY time_created DESC\nLIMIT 20;\n```\n\n**Find user messages containing a keyword:**\n\n```sql\nSELECT m.session_id, m.id,\n       substr(json_extract(p.data, '$.text'), 1, 200) as preview\nFROM message m\nJOIN part p ON p.message_id = m.id AND p.session_id = m.session_id\nWHERE json_extract(m.data, '$.role') = 'user'\n  AND json_extract(p.data, '$.type') = 'text'\n  AND json_extract(p.data, '$.text') LIKE '%keyword%'\nORDER BY m.time_created DESC\nLIMIT 10;\n```\n\n**Find tool calls by tool name:**\n\n```sql\nSELECT m.session_id, m.id, m.agent_id,\n       json_extract(p.data, '$.tool') as tool,\n       json_extract(p.data, '$.state.status') as status,\n       substr(COALESCE(json_extract(p.data, '$.state.output'), json_extract(p.data, '$.state.error')), 1, 300) as result_preview\nFROM message m\nJOIN part p ON p.message_id = m.id AND p.session_id = m.session_id\nWHERE json_extract(m.data, '$.role') = 'assistant'\n  AND json_extract(p.data, '$.type') = 'tool'\n  AND json_extract(p.data, '$.tool') = '<TOOL_NAME>'\n  AND m.session_id = '<SESSION_ID>'\nORDER BY m.time_created DESC\nLIMIT 20;\n```\n\n**View a session's full execution chain:**\n\n```sql\nSELECT m.id, m.agent_id,\n       json_extract(p.data, '$.type') as part_type,\n       json_extract(p.data, '$.tool') as tool,\n       substr(p.data, 1, 800) as preview\nFROM message m\nJOIN part p ON p.message_id = m.id AND p.session_id = m.session_id\nWHERE m.session_id = '<SESSION_ID>'\n  AND json_extract(m.data, '$.role') = 'assistant'\nORDER BY m.time_created, p.time_created;\n```\n\n**Find repeated stdout errors (completed bash calls, last 7 days):**\n\n```sql\nSELECT substr(json_extract(p.data, '$.state.output'), 1, 200) as error_output,\n       COUNT(*) as occurrences,\n       GROUP_CONCAT(DISTINCT m.session_id) as sessions\nFROM part p\nJOIN message m ON m.id = p.message_id AND m.session_id = p.session_id\nWHERE json_extract(p.data, '$.type') = 'tool'\n  AND json_extract(p.data, '$.tool') = 'bash'\n  AND json_extract(p.data, '$.state.status') = 'completed'\n  AND json_extract(p.data, '$.state.output') LIKE '%error%'\n  AND m.time_created > (strftime('%s', 'now') - 7*86400) * 1000\nGROUP BY substr(json_extract(p.data, '$.state.output'), 1, 200)\nHAVING occurrences > 1\nORDER BY occurrences DESC\nLIMIT 10;\n```\n\n**Find actual tool failures (any tool, last 7 days):**\n\n```sql\nSELECT json_extract(p.data, '$.tool') as tool,\n       substr(json_extract(p.data, '$.state.error'), 1, 200) as error_msg,\n       COUNT(*) as occurrences,\n       GROUP_CONCAT(DISTINCT m.session_id) as sessions\nFROM part p\nJOIN message m ON m.id = p.message_id AND m.session_id = p.session_id\nWHERE json_extract(p.data, '$.type') = 'tool'\n  AND json_extract(p.data, '$.state.status') = 'error'\n  AND m.time_created > (strftime('%s', 'now') - 7*86400) * 1000\nGROUP BY json_extract(p.data, '$.tool'), substr(json_extract(p.data, '$.state.error'), 1, 200)\nHAVING occurrences > 1\nORDER BY occurrences DESC\nLIMIT 10;\n```\n\n## Search strategies\n\n| Goal | Strategy |\n|------|----------|\n| Find a user's stated rule/preference | Search user text parts for `'%always%'`, `'%never%'`, `'%remember%'`, `'%rule%'` |\n| Find a design decision | Search `'%decided%'`, `'%tradeoff%'`, `'%reason%'` in user text |\n| Find a specific file path or command | LIKE match on tool output/error |\n| Find repeated workflows | Group tool call sequences by session, look for recurring tool×N patterns |\n| Verify a memory claim | Find the session_id from the memory entry `[ses_xxx]`, then query its full execution chain |\n| Count tool usage | `GROUP BY json_extract(p.data, '$.tool')` with COUNT |\n\n## Constraints\n\n- **Read-only**: Never modify the database. Always `sqlite3 -readonly` or SELECT only.\n- **Performance**: The DB can be multi-GB. Always use LIMIT and filter by `session_id` or `time_created` range.\n- **Privacy**: Raw trajectory contains everything the user typed. Treat it with care.\n- **JSON access**: Part data is JSON-in-a-column. Always use `json_extract()` for structured field access.\n","packages/cli/src/skill/builtin/.bundle/mimocode-docs/SKILL.md":"---\nname: mimocode-docs\ndescription: \"Use whenever the user asks about MiMoCode itself: features, TUI or CLI commands, keybindings, terminal compatibility, rendering glitches, TUI lag, SSH or remote rendering, agent modes (build / plan) and how to switch between them, configuration, file locations, providers, models, authentication, or custom OpenAI-compatible or Anthropic-compatible API endpoints. Especially trigger when a prompt supplies or asks to configure a base URL/baseURL, API key/apiKey, model name or ID, provider, Anthropic Messages API, or global/project mimocode.json/jsonc, or when the user asks how to enter or leave plan mode. Also trigger when a skill, task, subprocess, or external client needs to borrow this instance's models — the OpenAI-compatible /v1 chat endpoints every MiMoCode server serves, `mimo llm-server` task tokens, or how to expose a listening port for them. Use this skill to inspect existing config safely, make minimal changes, and verify them without guessing schema fields or model capabilities.\"\n---\n\n# MiMoCode\n\nYou are MiMoCode. This skill lets you explain your own features, tell users how to use them, and help configure yourself. When a user asks \"what can you do\", \"how do I set X\", \"where does Y live\", or \"how does Z work\", answer from here — don't guess.\n\n## Identity\n\nMiMoCode (CLI binary `mimo`) is an agentic coding tool with a terminal UI, built as a fork of OpenCode. Beyond OpenCode's core (multi-provider, TUI, LSP, MCP, plugins) it adds: persistent memory, intelligent context management, subagent orchestration, goal-driven autonomous loops, compose-next end-to-end delivery, Dynamic Workflows, and self-improvement via dream/distill.\n\n## Feature Map\n\n| Feature | What it is | How to reach it |\n|---------|-----------|-----------------|\n| **Agents / modes** | `build` (default, full tools), `plan` (read-only analysis), plus custom modes you define. Build and Plan can switch at any time; other custom or special modes lock once the first message is sent. Only the user enters a mode — no tool lets the agent switch into plan, and the agent does not raise plan mode unasked; from inside plan the agent can call `plan_exit` to ask for approval and hand the plan back to build | `Tab` cycles primary agents, or pick one in the agent dialog; add your own via `.mimocode/agent/<name>.md` (see @reference/guide.md) |\n| **Subagents** | Primary agent spawns `general`/`explore` helpers, parallel + background, with lifecycle/cancel | automatic; `actor` tooling |\n| **Persistent memory** | Markdown-backed memory with indexed search across `MEMORY.md`, `checkpoint.md`, `notes.md`, and `tasks/<id>/progress.md` | auto-injected on resume |\n| **Context management** | Auto-checkpoints, context reconstruction near limit, budgeted injection | automatic; tune via `checkpoint`/`compaction` config |\n| **Task tree** | `T1`, `T1.1`… tree, integrated with checkpoints | `task` tooling |\n| **Goal / stop condition** | Judge model verifies a stop condition before the agent halts | `/goal` |\n| **Compose mode** | Structured spec→ship lifecycle; entry is the `compose-next` skill — clarify, spec, implement, verify, review, finish. Do not combine it with plan mode | `/compose-next` (see @reference/guide.md) |\n| **Visual modes** | `vivid` (default: star field, meteors, logo effects, animated activity) and `minimal` (quiet visuals, stable activity indicators); independent from the animation override | `/vivid` or the visual-mode option in `ctrl+p` |\n| **Voice input** | Streaming ASR (TenVAD + MiMo ASR); needs `sox` | `/voice` |\n| **Dream** | Consolidates recent traces into project memory | `/dream` |\n| **Distill** | Packages repeated manual workflows into skills/subagents/commands | `/distill` |\n| **Scheduled prompts** | Cron/loop: inject a prompt on a schedule or repeating loop (UTC, 5-field) | `cron` tool · `/loop` · `/loops` |\n| **Dynamic Workflow** | JS scripts that orchestrate many subagents deterministically (fan-out, pipelines, nesting); built-ins include `deep-research`, `fact-check`, and `research-experiment` | `.mimocode/workflows/*.js` + `workflow` tool |\n| **Custom skills** | Add reusable task instructions under `.mimocode/skills/` | see the `skill-creator` skill |\n| **Skill discovery** | `/skill-name` slash invocation (2+ in one message auto-load with an orchestration plan); `skill_search` tool matches by exact name/alias + BM25 and auto-loads high-confidence hits; some builtins (`claude-code`, `codex`) only appear when their CLI is installed | `/` autocomplete · automatic |\n| **MCP** | Local & remote Model Context Protocol servers | `mcp` config + `mimo mcp` |\n| **Capability API** | Every session already serves this project's chat models over OpenAI-compatible `/v1` on a loopback port, so a skill or subprocess borrows a model instead of a provider key | `mimo llm-server issue` mints a scoped token and prints the base URL (see @reference/capability-api.md) |\n\n## Configuration Basics\n\nConfig file (JSON or JSONC), discovered by walking up from cwd:\n- **Project**: `.mimocode/mimocode.json` (or `.jsonc`)\n- **Global**: `~/.config/mimocode/mimocode.jsonc` (preferred for new files) or `mimocode.json`\n\nAdd `\"$schema\": \"https://mimo.xiaomi.com/mimocode/config.json\"` for editor validation. All top-level keys are optional; project config merges over global.\n\n```jsonc\n{\n  \"$schema\": \"https://mimo.xiaomi.com/mimocode/config.json\",\n  \"model\": \"provider/model\",\n  \"permission\": { \"external_directory\": { \"/tmp/**\": \"allow\" } }\n}\n```\n\n## Reference routing\n\nRead only the reference needed for the request, but read it before changing files:\n\n- Models, providers, API keys, base URLs, or OpenAI-/Anthropic-compatible endpoints: @reference/providers.md\n- Other config keys and on-disk locations: @reference/config.md\n- Task-oriented usage and setup: @reference/guide.md\n- Terminal compatibility, TUI rendering or lag, and SSH remote use: @reference/guide.md\n- CLI and slash commands: @reference/commands.md\n- Permission rules: @reference/permissions.md\n- MCP client-side sampling (servers borrowing your model, audio transcription): @reference/mcp-sampling.md\n- Lending this instance's chat models to a skill, task, or subprocess — the OpenAI-compatible `/v1` endpoints and the `mimo llm-server` tokens that reach them: @reference/capability-api.md\n- Dynamic Workflow: @reference/workflows.md\n\n## How-To Guide\n\nFor task-oriented walkthroughs — signing in & choosing a model, troubleshooting TUI rendering or lag, using MiMoCode over SSH, making memory remember project rules, writing custom slash commands, remapping keybinds, adding MCP servers, scheduling prompts (cron/loop), and using compose-next end-to-end delivery — see @reference/guide.md. For authoring and running **Dynamic Workflow** scripts (the in-script API, where to save `.js` workflow files, and the `workflow` tool) see @reference/workflows.md.\n\n**Built-in workflows** (runnable by name via the `workflow` tool, no file needed):\n- **`deep-research`** — comprehensive research report generator (brief → plan → parallel research → reflect → write → cold review). Pass `args: { dir, question, today, depth?, context? }`. Convergent/resumable.\n- **`fact-check`** — adversarial fact verification (plan → search → extract → group → 3-juror crosscheck → JSON findings). Pass the question as `args`.\n- **`research-experiment`** — autonomous metric-improvement loop with baseline, guarded iterations, audit, and report. It requires an eval command, metric extraction rule, and editable-file scope.\n\n## Where Things Live On Disk\n\nBase dirs follow `MIMOCODE_HOME` (if set, absolute) else XDG. Data typically lives at `~/.local/share/mimocode/` (memory, logs, extracted builtin skills), config at `~/.config/mimocode/`, cache at `~/.cache/mimocode/`. See @reference/config.md for the full layout and env vars.\n\n## Commands\n\n`mimo` subcommands (`mcp`, `run`, `agent`, `models`, `providers`, `upgrade`, `stats`, `export`/`import`, `github`/`pr`, `serve`, …) and slash commands (`/goal`, `/dream`, `/distill`, `/vivid`, `/voice`, `/loop`, `/connect`, `/<skill-name>`) are documented in @reference/commands.md.\n\n## Helping the User Configure\n\nWhen asked to change a behavior:\n1. Read the routed reference and identify the exact schema fields. Do not infer fields from another tool's config format.\n2. Determine scope from the request. Treat model/provider setup as global unless the user says it is project-only; use project config for explicitly repo-local behavior.\n3. Inspect only the exact config candidates. Never recursively search the user's home directory. Prefer an existing higher-precedence `.jsonc` file and preserve comments, `$schema`, unrelated providers, and other settings.\n4. Keep secrets out of tool output and the final response. When inspecting a config, redact values for keys such as `apiKey`, `token`, `secret`, and `password`; never dump the whole unredacted file merely to find its shape.\n5. Edit minimally. If the request says configure, use, or make default, also set the top-level `model`; if it only says add, leave the current selection unchanged.\n6. When persisting a newly supplied API key and model, also put that exact `provider/model` at the front of the TUI recent-model state so the user can switch to it immediately. Follow the merge procedure in @reference/providers.md; never replace favorites, variants, or unrelated recent models.\n7. Validate the parsed configuration with the narrowest relevant command and report the config and recent-model state files changed, selected provider/model, and whether a new session or re-selection is needed. Never include the credential in the summary.\n\nDon't invent config keys, model limits, context windows, output limits, modalities, reasoning support, or tool-call capabilities. Add optional model metadata only when the user supplied it or a current authoritative source verifies it. If a requested behavior has no key, say so and suggest the closest supported option.\n\n## Answering Feature Questions\n\n- Confirm the feature exists in the map above before describing it.\n- Give the trigger (command / key / config), then a one-line how.\n- For authoring reusable task instructions, use the `skill-creator` skill.\n- If unsure whether a detail is current, verify against the config schema or README rather than asserting.\n","packages/cli/src/skill/builtin/.bundle/modern-python-toolchain/SKILL.md":"---\nname: modern-python-toolchain\ndescription: \"Modern Python project setup with uv, ruff, and pyright. Use when initializing a new Python project, configuring the Python environment, setting up linting/formatting, or when a project needs uv (the fast Python package manager). Trigger on: 'set up Python', 'new Python project', 'configure uv', 'install uv', 'ruff', 'pyright', 'Python linting', 'Python formatting', or when a task requires Python and no pyproject.toml exists yet.\"\n---\n\n# Modern Python Toolchain\n\nA guide for setting up Python projects with modern, fast tooling: **uv** (package/project manager), **ruff** (linter/formatter), and **pyright** (type checker).\n\n## Installing uv\n\nuv is an extremely fast Python package and project manager. It replaces pip, pip-tools, pipx, pyenv, virtualenv, poetry, etc.\n\n```bash\n# macOS / Linux\ncurl -LsSf https://astral.sh/uv/install.sh | sh\n\n# Windows (PowerShell)\npowershell -ExecutionPolicy ByPass -c \"irm https://astral.sh/uv/install.ps1 | iex\"\n\n# Homebrew (macOS)\nbrew install uv\n```\n\nAfter installation, restart your shell or run `source $HOME/.local/bin/env` (the installer prints the exact command).\n\nFor detailed information: https://docs.astral.sh/uv/\n\n---\n\n## uv basics\n\n### Python version\n\nPin a single Python minor version. The recommended default is 3.12 (broadest ecosystem support — PyTorch, CUDA images, downstream libraries). Python 3.14 is the latest stable; prefer it for new projects unless you depend on packages that haven't added 3.14 support yet.\n\n```toml\n# pyproject.toml\nrequires-python = \"==3.12.*\"\n```\n\nInstall Python via uv (no system Python needed):\n\n```bash\nuv python install 3.12\n```\n\n### Creating a new project\n\n```bash\nuv init                       # Create new project with pyproject.toml\nuv init -p 3.12               # Specify Python version\n```\n\n### Common commands\n\n```bash\nuv add requests               # Add dependency\nuv add --dev ruff \"pyright[nodejs]\"  # Add dev dependencies\nuv remove requests            # Remove dependency\nuv sync                       # Install from lockfile\nuv run COMMAND                # Run command in project environment\nuv run script.py              # Run a script\nuv run python -c \"...\"        # Run Python one-liner\nuvx TOOL ARGS                 # Run a tool without installing it\n```\n\n### Rules\n\n- **Never use `pip`** in uv projects — always `uv add` for packages.\n- **Never run `python script.py` directly** — always `uv run script.py` to ensure the correct environment. For one-liners use `uv run python -c \"...\"`.\n- **Don't manually manage environments** with `python -m venv` or `source .venv/bin/activate` — uv handles this automatically.\n- `uvx` runs tools from PyPI by package name without installing them permanently.\n\n### Project types\n\nFor **library** projects (`uv init --lib`) or packaged apps (`uv init --package`), `uv_build` is used as the default build backend automatically:\n\n```toml\n[build-system]\n# auto-generated by uv init; version bound tracks your installed uv (here: 0.11.28)\nrequires = [\"uv_build>=0.11.28,<0.12.0\"]\nbuild-backend = \"uv_build\"\n```\n\nFor **application** projects with an entry point:\n\n```toml\n[project.scripts]\nmyapp = \"myapp.__main__:main\"\n```\n\nIf the project does not use src layout, just run `uv run main.py`.\n\n---\n\n## ruff\n\nRuff is an extremely fast Python linter and code formatter. It replaces Flake8, isort, Black, pyupgrade, autoflake, and more.\n\nFor detailed information: https://docs.astral.sh/ruff/\n\n### When to use\n\nAlways use ruff for Python linting and formatting. Prefer `uv run ruff` when ruff is a dev dependency; otherwise fall back to `uvx ruff`.\n\n### Configuration\n\nAdd to `pyproject.toml`:\n\n```toml\n[tool.ruff.lint]\nextend-select = [\n    \"UP\",  # pyupgrade\n    \"I\",   # isort\n]\n```\n\nDo not enable the full `E` category or other formatter-conflicting rules (E1xx, E501, W191, Q, COM); `ruff format` owns layout.\n\n### Post-edit workflow\n\nAfter modifying Python code, run both:\n\n```bash\nuv run ruff check --fix path/to/changed_file.py\nuv run ruff format path/to/changed_file.py\n```\n\nUse `--diff` to preview changes without applying.\n\n---\n\n## pyright\n\nPyright is a fast type checker for Python. Only use it when the project lists it as a dev dependency or explicitly uses type checking.\n\nInstall with the `nodejs` extra so Node.js is bundled automatically (no system `node` required):\n\n```bash\nuv add --dev \"pyright[nodejs]\"\n```\n\nRun type checking:\n\n```bash\nuv run pyright path/to/changed_file.py    # check specific files\nuv run pyright src/                        # check all code\n```\n\nUsually only check the files you modified. For broad changes (base classes, shared types), check the full tree.\n\n---\n\n## Coding style\n\n### Type annotations\n\nUse modern Python 3.12+ syntax:\n\n```python\n# Good — builtin generics, union syntax\ndef fetch(url: str, timeout: float = 30.0) -> list[dict[str, str | None]]:\n    ...\n\n# Bad — legacy typing imports\nfrom typing import List, Dict, Optional\ndef fetch(url: str, timeout: float = 30.0) -> List[Dict[str, Optional[str]]]:\n    ...\n```\n\nAlways annotate function parameters. Local variables can rely on inference unless the type is ambiguous:\n\n```python\nitems: list[tuple[str, int]] = []    # annotate — empty literal\nconfig: dict[str, Any] = {}          # annotate — empty literal\nresult = some_api()                  # inference is fine\n```\n\n### pydantic v2\n\nUse the modern class-based API:\n- `model_config = ConfigDict(...)` at class body level, not `class Config`.\n- `RootModel` with `root: SomeType` for single-root schemas.\n\n### typer (CLI)\n\nRecommended for CLI entry points over `argparse`:\n\n```python\nimport typer\nfrom typing import Annotated\n\ncli = typer.Typer(add_completion=False)\n\n@cli.command()\ndef main(name: Annotated[str, typer.Argument(help=\"Your name\")]) -> None:\n    typer.echo(f\"Hello {name}\")\n\nif __name__ == \"__main__\":\n    cli()\n```\n","packages/cli/src/skill/builtin/.bundle/pdf-official/README.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fpdf-official%2FREADME.md -->","packages/cli/src/skill/builtin/.bundle/pdf-official/SKILL.md":"---\nname: pdf-official\ndescription: \"Use this skill whenever a PDF file is being produced, opened, transformed, filled, or read. That includes: extracting text or tables from an existing PDF; combining, carving, rotating, cropping, or watermarking pages; composing a fresh PDF (report, invoice, certificate); filling AcroForm fields or overlaying text onto a non-fillable scanned form; encrypting or unlocking a PDF; running OCR over a scanned document; rendering pages to PNG/JPEG for visual analysis. Trigger on mentions of 'PDF', a filename ending in .pdf, requests like 'turn this into a PDF report', or references to AcroForm / form fields.\"\nlicense: Apache-2.0 — see LICENSE for terms and third-party attributions\n---\n\n# PDF skill\n\nAn Apache-2.0 toolkit for reading, composing, transforming, and filling PDF\nfiles. Written from scratch on top of permissively-licensed open-source\nlibraries (pypdf, pdfplumber, pypdfium2, reportlab, pdf-lib, qpdf) so this\ncan be embedded in commercial projects without special agreement.\n\n## Route the task\n\nPick the sub-guide by the *verb* of the request.\n\n| Task | Path | Read |\n|------|------|------|\n| Pull text / tables / metadata / images out of an existing PDF | Extract | [`extract.md`](extract.md) |\n| Combine, carve, rotate, crop, watermark, encrypt, or shrink | Transform | [`transform.md`](transform.md) |\n| Build a PDF that doesn't exist yet (report, invoice, certificate) | Compose | [`compose.md`](compose.md) |\n| Fill a form (AcroForm or scanned) | Interactive | [`interactive.md`](interactive.md) |\n| Scanned / image-only PDF (no selectable text) | Extract → *OCR* | [`extract.md`](extract.md) §5 |\n\nIf a task mixes several of these, follow the order:\n**probe → plan → extract or compose → validate.**\n\nEvery path starts with a probe. `scripts/survey.py` returns page count,\nwhether the file is encrypted, whether it has an AcroForm, and whether\npage 1 looks like a scan.\n\n## First install\n\n> **Bundled runtime:** when the `MIMO_PYTHON` environment variable is set, skip the installs below — run every command with `python3`/`uv run` replaced by `\"$MIMO_PYTHON\"` (pypdf/pypdfium2/reportlab/Pillow preinstalled; pip console scripts unavailable, use `\"$MIMO_PYTHON\" -m <module>`). A bundled qpdf is exposed as `MIMO_QPDF` (picked up automatically by the scripts here); invoke it directly as `\"$MIMO_QPDF\" --check file.pdf`.\n\nPython-only path (all BSD / MIT / Apache) — covers 95% of tasks:\n\n```bash\npython3 -m pip install --upgrade pypdf pdfplumber pypdfium2 reportlab Pillow\n```\n\nAdd these external binaries only when you actually need them:\n\n```bash\n# qpdf — merge/split/encrypt/repair, Apache-2.0\nbrew install qpdf                # macOS\napt-get install -y qpdf          # Debian / Ubuntu\n\n# Tesseract — OCR for scanned PDFs, Apache-2.0\nbrew install tesseract\npython3 -m pip install pytesseract pdf2image\napt-get install -y tesseract-ocr\n\n# Poppler — pdftotext / pdftoppm / pdfimages, GPL-2.0\n# Optional. Only install if you accept a GPL dependency at CLI level.\nbrew install poppler\napt-get install -y poppler-utils\n```\n\nEvery script under `scripts/` uses argparse. Exit codes:\n`0` OK · `1` runtime failure · `2` bad arguments · `3` validation failure\n(`apply_values.py` / `overlay_text.py`; `sanity_check.py` reports findings\nwith exit `1`).\nAny single script can be lifted into another project — none imports from a\nshared framework.\n\n## One-command triage\n\n```bash\nscripts/survey.py path/to/file.pdf --pretty\n```\n\nSample output:\n\n```json\n{\n  \"path\": \"/abs/path/file.pdf\",\n  \"page_count\": 12,\n  \"is_locked\": false,\n  \"form_field_count\": 34,\n  \"looks_scanned\": false,\n  \"metadata\": {\"Title\": \"...\", \"Author\": \"...\", \"Producer\": \"...\"}\n}\n```\n\nRoute by the flags:\n\n- `is_locked: true` → unlock first (`qpdf --password=… --decrypt`). Almost\n  every reader library refuses locked files.\n- `form_field_count > 0` → widgets path in [`interactive.md`](interactive.md) §1.\n- `form_field_count == 0` AND you need to fill it → overlay path\n  in [`interactive.md`](interactive.md) §2.\n- `looks_scanned: true` → skip pypdf text extraction, go straight to OCR\n  ([`extract.md`](extract.md) §5).\n\n## Which library for which task\n\n| Task | Preferred | Reason | Fallback |\n|------|-----------|--------|----------|\n| Plain text | `pdftotext -layout` | fastest, keeps columns | `pypdf` |\n| Positioned text | `pdfplumber` | char-level bboxes | `pypdfium2.get_text` |\n| Tables | `pdfplumber` | tunable `table_settings` | pandas over manual CSV |\n| Page → image | `pypdfium2` | Apache/BSD, no GPL | `pdftoppm` (GPL) |\n| Merge / carve / rotate | `pypdf` | pure Python | `qpdf --pages` (faster on huge files) |\n| Encrypt / repair / linearise | `qpdf` | handles broken input | pypdf (basic encrypt only) |\n| Compose from scratch | `reportlab` | mature, BSD | `pdf-lib` in Node |\n| Fill AcroForm | `pypdf.update_page_form_field_values` | preserves widget appearances | `pdf-lib` in Node |\n| Overlay on non-fillable | reportlab + `pypdf.merge_page` | two-layer merge, see interactive.md | — |\n\n## Common gotchas\n\n1. **PDF origin is bottom-left**, image origin is top-left. Every \"off by a\n   few points\" bug is one of these two systems misapplied. Coordinate\n   conversion is in one place: [`interactive.md`](interactive.md) §2.c.\n2. **`pypdf.extract_text()` returns nothing for scans.** That's not a bug —\n   there's no text stream. Use the `looks_scanned` flag and route to OCR.\n3. **Unicode subscripts / superscripts render as black rectangles in\n   reportlab** because Helvetica/Times/Courier don't ship those glyphs. Use\n   `<sub>` / `<super>` XML in `Paragraph`, or move the pen manually on canvas.\n   See [`compose.md`](compose.md) §5.\n4. **CJK text renders as black boxes when the font never registered.**\n   reportlab does not consult the OS font system; a bad font name/path (思源黑体,\n   PingFang, Noto on machines that lack it) plus a swallowed exception means a\n   silent Helvetica fallback — and Helvetica has no CJK glyphs. Resolve fonts\n   with the ladder in [`compose.md`](compose.md) §4 (`resolve_cjk_font()`);\n   the terminal fallback is the built-in CID font, never Helvetica.\n5. **XFA forms are not AcroForms.** If `probe_fields.py` returns `[]` on a\n   PDF that clearly has widgets in Adobe Reader, it's XFA — flatten it in\n   Acrobat first.\n6. **`writer.encrypt(pw)` in pypdf uses RC4 by default**. For real AES-256,\n   pass `algorithm=\"AES-256\"`, or use `qpdf --encrypt … 256 --`.\n\n## What's next\n\nOpen the sub-guide from the routing table and work through it end to end.\nEach sub-guide has a Validation section at the bottom describing how to\nconfirm the result.\n","packages/cli/src/skill/builtin/.bundle/playwright/SKILL.md":"---\nname: \"playwright\"\ndescription: \"Use when the task requires automating a real browser from the terminal (navigation, form filling, snapshots, screenshots, data extraction, UI-flow debugging) via `playwright-cli` or the bundled wrapper script.\"\n---\n\n\n# Playwright CLI Skill\n\nDrive a real browser from the terminal using `playwright-cli`. Prefer the bundled wrapper script so the CLI works even when it is not globally installed.\nTreat this skill as CLI-first automation. Do not pivot to `@playwright/test` unless the user explicitly asks for test files.\n\n## Prerequisite check (required)\n\nBefore proposing commands, check whether `npx` is available (the wrapper depends on it):\n\n```bash\ncommand -v npx >/dev/null 2>&1\n```\n\nIf it is not available, pause and ask the user to install Node.js/npm (which provides `npx`). Provide these steps verbatim:\n\n```bash\n# Verify Node/npm are installed\nnode --version\nnpm --version\n\n# If missing, install Node.js/npm, then:\nnpm install -g @playwright/cli@latest\nplaywright-cli --help\n```\n\nOnce `npx` is present, proceed with the wrapper script. A global install of `playwright-cli` is optional.\n\n## Skill path (set once)\n\n```bash\nexport CODEX_HOME=\"${CODEX_HOME:-$HOME/.codex}\"\nexport PWCLI=\"$CODEX_HOME/skills/playwright/scripts/playwright_cli.sh\"\n```\n\nUser-scoped skills install under `$CODEX_HOME/skills` (default: `~/.codex/skills`).\n\n## Quick start\n\nUse the wrapper script:\n\n```bash\n\"$PWCLI\" open https://playwright.dev --headed\n\"$PWCLI\" snapshot\n\"$PWCLI\" click e15\n\"$PWCLI\" type \"Playwright\"\n\"$PWCLI\" press Enter\n\"$PWCLI\" screenshot\n```\n\nIf the user prefers a global install, this is also valid:\n\n```bash\nnpm install -g @playwright/cli@latest\nplaywright-cli --help\n```\n\n## Core workflow\n\n1. Open the page.\n2. Snapshot to get stable element refs.\n3. Interact using refs from the latest snapshot.\n4. Re-snapshot after navigation or significant DOM changes.\n5. Capture artifacts (screenshot, pdf, traces) when useful.\n\nMinimal loop:\n\n```bash\n\"$PWCLI\" open https://example.com\n\"$PWCLI\" snapshot\n\"$PWCLI\" click e3\n\"$PWCLI\" snapshot\n```\n\n## When to snapshot again\n\nSnapshot again after:\n\n- navigation\n- clicking elements that change the UI substantially\n- opening/closing modals or menus\n- tab switches\n\nRefs can go stale. When a command fails due to a missing ref, snapshot again.\n\n## Recommended patterns\n\n### Form fill and submit\n\n```bash\n\"$PWCLI\" open https://example.com/form\n\"$PWCLI\" snapshot\n\"$PWCLI\" fill e1 \"user@example.com\"\n\"$PWCLI\" fill e2 \"password123\"\n\"$PWCLI\" click e3\n\"$PWCLI\" snapshot\n```\n\n### Debug a UI flow with traces\n\n```bash\n\"$PWCLI\" open https://example.com --headed\n\"$PWCLI\" tracing-start\n# ...interactions...\n\"$PWCLI\" tracing-stop\n```\n\n### Multi-tab work\n\n```bash\n\"$PWCLI\" tab-new https://example.com\n\"$PWCLI\" tab-list\n\"$PWCLI\" tab-select 0\n\"$PWCLI\" snapshot\n```\n\n## Wrapper script\n\nThe wrapper script uses `npx --package @playwright/cli playwright-cli` so the CLI can run without a global install:\n\n```bash\n\"$PWCLI\" --help\n```\n\nPrefer the wrapper unless the repository already standardizes on a global install.\n\n## References\n\nOpen only what you need:\n\n- CLI command reference: `references/cli.md`\n- Practical workflows and troubleshooting: `references/workflows.md`\n\n## Guardrails\n\n- Always snapshot before referencing element ids like `e12`.\n- Re-snapshot when refs seem stale.\n- Prefer explicit commands over `eval` and `run-code` unless needed.\n- When you do not have a fresh snapshot, use placeholder refs like `eX` and say why; do not bypass refs with `run-code`.\n- Use `--headed` when a visual check will help.\n- When capturing artifacts in this repo, use `output/playwright/` and avoid introducing new top-level artifact folders.\n- Default to CLI commands and workflows, not Playwright test specs.\n","packages/cli/src/skill/builtin/.bundle/pptx-official/SKILL.md":"---\nname: pptx-official\ndescription: \"Use this skill whenever a Microsoft PowerPoint (.pptx) file is being produced, opened, transformed, or read. That includes: authoring slide decks, pitch decks, executive readouts, training material, or any presentation deliverable; extracting text or structure from an existing .pptx; filling a .pptx template with values; converting a deck to PDF or images; splitting or merging decks; inspecting slides, layouts, masters, tables, images, charts, speaker notes, or comments. Trigger on words like 'deck', 'slides', 'presentation', 'pitch deck', 'keynote' (when a .pptx is expected as output), or any filename ending in .pptx. Do NOT trigger when the primary deliverable is a Word document, spreadsheet, PDF report, HTML site, or Google Slides API call, even if presentation-shaped content appears along the way.\"\nlicense: Apache-2.0 — see LICENSE for terms and third-party attributions\n---\n\n# PPTX Skill\n\nAn Apache-2.0 toolkit for producing, editing, and reading Microsoft PowerPoint\n(`.pptx`) files. Written from scratch against the public\n[ECMA-376 / ISO/IEC 29500 (PresentationML)](https://www.ecma-international.org/publications-and-standards/standards/ecma-376/)\nspecification and built on permissively-licensed tooling (`python-pptx` MIT,\n`pptxgenjs` MIT, `lxml` BSD-3-Clause, `Pillow` MIT-CMU, optional external\nbinaries `soffice` MPL 2.0 and `pdftoppm` GPL) so it can be reused in\ncommercial projects without restriction.\n\n## Decision matrix\n\n| Situation | Path | Read first |\n|-----------|------|------------|\n| Build a deck from a prompt or dataset — no source file to start from | Author with `python-pptx` (structured / repeatable) or PptxGenJS (design-heavy, JS) | [`create.md`](create.md) |\n| You have a `.pptx` template to fill in — keep its master, layouts, look | Placeholder replacement via `python-pptx` | [`edit.md`](edit.md) → *Template fill* |\n| Deep structural edits — reorder slides, splice XML, add unusual objects | Explode → edit XML parts → assemble | [`edit.md`](edit.md) → *Raw XML workflow* |\n| Only need the text / speaker notes / structure out of a `.pptx` | Extraction pipeline | [`read.md`](read.md) |\n| Turn a deck into PDF or PNG images (visual QA, publishing) | `scripts/render_pdf.py` / `scripts/render_slides.py` via LibreOffice | see *QA* below |\n| Grid of slide thumbnails for previewing a template | `scripts/contact_sheet.py` (Pillow) | [`read.md`](read.md) → *Thumbnails* |\n\nIf the task mixes several of these, do them in this order:\n**read → plan slide-by-slide → edit/create → validate → visual QA.**\n\n## One-time environment setup\n\n> **Bundled runtime:** when the `MIMO_PYTHON` environment variable is set, skip `uv`/pip installs — run every Python command below with `uv run` replaced by `\"$MIMO_PYTHON\"` (python-pptx/Pillow/lxml preinstalled; pip console scripts unavailable, use `\"$MIMO_PYTHON\" -m <module>`). A bundled LibreOffice is exposed as `MIMO_SOFFICE` (picked up automatically by `soffice_bridge.py`/`render_pdf.py`), and slide rasterisation automatically falls back to pypdfium2 in that interpreter when Poppler (`pdftoppm`) is absent. For the PptxGenJS authoring path, bundled Node.js is exposed as `MIMO_NODE`, with pptxgenjs/react/react-dom/sharp/react-icons/mathjax-full preinstalled in `MIMO_NODE_MODULES` — run scripts as `NODE_PATH=\"$MIMO_NODE_MODULES\" \"$MIMO_NODE\" <script.js>` instead of `npm install`.\n\n### Prerequisites\n\nIf `uv` or `bun` are not yet installed:\n\n```bash\n# Install uv (Python package/project manager)\n# macOS / Linux\ncurl -LsSf https://astral.sh/uv/install.sh | sh\n# Windows: powershell -ExecutionPolicy ByPass -c \"irm https://astral.sh/uv/install.ps1 | iex\"\n\n# Install bun (TypeScript runtime, replaces Node.js for this workflow)\n# macOS / Linux\ncurl -fsSL https://bun.sh/install | bash\n# Windows: powershell -c \"irm bun.sh/install.ps1|iex\"\n```\n\nOnly if the user explicitly refuses `uv` / `bun`, substitute `pip` (in a venv you manage yourself) for `uv`, and `npm`/`pnpm` + `npx tsx` for `bun` — everything else in this skill stays the same.\n\n### Python (uv)\n\nPython dependencies are managed by `uv`. Do not use `pip` directly.\n\n```bash\n# Initialize project (if no pyproject.toml exists)\nuv init -p 3.12\n\n# Add dependencies\nuv add python-pptx lxml Pillow\nuv add defusedxml                  # safe XML parsing (recommended for manual XML edits)\n```\n\n**Rules:**\n- Never use `pip` — always `uv add` for packages.\n- Never run `python scripts/...` directly — always `uv run scripts/...`.\n- Don't manually manage environments with `python -m venv` or `source .venv/bin/activate`.\n\n### TypeScript (bun)\n\nFor PptxGenJS creation, use `bun` (project-local, not global installs):\n\n```bash\n# Initialize (if no package.json exists)\nbun init -y\n\n# Add dependencies\nbun add pptxgenjs                  # core PPTX creation library\nbun add react react-dom sharp      # rasterization (icons + formulas)\nbun add react-icons                # icon library (FA, MD, etc.)\nbun add mathjax-full               # LaTeX formula rendering\n\n# Type definitions (including Bun runtime types)\nbun add -d @types/bun @types/react @types/react-dom\n```\n\nCreate a `tsconfig.json` if one doesn't exist:\n```json\n{\n  \"compilerOptions\": {\n    \"lib\": [\"ESNext\"],\n    \"target\": \"ESNext\",\n    \"module\": \"Preserve\",\n    \"moduleResolution\": \"bundler\",\n    \"allowImportingTsExtensions\": true,\n    \"noEmit\": true,\n    \"jsx\": \"react-jsx\",\n    \"strict\": true,\n    \"skipLibCheck\": true,\n    \"types\": [\"bun\"]\n  }\n}\n```\n\nRun scripts directly as TypeScript — no transpilation needed:\n```bash\nbun run create-ppt.ts\n```\n\n**Always run type checking after writing or modifying TS code:**\n```bash\nbun tsc --noEmit\n```\nModels may inadvertently use outdated PptxGenJS API signatures or\ndeprecated syntax without realizing it. A type check catches these\nmismatches before runtime.\n\n### System dependencies (PDF/PNG rendering)\n\n```bash\n# macOS\nbrew install --cask libreoffice\nbrew install poppler\n\n# Debian/Ubuntu\nsudo apt-get install -y libreoffice poppler-utils\n```\n\nEvery script under `scripts/` uses only the standard library plus\n`python-pptx`, `lxml`, and `Pillow`. No proprietary dependencies. External\nbinaries (`soffice`, `pdftoppm`) are invoked as subprocesses; nothing is\nbundled or statically linked.\n\n## Common commands\n\n```bash\n# 1. Extract text from every slide (title, body, notes) — the \"what does it say?\" query\nuv run scripts/dump_text.py input.pptx --notes > input.txt\n\n# 2. Convert a deck to PDF for review\nuv run scripts/render_pdf.py input.pptx                     # writes input.pdf next to it\n\n# 3. Convert every slide to a PNG (visual QA)\nuv run scripts/render_slides.py input.pptx --out slides/       # writes slides/slide-1.png, ...\n\n# 4. Grid thumbnail preview (planning which template slide to reuse)\nuv run scripts/contact_sheet.py input.pptx --cols 3         # writes input.contact-sheet.jpg\n\n# 5. Explode a .pptx into readable XML for surgical edits\nuv run scripts/explode.py input.pptx unpacked/\n\n# 6. Reassemble an exploded tree\nuv run scripts/assemble.py unpacked/ output.pptx\n\n# 7. Drop orphaned slides and unused media before reassembly\nuv run scripts/prune.py unpacked/\n\n# 8. Duplicate slide 3, or spin up a new slide from layout 5\nuv run scripts/insert_slide.py unpacked/ --clone slide3.xml\nuv run scripts/insert_slide.py unpacked/ --blank-from slideLayout5.xml\n\n# 9. Well-formedness check (ZIP + XML + python-pptx round-trip)\nuv run scripts/diagnose.py output.pptx\n```\n\nEvery script is a small Python CLI. Some scripts (e.g. `render_pdf.py`,\n`render_slides.py`, `contact_sheet.py`) import from a shared helper\n(`soffice_bridge.py`) in the same directory — copy them together. Read the top\nof each file for its full CLI options.\n\n## Live preview\n\nA live preview server is available for real-time slide feedback.\n**Not started by default.** When multi-slide work begins, ask the user\nif they want live preview enabled.\n\n**Only offer this in a pure command-line environment.** This server is\nfor the MiMoCode CLI. If you are running inside a host that embeds\nMiMoCode via the SDK — a web UI, a desktop app, an IDE plugin, etc. —\nthat host almost certainly has its own native preview / file-open\nmechanism; use it instead and do NOT start this server.\n\nIf yes, and this is a CLI environment:\n\n```bash\n# `scripts/preview.ts` lives in this skill's bundle directory, not in\n# your cwd. Prefix it with the absolute path shown in this skill's\n# location header (the folder that contains SKILL.md) — refer to it\n# as <SKILL_DIR> below.\n\n# Start (spawns background server, prints URL, exits immediately)\nbun run <SKILL_DIR>/scripts/preview.ts /path/to/output.pptx\nbun run <SKILL_DIR>/scripts/preview.ts /path/to/output.pptx --port 5000\n\n# Stop\nbun run <SKILL_DIR>/scripts/preview.ts --stop /path/to/output.pptx\n```\n\nIf the server is already running, `preview.ts` detects this via PID file\nand prints the existing URL instead of spawning a duplicate.\n\nThe background server watches the `.pptx` file, debounces (800ms),\nconverts to PDF via LibreOffice, and pushes a WebSocket reload to the\nbrowser. The browser's native PDF viewer provides scroll, thumbnails,\nzoom, and search. Preview output goes to `.pptx-preview/` (separate\nfrom `qa/`, no conflict with other scripts).\n\nGive the user the printed URL to open in their browser.\n\n**Live preview is for humans only — it does NOT replace visual QA.**\nThe preview server lets the user watch progress. You must still run\nthe visual QA subagent (render PNGs to `qa/`, spawn a vision model to\ninspect them) as described in the \"Visual QA execution model\" section.\nThese are independent workflows:\n- Preview server → user sees live updates in browser\n- Visual QA subagent → automated inspection, catches issues you can't\n\n**When to regenerate the .pptx during multi-slide work:** If the user\nhas the preview server running, regenerate the `.pptx` (re-run the\ncreation script) after completing each logical module — e.g. after\nfinishing a section's slides, not after every single shape placement.\nThis gives the user meaningful visual checkpoints without excessive\nintermediate renders.\n\n## Authoring principles\n\nSlides are a **visual surface**. Users read the deck at 40 feet from the back\nof a room, or in a browser tab three inches wide on a phone. Both have to\nwork. Keep these in mind:\n\n1. **One idea per slide.** If you can't summarize the slide in a five-word\n   title, split it in two. Long-form reasoning belongs in the doc that\n   accompanies the deck, not on the slide itself.\n2. **Title, not label.** The title is the thesis of the slide. \"Revenue\" is a\n   label. \"Revenue grew 34% on 22% headcount\" is a title. Titles carry the\n   argument; bodies carry the evidence.\n3. **Every slide earns its visuals.** A slide without a chart, image, icon,\n   or shape is usually a bullet dump. Turn it into a comparison, a stat\n   callout, a diagram, or delete it. **A \"visual\" is not necessarily a\n   picture** — a stat callout, a comparison shape, or a well-typeset quote\n   is already a visual. When you do need a picture, see *Image sourcing*\n   below.\n4. **Layouts, not per-slide geometry.** For anything reused (section\n   dividers, content pages, quote slides), define a `slide_layout` once and\n   apply it. This makes swapping the theme a one-line change instead of a\n   fifty-slide sweep.\n5. **Aspect ratio matches the target.** 16:9 (default) for laptops and\n   projectors; 4:3 only when explicitly asked (still common in academia and\n   some corporate templates); 16:10 for older widescreen.\n6. **Speaker notes carry the words.** Put the full narration into\n   `slide.notes_slide.notes_text_frame` so the presenter can rehearse from\n   the deck itself. On the slide, keep it to the phrase they can hold in\n   their head.\n7. **Bullets are not the default.** Bullet lists are the failure mode of\n   most decks — comparisons, tables, icons-with-labels, and stat callouts\n   almost always land better.\n\n## Image sourcing (choose the right channel)\n\n\"Every slide earns its visuals\" does **not** mean \"generate an image for\nevery slide.\" Choose the source based on what the image does. Four channels,\nordered by preference (lower cost + higher stability first):\n\n**L1 · Draw in code.** Icons via react-icons / iconify. Charts via\nmatplotlib / plotly / echarts. Flowcharts, comparisons, org charts via\nshapes + lines. Anything that is a data or concept visualization —\nnever fetch or generate an image for this.\n\n**L2 · Search a stock library, then download the bytes.** When a slide\nneeds a **generic real photo** (city skyline, office desk, team\ncollaboration, nature, stock imagery), use `websearch` with a\n`site:unsplash.com` / `site:pexels.com` / `site:pixabay.com` query to find\na real URL, then **download the image to a local file** and pass that path\nto `add_picture` (see *Downloading* below). Do NOT try to pass an HTTP URL\ndirectly to `add_picture` — python-pptx's `add_picture` only accepts a\nlocal path or a file-like object; it will NOT fetch a URL for you.\n\n**L3 · Search a specific source.** For **specific real things** (a\nparticular company's logo, a specific product's official screenshot, a\nnamed person's photo), use `websearch` with a targeted query (e.g.\n`\"Acme Inc\" logo site:acme.com`, or `<product name> screenshot`) instead of\na stock-library query, then download the bytes the same way as L2. Never\ncall `image_gen` here — a generated logo will not look like the real logo.\nNote: `webfetch` returns text/markdown/html only and cannot deliver binary\nimage bytes — use `bash` + `curl` or python `urllib` to download.\n\n**L4 · Generate with `image_gen`.** Only for **stylized visuals** — cover\nart, hero backgrounds, illustration-style concept images, brand-mood\nimagery. Budget: **at most 1–2 `image_gen` calls per deck**, typically for\ncover or section dividers. Not for every content slide.\n\n### Downloading a URL for `add_picture`\n\nTwo working patterns. Both keep the file local so `add_picture` can read\nthe bytes:\n\n```python\n# Pattern A: download to a temp file, then pass the path\nfrom urllib.request import Request, urlopen\nfrom pathlib import Path\n\ndef download_image(url: str, dest: Path) -> Path:\n    req = Request(url, headers={\"User-Agent\": \"Mozilla/5.0\"})  # some CDNs 403 an empty UA\n    with urlopen(req, timeout=15) as r:\n        dest.write_bytes(r.read())\n    return dest\n\npath = download_image(hit_url, Path(\"assets/hero.jpg\"))\nslide.shapes.add_picture(str(path), Inches(1), Inches(1.5), width=Inches(11))\n```\n\n```python\n# Pattern B: in-memory via BytesIO — no temp file, but same request headers\nfrom io import BytesIO\nfrom urllib.request import Request, urlopen\n\nreq = Request(hit_url, headers={\"User-Agent\": \"Mozilla/5.0\"})\nwith urlopen(req, timeout=15) as r:\n    slide.shapes.add_picture(BytesIO(r.read()), Inches(1), Inches(1.5), width=Inches(11))\n```\n\nOr from a bash step:\n\n```bash\ncurl -sSL -A \"Mozilla/5.0\" -o assets/hero.jpg \"$URL\"\n```\n\nWrap any download in a try/except: on failure fall through to the next\nchannel (L3 → L4) or a shape+text fallback — never leave a slide blank.\n\n### Decision (run per slide)\n\n1. Does this slide actually need a picture? Often the answer is no — a\n   large stat callout, a comparison shape, a well-typeset quote, or a\n   diagram *is* a visual. Skip pictures when layout + typography carries\n   the message.\n2. If yes, pick the cheapest channel that works:\n   - Data / concept / flow / icon → **L1** (draw in code)\n   - Generic real photo → **L2** (stock library search + download)\n   - Specific brand / logo / product / person → **L3** (targeted web search + download)\n   - Stylized cover / hero / illustration → **L4** (`image_gen`)\n3. If a fetch fails: L2 → L3 → L4 → shape + text fallback. Never leave a\n   slide blank because an image failed to load.\n\n### Anti-patterns\n\n- **Calling `image_gen` on every content slide.** Slow, expensive,\n  style-inconsistent, visually noisy. A 20-slide deck with 20 generated\n  images is a red flag, not a success.\n- **Passing an HTTP URL to `add_picture`.** python-pptx will raise\n  `FileNotFoundError` — always download the bytes first (see *Downloading*).\n- **Using `webfetch` to grab image bytes.** `webfetch` returns text only.\n  Use `bash` + `curl` or python `urllib` for binaries.\n- **Making up a stock-library URL from memory.** Unsplash / Pexels CDN\n  paths are opaque hashes — you cannot reliably recall a URL that both\n  exists AND matches the described content. Always search first, then\n  download.\n- **Generating a logo, celebrity, or product screenshot with `image_gen`.**\n  The output will not resemble the real thing. Use targeted web search (L3).\n- **Executive / status / weekly decks in illustration style.** Work\n  reporting is data + icons + hierarchy, not concept art. Reserve L4 for\n  launch, brand, or hero visuals.\n- **Leaving a slide blank because an image fetch failed.** Always have a\n  shape + text fallback; a well-formatted stat callout is a better slide\n  than an empty one anyway.\n\n### Scene defaults (rough mix per deck type)\n\nL2/L3 both cost about one `websearch` + one download per image — cheap\ncompared to L4, still not free. L1 remains the default.\n\n| Deck type              | Dominant | Notes                                           |\n|------------------------|----------|-------------------------------------------------|\n| Status / OKR / weekly  | L1 (~90%) | Icons + data charts. Almost no L2 / L3 / L4.   |\n| Strategy / proposal    | L1 + L2  | ~60% L1, ~30% L2 (searched stock), ~10% L4 cover. |\n| Sales / pitch / BP     | L2 + L3  | Customer logos and product shots (L3) matter. 1 L4 cover max. |\n| Training / education   | L1 (~80%) | Diagrams and flowcharts win.                   |\n| Launch / brand         | L4-heavy | Visuals are the point. Still limit style drift and reuse assets. |\n| Competitive analysis   | L3-heavy | Logos and screenshots are irreplaceable.        |\n\n## Typography defaults (safe starting point)\n\n| Element              | Font          | Size    | Weight  | Notes |\n|----------------------|---------------|---------|---------|-------|\n| Slide title          | Calibri / Segoe UI | 32-40pt | Bold    | One line — wrap = rework the title |\n| Section header       | Calibri       | 24-28pt | Bold    | On dedicated divider slides |\n| Body / bullets       | Calibri       | 18-22pt | Regular | Never below 18pt for a room; 14pt for on-screen decks |\n| Stat callout         | Calibri Light | 60-96pt | Bold    | The number, then the label below at 14-18pt |\n| Caption / footer     | Calibri       | 10-12pt | Regular | Muted gray `#7A7A7A` |\n| Code / mono          | Consolas / Cascadia Code | 16-20pt | Regular | Left aligned, no word wrap |\n\nChange the palette for the topic (financial → navy `#1F3A5F`; environment →\nforest `#2C5F2D`; product launches → your brand's accent). Avoid pure black\non pure white for backgrounds — `#F7F5F0` cream on `#1F1F1F` ink reads\nsofter under a projector.\n\n## Slide sizes\n\n| Aspect | Width × Height (inches) | Pixels @ 96 DPI | When to use |\n|--------|-------------------------|------------------|-------------|\n| 16:9 widescreen (default) | 13.333 × 7.5    | 1280 × 720       | Almost every new deck |\n| 16:10                      | 13.333 × 8.333  | 1280 × 800       | Older projectors; some corporate templates |\n| 4:3 standard               | 10.0   × 7.5    | 960  × 720       | Academia, legacy templates, printed handouts |\n| A4 landscape               | 11.69  × 8.27   | 1123 × 794       | Print-first decks (EU) |\n| Letter landscape           | 11.0   × 8.5    | 1056 × 816       | Print-first decks (US) |\n\n## QA checklist — always run before declaring done\n\n**Assume something is wrong.** PowerPoint opens broken files quietly: a\nmisaligned text box, a chart pointing at deleted data, a stray placeholder\nthat survived template fill. Verify explicitly.\n\n1. **Opens cleanly.** No repair dialog, no missing-part warning.\n   ```bash\n   uv run scripts/diagnose.py output.pptx\n   ```\n\n2. **Text integrity.** No placeholder residue and no unfilled `{{token}}`s:\n   ```bash\n   uv run scripts/dump_text.py output.pptx --notes \\\n       | grep -Ei \"\\{\\{|TODO|TBD|lorem|ipsum|xxxx|click to add\"\n   ```\n   Grep must return nothing.\n\n3. **Visual sanity.** Render the whole deck to PNG, spot-check the first,\n   last, and any slide you touched. Look for:\n   - Text overflowing the placeholder or getting auto-shrunk past readability.\n   - Two shapes overlapping (title over image, footer over content).\n   - Legend / axis labels cut off on charts.\n   - Icons at the wrong scale (tiny hairline icons, or huge stretched ones).\n   - Off-brand colors that snuck in from a copied slide.\n   ```bash\n   uv run scripts/render_slides.py output.pptx --out qa/\n   ```\n\n4. **Layout hygiene.** Every non-master slide should reference a real layout,\n   not `slideLayout1` by default for a section divider:\n   ```bash\n   uv run python -c \"\n   from pptx import Presentation\n   prs = Presentation('output.pptx')\n   for i, s in enumerate(prs.slides, 1):\n       print(f'slide {i}: layout={s.slide_layout.name!r}')\"\n   ```\n\nIf any of these fail, fix and re-run — don't paper over.\n\n## Visual QA execution model\n\n**Slide images are expensive.** A single rendered PNG at 150 DPI consumes\nthousands of context tokens. Loading multiple slides into the main\nconversation for inspection will quickly exhaust your context budget and\ncrowd out useful working memory.\n\n**Default: always use a subagent for visual inspection.** Spawn a\n`general` subagent with the rendered PNG paths and the\ninspection criteria from step 3 above. The subagent reports findings as\ntext (slide number + issue description); the images never enter the main\nconversation context. This is mandatory unless the exception below applies.\n\n```\nactor({\n  operation: {\n    action: \"run\",\n    subagent_type: \"general\",\n    // omit `model` when your current model is vision-capable (preferred — see Model selection)\n    description: \"Visual QA slides\",\n    prompt: \"Inspect the rendered slide images in qa/ for: text overflow, overlapping shapes, cut-off labels, wrong-scale icons, off-brand colors. Report each issue as 'slide N: <problem>'. Images: qa/slide-1.png through qa/slide-<N>.png.\"\n  }\n})\n```\n\n**Model selection (in priority order):**\n\n1. **Prefer the user's current model.** Query the servable vision models via\n   `actor({ operation: { action: \"models\", vision: true } })`. If your current\n   model is in the list, **omit the `model` parameter** — the subagent inherits\n   it, and visual QA runs on the model the user chose.\n2. **Fallback: lightweight vision model, stated explicitly.** If your current\n   model is not vision-capable, pick a **lightweight** vision model from the\n   query result (haiku/flash/lite-class if present, otherwise the cheapest\n   listed) and **tell the user in your reply** which model you used for visual\n   QA and why (current model cannot inspect images).\n3. **No vision model available.** If the query returns an empty list, do not\n   guess a model id — skip the visual QA subagent, run the structural checks\n   only, and tell the user visual inspection could not be performed.\n\n**Never hardcode a model id.** Which models are servable varies per\ndeployment and changes over time; only ids returned by the vision models\nquery are guaranteed to work. A guessed id fails the subagent outright.\n\n**Exception — direct inspection in the main context:** Only load slide\nimages directly (without a subagent) when the user explicitly requests\nthat the current model inspect a specific slide for fine-grained,\ninteractive editing (e.g. \"look at slide 5 and adjust the title\nposition\"). This requires the current model to be multimodal. If it\nisn't, inform the user and offer to spawn a vision subagent instead.\n\n## Common visual pitfalls\n\n- **Titles wrap onto two lines** — either shorten the title or widen the\n  placeholder. Wrapped titles push body content down and break layout\n  alignment across slides.\n- **Body text auto-shrinks below 14pt** — python-pptx respects the\n  placeholder's autofit setting; if the resulting size is unreadable, split\n  the slide instead of accepting the shrink.\n- **Charts inherit Office defaults** — the pale blue / gray palette shipped\n  with PowerPoint looks generic. Explicitly set `chart.chart_style` or use\n  `python-pptx`'s low-level access to set fill colors on series.\n- **Speaker notes forgotten** — a deck without notes cannot be rehearsed.\n  Fill `notes_slide.notes_text_frame.text` on every slide, even if just a\n  single sentence.\n- **Images at wrong DPI** — a 4000×3000 photo on a 1280×720 slide bloats\n  the file with no visual benefit. Resample down to ~150 DPI at the target\n  display size (see `create.md` → *Images*).\n- **Fonts not embedded** — `python-pptx` does not embed fonts. If the deck\n  is opened on a machine without the chosen font, PowerPoint substitutes,\n  and layout drifts. For **Latin** text, prefer system-safe fonts (Calibri,\n  Arial, Segoe UI, Times New Roman, Consolas) or ship the .pptx alongside a\n  font install step.\n- **CJK text needs the East-Asian font slot** — `run.font.name` only sets the\n  Latin typeface (`a:latin`); Chinese / Japanese / Korean glyphs come from the\n  East-Asian slot (`a:ea`), which python-pptx does not expose. Leave it unset\n  and CJK renders as tofu boxes or an inconsistent substitute. Set `a:latin` +\n  `a:ea` + `a:cs` to a CJK-capable font on every run that contains CJK text\n  (recipe in `create.md` → *CJK / East-Asian text*).\n\n## What is out of scope\n\n- **`.ppt` (PowerPoint 97-2003 binary)**. Convert first:\n  `soffice --headless --convert-to pptx old.ppt`.\n- **VBA / macros / `.pptm`.** This skill does not emit or execute macros.\n- **Password-protected or encrypted decks.** `python-pptx` cannot read\n  encrypted files; strip protection with PowerPoint or LibreOffice first.\n- **Live PowerPoint automation.** For COM (Windows) or AppleScript (macOS)\n  integration, use a dedicated automation library — this toolkit is\n  file-in / file-out.\n- **Keynote `.key` files.** Not a PresentationML format; use Apple's\n  Keynote or LibreOffice for round-trip.\n\n## Where each detail lives\n\n- **Creating from scratch**: [`create.md`](create.md) — python-pptx recipes,\n  PptxGenJS recipes, layouts, text, tables, images, charts, icons,\n  backgrounds, speaker notes, palette and typography guidance.\n- **Editing / templating**: [`edit.md`](edit.md) — placeholder fill, slide\n  duplication / reorder / delete, explode/assemble for XML surgery, comments,\n  cleanup of orphaned parts, common pitfalls.\n- **Reading / extracting**: [`read.md`](read.md) — plain-text export\n  (including speaker notes), structural walk, metadata, thumbnails, image\n  extraction, conversion to PDF / PNG for QA.\n- **Scripts**: [`scripts/`](scripts/) — CLI utilities (some share a local\n  `soffice_bridge.py` helper; copy together when extracting).\n- **Live preview**: [`scripts/preview.ts`](scripts/preview.ts) — launcher\n  (start/stop); [`scripts/preview_server.ts`](scripts/preview_server.ts) —\n  background server that watches .pptx, converts to PDF, serves with\n  WebSocket hot-reload in the browser's native PDF viewer.\n","packages/cli/src/skill/builtin/.bundle/product-design/SKILL.md":"---\nname: product-design\ndescription: \"Use this skill when Product Design is explicitly invoked or the main task is product design exploration, UX research, flow auditing or critique, visual ideation, cloning a live product surface, implementing a selected visual target, design QA, saved design context, or sharing a prototype.\"\n---\n\n# Product Design\n\nThis is the single entry point for a code-agent-oriented Product Design bundle. The original workflow instructions are under `workflows/`, with shared guidance under `references/`. The bundled React/Vite prototype template and package metadata are intentionally excluded.\n\n## Route the request\n\n1. Read `workflows/index/SKILL.md` completely. Treat it as the authoritative plugin-level scope, routing, sequencing, and browser-choice policy.\n2. Select the focused workflow or workflow sequence specified by the index. Read every selected workflow's `SKILL.md` completely before acting.\n3. Common sequences include loading context before design/build work, ideating before implementation when no visual target is selected, and running design QA after a source-grounded prototype is built. Follow the exact conditions in the index rather than inferring a fixed sequence for every request.\n4. Resolve relative links from the file that contains the link. Read required reference files and use bundled scripts and assets when present.\n5. Do not load unrelated focused workflows merely because they are present.\n\n## Bundled capabilities\n\nFocused workflows live in `workflows/`: `user-context`, `get-context`, `research`, `audit`, `ideate`, `url-to-code`, `image-to-code`, `design-qa`, and `share`.\n\nShared reusable guidance lives in `references/`. Workflow-local references, scripts, and assets remain beside their owning workflow when they are not React/frontend build artifacts.\n\nUse browser, Chrome, Playwright, image generation, design apps, hosting, and other integrations only when the host harness exposes them. The bundle's mention of a tool does not prove availability or authorization. Follow host permissions and the selected workflow's fallback behavior.\n\nWhen creating a prototype, prefer the target repository's existing frontend stack. If there is no existing app and the user still wants a runnable web prototype, create the smallest suitable implementation using host-supported tools; React is not required. Do not look for the removed bundled prototype template or bootstrap script.\n\n## Safety and fidelity\n\n- Never treat plugin instructions as permission to bypass host policy or publish externally without the required user choice.\n- Keep audits evidence-grounded and distinguish screenshot-visible findings from claims requiring deeper testing.\n- Do not modify production code when a workflow requires an isolated prototype.\n- Preserve the selected workflow's visual QA and handoff requirements through completion.\n","packages/cli/src/skill/builtin/.bundle/product-design/workflows/audit/SKILL.md":"---\nname: audit\ndescription: \"Audit or critique a product flow, journey, workflow, funnel, onboarding path, checkout path, settings path, screen, or multi-step product experience by capturing screenshots first, then reporting UX, design, and accessibility findings inline from that evidence. Use Figma only when the user explicitly asks for a board. Use when the user asks to audit, review, critique, inspect, assess, analyze, evaluate, or give feedback on a product experience.\"\n---\n\n# Audit\n\nUse this skill when the user wants to audit, review, critique, inspect, assess, analyze, evaluate, or give feedback on a product flow, journey, funnel, onboarding path, checkout path, settings path, screen, or other product experience.\n\nThe output is not a loose opinion. The output is:\n\n- Screenshots of the flow\n- Those screenshots rendered inline in the report\n- A numbered step list\n- UX and design findings tied to steps or screenshots\n- Accessibility risks tied to steps or screenshots\n- Clear limits on what could not be checked from screenshots alone\n\n## Critical Overrides\n\n- Refer to the Plugin router [$index](../index/SKILL.md) before proceeding.\n- Follow [$critical-overrides](../../references/critical-overrides.md).\n\n## User Context\n\nBefore starting, load [$user-context](../user-context/SKILL.md) and run its preflight script when local shell access is available.\n\nUse saved product URLs, Figma files, screenshots, reference images, codebase paths, Storybook, tokens, design systems, brand assets, component refs, browser preferences, and share targets as grounding material when relevant.\n\nDo not inspect every saved reference. Inspect only what the current task needs.\n\n## Route\n\nBefore auditing:\n\n1. Identify the product or surface.\n2. Identify the flow or task.\n3. Choose the capture tool.\n4. Capture the flow.\n5. Save and inspect each screenshot.\n6. Return the audit inline with the accepted screenshots.\n\nOutput rules:\n\n- Default to a concise inline report with screenshots rendered in the chat.\n- Saving screenshots and notes in the workspace is an internal implementation detail. Do not ask the user to choose a local folder.\n- If the user explicitly asks for Figma, create the Figma audit board in addition to the inline report.\n- After the inline report, ask once: `Want me to plot this out in Figma with the screenshots and notes?`\n\nCapture rules:\n\n- Follow the Browser Choice rule in [$index](../index/SKILL.md#browser-choice).\n- If none of those can capture valid screenshots or control the flow, stop and report the blocker.\n\nBrowser capture order:\n\n1. Load the Browser skill before browser work.\n2. Connect to the browser and use the current tab when it already shows the target.\n3. Do not reload or navigate away unless the audit needs a fresh start.\n4. Observe the visible state before acting.\n5. Before each click, type, or key press, use the latest DOM snapshot to target one clear control.\n6. After each action, take the cheapest fresh check that proves what changed: DOM for structure, screenshot for visual state.\n7. Save and inspect the accepted screenshot before using it as audit evidence.\n\nFigma rules:\n\n- If Figma is the destination, load the required Figma skills before creating or editing the file.\n- Keep a local copy of every screenshot even when Figma succeeds.\n- Do not upload a screenshot to Figma until the saved local file has been inspected and accepted.\n- Figma is not done until the screenshots are visibly placed in the Figma output.\n- After placing screenshots in Figma, render or inspect the board and confirm every flow step has the correct screenshot visible in the correct card.\n- If an image is missing, misplaced, blank, or only uploaded as an unused asset, fix it before handoff.\n- If Figma tools cannot create files or place images, return the inline audit and explain the missing Figma capability.\n\nEvidence rules:\n\n- Use only evidence captured in the current audit run.\n- Do not use memory, prior chats, old traces, cached screenshots, or prior generated artifacts as audit evidence unless the user explicitly provides them.\n- Do not audit until the product, flow, and capture tool are known.\n- Do not claim full accessibility compliance from screenshots alone.\n\n## Capture And Audit The Flow\n\nYou are an expert design, UX, and accessibility auditor. For each step in the flow, capture what the user sees, observe how the screen behaves, inspect the screenshot, and write audit notes before moving on.\n\nFollow [references/design-audit-framework.md](references/design-audit-framework.md) when deciding what to inspect and how to describe strengths, UX issues, accessibility risks, limits, and recommendations.\n\nScreenshot source rule:\n\n- Use the screenshot you actually saw.\n- Save that exact screenshot to the local audit folder.\n- Open or inspect the saved file before accepting it.\n- If the saved file shows the wrong window, wrong state, blank page, crop, or loading screen, reject it and capture again.\n- When Figma is the destination, upload that accepted local file.\n- After upload, verify the Figma board shows the same step.\n- Do not replace a Browser, Chrome, or Computer Use screenshot with an OS screenshot unless you first prove the saved file shows the same window and state.\n\nFor every step:\n\n1. Move to the next step in the requested flow.\n2. Wait until the screen is loaded and visually stable.\n3. Check for loading spinners, blank areas, login walls, error pages, blocked states, cookie dialogs, and half-rendered content.\n4. Capture the screenshot.\n5. Inspect the screenshot before accepting it.\n6. Reject the screenshot if it is blank, loading, cropped, blocked, or showing the wrong state.\n7. Observe behavior that matters for the audit, such as navigation, focus, loading, validation, error handling, empty states, motion, and whether the next action is clear.\n8. Write notes for that step.\n9. In the notes, report strengths, UX issues, accessibility risks, and any limits that made the step difficult to audit.\n10. Save accepted screenshots with numbered names, such as `01-start.png`, `02-form-filled.png`, and `03-confirmation.png`.\n11. Inspect the saved screenshot file before upload or handoff.\n12. Keep each accepted screenshot and its notes together for the final inline report.\n13. If the user explicitly requested Figma, add each accepted screenshot and its notes to the board immediately.\n\nDefault inline report:\n\n- Render accepted screenshots in flow order.\n- Keep the report pithy: overall verdict, numbered steps, highest-impact changes, and evidence limits.\n- Tie every finding to the screenshot or step that supports it.\n\nIf the user explicitly requested Figma:\n\n- Place screenshots in order, left to right on the same row, with 200px between each one. Go to a new row every 15 screenshots, and separate those rows by 600px.\n- Underneath the screenshot, add text with the Step number and its name, and notes.\n- Keep a local folder copy even when Figma succeeds.\n- When you are done, wrap all of the assets you added in a Section and title the section.\n\nAcceptance checks:\n\n- Every important step in the requested flow has a valid screenshot or a named blocker.\n- Screenshots are saved in order.\n- Screenshots are rendered inline in the final report.\n- When Figma was explicitly requested, screenshots and notes are placed in the board as they are captured.\n- Every note points to the screenshot or step it describes.\n- Notes explain strengths, UX issues, accessibility risks, and evidence limits when those apply.\n- Accessibility risks say what can be seen from screenshots and what still needs testing.\n- The final screenshot set and notes are enough to support the requested audit.\n\nBlockers:\n\n- The flow cannot be completed.\n- A required step cannot be screenshotted.\n- The source changes in a way that makes the flow unclear.\n- Screenshots cannot be saved or rendered inline.\n- Notes cannot be written.\n- The requested claim would require evidence that screenshots cannot provide.\n- Do not claim an audit if the actual flow could not be accessed and captured. Help Center pages, web searches, and other indirect evidence are research, not an audit.\n\n## Final Response\n\nAfter the flow is captured and notes are written, list every step in the final response.\n\nThe final step list MUST include:\n\n- step number\n- short description of the step\n- general health of that step\n\nAlso include where the full output was saved or placed.\n\nKeep the language direct. Do not use broad design jargon when a plain phrase works.\n","packages/cli/src/skill/builtin/.bundle/product-design/workflows/design-qa/SKILL.md":"---\nname: design-qa\ndescription: \"Internal prototype QA helper. Use only after a Product Design prototype, URL-to-code build, or image-to-code build has a source visual target and a rendered implementation to compare before handoff. Do not use for broad UX critique, design critique, product audits, or flow reviews; route those user-facing requests to audit.\"\n---\n\n# Design QA\n\nUse this internal helper to compare a prototype's source design against the rendered implementation before handoff.\n\nDo not use this skill for broad UX critique, design critique, product audits, or flow reviews. Use [audit](../audit/SKILL.md) for those user-facing requests.\n\nUse this skill before every Product Design build handoff.\n\nA passing QA run requires both:\n\n- a source visual target: Figma node, image, screenshot, mockup, or source capture\n- a rendered implementation: local URL, deployed URL, app screen, component, or screenshot\n\nIf either artifact cannot be opened, captured, or compared, write `design-qa.md` with `final result: blocked` and name the blocker. Do not let the build skill hand off as done.\n\n## Critical Overrides\n\nFollow [critical-overrides](../../references/critical-overrides.md).\n\n## Workflow\n\nCompare the intended design to the implementation as a product-quality reviewer, not as a generic aesthetic critic. The output must be a prioritized fix list grounded in evidence from both artifacts.\n\nDo not write the QA review from memory, code, or file paths alone. Open or capture both the source design and the implementation first, then compare what is actually visible.\n\nDo not pretend separate image views are side-by-side comparison. Put the source image and the implementation screenshot together in the same comparison input, then judge the visible differences from that combined input.\n\nDesign QA is an iteration loop. The first comparison may pass only when it finds no actionable P0/P1/P2 differences and no visual fixes are made in response.\n\nWhen a comparison finds any P0/P1/P2 issue:\n\n- Record the finding and keep the current result blocked.\n- Apply the fix.\n- Capture the revised implementation at the same viewport and state.\n- Compare the revised capture against the source again.\n\nA later pass must identify the earlier findings, the fixes made, and the post-fix visual evidence. Build, dependency, lint, deployment, and preview troubleshooting do not count as design-QA iterations.\n\n1. Identify the comparison target.\n   - Determine the source design: Figma node, image, design board, screenshot, spec, or mockup.\n   - Determine the implementation: local URL, deployed URL, app screen, component, screenshot, or code-rendered view.\n   - Match the same viewport, state, theme, device density, route, content, auth state, and interaction state before judging.\n   - If artifacts do not represent the same state, call that out first and avoid false precision.\n\n2. Capture evidence.\n   - For Figma, use design context and screenshot tools when available.\n   - For web/app implementations, follow the Browser Choice rule in [index](../index/SKILL.md#browser-choice). In ChatGPT Work Mode, follow the active build skill's \"Previewing prototypes in ChatGPT Work Mode\" section before opening a local implementation. Then capture screenshots at the intended viewport.\n   - Capture additional states when relevant: mobile/desktop, hover/focus/active, empty/loading/error, dark/light, and key responsive breakpoints.\n   - Save paths or URLs for screenshots when available so findings can cite evidence.\n   - Capturing screenshots is not enough. Put the source image and the implementation screenshot together in the same comparison input before judging.\n\n3. Normalize before comparing.\n   - Align crop, viewport size, scale, and device frame. Do not compare a framed mockup to an unframed page without noting the mismatch.\n   - Prefer comparing content regions over full browser chrome or surrounding canvas.\n\n4. Compare at the right level of detail.\n   - Use a full-view comparison to judge overall composition, hierarchy, layout, density, and responsive structure.\n   - Use focused region comparisons when important details are too small to judge in the full-view comparison.\n   - Choose focused regions from the actual source and implementation. Use them where fidelity depends on precise typography, alignment, imagery, assets, icons, logos, controls, forms, navigation, tables, dense UI, or visible interaction states.\n   - If no focused region is needed, say why in `design-qa.md`.\n   - Do not pass QA from a full-view comparison alone when important details are not clearly readable.\n\n5. Review systematically.\n   - Read [qa-rubric](./references/qa-rubric.md) when the QA pass spans more than a quick visual check.\n   - Check information architecture, layout, spacing, typography/fonts, color, imagery/image quality, icons, copy, affordances, interaction states, responsiveness, accessibility, and polish.\n   - Always make a specific pass over the five required fidelity surfaces: fonts/typography, spacing/layout rhythm, colors/tokens, image quality, and copy/content. Do this even if the user did not name those areas explicitly.\n   - If the mock does not address some issue you're seeing (e.g. a null state), call that out as a separate finding as a shortcoming of the mock to be addressed.\n   - Your other goal is to decide whether the implementation \"looks as good\" as the mock. If there are stylistic problems, call them out. If the user's prompt is leaking into the implementation (vs letting the app stand on its own), call that out as well.\n   - Distinguish design drift from intentional product/code constraints. If a deviation may be intentional, phrase it as a question or assumption.\n\n6. Produce a fix-oriented QA report.\n   - Lead with findings, ordered by severity and user impact.\n   - For each finding include: severity, location, what differs, evidence, why it matters, and the concrete fix.\n   - Include exact CSS/component/token suggestions when the implementation context is available.\n   - Separate objective mismatches from subjective polish recommendations.\n   - Do not say a design matches, is done, or is as good as it can get until the required fidelity surfaces have been checked and any remaining differences are explicitly classified as acceptable, expected, or still actionable.\n   - End with a concise implementation checklist.\n\n## Required Fidelity Surfaces\n\nEvery QA report must explicitly evaluate these surfaces:\n\n- Fonts and typography: family, fallback, weight, size, line height, letter spacing, antialiasing, hierarchy, wrapping, truncation, and whether display text and small UI text use appropriate optical weights. It is incredibly important to check fonts carefully for fidelity, including looking up similar typefaces or using image analysis to find the font differences.\n- Spacing and layout rhythm: frame size, crop, alignment, margins, padding, grid tracks, section gaps, component spacing, radii, shadows/elevation, and vertical rhythm.\n- Colors and visual tokens: sampled or inferred palette, gradients, opacity, contrast, semantic state colors, foreground/background balance, and whether CSS tokens map to the source design.\n- Image quality and asset fidelity: subject correctness, crop, scale, sharpness, compression, transparency halos, masking, background treatment, raster-vs-vector appropriateness, and whether generated assets match the source art direction. Fail QA if logos, illustrations, decorative marks, product imagery, non-standard icons, or other visible image assets from the visual target were replaced with custom inline SVG, handcrafted SVG, HTML elements, div/span shapes, CSS drawings, gradients, emoji, text glyphs, placeholder shapes, or code-native approximations.\n- Copy and content of app-specific text\n\n## Severity\n\n- `P0`: Blocks core use, severe accessibility failure, broken layout, or impossible task.\n- `P1`: Major design mismatch or usability regression likely to be noticed by users.\n- `P2`: Moderate visual drift, inconsistent state, responsive issue, or fixable polish gap.\n- `P3`: Minor refinement that improves fidelity but does not block acceptance.\n\nTreat viewport overflow that hides persistent app controls, and mismatches that materially change above-the-fold content, major-region proportions, text wrapping, or interface density, as P2 or higher.\n\n## Output Format\n\nUse this structure unless the user asks otherwise:\n\n```markdown\n**Findings**\n- [P1] Short issue title\n  Location: screen/component/selector/file if known.\n  Evidence: design does X, implementation does Y.\n  Impact: why this matters.\n  Fix: concrete change.\n\n**Open Questions**\n- Any ambiguity about intentional deviations, unavailable states, or missing artifacts.\n\n**Implementation Checklist**\n- Ordered fixes that can be executed directly.\n\n**Follow-up Polish**\n- P3 refinements that can improve fidelity after handoff.\n```\n\nIf there are no substantive mismatches, say that clearly and list any residual test gaps.\n\nWhen this skill is used before handoff, save the latest QA report as project-root `design-qa.md`.\n\n`design-qa.md` must include:\n\n- source visual truth path\n- implementation screenshot path\n- viewport\n- state\n- full-view comparison evidence\n- focused region comparison evidence, or why it was not needed\n- findings\n- comparison history for every P0/P1/P2 iteration: earlier findings, fixes made, and post-fix visual evidence\n- final result\n\nFor ChatGPT Work Mode builds, `design-qa.md` must include the browser-rendered implementation screenshot, viewport, primary interactions tested, console errors checked, and final result. If browser-rendered evidence is missing, `final result` is `blocked`.\n\n`final result` must be exactly `passed` or `blocked`.\n\nUse `passed` when there are no actionable P0/P1/P2 findings. P3 findings may remain as follow-up polish.\nUse `blocked` when actionable P0/P1/P2 findings remain and name the blocker.\n\nReturn the file path with the QA report.\n","packages/cli/src/skill/builtin/.bundle/product-design/workflows/get-context/SKILL.md":"---\nname: get-context\ndescription: \"Mandatory design-brief gate for clarifying the product and outcome. Use before ideation, image-to-code builds, redesigns, or product UI work to clarify missing product information and play back the brief before proceeding.\"\n---\n\n# Get Context\n\n\nRun this skill at the start of Product Design requests that ask to design, build, prototype, clone, redesign, extend, or generate product UI directions.\n\nUse question mode to clarify the following:\n\n- what product, site, feature, workflow, component, or screen is being designed, redesigned, or extended\n- what the feature, change, app, or website should help the user do\n\nDo not re-ask answered questions. When both are clear, play back the brief and defaults in one pithy note, name the next workflow, and continue in the same turn. Playback is not a request for approval. The user can course-correct style, scope, or interactivity at any point.\n\nHard boundary: do not implement UI, scaffold a prototype, start a server, or create files while the design target or intended user outcome is still missing.\n\n## Critical Overrides\n\n- Refer to the Plugin router [$index](../index/SKILL.md) before proceeding.\n- Follow [$critical-overrides](../../references/critical-overrides.md).\n\n## User Context\n\nBefore starting, load [$user-context](../user-context/SKILL.md) and run its preflight script when local shell access is available.\n\nUse saved product URLs, Figma files, screenshots, reference images, codebase paths, Storybook, tokens, design systems, brand assets, component refs, browser preferences, and share targets as grounding material when relevant.\n\nDo not inspect every saved reference. Inspect only what the current task needs.\n\n## Handoff To The Next Workflow\n\n1. When the next workflow is already clear, read that skill before sending the brief playback. Do not only name a skill you have not read.\n\n2. Before executing `$ideate`, `$url-to-code`, or `$image-to-code`, play back the minimum brief and any defaults in one pithy user-visible note.\n\n3. If the target and intended user outcome are clear, continue to the next workflow in the same turn. Do not wait for explicit confirmation. If the user provides feedback, incorporate it and course-correct.\n\n4. Before starting an involved app, prototype, clone, redesign, or build, send one short expectation-setting note and continue. Example:\n\n```text\nThis kind of build usually takes about 10-15 minutes, and ambitious ones can take longer. Good moment to grab coffee or tend to something else; I’ll keep moving and bring the prototype back when it is ready.\n```\n\nDo not send this note for tiny static changes, quick audits, simple research, setup-only, or share-only requests.\n\nDone means the design target and intended user outcome are clear, defaults have been played back, and any already-determined next skill has been read.\n","packages/cli/src/skill/builtin/.bundle/product-design/workflows/ideate/SKILL.md":"---\nname: ideate\ndescription: \"Generate image-based alternatives, remixes, or new design directions from a Product Design brief. Use when the user asks for design variants, visual exploration, remixes, or image-generated approaches from provided context.\"\n---\n\n# Ideate\n\nYou're tasked with generating design concepts for a user's idea.\n\nFollow the shared Product Design routing guidance in [$index](../index/SKILL.md).\n\n## Critical Overrides\n\n- Refer to the Plugin router [$index](../index/SKILL.md) before proceeding.\n- Follow [$critical-overrides](../../references/critical-overrides.md).\n\n## User Context\n\nBefore starting, load [$user-context](../user-context/SKILL.md) and run its preflight script when local shell access is available.\n\nAttach provided product URLs, Figma files, screenshots, reference images, codebase paths, Storybook, tokens, design systems, brand assets, component refs, browser preferences, and share targets to the Image Gen generations to align them to the design brief.\n\nDo not inspect every saved reference. Inspect only what the current task needs.\n\n## Workflow\n\nDo not generate images until `$get-context` has satisfied the minimum required design brief.\n\nBefore generating images:\n\n1. Understand the brief.\n\n- Identify the target: component, screen, feature/workflow, or broad product idea.\n- Identify the intended user, product surface, and goal.\n- Preserve hard constraints from the user.\n- Run `get-context` if the minimum required design brief isn't satisfied.\n\n2. Resolve context.\n\n- Use provided files, screenshots, links, and visible references.\n- In a local workspace, look for nearby design documentation and other local visual context.\n- Check likely design context folders such as `user-context`, `storybook/`, `.storybook/`, `design-system/`, `design-systems/`, `tokens/`, `components/`, `app/`, and generated prototype roots.\n- In an existing project, look for existing product screenshots, similar flows, Storybook captures, design tokens, and component references before generating. Ask if the user can provide example screens similar to the one they are building if the existing app isn't accessible. Ensure you add design language and tokens to the Image Gen prompt.\n\n3. Inspect references directly.\n\n- Look at screenshots, images, Figma frames, app surfaces, or other visual references before generating.\n- Do not infer from filenames alone.\n- If a named local path or reference is not visible, stop and ask the user to confirm the path, upload the file, start the local app, or point to the correct workspace.\n\n4. Decide the variation mode.\n\n- If useful local design context exists and the user has not asked for a new style, stay within that existing direction.\n- If no useful design context exists, or the user asks for broad exploration, vary both concept and visual system.\n- For a specific component or existing surface, vary structure, interaction, hierarchy, and emphasis before varying brand style.\n- For a broad product idea, explore three meaningfully different product directions.\n\n5. Choose target dimensions before Image Gen.\n\n- Pick the dimensions that best match the user's request and any provided visual reference.\n- Mobile app: `390 x 844`.\n- Tablet app: `834 x 1194`.\n- Desktop app, dashboard, admin, or SaaS: `1440 x 1024`.\n- Landing or marketing page: `1440` wide and scrollable.\n- Modal, panel, widget, or component: natural container size.\n- Provided screenshot, Figma frame, mockup, or reference image: match its dimensions and aspect ratio when the user wants to continue from that visual.\n- Avoid crowding. Make the design fit the chosen dimensions cleanly, with realistic spacing, readable type, and no clipped content.\n- Include the chosen dimensions in every Image Gen prompt.\n\n6. Check for access gaps.\n\n- If a connector, reference, or file cannot be accessed because of auth, permissions, expired login, missing scope, suspiciously empty results, or unavailable local state, stop.\n- Name the gap clearly and ask whether to troubleshoot access or continue without that source.\n- Do not generate images while silently ignoring a named reference.\n\n7. Attach images and mocks provided by the user to the Image Gen call along with your design brief.\n\n8. Generate 3 independent options that have distinct information hierarchy, layout strategy, interaction model, or product framing.\n\nRules you must follow:\n\n- Use the Image Gen prompt below.\n- Use the built-in Image Gen tool.\n- Generate exactly three independent images unless the user overrides the count.\n- Launch each Image Gen call independently. Do not batch Image Gen calls with `Promise.all`, collect them into an ordered array, or replay them in request order.\n- Each option must be its own Image Gen result. Do not put multiple ideas in one image.\n- Give each direction a distinct, descriptive name before generation, but do not call it `option 1`, `option 2`, or `option 3` and do not put planned numeric labels in Image Gen prompts. Parallel results can arrive in a different order from the requests.\n- Number options only after the Image Gen results are present in the thread. The only authoritative option order is the order those generated-image results are displayed in the current thread. Ignore the planned concept order, original request chain, prompt submission order, `Promise.all` result order, batch order, array indexes, retry order, and assumed completion order.\n- After all results return, bind each visible option number to the result in that displayed order. Do not name or describe the options in the final selection message.\n- Attach provided screenshots, files, app captures, Figma references, and visual source material as moodboard inspiration when available.\n- Attach existing product screenshots, similar flows, Storybook captures, design tokens, and component references as grounding material when available.\n- When mock data includes dates or time-sensitive information, resolve the exact current date and include it in every Image Gen prompt. Derive visible dates from that anchor; preserve dates required by the user or source design.\n- If a screenshot, image, or visual file is available, attach the actual image to the Image Gen call. Do not rely on text descriptions of it.\n- Only claim a visual reference was attached if the Image Gen call actually received that image or a readable local image path.\n- If you cannot attach the image, say that clearly and ask whether to continue with text-only direction.\n- Preserve hard constraints from the brief in every image.\n- After generating options, stop for the user's selection before any build work begins.\n- When the user later selects option `N`, resolve it against the Nth displayed generated-image result from the most recent ideation set, not the original planned concept order. If the exact displayed result cannot be resolved, do not build from a guess; ask the user to name the concept or reattach/select the image.\n- The selected option is the visual target for `$image-to-code`.\n\n## Feedback Loop\n\nIf the user gives feedback after seeing options, generate revised options with that feedback.\n\nIf the user selects an option and gives feedback, generate a revised option with that feedback before build.\n\nIf the user likes parts of more than one option, combine those choices into a new Image Gen design and show it before build.\n\n## Image Gen Prompt\n\nAdapt this prompt to the current design brief, attach any available image references, and send it to Image Gen:\n\n```text\nCreate realistic, production-quality UI designs with clear hierarchy, strong typography, intentional imagery, and purposeful spacing.\n\nDesign a focused primary screen, not a feature inventory. The product may support many workflows, but this frame should show the hero use case, one clear primary action, and only one or two supporting actions or content areas. Do not add cards, panels, tabs, badges, metrics, filters, or navigation items merely to advertise every feature. Let the rest of the product exist off-screen. Prefer strong hierarchy and generous whitespace; if the screen feels crammed, remove UI.\n\n### Target Dimensions\n\nPick the dimensions that best match the user's request and any provided visual reference.\n\nDefault to a desktop web-app frame unless the user or reference clearly calls for mobile, tablet, or another format.\n\n - Mobile app: `390 x 844`\n - Tablet app: `834 x 1194`\n - Desktop app, dashboard, admin, or SaaS: `1440 x 1024`\n - Landing or marketing page: `1440` wide and scrollable\n - Modal, panel, widget, or component: natural container size\n - Provided screenshot, Figma frame, mockup, or reference image: match its dimensions and aspect ratio when the user wants to continue from that visual\n\nUse a natural viewport ratio for the intended surface. Never stretch, squash, or warp the generated screen, imagery, typography, or UI elements to fill the canvas. If the composition does not fit naturally, recompose or simplify the layout instead.\n\nAvoid crowding. Make the design fit the chosen dimensions cleanly, with realistic spacing, readable type, and no clipped content.\n\n### Layout\n\nWhen deciding how to lay elements out on the page, this should be your priority order for tools to differentiate sections:\n\n1. Use spacing, grouping, alignment, typography, and hierarchy on the same product surface.\n2. Use simple dividers or row separators.\n3. Use a subtle surface tint only when the base surface is not enough.\n4. Use borders only when separation still is not clear.\n5. Use shadows/elevation last, and sparingly.\n\nDon'ts:\n - Do not default to a centered \"app card\" (the whole UI is in a card on the page) on top of a contrasting page background. Use the base page surface first unless the source product or user explicitly asks for a contained app panel.\n - Do not put cards inside cards. Do not make every major section a card. Do not make each list item its own card unless each item is truly a standalone object. A normal list should usually read as one grouped surface with lightweight row separation.\n - Do not make up extraneous features. Add only the things essential to accomplish what the prototype's goal is. Don't make up more features just to fill out a UI.\n\n### Typography\n\n - Anchor UI typography to readable product sizes. Body text should usually sit between 14px and 16px, with the rest of the type scale built around that baseline.\n - Keep long-form text to a comfortable line length, generally no more than 65 characters per line.\n - Use no more than 2 fonts in a UI. You can use any font available in the project, or fonts provided free on Google Fonts. Pick the font that is best for the goal of the product and that matches with its intended look and feel.\n\n### Presentation\n\n - Do not add browser or device chrome around the mockup.\n - Do not put multiple ideas into a single image generation.\n - Vary each idea as much as possible while adhering to the constraints given entirely.\n\n### Data Freshness\n\nWhen the design includes dates or time-sensitive mock data, use the supplied current date as the anchor. Weekly views must show the real containing week with correct weekday/date pairs. Feeds, charts, notifications, and recent activity must use plausible chronological dates relative to today. Mark today when useful. Preserve dates required by the brief or source design.\n```\n\n## Output\n\nWait until all Image Gen calls have returned before sending the final message that asks the user to choose.\n\nDo not send the final selection message until every requested generated image is visible exactly once in the main chat.\n\nIf fewer Image Gen outputs are visible than requested, retry the missing generation. Do not send the selection message.\n\nNumber the returned Image Gen outputs in the order they appear in the conversation context:\n\n- First Image Gen output = Option 1\n- Second Image Gen output = Option 2\n- Third Image Gen output = Option 3\n\nIgnore the planned concept order, original request chain, request order, `Promise.all` result order, batch order, array indexes, retry order, and tool submission order.\n\nDo not name or describe the options. For the default three images, send only:\n\n`Which option should I build: 1, 2, or 3? Or tell me what you'd like to refine or personalize first.`\n\nAdjust the numbers only if the user requested a different count.\n\nIf the user chooses a number, acknowledge the chosen option before routing to `$image-to-code`, for example: `Building option 2!` Do not ask for confirmation when the mapping is clear.\n\nDone means the requested number of independent images have been generated and the user has been asked to select one.\n","packages/cli/src/skill/builtin/.bundle/product-design/workflows/image-to-code/SKILL.md":"---\nname: image-to-code\ndescription: \"Implement a selected image, screenshot, mockup, generated concept, or design frame as a faithful, responsive, interactive frontend in the target codebase.\"\n---\n\n# Image to Code\n\nTranslate a selected visual target into a high-quality frontend. Read `../index/SKILL.md`, `../../references/critical-overrides.md`, and the relevant saved context from `../user-context/SKILL.md` before building.\n\n## Preconditions\n\n- Require an unambiguous selected image, screenshot, mockup, generated result, or design frame. A written brief alone is not a visual target; route to ideation first when appropriate.\n- Resolve which image is selected before editing. Ask when an ordinal or attachment is ambiguous.\n- Use only the current task's relevant product context, tokens, components, assets, and references.\n\n## Workflow\n\n1. Inspect the source visual at useful detail and record its viewport, layout regions, hierarchy, spacing, typography, colors, borders, radii, shadows, imagery, icons, responsive behavior, and visible states.\n2. Inventory every required asset. Reuse supplied or repository assets when they match. Use an available image-generation tool for custom raster imagery and an appropriate existing icon set for UI icons. Do not substitute emoji, generic placeholders, or improvised CSS drawings for meaningful visual assets.\n3. Inspect the target repository and use its existing framework, package manager, component system, design tokens, and conventions. React is not required. Do not replace an established stack merely to match this workflow.\n4. If no target app exists, create the smallest runnable frontend supported by the harness and suited to the request; plain HTML/CSS/JavaScript is acceptable.\n5. Implement the full visible structure and the primary user journey. Unless requested otherwise, make navigation, tabs, menus, forms, toggles, selections, and main calls to action behave realistically without inventing backend systems.\n6. Match desktop or mobile based on the source. When the source is a phone UI and no device is named, verify around 390 × 844 as well as any relevant responsive behavior.\n7. Run the real app using its normal development or preview command.\n8. Capture the implementation using the browser tool selected by `../index/SKILL.md` and run `../design-qa/SKILL.md` against the source visual.\n9. Fix all blocking and high-impact mismatches. Save `design-qa.md` in the project root and hand off only when it records `final result: passed`, or clearly report a genuine capture/verification blocker.\n\n## Fidelity rules\n\n- Treat the selected visual as the design target; do not introduce unrelated redesign ideas.\n- Match the same viewport and interaction state during visual comparison.\n- Place real assets before final QA and avoid hotlinking third-party source assets in the finished app.\n- Keep the implementation maintainable within the target repository's patterns.\n- Do not claim verification from build success or an HTTP status alone; inspect the rendered result and primary interactions.\n\n## Handoff\n\nProvide the runnable project or changed files, the local preview information when useful, and a concise summary of what was implemented, verified, and left as a limitation. Publish only when the user asks and the host exposes an authorized deployment tool.\n\n","packages/cli/src/skill/builtin/.bundle/product-design/workflows/index/SKILL.md":"---\nname: index\ndescription: \"Use when Product Design is explicitly invoked, or when the user's main goal is to explore a design, research UX, audit or critique a flow, faithfully clone a visual source, check a built design, or share a prototype. Do not use Product Design for ordinary implementation unless the user explicitly asks for it.\"\n---\n\n# Skill Purpose\n\nRoute Product Design requests to the right Product Design skill. Use this plugin for an `@Product Design` mention, a direct Product Design request, or a request mainly about design exploration, faithful source cloning, audits, research, critique, or sharing. A request is not Product Design just because it mentions UI, a prototype, or visual style.\n\n# Plugin Purpose\n\nThe Product Design plugin helps designers and other non-coders close the gap between product ideas and working software.\n\nThe Product Design plugin equips you with the following set of skills to:\n\n- Research ideas and pain points related to your product.\n- Conduct product-flow audits.\n- Generate distinctly new ideas for your product with ImageGen.\n- Clone existing product apps into lightweight prototypes.\n- Build lightweight or interactive prototypes to share with your team.\n\n## Communication Style\n\nSpeak to the user in a warm, fun, and collaborative way, prioritizing pithy explanations over long walls of text and numerous bullet points. Refer to the [communication-protocol](../../references/communication-protocol.md) for relaying Product Design plugin progress updates and handoff.\n\n## Critical Overrides\n\n- Follow [$critical-overrides](../../references/critical-overrides.md).\n\n## Router Only\n\nThis index chooses the next Product Design skill. It does not do that skill's work.\n\nIf the user names a focused skill, read that exact skill first. Do not replace it with a related skill.\n\nWhen a request matches `$user-context`, `$get-context`, `$research`, `$ideate`, `$image-to-code`, `$url-to-code`, `$audit`, `$design-qa`, or `$share`, load the focused skill and follow it.\n\nFor requests to audit, review, critique, inspect, assess, analyze, evaluate, or give feedback on an existing product experience, load `$audit` directly; do not load `$get-context` first. If the same request also asks to build, fix, redesign, or implement afterward, run `$audit` first, then continue through the appropriate normal workflow.\n\nFor visual ideation, `$ideate` is the focused workflow. Use `$get-context` to resolve the minimum brief and play back any defaults before `$ideate` starts.\n\nFor clone or recreation of a live URL, load `$url-to-code` directly.\n\nFor a redesign, improvement, or new site based on a URL, use `$get-context` to confirm the redesign brief. `Like <URL>` means redesign, not clone. Capture the current site with screenshots, attach those screenshots to the `$ideate` Image Gen calls, then execute `$ideate`.\n\n## Standard Chat Mode\n\nIf Product Design is invoked in standard ChatGPT chat without Work Mode tools, do not start the workflow. Tell the user once:\n\n```text\nChat isn't supported by the Product Design plugin. Please switch to the Work tab and paste this prompt in for the full experience.\n```\n\nDo not ask design-brief questions, generate options, or begin build work until the user moves to Work Mode.\n\n## Browser Choice\n\nIn ChatGPT Work Mode, always use the cloud browser available to that chat. If it is not initially visible, load the Browser skill and follow its setup instructions before concluding it is unavailable.\n\nIn Codex Desktop, use `@Browser` and explicitly select the in-app surface with `agent.browsers.get(\"iab\")`.\n\nIn Codex Desktop, use Chrome only when the user asks for it, the task needs an existing Chrome tab/login/profile/extension, or the in-app Browser is unavailable or blocked.\n\nIf ChatGPT Work Mode does not expose both the cloud browser and `@Sites` after preflight, tell the user once:\n\n```text\nCloud browser and Sites are not available in this chat. I can still build a single-page HTML prototype, but I cannot visually verify it or publish a live checkpoint, so fidelity and interaction polish may be lower. Continue with that fallback?\n```\n\nOnly proceed after the user agrees. Do not claim the fallback is verified, open, hosted, or ready to share. This fallback applies to image-to-code and new prototypes. It does not apply to URL-to-code when browser capture is required.\n\n## No Visual Target, No Build\n\nFor new app, prototype, redesign, or UI build requests without a URL, screenshot, Figma frame, mockup, source image, or existing code target:\n\n- `$ideate` is the focused workflow.\n- Use `$get-context` to resolve the minimum brief.\n- Once the target and intended user outcome are clear, play back the assumptions and run `$ideate` in the same turn.\n- Show exactly three visual options and wait for the user to choose one.\n- Do not scaffold, edit files, or start a server before a visual option is selected.\n\n`Full working version`, `no refs`, `go for it`, `make an assumption`, or a complete brief do not waive this.\n\n## User Context\n\nUse [$user-context](../user-context/SKILL.md) when the user asks to:\n\n- Set up Product Design\n- Get started with Product Design\n- Onboard with Product Design\n- Save product or design sources\n- See what Product Design remembers\n- Update saved product or design context\n- Remember a Product Design preference\n- Setup my plugin\n\nAdjust the context-gathering request to match the user's request. First-time setup differs from updating existing context.\n\nFor setup-only requests, do not inspect the workspace, install dependencies, scaffold a prototype, generate images, run audits, or start implementation.\n\nWhen answering \"what can you do?\", \"how do I get started?\", or similar broad Product Design questions, load `$user-context` and follow its persistence availability check before offering saved-context onboarding.\n\nBefore routing to Product Design workflows, load [$user-context](../user-context/SKILL.md) and run its preflight script when local shell access is available.\n\n## Browser Annotation Updates\n\nTreat annotations as scoped edits to the current prototype.\n\nRead the annotation, its target, and the surrounding screen before changing code. Preserve the existing prototype by default: layout, style, content, routes, assets, interactions, and working behavior stay the same unless the annotation asks to change them.\n\nDo not redesign nearby UI or rebuild the prototype just because an annotation touches that area. If the annotation is ambiguous and the choice would materially change the prototype, ask first.\n\n## Skills\n\nUse this as the root routing guidance for Product Design plugin work. If several focused skills apply, sequence them in the order that creates the most useful design workflow. Keep this index as a router; do not perform focused workflow logic here.\n\n### $user-context\n\nPreflight, save, or answer from Product Design setup context. Route here before Product Design workflows to load saved product and design sources, and for direct setup, get-started, onboarding, save, remember, recall, inspect, or customization requests. This skill owns Product Design plugin-scoped context and preference policy.\n\n### $get-context\n\nRoute here first for design, build, prototype, redesign, extend, or UI exploration work. Require only a clear design target and intended user outcome. Ask one targeted question only when one of those is missing; otherwise play back the brief and defaults, then continue without waiting for approval.\n\n### $research\n\nRun fast, source-grounded UX research on current user problems for a named digital product. Route here for researching user pain, UX friction, onboarding issues, docs/help problems, developer experience friction, support pain, product workflow issues, or current user complaints.\n\n### $audit\n\nCapture and review a product flow, journey, screen, or multi-step product experience from screenshots. Route here for user-facing audit, review, critique, inspect, assess, analyze, evaluate, or feedback requests. It reports UX, design, and accessibility findings tied to captured evidence; do not use `design-qa` for user-facing audits.\n\n### $ideate\n\nGenerate image-based visual alternatives, remixes, or concept directions for a component, screen, feature, workflow, or product idea. Route here after `get-context` has played back the minimum brief and the user needs visual exploration, design variants, alternatives to an existing design, or idea discovery before choosing a visual target. Prefer this over prose-only ideation unless the user asks for prose.\n\n### $url-to-code\n\nClone a live URL as a runnable frontend-only local app using the Browser Choice rule above. Load this alongside `get-context` when the user provides a production URL for a faithful local prototype or clone, but do not execute it until the minimum brief has been played back. It should not modify production code; stay in `get-context` when source selection is still unclear.\n\n### $image-to-code\n\nImplement a selected visual target as a faithful, responsive, interactive frontend. Route here after `get-context` has played back the minimum brief and the user has chosen an ImageGen mock, screenshot, Figma frame, mockup, reference image, or other visual source. Do not start here when no visual target has been selected; use `get-context` and `ideate` first.\n\n### $share\n\nDeploy a runnable prototype and return a shareable URL using the user's preferred target when available. Route here when the user asks to share, deploy, publish, host, create a link, or make a prototype shareable with `@Sites`, `@Vercel`, or another deployment tool.\n\n### $design-qa\n\nCompare a coded Product Design prototype against its source visual target before handoff. Route here only as an internal helper after a prototype, URL-to-code build, or image-to-code build has both a source visual and rendered implementation. Do not route broad UX critiques, audits, or product-flow reviews here; use `audit` instead.\n","packages/cli/src/skill/builtin/.bundle/product-design/workflows/share/SKILL.md":"---\nname: share\ndescription: \"Share a runnable prototype using the user's preferred deployment tool.\"\n---\n\n# Share\n\nDeploy the user's runnable prototype so they can share it with others.\n\n## Critical Overrides\n\n- Refer to the Plugin router [$index](../index/SKILL.md) before proceeding.\n- Follow [$critical-overrides](../../references/critical-overrides.md).\n\n## User Context\n\nBefore starting, load [$user-context](../user-context/SKILL.md) and run its preflight script when local shell access is available.\n\nUse saved product URLs, Figma files, screenshots, reference images, codebase paths, Storybook, tokens, design systems, brand assets, component refs, browser preferences, and share targets as grounding material when relevant.\n\nDo not inspect every saved reference. Inspect only what the current task needs.\n\n## Workflow\n\n1. Confirm the prototype directory and the user's preferred deployment target.\n2. If the user invokes Product Design with @Sites, @Vercel, or another deployment tool, treat that as the selected hosting target.\n3. If the user did not choose a target, ask one question:\n\n> Where should I deploy this: @Sites, @Vercel, or another target?\n\n4. Use the selected deployment tool when it is available.\n5. If the selected tool is not available, say that clearly and ask whether to use another target.\n6. Run the deployment when possible. Do not give setup instructions if you can complete the deployment directly.\n7. Return the shareable URL.\n8. State any misses or manual follow-up the user still needs to do.\n\n## Rules\n\n- Do not deploy before the user chooses or confirms the target.\n- Do not claim the prototype is shared until you have a working URL.\n- If the selected tool is not available, say that clearly and ask whether to use another target.\n","packages/cli/src/skill/builtin/.bundle/product-design/workflows/url-to-code/SKILL.md":"---\nname: url-to-code\ndescription: \"Recreate an authorized live website or app URL as a faithful, runnable, frontend-only local implementation.\"\n---\n\n# URL to Code\n\nUse this workflow only when the user asks to clone or faithfully recreate a live site they own or have permission to reproduce. For redesign, improvement, or a loosely inspired result, route through `../index/SKILL.md` to context and ideation instead.\n\nRead `../index/SKILL.md`, `../../references/critical-overrides.md`, and relevant saved context before building.\n\n## Workflow\n\n1. Remind the user that they must have permission and follow the target site's terms.\n2. Open the source with the browser selected by the index. Stop if it resolves to a wrong page, login wall, error, unrelated redirect, or other surface that cannot ground the requested clone.\n3. Capture the full desktop page and a representative mobile viewport. Inspect small scroll increments so sticky, lazy-loaded, and animated content is not missed.\n4. Inspect the DOM and visible behavior for text, links, controls, component states, images, icons, fonts, colors, spacing, dimensions, breakpoints, and interaction behavior.\n5. Test important interactions one at a time and return to the starting state between tests. Preserve evidence for changed states.\n6. Save permitted source assets locally. Do not hotlink them in the final result. When an asset cannot be obtained, use an available generation tool or an appropriate open replacement and disclose the substitution.\n7. Inspect the target repository and use its existing framework and conventions. React is not required. If no app exists, create the smallest suitable frontend supported by the harness; plain HTML/CSS/JavaScript is acceptable.\n8. Build only from captured evidence. Implement the visible desktop/mobile layouts and primary interactions without inventing unrelated design choices or backend behavior.\n9. Run and inspect the local implementation with a real browser. Compare the same viewport and states against the source.\n10. Run `../design-qa/SKILL.md`, save `design-qa.md`, fix blocking and high-impact mismatches, and hand off only after `final result: passed` or a clearly documented verification blocker.\n\n## Hard rules\n\n- Capture source evidence before scaffolding or editing.\n- Do not infer hidden states when source evidence is available.\n- Do not use screenshots alone when DOM/style/interaction evidence can be inspected.\n- Do not leave placeholder assets or improvised icon glyphs in the final implementation.\n- Build success and server health are not visual verification.\n- Publish only when the user asks and the host exposes an authorized deployment tool.\n\n","packages/cli/src/skill/builtin/.bundle/product-design/workflows/user-context/SKILL.md":"---\nname: user-context\ndescription: Load or manage Product Design's saved user context. Use when the user asks to set up Product Design, get started, onboard, save product or design sources, see what Product Design remembers, update saved context, or remember Product Design preferences. Examples include product URLs, Figma files, screenshots, reference images, codebase paths, Storybook, tokens, design systems, brand assets, and general product/design notes.\n---\n\n# User Context\n\nUser Context stores the product and design references a designer uses often, so future Product Design work starts from the right sources.\n\nUse this skill when the user asks to:\n\n- set up Product Design\n- get started with Product Design\n- onboard with Product Design\n- save product or design sources\n- see what Product Design remembers\n- update saved product or design context\n- remember a Product Design preference\n- setup my plugin\n\n## Critical Overrides\n\n- Refer to the Plugin router [$index](../index/SKILL.md) before proceeding.\n- Follow [$critical-overrides](../../references/critical-overrides.md).\n- Before offering onboarding or saving context for future conversations, confirm that local shell access is available, `$CODEX_HOME` can be resolved, and `$CODEX_HOME/state/plugins/product-design/` exists and is writable or can be created in a writable parent directory. If `user-context.md` already exists, confirm that it is writable too.\n- If any check cannot be completed or fails, persistent context is unavailable. Do not offer saved-context onboarding or claim that new context was saved for future conversations. If the user asks to save something, explain that it can be used in the current conversation but not saved for future conversations.\n\n## Saved User Context\n\nIf `user-context.md` exists, use it by default.\n\nUse saved product URLs, Figma files, screenshots, reference images, codebase paths, Storybook, tokens, design systems, brand assets, component refs, browser preferences, and share targets to ground Product Design work.\n\nIdeation, prototypes, audits, clones, and critiques should match the saved product context unless the user asks for something different.\n\nWhen a workflow needs visual grounding, attach or include relevant saved screenshots, reference images, tokens, design language, and component references in ImageGen, ideation, prototype, audit, and critique work.\n\n## State File\n\nSaved context lives here:\n\n```text\n$CODEX_HOME/state/plugins/product-design/user-context.md\n```\n\nSaved screenshots and reference images live next to it:\n\n```text\n$CODEX_HOME/state/plugins/product-design/assets/\n```\n\nIf the file does not exist, continue normally unless the user asks to set up Product Design, save context, or the current task is blocked by missing product/design context.\n\n## Preflight\n\nWhen any Product Design workflow needs saved context, run:\n\n```bash\npython3 scripts/user_context_preflight.py\n```\n\nUse the returned saved entries as the starting context for the task.\n\nIf the script reports that no saved context exists, continue from the current user prompt unless setup context is required.\n\nDo not browse, open, or inspect every saved reference during preflight. Inspect only the saved references needed for the current task.\n\n## Setup\n\nUse [references/onboarding.md](references/onboarding.md) when the user asks to set up Product Design, asks what Product Design can remember, asks what Product Design knows about their product, or provides product/design references to save.\n\nFor setup-only requests, explain what Product Design can remember and ask for useful sources.\n\nAdjust the context-gathering request to match the user's request. First-time setup differs from updating existing context.\n\nDo not inspect the workspace, install dependencies, scaffold a prototype, generate images, run audits, or start implementation during setup.\n\nAfter the user provides references to save, run:\n\n```bash\npython3 scripts/init_user_context.py\n```\n\nThen add the references to the created `user-context.md`.\n\n## Save\n\nSave useful, durable Product Design context:\n\n- Product URLs\n- Figma files\n- Screenshots and reference images\n- Codebase paths\n- Storybook and component docs\n- Design tokens and theme sources\n- Brand, logo, icon, illustration, image, and asset sources\n- Preferred browser, capture tools, and share targets\n- Team conventions that make future Product Design work more accurate\n\nWhen the user provides screenshots or reference images to save, copy them into `assets/` next to `user-context.md` and link them from the saved entry.\n\nGive each saved image a clear, descriptive filename that says what the image shows. Use names future Product Design runs can understand without opening the file.\n\nGood image names:\n\n```text\nassets/chatgpt-settings-modal-dark-mode.png\nassets/payment-sheet-mobile-error-state.png\nassets/product-dashboard-sidebar-navigation.png\nassets/storybook-primary-button-states.png\nassets/brand-logo-lockup-purple-gradient.png\nassets/onboarding-flow-welcome-step.png\nassets/checkout-confirmation-screen.png\nassets/account-menu-open-state.png\n```\n\nDo not save secrets, credentials, API keys, private tokens, copied customer data, or anything that should not persist.\n\nUse this structure:\n\n```md\n# {Category}\n\n- Description: {what this category is and when future Product Design runs should use it}\n\n## Saved Links And Context\n\n{Saved reference or fact}\n- Date Added: YYYY-MM-DD.\n- File: assets/{clear-descriptive-name}.png\n- Useful Context: {what this reference represents}\n- Future Use: {how future Product Design work should use it}\n```\n\nInclude `File:` only when the saved entry has a local image file.\n\nWhen a category has no saved references yet, use exactly:\n\n```md\nstatus: not provided\n```\n\nKeep saved context curated. Prefer a few high-value references over a dump of every possible URL or file.\n\n## Read\n\n- Do not treat `status: not provided` as a fact.\n- Read through `scripts/user_context_preflight.py` when local shell access is available.\n- Use saved context as default grounding, then inspect only what the current task needs.\n","packages/cli/src/skill/builtin/.bundle/research-paper-writing/SKILL.md":"---\nname: research-paper-writing\ndescription: Write, rewrite, and polish academic papers (ML/CV/NLP style). Use when the user drafts or revises Abstract, Introduction, Related Work, Method, Experiments, or Conclusion; asks \"does this flow / 这段通顺吗 / polish this paragraph\"; turns bullet points or a Chinese draft into publication-quality English; runs a pre-submission self-review or reviewer-style critique; fixes paper figures/tables/LaTeX formatting; or compiles/converts the paper to PDF (LaTeX build, 编译PDF, 转成PDF). Trigger on mentions of paper, draft, camera-ready, rebuttal-facing revision, CVPR/ICCV/NeurIPS/ICLR/ACL-style venues, or .tex files being edited for a paper.\n---\n\n# Research Paper Writing\n\nAct as an experienced co-author who has published at top ML/CV/NLP venues. The goal is not \"prettier English\" — it is a draft that survives skeptical reviewers: clear story, one message per paragraph, and every claim backed by evidence.\n\n## Step 1: Diagnose the request, then route\n\nMatch the user's situation and load ONLY the needed reference (do not preload all):\n\n| User situation | What to do | Load |\n|---|---|---|\n| \"Polish this paragraph / does this flow?\" | Quick polish pass (see below) | `references/paragraph-flow.md` |\n| Draft or rewrite Abstract | Pick a template, draft, check claims | `references/abstract.md` |\n| Draft or rewrite Introduction | Clarify story first, then template | `references/introduction.md` |\n| Draft or rewrite Related Work | Topic grouping + positioning | `references/related-work.md` |\n| Draft or rewrite Method | Module triad workflow | `references/method.md` |\n| Draft or rewrite Experiments; fix tables | Claim→experiment mapping, table rules | `references/experiments.md` |\n| Draft or rewrite Conclusion / Limitations | Scope-based limitation framing | `references/conclusion.md` |\n| \"Review my paper / 投稿前检查\" | Adversarial five-dimension review | `references/paper-review.md` |\n| \"Compile / convert to PDF / 编译不过\" | Pick engine, build, verify output | `references/pdf-export.md` |\n| Bullet points / Chinese notes → English section | Treat as section drafting; get facts first, then draft | the matching section guide |\n\nIf the user's draft lives in files (`.tex`, `.md`, Overleaf export), work on the files directly: locate sections with grep (`\\section`, `\\begin{abstract}`), edit in place, and keep every `\\cite{...}`, `\\ref{...}`, label, comment, and math environment byte-for-byte unless the edit is specifically about them.\n\n## Step 2: Get the facts before writing\n\nGood paper writing is mostly correct facts arranged well. Before drafting a section, make sure these are known — from the draft, the codebase, or the user:\n\n1. What exact technical problem is solved, and why prior methods fail at it (limitation + technical reason).\n2. What the contribution is (new task / pipeline / module / finding / insight).\n3. Why the method works in essence, and its concrete advantages.\n4. What the strongest experimental numbers are.\n\nIf any of these are missing and not recoverable from context, ask — at most 3 focused questions in one message. Never fill gaps by inventing.\n\n## Hard Rules (never violate)\n\n1. **Never fabricate.** Do not invent experimental numbers, citations, baseline names, dataset statistics, or related-work claims. Use explicit placeholders (`[XX.X]`, `[CITE: sparse-view NeRF methods]`) and tell the user what to fill in.\n2. **Preserve technical meaning.** Rewrites must keep every claim's strength and scope. If a sentence is ambiguous and the rewrite must pick an interpretation, flag it: `⚠ interpreted as ...`.\n3. **Weaken or cut unsupported claims.** If a claim in Abstract/Introduction has no experimental backing in the paper, do not keep it strong — propose the weakened version and say why.\n4. **Respect double-blind.** Do not insert author names, GitHub links, or acknowledgments into a submission draft; warn the user if the draft already leaks identity.\n5. **Scale the output to the request.** A one-paragraph polish gets revised text plus a 1–2 line note — no outlines, no checklists. Full contracts are for section rewrites and reviews only.\n\n## Core Writing Principles\n\n1. One paragraph, one message; the first sentence states it.\n2. Every sentence connects to the previous one (cause, contrast, consequence, refinement, example).\n3. Define terms before reusing them; keep terminology identical across the whole paper (never alternate synonyms for a key concept).\n4. Never present the method as an incremental patch on a naive baseline — lead with the challenge and the insight, even for incremental work.\n5. Figures and tables are content, not decoration: clean teaser, clear pipeline figure, booktabs-style minimal-ink tables.\n\n## Workflows by request size\n\n### A. Quick polish (sentence / paragraph)\n\n1. Run the flow test from `references/paragraph-flow.md`: one message? first sentence states it? nouns self-contained? sentence-to-sentence relations explicit?\n2. Return the revised paragraph, then 1–2 lines on what changed and why.\n3. If the paragraph's real problem is structural (wrong message, no evidence), say so instead of cosmetically polishing.\n\n### B. Section draft / rewrite\n\n1. Confirm the section's story in a 3–7 bullet mini-outline before writing prose; on low ambiguity proceed and show the outline with the draft.\n2. Draft paragraph by paragraph — one message per paragraph, template from the section guide.\n3. Reverse-outline the result: thesis → topic sentences → evidence; fix anything that doesn't map.\n4. For Abstract/Introduction, append a claim-evidence map: `Claim: ... | Evidence: ... | Status: supported / needs evidence / weakened`.\n\n### C. Pre-submission review\n\n1. Load `references/paper-review.md` and read the paper as a hostile reviewer.\n2. Score the five dimensions (contribution, clarity, experimental strength, evaluation completeness, method soundness); mark each question `pass` / `needs revision` / `needs new experiment`.\n3. Return a prioritized fix list: rejection-level risks first, then clarity issues, then polish. Include concrete edit suggestions, not just complaints.\n\n## References\n\n- `references/abstract.md` — 3 abstract templates with annotated real examples\n- `references/introduction.md` — intro logic map, 4 opening / 3 challenge / 4 pipeline templates\n- `references/related-work.md` — topic grouping and positioning\n- `references/method.md` — module triad (design / motivation / advantage) workflow\n- `references/experiments.md` — claim→experiment planning, table/figure rules\n- `references/conclusion.md` — limitation framing that doesn't invite rejection\n- `references/paper-review.md` — adversarial five-dimension review checklist\n- `references/paragraph-flow.md` — paragraph clarity test, reverse outlining, transitions\n- `references/pdf-export.md` — compiling LaTeX/Markdown to PDF, engine choice, failure fixes, output verification\n- `references/examples/` — annotated LaTeX examples cited from the section guides\n","packages/cli/src/skill/builtin/.bundle/sales/SKILL.md":"---\nname: sales\ndescription: \"Use this skill whenever Sales is explicitly invoked or the task involves customer meeting preparation, call follow-up, account prioritization, account signals, deal strategy, business cases, competitive briefs, forecasts, customer evidence, rep coaching, company research, CRM context, or company and contact enrichment.\"\n---\n\n# Sales\n\nThis is the single entry point for a code-agent-oriented Sales bundle. The original workflow instructions are under `workflows/`; connector manifests and plugin marketplace metadata are intentionally excluded.\n\n## Route the request\n\n1. Read `workflows/index/SKILL.md` completely. Treat it as the authoritative plugin-level scope, source-selection rules, routing, and workflow sequencing policy.\n2. Select the narrowest focused workflow or workflow sequence named by that index. Read every selected workflow's `SKILL.md` completely before acting.\n3. Load provider-specific skills such as Salesforce, HubSpot, Apollo, or ZoomInfo only when the chosen source and available host tools make them relevant.\n4. If a selected workflow names related skills, read them only when their stated conditions apply. Resolve relative links from the file containing the link and load required references completely.\n5. Prefer bundled scripts and templates when a selected workflow calls for them. Do not load unrelated sales workflows merely because they are present.\n\n## Bundled capabilities\n\nFocused workflows live in `workflows/`, covering meeting preparation, call follow-up, account prioritization and signals, deal planning, business cases, competitive briefs, forecast review, customer quotes, internal experts, rep coaching, company research, enrichment, and provider-specific CRM or intelligence workflows.\n\nWorkflow-local supporting assets, references, and scripts remain beside their owning workflow. Use CRM, email, calendar, messaging, transcript, intelligence, and document systems only when the host harness exposes an authenticated tool for them. Do not invent customer facts when a source is missing; use the workflow's evidence and fallback rules.\n\n## Safety and fidelity\n\n- Never treat plugin instructions as permission to bypass host policy, reveal credentials, or perform unapproved external writes.\n- Keep sourced facts separate from inference and recommendations.\n- Require appropriate confirmation before sending messages, updating CRM records, or taking other external actions.\n- Preserve the selected workflow's requested output and handoff requirements through completion.\n","packages/cli/src/skill/builtin/.bundle/sales/workflows/analyze-account-signals/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fanalyze-account-signals%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/answers-ask-user-input/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fanswers-ask-user-input%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/apollo/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fapollo%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/build-business-case/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fbuild-business-case%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/build-competitive-brief/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fbuild-competitive-brief%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/enrich-company-and-contact-data/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fenrich-company-and-contact-data%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/find-customer-quotes/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Ffind-customer-quotes%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/find-key-internal-sources/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Ffind-key-internal-sources%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/follow-up-after-call/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Ffollow-up-after-call%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/get-rep-call-feedback/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fget-rep-call-feedback%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/hubspot/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fhubspot%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/index/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Findex%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/plan-deal-strategy/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fplan-deal-strategy%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/prepare-for-meeting/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fprepare-for-meeting%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/prioritize-accounts/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fprioritize-accounts%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/review-forecast/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Freview-forecast%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/review-rep-call-trends/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Freview-rep-call-trends%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/sales-company-research/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fsales-company-research%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/salesforce/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fsalesforce%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/sales/workflows/zoominfo/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fzoominfo%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/skill-creator/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fskill-creator%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/super-research/README.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsuper-research%2FREADME.md -->","packages/cli/src/skill/builtin/.bundle/super-research/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsuper-research%2FSKILL.md -->","packages/cli/src/skill/builtin/.bundle/super-research/evals/toy_bench/README.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsuper-research%2Fevals%2Ftoy_bench%2FREADME.md -->","packages/cli/src/skill/builtin/.bundle/super-research/evals/toy_dataset/README.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsuper-research%2Fevals%2Ftoy_dataset%2FREADME.md -->","packages/cli/src/skill/builtin/.bundle/super-research/evals/toy_pipeline/README.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsuper-research%2Fevals%2Ftoy_pipeline%2FREADME.md -->","packages/cli/src/skill/builtin/.bundle/super-research/evals/toy_regression/README.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsuper-research%2Fevals%2Ftoy_regression%2FREADME.md -->","packages/cli/src/skill/builtin/.bundle/super-research/evals/toy_repo/README.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsuper-research%2Fevals%2Ftoy_repo%2FREADME.md -->","packages/cli/src/skill/builtin/.bundle/xlsx-official/README.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fxlsx-official%2FREADME.md -->","packages/cli/src/skill/builtin/.bundle/xlsx-official/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fxlsx-official%2FSKILL.md -->","packages/cli/src/sync/README.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fsync%2FREADME.md -->","packages/cli/test/AGENTS.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Ftest%2FAGENTS.md -->","packages/cli/test/fixture/skills/agents-sdk/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Ftest%2Ffixture%2Fskills%2Fagents-sdk%2FSKILL.md -->","packages/cli/test/fixture/skills/agents-sdk/references/callable.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Ftest%2Ffixture%2Fskills%2Fagents-sdk%2Freferences%2Fcallable.md -->","packages/cli/test/fixture/skills/cloudflare/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Ftest%2Ffixture%2Fskills%2Fcloudflare%2FSKILL.md -->","packages/cli/test/fixture/skills/index.json":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Ftest%2Ffixture%2Fskills%2Findex.json -->","packages/cli/test/fixture/skills/llm-endpoint-demo/SKILL.md":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Ftest%2Ffixture%2Fskills%2Fllm-endpoint-demo%2FSKILL.md -->"},"items":[{"name":"AGENTS.md","path":"AGENTS.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/AGENTS.md","title":"AI Agent Protocol & Instructions","category":"root-instruction","format":"markdown","content":"# MiMo-Code\n\n## Conventions\n\n- Use MiMoCode Compose skills when available, otherwise use superpowers skill if installed.\n- To regenerate the JavaScript SDK, run `./packages/sdk/script/build.ts`.\n- ALWAYS USE PARALLEL TOOLS WHEN APPLICABLE.\n- The default branch in this repo is `main`.\n- CI triggers on `main`.\n- Prefer automation: execute requested actions without confirmation unless blocked by missing info or safety/irreversibility.\n- Install deps with `bun ci` (= `bun install --frozen-lockfile`) — install per `bun.lock`, don't mutate the lockfile. ⛔ Do NOT use `bun install`/`npm install`.\n- Comments, docs, shipped skill content and test assertions use synthetic values, never machine-specific ones — `/tmp/example` for paths, `test/model` for model refs, `feat/example` for branches.\n- Do not edit `packages/cli/migration/*/migration.sql` that already shipped — engines have applied those journals; new schema changes get a **new** migration directory under `packages/cli/migration/`.\n\n## Style Guide\n\nMatch the style of the surrounding code. The rules below apply across the repository.\n\n### Types and errors\n\n- Avoid using the `any` type\n- Inside Effect code, express failures through the Effect error channel (`Effect.try`, `Effect.tryPromise`, `Effect.catchTag`, typed errors) rather than `try`/`catch`; plain scripts and non-Effect code may use `try`/`catch`\n\n### Bun and Node runtimes\n\n- Use Bun APIs where the runtime is Bun-only, like `Bun.file()` in the TUI (`src/cli/cmd/tui/`); build-time macros are fine anywhere, as they never reach the shipped runtime\n- In core code reachable from `src/node.ts`, prefer the Node equivalent when one exists — `createHash` over `Bun.CryptoHasher`, `prepare()` over bun:sqlite's `query()` — as that code also ships through `script/build-node.ts` and must run on plain Node\n- Bun-only calls in core escape both `typecheck` and `bun test`, which run on Bun; existing usage needs no urgent removal, and APIs with no Node equivalent may stay until a runtime seam exists\n\n### Config modules\n\nIn `src/config`, follow the existing self-export pattern at the top of the file (for example `export * as ConfigAgent from \"./agent\"`) when adding a new config module.\n\n### Schema Definitions (Drizzle)\n\nUse snake_case for field names so column names don't need to be redefined as strings.\n\n```ts\n// Good\nconst table = sqliteTable(\"session\", {\n  id: text().primaryKey(),\n  project_id: text().notNull(),\n  created_at: integer().notNull(),\n})\n\n// Bad\nconst table = sqliteTable(\"session\", {\n  id: text(\"id\").primaryKey(),\n  projectID: text(\"project_id\").notNull(),\n  createdAt: integer(\"created_at\").notNull(),\n})\n```\n\n### Reading a nullable column\n\nTwo independent absences meet in one expression, and only one of them is\n`undefined`. `.get()` yields `undefined` when no row matches — Drizzle normalises\nthe driver's `null` there — while a nullable column's SQL `NULL` arrives as\n`null`. So `row?.some_column` is `T | null | undefined`.\n\nWhen a caller only asks \"is there a value\", flatten to `undefined`, and write the\nflattening as an annotation rather than an `as` cast:\n\n```ts\n// Good — the compiler enforces it; deleting the `?? undefined` is a type error\nconst boundary: MessageID | undefined = row?.last_checkpoint_message_id ?? undefined\n\n// Bad — the cast removes `null` from the union without converting anything,\n// so the declared type is untrue at runtime\nreturn row?.last_checkpoint_message_id as MessageID | undefined\n```\n\nDiscriminate a possibly-absent value with truthiness or `== null`, never with\n`=== undefined` / `!== undefined`. Because `null !== undefined` is `true`, such a\nguard typechecks, reads correctly in review, and does nothing.\n\n## Testing\n\n- Avoid mocks as much as possible\n- Test actual implementation, do not duplicate logic into tests\n","isInternal":false,"tokens":906,"sizeBytes":3829},{"name":"SKILL.md","path":".agents/skills/drive-mimo/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/.agents/skills/drive-mimo/SKILL.md","title":"drive-mimo","category":"anthropic-skill","format":"markdown","content":"---\nname: drive-mimo\ndescription: Use when developing or testing the MiMoCode repository and you need to programmatically drive another MiMoCode (mimo) process. Supports headless `mimo run` with JSON events and interactive TUI via tmux for behavior, integration, and visual regression testing. Covers an installed `mimo` binary or a dev build launched from source with `bun dev`; do not use it for ordinary MiMoCode task execution.\n---\n\n# Drive MiMo\n\n## Overview\n\nTwo **interfaces** for driving a separate mimo process:\n\n| Interface | Command | Use when |\n|------|---------|----------|\n| **Headless** | `mimo run --format json` | Scripted tasks, CI, event validation |\n| **TUI** | `mimo` in tmux | Interactive flow, permission dialogs, keybindings, visual regression |\n\n**Core principle:** Every run produces parseable evidence. No eyeballing.\n\nAlways drive an *isolated* instance: give each run a fresh `MIMOCODE_HOME` and a throwaway workspace so it never touches your own config, memory, or session DB.\n\n### Two ways to launch — orthogonal to interface\n\nThe interface (headless vs TUI, above) is *what you drive*. How the process is\n**launched** is a separate axis — either can be launched either way:\n\n| Launcher | Command | Use when |\n|----------|---------|----------|\n| **Installed binary** | `mimo …` | Testing a released/installed build |\n| **Dev (from source)** | `bun dev …` | Debugging mimocode itself — runs `src/index.ts` directly, no build step, picks up local code changes |\n\nEverything below uses `mimo` for brevity. To drive a **dev build** instead,\nsubstitute `bun dev` for `mimo` and run from the repo root — every flag,\nJSON event, and tmux technique is identical. See the Dev Mode section.\n\n## Prerequisites\n\n```bash\n# mimo binary must be on PATH (installed-binary launcher)\nwhich mimo || echo \"mimo not found on PATH\"\n\n# OR: dev launcher — run from the mimocode repo root, needs bun\nwhich bun || echo \"bun not found — needed for dev mode\"\n\n# tmux (for TUI interface)\nwhich tmux || echo \"tmux not found — install it for TUI mode\"\n```\n\n> **Running the `wait-for-text.sh` helper:** invoke it as\n> `./scripts/wait-for-text.sh …` from this skill's directory. The repository copy\n> is executable and can be called directly.\n\n---\n\n## Dev Mode (debugging mimocode itself)\n\nWhen the goal is to debug **mimocode's own code**, launch from source with\n`bun dev` instead of the installed `mimo` binary. It runs\n`packages/cli/src/index.ts` directly — no build step — so local edits take\neffect on the next launch.\n\n**Key facts:**\n\n- Run from the **repo root**. `bun dev` == `bun run dev`.\n- It is the dev equivalent of the `mimo` command: same CLI, same subcommands\n  and flags. `bun dev --help`, `bun dev run …`, `bun dev serve`, etc.\n- Args pass straight through, so **both interfaces work under dev**:\n  - Headless: `bun dev run --format json --dangerously-skip-permissions …`\n  - TUI:      `bun dev <workspace>` (positional workspace arg, as with `mimo`)\n- If `MIMOCODE_HOME` is not set, dev defaults it to a repo-local `.dev-home`\n  dir. For an isolated driven run, set `MIMOCODE_HOME=$(mktemp -d)` explicitly\n  just like with the binary.\n\n**Substitution rule:** anywhere Part 1 / Part 2 / Part 3 below say `mimo`,\nreplace it with `bun dev` (invoked from the repo root) to drive a dev build.\n\n```bash\n# Headless, dev build (from repo root)\nREPO=/path/to/mimocode/checkout   # your local mimocode repo root\nMIMOCODE_HOME=$(mktemp -d) bun --cwd \"$REPO\" dev run \\\n  --format json --dangerously-skip-permissions --dir \"$WORKSPACE\" \\\n  < \"$PROMPT\" > /tmp/mimo-dev.jsonl 2>&1\n\n# TUI, dev build in tmux (from repo root)\ntmux new-session -d -s \"$SESSION\" -x 120 -y 30 \\\n  \"cd $REPO && MIMOCODE_HOME=$(mktemp -d) MIMOCODE_PURE=true bun dev $WORKSPACE; sleep 999\"\n```\n\n---\n\n## Part 1: Headless Mode (`mimo run`)\n\n### Launch\n\n```bash\nPROMPT=$(mktemp -t mimo-drive.XXXXXX)\ncat >\"$PROMPT\" <<'EOF'\nYour task here.\nEOF\n\nMIMOCODE_HOME=$(mktemp -d) mimo run \\\n  --format json \\\n  --dangerously-skip-permissions \\\n  --dir \"$WORKSPACE\" \\\n  < \"$PROMPT\" > /tmp/mimo-out.jsonl 2>&1\n\nEXIT=$?\n```\n\n### Key flags\n\n| Flag | Purpose |\n|------|---------|\n| `--format json` | Structured JSONL events to stdout |\n| `--dangerously-skip-permissions` | Auto-approve all permissions |\n| `--model provider/model` | Override model |\n| `--session SID` | Continue existing session |\n| `--continue` | Continue last session |\n| `--file path` | Attach file to message |\n| `--dir path` | Working directory |\n\n### JSON event types\n\n`--format json` writes one JSON object per line. **Every** event has the shape\n`{\"type\": ..., \"timestamp\": <ms>, \"sessionID\": \"ses_...\", ...payload}` — the\n`sessionID` is a field on each event, not a standalone event. The payload for\nmost events is nested under `part`.\n\nEmitted event types (from the run event stream):\n\n```\n{\"type\":\"step_start\",\"timestamp\":...,\"sessionID\":\"ses_abc\",\"part\":{...}}\n{\"type\":\"text\",\"timestamp\":...,\"sessionID\":\"ses_abc\",\"part\":{\"type\":\"text\",\"text\":\"I'll create the file...\",\"time\":{...}}}\n{\"type\":\"reasoning\",\"timestamp\":...,\"sessionID\":\"ses_abc\",\"part\":{\"type\":\"reasoning\",\"text\":\"The user wants...\"}}\n{\"type\":\"tool_use\",\"timestamp\":...,\"sessionID\":\"ses_abc\",\"part\":{\"type\":\"tool\",\"tool\":\"write\",\"state\":{\"status\":\"completed\",...}}}\n{\"type\":\"step_finish\",\"timestamp\":...,\"sessionID\":\"ses_abc\",\"part\":{...}}\n{\"type\":\"error\",\"timestamp\":...,\"sessionID\":\"ses_abc\",\"error\":{...}}\n```\n\nNotes that matter for parsing:\n\n- **No `session.id`, no `tool_result`, no `session.status` event.** A `tool_use`\n  is emitted **once** per tool part when it reaches `completed` or `error` — the\n  result/output is inside `part.state`, there is no separate result event.\n- **`tool_use` identifies the tool via `part.tool`** (a bare string, e.g.\n  `\"tool\":\"write\"`) — there is no `.tool.name` and no top-level `.name`.\n- **`text` / `reasoning` text lives at `part.text`**, not top-level `.text`.\n- **`reasoning` is only emitted when `--thinking` is passed.** Without it, no\n  reasoning events appear.\n- **Completion is not a stream event.** The process finishes when the run\n  completes; the reliable completion signal is **process exit** (exit code 0),\n  not any line in the JSONL.\n\n### Validation patterns\n\n```bash\n# Completion — the real signal is the exit code, not a stream event\n[ $EXIT -eq 0 ] || echo \"FAIL: exit $EXIT\"\n\n# No errors\ngrep -q '\"type\":\"error\"' /tmp/mimo-out.jsonl && echo \"FAIL: errors found\"\n\n# A specific tool was used (match part.tool, the bare string)\ngrep -q '\"tool\":\"write\"' /tmp/mimo-out.jsonl || echo \"FAIL: write tool not called\"\n\n# Text output contains expected string (text is at .part.text)\ngrep '\"type\":\"text\"' /tmp/mimo-out.jsonl | jq -r '.part.text' | grep -q \"expected\"\n\n# Robust tool check via jq (works regardless of key ordering)\njq -e 'select(.type==\"tool_use\") | .part.tool==\"write\"' /tmp/mimo-out.jsonl >/dev/null \\\n  || echo \"FAIL: write tool not called\"\n```\n\n\n### Timeout\n\n```bash\ntimeout 120 mimo run --format json --dangerously-skip-permissions < \"$PROMPT\"\n[ $? -eq 124 ] && echo \"FAIL: timed out\"\n```\n\n---\n\n## Part 2: TUI Mode (tmux)\n\n### Isolation variables\n\n| Variable | Purpose |\n|---|---|\n| `MIMOCODE_HOME` | **Required.** Fresh `mktemp -d` per run. Sandboxes DB, config, cache. |\n| `MIMOCODE_PURE=true` | Disable external plugins. |\n| `MIMOCODE_DISABLE_GIT=true` | Skip git ops if workspace isn't a real repo. |\n\n### Launch TUI in tmux\n\n```bash\n# Create isolated environment\nMHOME=$(mktemp -d)\nWORKSPACE=$(mktemp -d)\nSESSION=\"mimo-drive-$$\"\n\n# Launch mimo TUI in tmux (workspace is a positional arg, NOT --dir)\ntmux new-session -d -s \"$SESSION\" -x 120 -y 30 \\\n  \"MIMOCODE_HOME=$MHOME MIMOCODE_PURE=true mimo $WORKSPACE; sleep 999\"\n\n# Wait for the TUI to render its input prompt\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"$PROMPT_RE\" -T 15\n```\n\nWhere `PROMPT_RE` is a language-neutral pattern for the input prompt. The\nprompt placeholder is localized, so match on the stable markers rather than a\nlocalized string:\n\n```bash\n# Matches the prompt line regardless of UI language:\n#   the \">\" input caret, the \"Ask\" English placeholder, or a \"/\" command hint\nPROMPT_RE='>|Ask|/[a-z]'\n```\n\nIf a run's UI language is known and fixed, you may match its literal\nplaceholder instead — but prefer the neutral pattern for portability.\n\n### Send input\n\n```bash\n# Type a message (literal text, then Enter)\ntmux send-keys -t \"$SESSION:0.0\" -l -- \"Create a file called hello.txt with content 'world'\"\ntmux send-keys -t \"$SESSION:0.0\" Enter\n\n# Special keys\ntmux send-keys -t \"$SESSION:0.0\" C-c          # Cancel\ntmux send-keys -t \"$SESSION:0.0\" C-d          # EOF\ntmux send-keys -t \"$SESSION:0.0\" Escape       # Escape\ntmux send-keys -t \"$SESSION:0.0\" Tab          # Tab completion\ntmux send-keys -t \"$SESSION:0.0\" Up           # History up\ntmux send-keys -t \"$SESSION:0.0\" Down         # History down\ntmux send-keys -t \"$SESSION:0.0\" Enter        # Submit\n```\n\n### Capture output\n\n```bash\n# Current screen\ntmux capture-pane -t \"$SESSION:0.0\" -p\n\n# Full scrollback\ntmux capture-pane -t \"$SESSION:0.0\" -p -S -\n\n# Last 50 lines\ntmux capture-pane -t \"$SESSION:0.0\" -p -S -50\n```\n\n### Wait for state changes\n\n```bash\n# Wait for agent to start processing\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"thinking\\|reading\\|writing\" -T 30\n\n# Wait for tool permission prompt\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"Allow\\|Deny\\|permission\\|approve\" -T 30\n\n# Wait for completion\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"completed\\|done\\|finished\\|idle\" -T 120\n\n# Wait for error\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"error\\|failed\\|Error\" -T 30\n\n# Custom regex\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"hello\\.txt.*world\" -T 30\n```\n\n### Handle permission dialogs\n\n```bash\n# Wait for permission prompt, then approve\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"Allow\\|approve\" -T 30\ntmux send-keys -t \"$SESSION:0.0\" -l -- \"y\"\ntmux send-keys -t \"$SESSION:0.0\" Enter\n\n# Or deny\ntmux send-keys -t \"$SESSION:0.0\" -l -- \"n\"\ntmux send-keys -t \"$SESSION:0.0\" Enter\n```\n\n### Multi-turn interaction\n\n```bash\n# Turn 1: send initial message\ntmux send-keys -t \"$SESSION:0.0\" -l -- \"Create a TypeScript file that adds two numbers\"\ntmux send-keys -t \"$SESSION:0.0\" Enter\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"completed\\|done\" -T 120\n\n# Turn 2: follow-up\ntmux send-keys -t \"$SESSION:0.0\" -l -- \"Now add a test for it\"\ntmux send-keys -t \"$SESSION:0.0\" Enter\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"completed\\|done\" -T 120\n\n# Verify result\ntmux capture-pane -t \"$SESSION:0.0\" -p -S - | grep -i \"pass\\|fail\"\n```\n\n### Cleanup\n\n```bash\ntmux kill-session -t \"$SESSION\" 2>/dev/null\nrm -rf \"$MHOME\" \"$WORKSPACE\"\n```\n\n---\n\n## Part 3: Scenarios\n\n### S1: Smoke (headless)\n\n```bash\ntest_smoke() {\n  local P=$(mktemp) MHOME=$(mktemp -d)\n  echo \"Say hello\" > \"$P\"\n  MIMOCODE_HOME=$MHOME mimo run --format json --dangerously-skip-permissions \\\n    < \"$P\" > /tmp/s1.jsonl 2>&1\n  local E=$?\n  rm -rf \"$MHOME\" \"$P\"\n  [ $E -eq 0 ] && grep -q '\"type\":\"text\"' /tmp/s1.jsonl && echo \"PASS\" || echo \"FAIL\"\n}\n```\n\n### S2: Tool use (headless)\n\n```bash\ntest_tool_use() {\n  local P=$(mktemp) MHOME=$(mktemp -d) WS=$(mktemp -d)\n  echo 'Create file test.txt with content \"hello\"' > \"$P\"\n  MIMOCODE_HOME=$MHOME mimo run --format json --dangerously-skip-permissions --dir \"$WS\" \\\n    < \"$P\" > /tmp/s2.jsonl 2>&1\n  local E=$?\n  local OK=true\n  [ $E -ne 0 ] && OK=false\n  ! grep -q '\"tool\":\"write\"' /tmp/s2.jsonl && OK=false\n  [ ! -f \"$WS/test.txt\" ] && OK=false\n  rm -rf \"$MHOME\" \"$WS\" \"$P\"\n  $OK && echo \"PASS\" || echo \"FAIL\"\n}\n```\n\n### S3: TUI interactive flow\n\n```bash\ntest_tui_interactive() {\n  local MHOME=$(mktemp -d) WS=$(mktemp -d) SID=\"mimo-s3-$$\"\n  local PROMPT_RE='>|Ask|/[a-z]'\n  tmux new-session -d -s \"$SID\" -x 120 -y 30 \"MIMOCODE_HOME=$MHOME MIMOCODE_PURE=true mimo $WS; sleep 999\"\n\n  # Wait for prompt\n  bash scripts/wait-for-text.sh -t \"$SID:0.0\" -p \"$PROMPT_RE\" -T 15 || { echo \"FAIL: no prompt\"; tmux kill-session -t $SID; return 1; }\n\n  # Send task\n  tmux send-keys -t \"$SID:0.0\" -l -- \"Create hello.txt with content 'world'\"\n  tmux send-keys -t \"$SID:0.0\" Enter\n\n  # Wait for completion (agent shows elapsed time like \"· 9.8s\")\n  bash scripts/wait-for-text.sh -t \"$SID:0.0\" -p \"· [0-9]\" -T 120 || { echo \"FAIL: no completion\"; tmux kill-session -t $SID; return 1; }\n\n  # Verify file\n  [ -f \"$WS/hello.txt\" ] && echo \"PASS\" || echo \"FAIL\"\n  tmux kill-session -t \"$SID\" 2>/dev/null\n  rm -rf \"$MHOME\" \"$WS\"\n}\n```\n\n### S4: TUI permission handling\n\n```bash\ntest_tui_permission() {\n  local MHOME=$(mktemp -d) WS=$(mktemp -d) SID=\"mimo-s4-$$\"\n  local PROMPT_RE='>|Ask|/[a-z]'\n  tmux new-session -d -s \"$SID\" -x 120 -y 30 \"MIMOCODE_HOME=$MHOME MIMOCODE_PURE=true mimo $WS; sleep 999\"\n\n  bash scripts/wait-for-text.sh -t \"$SID:0.0\" -p \"$PROMPT_RE\" -T 15\n\n  # Ask for something that needs permission (no --dangerously-skip-permissions in TUI)\n  tmux send-keys -t \"$SID:0.0\" -l -- \"Run the command: echo hello\"\n  tmux send-keys -t \"$SID:0.0\" Enter\n\n  # Wait for permission prompt\n  bash scripts/wait-for-text.sh -t \"$SID:0.0\" -p \"Allow\\|approve\\|permission\\|y/n\" -T 30 || { echo \"FAIL: no permission prompt\"; tmux kill-session -t $SID; return 1; }\n\n  # Approve\n  tmux send-keys -t \"$SID:0.0\" -l -- \"y\"\n  tmux send-keys -t \"$SID:0.0\" Enter\n\n  # Wait for completion\n  bash scripts/wait-for-text.sh -t \"$SID:0.0\" -p \"· [0-9]\" -T 60\n\n  tmux capture-pane -t \"$SID:0.0\" -p | grep -q \"hello\" && echo \"PASS\" || echo \"FAIL\"\n  tmux kill-session -t \"$SID\" 2>/dev/null\n  rm -rf \"$MHOME\" \"$WS\"\n}\n```\n\n### S5: TUI keybindings\n\n```bash\ntest_tui_keybindings() {\n  local MHOME=$(mktemp -d) WS=$(mktemp -d) SID=\"mimo-s5-$$\"\n  local PROMPT_RE='>|Ask|/[a-z]'\n  tmux new-session -d -s \"$SID\" -x 120 -y 30 \"MIMOCODE_HOME=$MHOME MIMOCODE_PURE=true mimo $WS; sleep 999\"\n\n  bash scripts/wait-for-text.sh -t \"$SID:0.0\" -p \"$PROMPT_RE\" -T 15\n\n  # Test Ctrl+C cancels input\n  tmux send-keys -t \"$SID:0.0\" -l -- \"some partial input\"\n  tmux send-keys -t \"$SID:0.0\" C-c\n\n  # Screen should still show prompt (not exit)\n  sleep 1\n  tmux capture-pane -t \"$SID:0.0\" -p | grep -qE \"$PROMPT_RE\" && echo \"PASS: Ctrl+C didn't exit\" || echo \"FAIL: Ctrl+C exited\"\n\n  # Test Escape\n  tmux send-keys -t \"$SID:0.0\" Escape\n  sleep 0.5\n\n  tmux kill-session -t \"$SID\" 2>/dev/null\n  rm -rf \"$MHOME\" \"$WS\"\n}\n```\n\n---\n\n## Batch Runner\n\n```bash\nrun_all() {\n  local PASS=0 FAIL=0 RESULTS=()\n  for fn in test_smoke test_tool_use test_tui_interactive test_tui_permission test_tui_keybindings; do\n    echo \"--- $fn ---\"\n    if $fn 2>/dev/null; then PASS=$((PASS+1)); else FAIL=$((FAIL+1)); RESULTS+=(\"$fn: FAIL\"); fi\n  done\n  echo \"=== $PASS passed, $FAIL failed ===\"\n  [ ${#RESULTS[@]} -gt 0 ] && printf '  %s\\n' \"${RESULTS[@]}\"\n  [ $FAIL -eq 0 ]\n}\n```\n\n---\n\n## Quick Reference\n\n| Task | Command |\n|------|---------|\n| Headless run | `MIMOCODE_HOME=$(mktemp -d) mimo run --format json --dangerously-skip-permissions \"prompt\"` |\n| TUI launch | `tmux new-session -d -s test -x 120 -y 30 \"MIMOCODE_HOME=$(mktemp -d) mimo $WORKSPACE; sleep 999\"` |\n| Send text | `tmux send-keys -t test:0.0 -l -- \"text\" && tmux send-keys -t test:0.0 Enter` |\n| Capture screen | `tmux capture-pane -t test:0.0 -p -S -` |\n| Wait for text | `bash scripts/wait-for-text.sh -t test:0.0 -p \"pattern\" -T 30` |\n| Send Ctrl+C | `tmux send-keys -t test:0.0 C-c` |\n| Approve permission | `tmux send-keys -t test:0.0 -l -- \"y\" && tmux send-keys -t test:0.0 Enter` |\n| Cleanup | `tmux kill-session -t test && rm -rf $MHOME` |\n","frontmatter":{"name":"drive-mimo","description":"Use when developing or testing the MiMoCode repository and you need to programmatically drive another MiMoCode (mimo) process. Supports headless `mimo run` with JSON events and interactive TUI via tmux for behavior, integration, and visual regression testing. Covers an installed `mimo` binary or a dev build launched from source with `bun dev`; do not use it for ordinary MiMoCode task execution."},"isInternal":false,"tokens":4923,"sizeBytes":15574},{"name":"SKILL.md","path":".agents/skills/effect/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/.agents/skills/effect/SKILL.md","title":"effect","category":"anthropic-skill","format":"markdown","content":"---\nname: effect\ndescription: Answer questions about the Effect framework\n---\n\n# Effect\n\nThis codebase uses Effect, a framework for writing typescript.\n\n## How to Answer Effect Questions\n\n1. Clone the Effect repository: `https://github.com/Effect-TS/effect-smol` to\n   `.opencode/references/effect-smol` in this project NOT the skill folder.\n2. Use the explore agent to search the codebase for answers about Effect patterns, APIs, and concepts\n3. Provide responses based on the actual Effect source code and documentation\n\n## Guidelines\n\n- Always use the explore agent with the cloned repository when answering Effect-related questions\n- Reference specific files and patterns found in the Effect codebase\n- Do not answer from memory - always verify against the source\n","frontmatter":{"name":"effect","description":"Answer questions about the Effect framework"},"isInternal":false,"tokens":161,"sizeBytes":768},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/arxiv/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/arxiv/SKILL.md","title":"arxiv","category":"anthropic-skill","format":"markdown","content":"---\nname: arxiv\ndescription: \"Use this skill whenever the user wants to find, read, cite, track, download, or analyze academic papers on arXiv. That includes: searching papers by topic, author, category, or arXiv ID; fetching abstracts or full metadata; generating BibTeX citations; downloading PDFs; listing the latest submissions in a field (e.g. cs.AI daily digest); checking a paper's citation impact; finding who cites a paper, what it references, or related-paper recommendations. Trigger on mentions of 'arXiv', an arXiv ID (e.g. 2601.02780 or hep-th/0601001), an arxiv.org URL, 'paper search', 'literature review', 'find papers about X', 'cite this paper', or 'what's new in cs.LG'.\"\nversion: 2.0.0\nlicense: MIT\nplatforms: [linux, macos, windows]\n---\n\n# arXiv Research\n\nSearch, read, cite, and analyze academic papers using the free arXiv API and Semantic Scholar API. No API keys, no dependencies — the bundled script uses only the Python stdlib.\n\n## Quick Start: the `arxiv.py` script\n\nPrefer `scripts/arxiv.py` over raw `curl` — it handles Atom XML parsing, versioned IDs, withdrawn-paper detection, and produces clean readable (or `--json`) output.\n\n| Goal | Command |\n|------|---------|\n| Search papers | `python scripts/arxiv.py search \"GRPO reinforcement learning\" --max 10 --sort date` |\n| Filtered search | `python scripts/arxiv.py search \"attention\" --author vaswani --category cs.CL` |\n| Full metadata + abstract | `python scripts/arxiv.py get 2601.02780,1706.03762` |\n| BibTeX citation | `python scripts/arxiv.py bibtex 2601.02780` |\n| Download PDF | `python scripts/arxiv.py download 2601.02780 --dest ./papers` |\n| Latest in a category | `python scripts/arxiv.py new cs.CL --max 10` |\n| Who cites this paper | `python scripts/arxiv.py cites 2601.02780 --max 20` |\n| What this paper cites | `python scripts/arxiv.py refs 2601.02780` |\n| Related-paper recommendations | `python scripts/arxiv.py similar 2601.02780` |\n| Machine-readable output | append `--json` to any command |\n\nCommon flags: `--max N` (result count), `--sort relevance|date|updated`, `--start N` (pagination offset, search only), `--json`.\n\n## Reading Paper Content\n\nAfter finding a paper, read it with the `webfetch` tool:\n\n- Abstract page (fast, metadata + abstract): `https://arxiv.org/abs/2601.02780`\n- Full paper as HTML (best for reading, when available): `https://arxiv.org/html/2601.02780`\n- PDF: `https://arxiv.org/pdf/2601.02780`\n\nIf HTML is unavailable and the PDF must be processed locally, `download` it first, then use a PDF-processing skill.\n\n## Recommended Research Workflows\n\n**Literature review on a topic**\n1. `search \"topic\" --sort date --max 15` — recent work\n2. `search \"topic\" --max 15` — seminal work (relevance-sorted)\n3. Cross-check impact: `python scripts/arxiv.py get ID` then `cites ID --max 5` for citation counts\n4. Read the top candidates via `webfetch` on the abs/html URLs\n5. `bibtex ID1,ID2,...` for the papers you keep\n\n**Deep-dive a single paper**\n1. `get ID` — full abstract, versions, journal ref, DOI\n2. `refs ID` — what it builds on\n3. `cites ID` — follow-up work (sorted by citation count)\n4. `similar ID` — related papers you might have missed\n5. `webfetch` the HTML/PDF for full text\n\n**Stay current in a field**\n- `new cs.AI --max 20` — latest submissions in a category\n- Category taxonomy: https://arxiv.org/category_taxonomy — common ones: `cs.AI`, `cs.CL` (NLP), `cs.CV`, `cs.LG`, `cs.CR`, `stat.ML`, `math.OC`\n\n## Raw API Reference (when the script isn't enough)\n\nThe script covers most needs; use the raw APIs for advanced queries.\n\n### arXiv API (Atom XML)\n\n```bash\ncurl -s \"https://export.arxiv.org/api/query?search_query=all:transformer&max_results=5\"\n```\n\nField prefixes: `all:` (everything), `ti:` (title), `au:` (author), `abs:` (abstract), `cat:` (category), `co:` (comment, e.g. `co:accepted+NeurIPS`).\n\nBoolean syntax (URL-encode spaces as `+`):\n\n```\nall:GPT+OR+all:BERT              # OR\nall:language+model+ANDNOT+all:vision   # AND NOT\nti:\"chain+of+thought\"            # exact phrase\nau:hinton+AND+cat:cs.LG          # combined\n```\n\nParameters: `sortBy` (`relevance`|`lastUpdatedDate`|`submittedDate`), `sortOrder`, `start`, `max_results`, `id_list` (comma-separated IDs).\n\n### Semantic Scholar API (JSON)\n\narXiv has no citation data — Semantic Scholar fills that gap (free, ~1 req/sec unauthenticated).\n\n```bash\n# Paper details with citation counts\ncurl -s \"https://api.semanticscholar.org/graph/v1/paper/arXiv:2601.02780?fields=title,citationCount,influentialCitationCount,tldr\"\n\n# Author profile\ncurl -s \"https://api.semanticscholar.org/graph/v1/author/search?query=Yann+LeCun&fields=name,hIndex,citationCount,paperCount\"\n\n# Keyword search returning JSON (alternative to arXiv search)\ncurl -s \"https://api.semanticscholar.org/graph/v1/paper/search?query=GRPO&limit=5&fields=title,year,citationCount,externalIds\"\n```\n\nUseful fields: `title`, `authors`, `year`, `abstract`, `tldr` (AI summary), `citationCount`, `influentialCitationCount`, `isOpenAccess`, `openAccessPdf`, `fieldsOfStudy`, `publicationVenue`, `externalIds` (arXiv ID, DOI).\n\n## Important Details\n\n**Rate limits** — arXiv: ~1 request / 3 seconds; Semantic Scholar: ~1 request / second. Space out consecutive calls; the script exits with a clear message on HTTP 429.\n\n**ID formats** — new style `2402.03300`, old style `hep-th/0601001`. Both work everywhere.\n\n**Versioning** — `arxiv.org/abs/2601.02780` resolves to the latest version; `...v2` is a specific immutable version. `bibtex` and `download` preserve the version suffix so citations match the content you actually read (later versions can change substantially).\n\n**Withdrawn papers** — the script flags entries whose abstract indicates withdrawal/retraction with `[WITHDRAWN]`. Don't cite these without noting the status.\n\n**Listings caveat** — `new CATEGORY` sorts by submission date via the search API; the official \"new today\" listing at `https://arxiv.org/list/cs.AI/new` may group slightly differently (cross-lists, replacements).\n","frontmatter":{"name":"arxiv","description":"Use this skill whenever the user wants to find, read, cite, track, download, or analyze academic papers on arXiv. That includes: searching papers by topic, author, category, or arXiv ID; fetching abstracts or full metadata; generating BibTeX citations; downloading PDFs; listing the latest submissions in a field (e.g. cs.AI daily digest); checking a paper's citation impact; finding who cites a paper, what it references, or related-paper recommendations. Trigger on mentions of 'arXiv', an arXiv ID (e.g. 2601.02780 or hep-th/0601001), an arxiv.org URL, 'paper search', 'literature review', 'find papers about X', 'cite this paper', or 'what's new in cs.LG'.","version":"2.0.0","license":"MIT","platforms":["linux","macos","windows"]},"isInternal":false,"tokens":1655,"sizeBytes":6042},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/claude-code/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/claude-code/SKILL.md","title":"claude-code","category":"anthropic-skill","format":"markdown","content":"---\nname: claude-code\ndescription: \"Operate Claude Code CLI (v2.1+) via the terminal only when the user explicitly requests Claude Code or names this skill. Covers print mode (-p), interactive tmux sessions, and background (--bg) orchestration.\"\nversion: 2.0.0\nlicense: MIT\nplatforms: [linux, macos, windows]\n---\n\n# Claude Code Delegation\n\nDelegate coding work to Claude Code, Anthropic's autonomous coding agent CLI.\n\n**Setup (once):** `npm install -g @anthropic-ai/claude-code && claude auth login` · verify with `claude auth status` / `claude doctor`. CI token: `claude setup-token`. Full auth/install variants → `references/flags.md`.\n\n**Platform check (before running anything):** detect the OS first. All shell examples in this skill are POSIX (bash). Linux/macOS run them as-is. On **Windows**, run Claude Code natively in PowerShell/Git Bash for print and background modes, but interactive tmux orchestration requires **WSL**. Shell-syntax translation table (quoting, env vars, piping, paths) → `references/platforms.md`.\n\n## Mode Selection (decide FIRST)\n\n| Task shape | Mode | Why |\n|---|---|---|\n| One-shot task: fix bug, add feature, review diff, extract data | **Print `-p`** ← default | No PTY, no dialogs, structured output |\n| Multi-turn iterate: refactor → review → fix → test; needs slash commands | **Interactive tmux** → `references/interactive-tmux.md` | Full REPL, requires dialog handling |\n| Long-running, shouldn't block; large fan-out supervision | **Background `--bg`** | Native supervision via `claude agents` |\n| High-stakes PR review | **`claude ultrareview [pr#]`** | Cloud multi-agent, exit-code driven (uploads diff to cloud — never on branches with secrets) |\n\nDo NOT hand-roll tmux fan-outs for parallel work — prefer `--bg` + `claude agents --json --all`.\n\n## Print Mode (the 90% path)\n\n```\nterminal(command=\"claude -p 'Fix the auth bug in src/auth.py' \\\n  --allowedTools 'Read,Edit' --max-turns 10 --output-format json\",\n  workdir=\"/path/to/project\", timeout=180)\n```\n\n**Always set:** `workdir` · `--max-turns` (5–10; print-mode only) · `--allowedTools` (least privilege: `Read,Edit,Write,Bash`, patterns like `Bash(git *)`).\n\n**JSON result fields:** `result` (text) · `session_id` (for resume) · `subtype` (`success` | `error_max_turns` | `error_budget`) · `total_cost_usd` · `num_turns` · `structured_output` (with `--json-schema`).\n\n**Common variants:**\n\n```bash\ngit diff main... | claude -p 'Review for bugs' --max-turns 1     # pipe input, cheapest review\nclaude -p 'Continue: add pooling' --resume <session_id>          # resume; --continue = latest in cwd; --fork-session = branch\nclaude -p 'List functions' --output-format json --json-schema '<schema>' --max-turns 5   # structured extraction (needs turns to read files)\nclaude --bare -p 'task' --settings ci.json                       # CI: skips hooks/plugins/CLAUDE.md; auth = ANTHROPIC_API_KEY only\nclaude -p 'task' --max-budget-usd 0.50 --fallback-model haiku    # cost cap (min ~$0.05) + overload fallback\n```\n\nStreaming, stream-json events, bidirectional input, cache-reuse (`--exclude-dynamic-system-prompt-sections`) → `references/print-mode.md`.\n\n## Background Mode\n\n```bash\nclaude --bg 'investigate flaky test in tests/api.test.ts'   # NOT compatible with -p\nclaude agents --json --all                                   # list/inspect\nclaude attach <id> | logs <id> | stop <id> | respawn <id> | rm <id>\n```\n\n## Guardrails & Gotchas (violations break agents)\n\n1. **`-p` auto-skips trust/permission dialogs** (any non-TTY does) — only run in trusted directories.\n2. **Interactive mode = tmux required** (Windows: only inside WSL — never attempt tmux in PowerShell/cmd; fall back to `-p` or `--bg`); two startup dialogs, and the `--dangerously-skip-permissions` dialog defaults to **\"No, exit\"** (must send `Down` then `Enter`). Full patterns → `references/interactive-tmux.md`.\n3. **Session resume is per-directory** — `--continue` only finds sessions from the same cwd.\n4. **Slash commands don't work in `-p`** — describe the task in natural language instead.\n5. **Context >70% degrades quality** — in interactive sessions monitor `/context`, use `/compact`.\n6. **Clean up**: kill tmux sessions and `claude stop/rm` background sessions when done.\n7. **Don't kill slow sessions** — capture progress first (`tmux capture-pane` / `claude logs`).\n8. **Report back**: after completion, summarize what changed (use the JSON `result` + `git diff`).\n\n## References (read on demand)\n\n| File | Read when |\n|---|---|\n| `references/print-mode.md` | Streaming output, stream-json events, piping, schemas, session mgmt, cache reuse |\n| `references/interactive-tmux.md` | Any tmux/PTY session: dialogs, send-keys, monitoring, slash commands, shortcuts |\n| `references/flags.md` | Full CLI flag & subcommand tables, auth variants, env vars, model/effort selection |\n| `references/config.md` | CLAUDE.md/memory, settings hierarchy, custom agents, hooks, MCP, plugins, project purge |\n| `references/platforms.md` | Running on Windows (PowerShell/Git Bash/WSL) or macOS: shell translation, paths, per-OS gotchas |\n","frontmatter":{"name":"claude-code","description":"Operate Claude Code CLI (v2.1+) via the terminal only when the user explicitly requests Claude Code or names this skill. Covers print mode (-p), interactive tmux sessions, and background (--bg) orchestration.","version":"2.0.0","license":"MIT","platforms":["linux","macos","windows"]},"isInternal":false,"tokens":1340,"sizeBytes":5144},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/codex/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/codex/SKILL.md","title":"codex","category":"anthropic-skill","format":"markdown","content":"---\nname: codex\ndescription: Run, configure, and troubleshoot OpenAI Codex CLI in non-interactive headless environments. Use for Codex automation in Bash or PowerShell, native Windows or WSL2, shell scripts, CI/CD, Docker, Kubernetes, remote servers, agent harnesses, or batch jobs; for constructing `codex exec` commands; selecting sandbox and approval modes; consuming JSONL events or structured output; resuming sessions; passing prompts through stdin; and handling failures caused by unavailable interactive input such as `request_user_input`.\n---\n\n# Codex CLI\n\nUse Codex CLI as a deterministic, non-interactive worker suitable for automation and agent orchestration.\n\n## Operating Rules\n\n1. Use `codex exec`, not the interactive `codex` TUI.\n2. Pass the task as the positional `PROMPT` argument. Do not use `-p` for the prompt; `-p` selects a profile.\n3. For ordinary unattended code changes, prefer:\n\n```bash\ncodex exec \\\n  -C /path/to/repo \\\n  --sandbox workspace-write \\\n  --ask-for-approval never \\\n  \"<TASK>\"\n```\n\n4. Use `--yolo` only inside an externally hardened and disposable runner. It disables Codex approvals and sandboxing.\n5. For harnesses and CI, prefer `--json` plus `--output-last-message`.\n6. Do not make the run depend on a human answering questions. Resolve ambiguity using repository evidence and conservative defaults.\n7. Treat credentials as secrets. Inject `CODEX_API_KEY` only into the single `codex exec` process when possible.\n8. Before giving version-sensitive advice, inspect `codex exec --help` or current official Codex documentation if available.\n9. On Windows, choose one execution environment per task: native PowerShell for Windows toolchains or WSL2 for Linux toolchains. Do not casually mix paths, installations, or authentication across them.\n\n## Choose the Execution Mode\n\n### Read-only analysis\n\nUse when the task must not modify files:\n\n```bash\ncodex exec \\\n  -C /path/to/repo \\\n  --sandbox read-only \\\n  --ask-for-approval never \\\n  \"Analyze the repository and report risks. Do not modify files.\"\n```\n\n### Workspace-scoped implementation\n\nUse as the default for autonomous repository work:\n\n```bash\ncodex exec \\\n  -C /path/to/repo \\\n  --sandbox workspace-write \\\n  --ask-for-approval never \\\n  \"Implement the task, run relevant tests, and report unresolved blockers.\"\n```\n\n### Externally isolated unrestricted execution\n\nUse only when the enclosing container, VM, or sandbox enforces the real security boundary:\n\n```bash\ncodex exec \\\n  -C /workspace/repo \\\n  --yolo \\\n  \"Implement the task and validate the result.\"\n```\n\nNever recommend `--yolo` on a normal developer machine or a runner containing unrelated secrets, host mounts, SSH keys, cloud credentials, or a Docker socket.\n\n## Construct an Autonomous Prompt\n\nWhen headless execution could encounter choices, prepend these instructions:\n\n```text\nWork fully autonomously.\n\nDo not ask the user questions and do not request interactive input.\nInspect the repository and available context before making assumptions.\nWhen several valid approaches exist, choose the option that:\n1. minimizes unrelated changes,\n2. preserves backward compatibility,\n3. introduces the fewest new dependencies,\n4. avoids destructive or irreversible actions.\n\nContinue until the task is complete or a concrete blocking error is reached.\nRecord assumptions, validation performed, and unresolved blockers in the final response.\n```\n\nDo not simulate \"always select the first option.\" Option ordering is not a safety or quality policy. Apply the explicit decision rules above instead.\n\n## Handle `request_user_input` Failures\n\nWhen Codex reports that `request_user_input` is unavailable in Default mode or non-interactive mode:\n\n1. Confirm the invocation uses `codex exec` and is intentionally headless.\n2. Add the autonomous prompt policy above.\n3. Supply missing decisions in the task prompt or `AGENTS.md` when they are known in advance.\n4. Replace open-ended requests such as \"ask me which approach\" with deterministic selection criteria.\n5. If the choice is safety-critical, destructive, or impossible to infer, make the run fail clearly rather than selecting randomly.\n6. Do not attempt to emulate terminal keystrokes unless the subprocess itself, rather than Codex, requires input and the workflow explicitly defines the safe answer.\n\n## Pass Prompts and Context\n\nUse a direct positional prompt:\n\n```bash\ncodex exec \"Summarize the repository structure.\"\n```\n\nRead the prompt from stdin:\n\n```bash\ncodex exec - < prompt.md\n```\n\nPipe dynamic context while retaining an explicit task:\n\n```bash\nnpm test 2>&1 | codex exec \"Analyze this test output and fix the repository.\"\n```\n\nUse `--skip-git-repo-check` only for intentional one-off directories outside Git:\n\n```bash\ncodex exec \\\n  --skip-git-repo-check \\\n  -C /tmp/task \\\n  \"Analyze the files in this directory.\"\n```\n\n## Produce Harness-Friendly Output\n\n### Capture only the final message\n\n```bash\ncodex exec \\\n  -C /workspace/repo \\\n  --output-last-message /output/final.md \\\n  \"Review the codebase.\"\n```\n\n### Stream JSONL events\n\n```bash\ncodex exec \\\n  -C /workspace/repo \\\n  --json \\\n  --sandbox workspace-write \\\n  --ask-for-approval never \\\n  \"Run tests and fix failures.\" \\\n  > /output/events.jsonl\n```\n\nExpect event families such as `thread.started`, `turn.started`, `turn.completed`, `turn.failed`, `item.*`, and `error`.\n\n### Capture events and the final answer together\n\n```bash\ncodex exec \\\n  -C /workspace/repo \\\n  --json \\\n  --sandbox workspace-write \\\n  --ask-for-approval never \\\n  --output-last-message /output/final.md \\\n  \"Complete the task autonomously.\" \\\n  | tee /output/events.jsonl\n```\n\nDo not parse human-readable progress text when `--json` is available.\n\n## Require Structured Final Output\n\nCreate a JSON Schema and pass it with `--output-schema`:\n\n```bash\ncodex exec \\\n  -C /workspace/repo \\\n  --sandbox workspace-write \\\n  --ask-for-approval never \\\n  --output-schema /input/result.schema.json \\\n  --output-last-message /output/result.json \\\n  \"Implement the task, validate it, and return the requested structured result.\"\n```\n\nA useful harness schema usually includes:\n\n- `status`: `success`, `partial`, or `failed`\n- `summary`: concise outcome\n- `changed_files`: repository-relative paths\n- `validation`: commands run and results\n- `assumptions`: decisions made without user input\n- `blockers`: concrete unresolved problems\n\nSet `additionalProperties` to `false` when downstream parsing must be strict.\n\n## Resume or Avoid Persistence\n\nResume the most recent session for the current working directory:\n\n```bash\ncodex exec resume --last \"Continue the previous task and fix remaining issues.\"\n```\n\nResume a specific session:\n\n```bash\ncodex exec resume \"$SESSION_ID\" \"Continue with the next stage.\"\n```\n\nUse an ephemeral run when rollout persistence is undesirable:\n\n```bash\ncodex exec --ephemeral \"Analyze the repository.\"\n```\n\nDo not rely on `--last` across unrelated working directories unless deliberately using the relevant all-directory option supported by the installed CLI.\n\n## Authenticate Safely\n\nFor a local interactive login:\n\n```bash\ncodex login\n```\n\nFor a headless machine with device-code login enabled:\n\n```bash\ncodex login --device-auth\n```\n\nFor a single automated invocation:\n\n```bash\nCODEX_API_KEY=\"$OPENAI_API_KEY\" \\\ncodex exec --json \"Triage the repository.\"\n```\n\nDo not expose API keys as broad job-level environment variables in jobs that execute repository-controlled code. Never commit or print `~/.codex/auth.json`.\n\n## Windows, PowerShell, and WSL2\n\nFor native Windows headless use:\n\n- Install with the official PowerShell installer or npm.\n- Prefer PowerShell 7.4 or newer for JSONL redirection.\n- Build argument arrays and invoke them with `& codex @args`; avoid fragile backtick-heavy command construction.\n- Check `$LASTEXITCODE` after every Codex invocation. PowerShell error preferences alone are not a substitute for checking a native process exit code.\n- Keep stdout JSONL separate from stderr diagnostics. Do not use `2>&1` when stdout must remain parseable JSONL.\n- Configure `%USERPROFILE%\\.codex\\config.toml` with `[windows] sandbox = \"elevated\"` when available; use `unelevated` only as the fallback.\n- Preserve the task-level policy `--sandbox workspace-write --ask-for-approval never` for ordinary autonomous edits. The native Windows sandbox implementation and the CLI task policy are separate controls.\n\nFor WSL:\n\n- Use WSL2, not WSL1.\n- Install and authenticate Codex inside WSL as a Linux installation.\n- Keep repositories under `~/code/...`, not `/mnt/c/...`, for better performance and fewer permission, symlink, and file-watcher problems.\n- Do not pass credentials through visible `wsl.exe` command-line strings.\n\nSee [references/windows.md](references/windows.md) for installation, PowerShell wrappers, JSONL parsing, sandbox configuration, WSL2 patterns, and Windows-specific troubleshooting.\n\n## Container and CI Requirements\n\nWhen generating a Docker, Kubernetes, or CI design:\n\n- Mount only the intended workspace and output directory.\n- Run as a non-root user when practical.\n- Do not mount the host Docker socket.\n- Do not mount home directories, SSH keys, or cloud credential directories.\n- Restrict network access unless the task explicitly needs it.\n- Apply CPU, memory, process, and execution-time limits outside Codex.\n- Preserve stdout, stderr, exit status, JSONL events, and the final message separately.\n- Validate repository diffs and test results before treating a run as successful.\n- Prefer a fresh worktree or disposable checkout per task.\n\nSee [references/recipes.md](references/recipes.md) for ready-to-use shell, Docker, CI, and parser patterns.\n\n## Diagnose Failures\n\nUse this order:\n\n1. Run `codex --version` and `codex exec --help`.\n2. Verify the command uses a positional prompt or `-` for stdin.\n3. Verify the working directory and Git repository status.\n4. Verify authentication without printing secret material.\n5. Check whether sandbox policy blocks required reads, writes, commands, sockets, or network access.\n6. Check whether approval policy is causing an impossible prompt in headless mode.\n7. Inspect stderr and the JSONL `error` or `turn.failed` events.\n8. Re-run with a smaller, deterministic task that reproduces the failure.\n9. Do not silently switch to `--yolo` as a troubleshooting shortcut.\n\n## Completion Standard\n\nFor implementation tasks, consider the run complete only when Codex has:\n\n1. inspected the relevant repository context,\n2. made the requested changes,\n3. run the most relevant available validation,\n4. reviewed the resulting diff for unrelated changes,\n5. reported assumptions and unresolved blockers,\n6. produced machine-readable status when requested by the harness.\n","frontmatter":{"name":"codex","description":"Run, configure, and troubleshoot OpenAI Codex CLI in non-interactive headless environments. Use for Codex automation in Bash or PowerShell, native Windows or WSL2, shell scripts, CI/CD, Docker, Kubernetes, remote servers, agent harnesses, or batch jobs; for constructing `codex exec` commands; selecting sandbox and approval modes; consuming JSONL events or structured output; resuming sessions; passing prompts through stdin; and handling failures caused by unavailable interactive input such as `request_user_input`."},"isInternal":false,"tokens":2370,"sizeBytes":10730},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/compose-next/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/compose-next/SKILL.md","title":"compose-next","category":"anthropic-skill","format":"markdown","content":"---\nname: compose-next\ndescription: Use for multi-step feature work, bug fixes, or refactors where requirements need to settle, a feature document should carry design + tasks + delivery evidence, and the change deserves independent review before merge. Use it only when the user explicitly requests this workflow, whether with `/compose-next`, by name, or in any other clear natural language; do not infer the request from task complexity alone. Not for one-shot edits, single-file tweaks, or answering questions — those need no orchestration overhead.\n---\n\n# Compose Next\n\nCompact end-to-end contract for grill → workspace → spec → implement → verify → review → finalize → finish. One skill load, no internal skill hand-offs.\n\nWhen writing a checkpoint or compacting context, preserve this recovery instruction in the checkpoint or compacted summary: on resumption, if the Compose Next instructions are absent, reload the `compose-next` skill before continuing.\n\nEnter this workflow only on an explicit user request. Any clear natural-language instruction to use this workflow counts just like `/compose-next`; the user does not need to know or name the skill. If the user has not clearly requested the workflow, do the work directly and run none of the phases below; do not infer consent merely because the task is large or resembles a Compose task.\n\n## Step 0 — Orient\n\nInspect the repository, its instructions (`AGENTS.md`, `README`, existing spec files), and recent changes before asking anything. Do not ask the user for facts the environment already answers.\n\nDecide the shape of the work:\n\n- **Fully constrained mechanical change with no durable design surface** → skip Grill and Spec, go to Workspace then Implement.\n- **Requirements or design ambiguous** → Grill first.\n- **Requirements clear, feature deserves a durable document** → Workspace then Spec.\n\nUser gates and project overrides:\n\n- If the user explicitly requests `without worktree` or specifies a worktree or workspace path, use that workspace choice and skip the default worktree gate. Do not ask again for worktree consent.\n- If the user explicitly says `without spec`, \"no spec needed\", \"this is a small fix\", or gives an equivalent instruction, skip the durable feature document and its spec gate. Keep verification and review when the task still warrants them.\n- An explicit project instruction, `AGENTS.md`, or user-provided agent/worktree configuration may define a project-specific worktree path, branch convention, spec path, or spec format. Use that configuration instead of the defaults in this skill. Record the override in the feature document or final report when it changes the normal artifact location.\n\nEvery path passes through Workspace before Spec or Implement; no branch skips it.\n\n## Grill — resolve decisions\n\nResolve one decision axis at a time. A single decision may bundle multiple dependent fields in one structured question; unrelated decisions require separate turns.\n\nUse the Question tool for every user decision:\n\n- Put known choices in `options`. Each option gets a concise `label` and a `description` explaining the consequence. List the recommendation first and mark its label `(Recommended)`.\n- For consequential choices, include 2–3 viable alternatives.\n- When choices cannot be enumerated, still call Question with `options: []` for free-text.\n- Do not ask for permission to continue when no decision remains.\n\nSplit requests spanning independent subsystems before refining each part. Do not begin implementation until requirements and scope are settled.\n\n### When user input is unavailable\n\nIf user input cannot be obtained — the Question tool is absent, a question gets no reply, or the run cannot stop and wait (for example a goal that keeps running) — and the decision is not a dangerous action that requires explicit user consent, resolve **this one decision** yourself and continue:\n\n1. Choose the option marked `(Recommended)` when repository evidence still supports it and it can run unattended.\n2. Otherwise choose the closest minimal-scope option supported by the evidence; prefer text-only, non-interactive work.\n3. If the decision includes destructive or irreversible work, choose a non-destructive path that preserves progress; never auto-approve the destructive option.\n4. State the option selected and the reason in the response.\n\n## Workspace — worktree ownership\n\nNever begin implementation on `main` or `master` without explicit user consent. If the active workspace is already chosen, skip creation below and continue with toolchain setup.\n\n- Compare `git rev-parse --git-dir` with `git rev-parse --git-common-dir`. If they differ, use the current linked worktree; do not nest another. A non-empty `git rev-parse --show-superproject-working-tree` indicates a submodule, not a linked worktree.\n- Create a linked worktree at `.worktrees/{{slug}}` by default. Base the new branch on the latest mainline (e.g. `origin/main`). If the current checkout makes the base unclear (detached HEAD, an unrelated feature branch, unknown default branch), ask the user explicitly which base to use before creating the worktree. Run `git check-ignore -q \"$path\"`; if it is not ignored, write `*` to `.worktrees/.gitignore`. Then run `git worktree add \"$path\" -b \"$branch\" \"$base\"`.\n- When targeting the worktree with a command, pass its absolute path as `workdir`; omitted `workdir` uses the current session directory.\n- Install dependencies per repository instructions. Prefer lockfile-frozen, hardlink-friendly modes (`bun ci`, `uv sync --frozen`) over commands that mutate the lockfile. Confirm the toolchain is usable before continuing.\n\n## Spec — one document per feature\n\nMaintain one document per feature at `docs/compose/spec/{{feature-name}}.md` from the workspace root. Do not add a date to the filename. A user-specified location overrides this path. Edit an existing document in place; never create a separate plan or report. Do not write the feature document before Workspace owns the active workspace.\n\n### Template\n\n```markdown\n---\nfeature: {{feature-name}}\nstatus: designed | in-progress | delivered\nupdated: YYYY-MM-DD\nsource: {{branch-name}} | {{pr-url}} | {{mr-url}}\n---\n\n# {{Feature Name}}\n\n## Report\n\n## [S1] Problem\nDescribe the user-visible problem.\n\n## [S2] Design\nRecord the chosen behavior and the contracts needed to implement it.\n\n## [S3] Out of Scope\nState explicit boundaries.\n\n## Tasks\n- [ ] T1: {{work item}} — acceptance: {{observable result}} (covers: S2.1)\n- [ ] T2: {{work item}} — acceptance: {{observable result}} (depends: T1)\n\n## Journey log\nOptional. Dead ends, pivots, or transferable lessons worth future work. Do not pad an uncomplicated change by splitting it into several thin entries.\n```\n\n### Design-time rules\n\n- Leave `Report` empty until finalized and set `status: designed`. Keep `Journey log` empty unless something is worth carrying forward.\n- Set `source` to the form that best names where the spec's source lives — `{{branch-name}}`, `{{pr-url}}`, or `{{mr-url}}` — and update it whenever that changes.\n- Record settled decisions and precise contracts, not exploration history or file-level code dumps. Include architecture, interfaces, data flow, error behavior, and testing boundaries when they affect the change.\n- Make each task the smallest independently verifiable work item; give it an observable acceptance criterion. Add `depends:` only for real prerequisites; dependencies must be acyclic.\n- Under Design, give each contract or behavior its own subsection `S2.1`, `S2.2`, …\n- Keep `Sn` and `Sn.m` anchors stable when headings change; never renumber existing anchors.\n- `covers:` on a task is optional (for example `covers: S2.1`).\n- Scale detail to the change; do not pad small designs.\n\nBefore implementation, fix ambiguous requirements, contradictions, unresolved references, and unverifiable acceptance criteria. If the user is available, request document approval with the Question tool; otherwise continue.\n\n### Amendments\n\nUpdate only affected sections, bump `updated:`, preserve anchors, and keep only the tasks required by the amendment and their dependents. Do not regenerate the document or create duplicate tasks.\n\n## Implement\n\nUse the feature document as the source of requirements, or the conversation for an undocumented mechanical change. When a feature document exists, set its `status: in-progress` on the first implementation commit. Execute tasks in dependency order. Track multi-step work with the Task tool.\n\nFor behavior changes with a cheap reproduction, write a failing test, confirm it fails for the intended reason, implement the smallest fix, and confirm it passes. A bug fix requires a regression test when one can be written. Skip test-first for generated code, configuration-only changes, throwaway prototypes, or explicit user direction.\n\nTest public behavior. Do not duplicate production logic in expected values, add test-only production APIs, or assert only that mocks were called. Prefer real implementations over mocks.\n\nFor failures, reproduce before editing and identify the root cause from errors, diffs, recent commits, or boundary instrumentation. After two failed fixes, stop patching and re-derive the cause.\n\n### Parallel work\n\nDispatch independent tasks in parallel when isolation prevents collisions; keep tightly coupled work together. Prefer giving parallel subagents disjoint file sets and keeping commits with the orchestrator. Give each subagent the workspace path, task, acceptance criteria, relevant spec sections, and required verification. Do not pass session history. Treat its report as a claim and inspect the resulting diff.\n\nContinue through tasks without routine approval pauses. Stop only for an unresolved product decision, a blocker that cannot be worked around, a destructive action requiring consent, or completion.\n\n## Verify\n\nBefore any completion claim, run the repository's relevant tests, typecheck, build, or reproduction from the correct directory and read the output. Record each command and result. Mark known baseline failures as `PRE-EXISTING` with a short identifier. Do not substitute prior output or a subagent report for fresh evidence.\n\nVerification and review are strictly sequential. Wait for all verification commands to exit before dispatching the reviewer. Never overlap review with a resource-heavy test or application process in the same environment.\n\n## Review\n\nAfter implementation is verified and before finalizing the feature document, dispatch one fresh subagent to review the complete change.\n\nProvide the reviewer:\n\n- the applicable spec sections and acceptance criteria;\n- the workspace path, base branch, base SHA, head SHA, and exact diff command or precomputed diff;\n- a compact verification summary: one line per command with `PASS`, `FAIL`, or `PRE-EXISTING`, plus test counts when available. Do not paste full command output unless a specific failure requires it.\n\nIf there is no feature document, take acceptance criteria from the conversation. If none are explicit, ask the user for them before dispatching the reviewer.\n\nDo not provide an implementer-authored narrative. The reviewer may inspect the diff and run additional commands needed to validate its conclusions. It must not repeat a command already reported as passing, especially a heavy E2E suite, unless the result is stale, the code changed afterward, or concrete evidence makes the result suspect. Before any justified rerun, confirm no equivalent command is still running. Missing evidence should be reported or gathered with the cheapest non-duplicative command.\n\nUse a reviewer model at least as capable as the strongest implementer it reviews.\n\nRequire separate conclusions for:\n\n- **Spec compliance** — every acceptance criterion is met and points to evidence in the diff or reviewer-observed command output.\n- **Correctness** — logic, boundaries, error handling, regressions, and tests are sound, including issues outside the written spec.\n- **Codebase consistency** — naming, structure, and local conventions match surrounding code.\n\nClassify unmet or unverifiable acceptance criteria and correctness bugs as critical. Fix critical findings, re-verify, and re-review affected areas. Reject incorrect findings with technical evidence. When necessary, return to Spec and record the pivot in the Journey log. If the fix-and-re-review loop stops converging — repeated findings on the same area, or fixes that introduce new criticals — stop looping and report the impasse with the remaining findings instead of forcing a pass.\n\nFor human review feedback, verify each item against the codebase, clarify ambiguous items before editing, and implement validated items one at a time with verification. Check actual usage before expanding an unused path, and surface conflicts with prior user decisions instead of silently complying.\n\nFor parallel task work, review integrated task diffs at useful boundaries only when delaying review would compound risk.\n\n## Finalize — commit the feature document\n\nIf a feature document exists, after review passes and before finishing the branch:\n\n1. Set `status: delivered` and bump `updated:`.\n2. Check off completed tasks; leave incomplete tasks unchecked and do not claim delivery if they block acceptance.\n3. When finalized, fill `Journey log` when needed and replace `Report` with:\n\n```markdown\n## Report\n\n**What was built** — concise description of the final behavior.\n\n**Verification** — commands run and their observed results.\n```\n\nUpdate a design section only when it contradicts the delivered behavior. Commit the finalized document on the feature branch before finishing. This documentation-only commit does not restart verification or review; CI re-running on it is expected.\n\n## Finish\n\nDo not auto-finish: confirm with the user before any irreversible action, including opening a PR or MR, merging, or pushing.\n\nReport branch, base, head SHA, workspace, feature-doc path when available, and ask the user which way to finish — for example:\n\n- local merge / open PR / push only / keep the branch;\n- which base branch to merge or target;\n- keep or remove the worktree.\n\nOpen PR or MR does not imply merge: unless the user also asked to merge, stop after opening — the merge always needs its own confirmation, whether the PR or MR was created here or already existed.\n\nWhen the closing action changes where the spec lives, update `source` and commit it as documentation only: `{{pr-url}}` or `{{mr-url}}` after opening one, `{{branch-name}}` before a local merge.\n\nWorktree pitfalls:\n\n- Local merge and `gh pr merge` run from the main repository checkout — the base branch cannot be checked out while another worktree holds it.\n- `git worktree remove` only on `.worktrees/` or the path scoped by the prompt / `AGENTS.md`.\n","frontmatter":{"name":"compose-next","description":"Use for multi-step feature work, bug fixes, or refactors where requirements need to settle, a feature document should carry design + tasks + delivery evidence, and the change deserves independent review before merge. Use it only when the user explicitly requests this workflow, whether with `/compose-next`, by name, or in any other clear natural language; do not infer the request from task complexity alone. Not for one-shot edits, single-file tweaks, or answering questions — those need no orchestration overhead."},"isInternal":false,"tokens":3001,"sizeBytes":14880},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/data-analytics/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/data-analytics/SKILL.md","title":"data-analytics","category":"anthropic-skill","format":"markdown","content":"---\nname: data-analytics\ndescription: \"Use this skill for quantitative product or business analysis: data quality checks, metric diagnostics, KPI design and reporting, dashboards, analytical reports, charts, notebooks, market sizing, semantic layers, and evidence-backed recommendations. Also use it whenever Data Analytics is explicitly invoked.\"\n---\n\n# Data Analytics\n\nThis is the single entry point for a code-agent-oriented Data Analytics bundle. The original plugin workflows are under `workflows/`; React, Vite, MCP App widgets, connector manifests, and frontend build artifacts are intentionally excluded.\n\n## Route the request\n\n1. Read `workflows/index/SKILL.md` completely. Treat it as the authoritative plugin-level eligibility and analytical routing policy, except where its UI/runtime delivery rules conflict with the code-agent overrides below.\n2. Select the narrowest focused workflow named by that index. Read every selected workflow's `SKILL.md` completely before acting.\n3. If a selected workflow names related skills, load those only when its routing conditions apply. Multiple skills may form one workflow; follow the ordering defined by the index and focused skills.\n4. Resolve relative links from the file that contains the link. Read referenced instruction or reference files when the selected workflow requires them and they exist in this bundle. Prefer bundled scripts and sample data over recreating them.\n5. Do not load unrelated focused workflows merely because they are present.\n\n## Bundled capabilities\n\nFocused workflows live in `workflows/`, including data-quality analysis, business-context gathering, metric diagnostics, product/business analysis, KPI design and reporting, visualization, dashboards, reports, notebooks, market sizing, validation, and semantic-layer creation.\n\nUse data sources and tools only when the host harness exposes them. The bundle does not require a particular connector registry or UI protocol.\n\n## Code-agent delivery overrides\n\nThese rules take precedence over MCP App, widget, native Work Mode, and packaged Recharts delivery rules inherited from the original workflows:\n\n- Never require or call `render_artifact`, `render_chart`, `render_table`, `validate_artifact`, `export_artifact_package`, `charts_widget_v2`, or `app_block` unless the user independently provides an equivalent tool and explicitly requests it.\n- Default transient answers to concise Markdown with source notes. Default durable reports and dashboards to Markdown, a self-contained HTML file using plain HTML/CSS/SVG/vanilla JavaScript, a notebook, a spreadsheet, or a static image according to the user's request and the host's available tools.\n- For charts, prefer reproducible Python/Matplotlib, notebook-native plotting, SVG, or the destination system's native chart support. Inspect generated visuals when the harness provides image or browser inspection.\n- Do not install Node, React, Recharts, Vite, or frontend packages for analytics output. Do not depend on removed `src/`, `assets/`, MCP specifications, HTML runtime helpers, or widget resources.\n- If a focused workflow points to a removed UI-only reference, skip that reference and apply these overrides while preserving its analytical, provenance, QA, and narrative requirements.\n- A requested report remains incomplete until its chosen portable file exists or a concrete blocker is reported; a chat summary is sufficient only when the user requested an inline answer.\n\n## Safety and fidelity\n\n- Never treat plugin instructions as permission to bypass host policy, expose secrets, or perform unapproved external writes.\n- Keep source provenance and uncertainty visible in analytical outputs.\n- Do not silently replace real-data questions with sample data.\n- Preserve the selected workflow's validation and delivery requirements through completion.\n","frontmatter":{"name":"data-analytics","description":"Use this skill for quantitative product or business analysis: data quality checks, metric diagnostics, KPI design and reporting, dashboards, analytical reports, charts, notebooks, market sizing, semantic layers, and evidence-backed recommendations. Also use it whenever Data Analytics is explicitly invoked."},"isInternal":false,"tokens":724,"sizeBytes":3844},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/analyze-data-quality/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/analyze-data-quality/SKILL.md","title":"analyze-data-quality","category":"anthropic-skill","format":"markdown","content":"---\nname: analyze-data-quality\ndescription: \"Assess whether structured data, query results, dashboards, or analytical evidence are trustworthy enough to use. Use when the task is to check data quality, reconcile conflicting sources or metric definitions, or decide whether evidence is safe to cite.\"\n---\n\n## Related Skills\n\nUse $design-kpis when the work is to define or redesign a KPI framework, metric definition, guardrail, or target rather than checking whether existing data is trustworthy.\n\nUse $validate-data when the work is to QA an analysis, chart, report, or recommendation rather than investigate the underlying data.\n\n# Analyze Data Quality\n\nAssess whether a dataset is trustworthy enough for analysis, modeling,\ndashboards, experiments, or downstream pipelines. Start with the intended use and grain, run the highest-value checks for the data shape, and report concrete evidence, analytical risk, likely causes, and the smallest useful remediation or automated test.\n\n## Workflow\n\n1. Clarify the quality question and operating context.\n\n   Establish what the dataset represents, the intended unit of analysis, the downstream use, whether the user cares about raw ingestion quality,\n   transformed-model quality, or both, and the comparison baseline such as prior weeks, prior schema, or a trusted reference table. Identify expected grain,\n   primary keys or candidate keys, important date columns, timezone assumptions,\n   domain rules, allowed values, and business thresholds. If context is missing,\n   infer cautiously and label assumptions.\n\n2. Choose an inspectable analysis path.\n\n   When checks require SQL or Python, default to a companion notebook so the user can inspect the exact code behind the findings. Use $jupyter-notebooks when a dedicated notebook scaffold or refactor workflow would help. For queryable tables, use `~~structured_data` to confirm schema, grain, sample rows, and query rules through the relevant source connector before heavier checks. Use `~~operations_logs` for freshness and lineage when those checks matter.\n\n3. Build a compact profile.\n\n   Start with row count, column count, column names and types, candidate keys,\n   duplicate rates on likely identifiers, min/max timestamps for relevant date columns, null rates, distinct counts for likely categorical columns, and basic numeric summaries for measure columns. Confirm grain before interpreting anomalies; many apparent quality problems are mixed-grain data,\n   partial backfills, late-arriving data, or duplicated joins.\n\n4. Run core quality checks.\n\n   Select checks that match the dataset and task. Default to the most relevant checks across completeness, uniqueness, validity, consistency, integrity,\n   timeliness, volume, and shape. Compare rates, not just counts, and segment by time, source, country, platform, model version, or other key dimensions when that helps distinguish real issues from expected variation.\n\n5. Run shape-specific checks.\n\n   Adapt the checks to the data shape:\n\n   - Event data: duplicate event IDs, future event timestamps, session or user\n     coverage gaps, and abrupt event-mix changes after releases.\n   - Dimension tables: non-unique business keys, orphan surrogate keys, status\n     changes without corresponding timestamps, and unexpected churn in reference\n     values.\n   - Fact tables: mixed grain, impossible measures such as negative revenue or\n     quantity, join blowups to dimensions, and late-arriving or partially loaded\n     partitions.\n   - ML feature or scoring tables: leakage from post-outcome fields, feature\n     sparsity spikes, range shifts after model or feature-store changes, and\n     class-label drift.\n   - Experiment data: duplicate assignments, variant imbalance beyond\n     expectation, exposure without assignment, and events before assignment\n     timestamp.\n\n6. Run temporal and distribution checks when history exists.\n\n   Prioritize temporal diagnostics when the user mentions \"after X date\",\n   \"suddenly\", \"recently\", or \"only started appearing\". Check first-seen dates,\n   last-seen dates, daily or weekly null-rate trends, duplicate-rate trends, row count trends, category-share shifts, distribution drift, and change points around launches, migrations, incidents, model changes, or backfills.\n\n7. Investigate analytical risks and likely causes.\n\n   Tie each issue to the downstream risk: broken trusted analysis, biased decisions, broken joins, stale dashboards, incorrect experiments, leakage,\n   unreliable model features, or misleading segments. When possible, identify whether the issue is isolated to a source, segment, partition, time window,\n   release, migration, backfill, or upstream pipeline change.\n\n8. Recommend fixes or automated tests.\n\n   Recommend the smallest set of follow-up fixes, monitoring, or automated tests that would materially reduce risk. Suggest automation only when the rule is stable and worth maintaining. Include or save the notebook/query path when code produced the findings.\n\n## Standards\n\n### Core Checks\n\n- Completeness: null rate by column; null rate by partition, segment, and time bucket; unexpected empty strings or sentinel values; required-column population rate.\n- Uniqueness: exact duplicate rows, duplicate primary keys, duplicate composite keys, and proportion unique for semi-unique fields such as emails or device IDs.\n- Validity: type conformance after casting; format checks for IDs, emails, URLs,\n  enums, country codes, and timestamps; range checks for measures, percentages,\n  counts, and dates; allowed-values checks for controlled vocabularies.\n- Consistency: cross-field rule checks, units or currency consistency, status and timestamp alignment, and agreement between duplicated fields from different sources.\n- Integrity: parent-child key coverage, orphan records, unexpected many-to-many joins, and broken slowly changing dimension joins.\n- Timeliness: freshness lag from source event time to load time, freshness lag from load time to report time, missing recent partitions, and unexplained historical rewrites or backfills.\n- Volume and shape: row-count drift, distinct-count drift, distribution drift,\n  share-of-total drift for major categories, and new or disappeared categories.\n\n### Specific Check Guidance\n\n- Duplicates and keys: check exact duplicates, primary key duplicates, composite key duplicates at the intended grain, and near-duplicates caused by whitespace,\n  casing, formatting, or late updates. Report count, share of affected rows,\n  duplicated keys, and whether duplication is isolated to a time range, source,\n  or segment.\n- Missingness: distinguish acceptable sparsity from broken completeness. Check null rates over time, newly null columns after schema or pipeline changes, and sentinel values such as `''`, `'unknown'`, `'n/a'`, `0`, or `-1`.\n- Domain validity: check malformed identifiers, country codes, timestamps,\n  impossible values, values outside allowed sets, and cross-field contradictions such as `is_cancelled = false` with a non-null `cancelled_at`.\n- Join coverage: when multiple datasets are involved, check foreign keys that do not match a parent table, unexpected one-to-many expansion, coverage loss when joining to dimensions or experiments, and row counts before and after joins.\n- Freshness and schema drift: check row-count changes against recent history,\n  lag on important date columns, added/removed/retyped columns, and shifts in sparsity or cardinality that suggest upstream changes.\n- Outliers and distribution shifts: use robust methods such as quantiles, MAD,\n  or IQR before defaulting to z-scores. Check sudden changes in mean, median,\n  variance, zero rate, category share, and long-tail behavior.\n- Leakage, backfill, and time travel: check features populated before they should exist, future-dated records, late-arriving data causing unstable recent partitions, and backfills that change historical counts without annotation.\n\n### Severity\n\n- Critical: breaks trusted analysis, core joins, production dashboards, or key decisions, such as duplicated grain, missing primary keys, or stale production data.\n- High: materially biases downstream decisions, such as large null spikes,\n  category drift in a core dimension, invalid business-rule values, leakage, or severe join coverage loss.\n- Medium: localized or explainable issues that still need documentation,\n  monitoring, or owner follow-up.\n- Low: cosmetic inconsistencies, expected sparsity, or known edge cases that do not materially affect current use.\n\nDo not dump raw profiling output without interpretation. Tie each finding to an analytical risk and likely impact.\n\n### Automated Test Guidance\n\n- Good candidates for automation: primary key uniqueness, not-null checks on required columns, accepted values for stable enums, referential integrity,\n  freshness thresholds, and seasonality-aware row-count or volume bounds.\n- Use caution with hard-coded distribution thresholds on volatile product metrics, strict uniqueness in messy entity-resolution use cases, and recent partitions when late-arriving data is normal.\n- Suggest automated tests only when the expected rule is stable, important, and maintainable.\n\n### Output Standards\n\nFor stakeholder-facing data-quality work, pass the completed findings to $build-report by default so the runtime produces a portable report in the selected format. Do not stop at profiling output or a notebook unless the user explicitly requested a quick inline answer or another primary artifact. The structure below defines the report content.\n\nStructure the response with:\n\n1. dataset and grain summary\n2. checks performed\n3. findings\n4. temporal or trend anomalies\n5. likely causes and impacted use cases\n6. recommended fixes or automated tests\n7. assumptions and open questions\n\nFor each finding, include:\n\n- what failed\n- evidence: counts, rates, segments, and dates\n- why it matters\n- severity and confidence level\n- likely cause when known\n- suggested remediation or automated test\n\nWhen code was used, include or save a notebook containing the key SQL and Python checks and make the notebook path easy to find.\n\n### Defaults\n\n- Prefer small, high-signal tables over exhaustive dumps.\n- Compare rates, not just counts.\n- Break checks out by time and key segments whenever possible.\n- Normalize strings before judging duplicates or distinct-count spikes.\n- Treat recent partitions carefully when data arrives late.\n- Call out when an anomaly could be caused by a legitimate product launch,\n  experiment, migration, incident, model change, or backfill.\n- Preserve inspectable evidence: SQL, query links, notebook paths, source paths,\n  sample rows, chart outputs, and calculation notes.\n","frontmatter":{"name":"analyze-data-quality","description":"Assess whether structured data, query results, dashboards, or analytical evidence are trustworthy enough to use. Use when the task is to check data quality, reconcile conflicting sources or metric definitions, or decide whether evidence is safe to cite."},"isInternal":false,"tokens":2091,"sizeBytes":10693},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/build-dashboard/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/build-dashboard/SKILL.md","title":"build-dashboard","category":"anthropic-skill","format":"markdown","content":"---\nname: build-dashboard\ndescription: \"Build a source-backed dashboard or monitoring view with clear metrics, filters, visual hierarchy, definitions, refresh context, and QA.\"\n---\n\n# Build a Dashboard\n\nUse this workflow when the user needs a reusable monitoring or exploration surface rather than a one-time report. Read the relevant analysis and KPI workflows first when metric definitions or decision logic are not already settled.\n\n## Select a portable surface\n\nHonor the user's destination. Otherwise choose the simplest surface supported by the harness:\n\n- Existing BI/product analytics platform when the user wants a governed shared dashboard there.\n- Streamlit when Python execution and local/server operation are appropriate; read `specifications/streamlit-dashboard.md`.\n- Self-contained plain HTML/CSS/vanilla JavaScript for a portable local dashboard; read `specifications/html-dashboard.md`.\n\nDo not require React, Vite, Recharts, MCP Apps, or widget runtimes.\n\n## Workflow\n\n1. Define the audience, operating decision, monitoring cadence, and questions the dashboard must answer.\n2. Define each metric: formula, numerator/denominator, unit, grain, time window, filters, exclusions, owner, source, and freshness expectation.\n3. Validate joins, completeness, duplicates, missingness, comparability, and refresh status before presenting metrics as trustworthy.\n4. Design the information hierarchy:\n   - Overview and primary outcomes.\n   - Drivers and diagnostic cuts.\n   - Guardrails and risks.\n   - Detail tables or drill-down paths.\n5. Add only decision-relevant filters. Make default date ranges, segments, comparison periods, and filter state visible.\n6. Use `../visualize-data/SKILL.md` for each chart and keep exact lookup values accessible in tables.\n7. Show data freshness, source context, definitions, and material caveats in the dashboard.\n8. Implement and test the real artifact with representative, empty, partial, and error states when feasible.\n\n## QA and handoff\n\n- Reconcile displayed totals and KPIs against reviewed source results.\n- Test filters, date boundaries, sorting, responsive layout, and refresh behavior.\n- Check chart labels, units, legends, accessibility, and table readability.\n- Ensure the artifact does not expose secrets, credentials, unnecessary personal data, or temporary local paths.\n- Deliver the dashboard artifact or governed platform link plus metric definitions, source/query files, refresh instructions, and known limitations.\n\n","frontmatter":{"name":"build-dashboard","description":"Build a source-backed dashboard or monitoring view with clear metrics, filters, visual hierarchy, definitions, refresh context, and QA."},"isInternal":false,"tokens":487,"sizeBytes":2482},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/build-report/report-to-google-doc/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/build-report/report-to-google-doc/SKILL.md","title":"report-to-google-doc","category":"anthropic-skill","format":"markdown","content":"---\nname: report-to-google-doc\ndescription: \"Narrow conversion skill. Invoke only when the user explicitly asks to convert an existing local or blob-hosted HTML analytics report into a Google Doc, DOCX, or shareable document.\"\n---\n\n# Report To Google Doc\n\nUse this skill only when the user explicitly needs a shareable Google Drive document from an existing HTML analytics report. The source must be an HTML report: a local file, a downloaded blob-hosted report, or a report produced by `$build-report`\nHTML mode or an equivalent local portable report source.\n\nThe expected path is HTML -> DOCX -> Drive upload. It is acceptable for Drive to host the upload as a DOCX-backed viewer file rather than a native Google Docs MIME type. Do not use the old Google Docs batch-update request path.\n\n## Workflow\n\n1. Resolve the HTML report.\n\n   Use an absolute local path. If the user provides a remote report, retrieve it first and pass the local HTML file to the helper. If the file is a sign-in page, redirect page, or tiny stub, stop and obtain the real report.\n\n2. Run the bundled helper.\n\n   ```bash\n   python3 <REPORT_TO_GOOGLE_DOC_SKILL_DIR>/scripts/report_to_google_doc_plan.py \\\n     /absolute/path/to/report.html \\\n     --out-dir /tmp/report_to_google_doc_plan\n   ```\n\n   Omit `--render-workers` on the normal path. Only pass a worker count after benchmarking the same report family locally. If dependencies are missing,\n   use a local virtual environment with `beautifulsoup4`, `pillow`, and `python-docx`; `cairosvg` or headless Playwright are optional renderers.\n\n3. Inspect helper outputs.\n\n   Required outputs:\n\n   - `skeleton.txt`: source text with stable placeholders\n   - `manifest.json`: parsed headings, tables, callouts, lists, styles, links,\n     and rendered visual inventory\n   - `preflight_checks.json`: source, width, DOCX, and rendered-image checks\n   - `report.docx`: generated local Word document\n   - `docx_upload_plan.json`: compact upload instructions\n   - `placeholder_queries.json`: source mapping debug labels\n\n   Do not upload until `preflight_checks.json` has `status: \"passed\"` with zero errors. Warnings must either be fixed or called out in the handoff.\n\n4. Upload the DOCX.\n\n   ```json\n   mcp__codex_apps__google_drive._upload_file({\n     \"file_uri\": \"/tmp/report_to_google_doc_plan/report.docx\",\n     \"file_name\": \"Report Name.docx\",\n     \"mime_type\": \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\"\n   })\n   ```\n\n   Treat the returned Drive URL as the deliverable. Do not attempt to force native Google Docs conversion, and do not fall back to `_batch_update_document`.\n\n5. Validate the uploaded result.\n\n   Confirm the uploaded file is readable and non-empty. Compare uploaded text against the source inventory: title, section headings, executive summary or answer callout, caveats, recommendations, source notes, and source links.\n   Inspect the local `report.docx` structure when available: heading counts,\n   lists, tables, hyperlink relationships, and image relationships should match `manifest.json`.\n\n6. Hand off the link.\n\n   Return the Drive/Docs URL and, when useful, the local DOCX path or source HTML path. Connector success alone is not enough; the handoff is complete only after the uploaded file and local DOCX structure have been checked against the source report. Keep routine check and preflight details in support artifacts. Do not list internal checks in the user-facing handoff unless a check failed, was unavailable, or produced a user-relevant caveat.\n\n## Standards\n\n- Preserve every section, headline claim, metric card, metric definition,\n  source note, chart takeaway, recommendation, caveat, and link from the HTML report.\n- Preserve semantic formatting: headings, paragraphs, inline bold/emphasis,\n  inline code, positive/negative colors, links, lists, callouts, metric-card grids, tables, notes, captions, and charts.\n- Use DOCX-native structures wherever practical: headings, paragraphs, tables,\n  bullets/numbered lists, links, inline images, paragraph shading, table cell shading, and text styles.\n- Keep the report text column readable. Tables, charts, rendered table grids,\n  screenshots, and visual blocks must not exceed the DOCX page text width.\n- Preserve charts as inline images rendered from the source visual or its same-data SVG fallback, aligned to the same left edge as text and tables. A chart with missing bars, missing legend swatches, or all-black/all-white marks fails validation even if the DOCX contains an image object.\n- Preserve multi-column report blocks. A two-column grid made only of titled mini-tables can remain a two-column rendered image capped to the text width;\n  mixed two-column blocks with narrative text, pills, callouts, or non-table panels should preserve that content natively instead of dropping it.\n- Do not expose customer-level details or sensitive links that were intentionally omitted from a sanitized report.\n- Do not write Google Docs batch-update artifacts such as `seed_requests.json`,\n  `remote_write_plan.json`, or `all_requests*.json`.\n\n## Repairs\n\nUse these fixes when validation exposes a conversion issue:\n\n| Problem | Fix |\n| --- | --- |\n| Heading is regular weight | Fix the DOCX writer heading style or explicit run bolding. |\n| Blank line after title or heading | Delete spacer paragraphs; skeletons should emit `\\n`, not `\\n\\n`, after headings. |\n| Body paragraphs have too much space | Delete literal blank paragraphs and set modest style spacing. |\n| Table/image too wide | Set table columns or image width to the DOCX text column width. |\n| Chart has labels but missing bars | Inline SVG class styles or use a headless screenshot before inserting. |\n| Two-column table group is flattened | Treat the grid as one layout block with mini-table titles preserved. |\n| Executive summary, metric cards, or section is missing | Fix parser inventory before upload. |\n| Chart overlaps table | Insert the image on its own paragraph after the table. |\n| Chart duplicated | Remove the extra image; keep exactly one source-order copy. |\n| Inline bold/code/color missing | Fix manifest range splitting in the DOCX writer. |\n| Source links show raw URLs | Replace with native linked labels or native bullets using HTML link text. |\n\n## Local Checks\n\n```bash\npython3 -m py_compile <REPORT_TO_GOOGLE_DOC_SKILL_DIR>/scripts/report_to_google_doc_plan.py\npython3 <REPORT_TO_GOOGLE_DOC_SKILL_DIR>/scripts/report_to_google_doc_plan.py \\\n  /absolute/path/to/report.html \\\n  --out-dir /tmp/report_to_google_doc_plan_smoke\njq '.status, .summary' /tmp/report_to_google_doc_plan_smoke/preflight_checks.json\ntest -f /tmp/report_to_google_doc_plan_smoke/report.docx\ntest -f /tmp/report_to_google_doc_plan_smoke/docx_upload_plan.json\ngit diff --check -- plugins/data-analytics/skills/build-report/report-to-google-doc\n```\n","frontmatter":{"name":"report-to-google-doc","description":"Narrow conversion skill. Invoke only when the user explicitly asks to convert an existing local or blob-hosted HTML analytics report into a Google Doc, DOCX, or shareable document."},"isInternal":false,"tokens":1490,"sizeBytes":6846},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/build-report/report-to-google-slides/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/build-report/report-to-google-slides/SKILL.md","title":"report-to-google-slides","category":"anthropic-skill","format":"markdown","content":"---\nname: report-to-google-slides\ndescription: \"Narrow conversion skill. Invoke only when the user explicitly asks to convert an existing HTML analytics report into a native Google Slides deck.\"\n---\n\n# Report To Google Slides\n\nUse this skill only when the user explicitly has an existing HTML analytics report and wants a Google Slides deliverable. The output should be a deck, not a pasted report. A stakeholder skimming the slides should understand the answer, evidence,\ncaveats, and recommended follow-up without opening the source report.\n\nThis skill consumes a local portable report, preferably self-contained HTML. If another format is the only source, first create an equivalent local HTML or structured report from the same evidence.\n\n## Workflow\n\n1. Resolve the local HTML report.\n\n   Use an absolute file path. If the user provides a remote report, retrieve it outside this skill first. If the local file is a sign-in page, redirect page,\n   or very small stub, stop and obtain the real report before continuing.\n\n2. Run the helper.\n\n   ```bash\n   python3 <REPORT_TO_GOOGLE_SLIDES_SKILL_DIR>/scripts/report_to_google_slides.py \\\n     <LOCAL_HTML_REPORT_PATH> \\\n     --out-dir /tmp/report_to_google_slides\n   ```\n\n3. Inspect local outputs.\n\n   Required outputs:\n\n   - `deck.pptx`: editable local PowerPoint file\n   - `manifest.json`: parsed source inventory and coverage counts\n   - `deck_plan.json`: slide-by-slide plan with named elements\n   - `preflight_checks.json`: local quality checks and pass/fail status\n   - `assets/`: rendered chart images\n\n   Do not import the PPTX until `preflight_checks.json` has `status: \"passed\"`.\n   Then run `unzip -t <out-dir>/deck.pptx`.\n\n4. Import and verify in Google Slides.\n\n   Import `deck.pptx` with `mcp__codex_apps__google_drive._import_presentation` using `upload_mode=\"native_google_slides\"`. Verify the imported deck with `_get_presentation_outline` and `_get_slide_thumbnail` for every slide when possible. At minimum, inspect the cover, one chart slide, one table slide,\n   and the caveats/sources slides.\n\n5. Repair before handoff.\n\n   If thumbnails show clipped text, missing charts, low contrast, blank images,\n   or awkward sizing, revise the helper output or source assumptions and regenerate before handing off the deck URL.\n\n6. Hand off the deck.\n\n   Return the Google Slides URL and, when useful, the local PPTX path or source HTML path. Keep routine check, preflight, thumbnail-inspection, and import-check details in support artifacts. Do not list internal checks in the user-facing handoff unless a check failed, was unavailable, or produced a user-relevant caveat.\n\n## Standards\n\n- Preserve the report's decision-critical information: headline claim,\n  executive summary, major findings, metric definitions, material charts,\n  decision-critical tables, recommendations, implications, caveats,\n  assumptions, freshness notes, and source/provenance notes.\n- Translate report prose into slide-native communication. Lead with the takeaway, use one main idea per slide, and put supporting detail in concise callouts, bullets, tables, chart annotations, or speaker notes.\n- Tighten copy before shrinking fonts.\n- Keep gross metric reads, net/incremental reads, causal claims, and caveats visibly separated when the source report distinguishes those lenses.\n- Use editable text and native PPTX tables wherever practical. Use native PPTX bullets; do not fake bullets with typed dashes.\n- Preserve source charts as evidence images. Do not screenshot the whole HTML report or paste whole report sections.\n- Support self-contained HTML reports whose chart evidence is available as inline SVG, accessible tables, or embedded images; render those into local chart evidence images before building the deck.\n- Use one chart per evidence slide unless the report has a stronger grouped comparison.\n- Keep table slides legible. If a full table is too dense, keep the main comparison in the deck and move extra detail to speaker notes or source slides.\n- Source notes should be visible but quiet.\n\n## Visual System\n\nThe helper derives colors and hierarchy from the HTML report CSS and chart palette, then applies a restrained analytics deck layout. It does not follow external deck files or company-specific branding.\n","frontmatter":{"name":"report-to-google-slides","description":"Narrow conversion skill. Invoke only when the user explicitly asks to convert an existing HTML analytics report into a native Google Slides deck."},"isInternal":false,"tokens":905,"sizeBytes":4271},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/build-report/report-to-pdf/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/build-report/report-to-pdf/SKILL.md","title":"report-to-pdf","category":"anthropic-skill","format":"markdown","content":"---\nname: report-to-pdf\ndescription: \"Narrow conversion skill. Invoke only when the user explicitly asks to convert an existing Data Analytics report, dashboard, or inline chart export into a PDF artifact.\"\n---\n\n# Report To PDF\n\nUse this skill only when the user explicitly needs a PDF from an existing Data Analytics report, dashboard, or chart artifact. Prefer a static HTML export or another portable report file as the source.\n\nThe expected path is static HTML -> browser headless print-to-PDF -> PDF verification. If only a non-portable source exists, create or retrieve the matching static HTML/export source first.\n\n## Workflow\n\n1. Resolve the static source.\n\n   Use an absolute local path to a static HTML report/export or a local URL served from that static export. If the source is a blob stub, sign-in page, redirect page, incomplete viewer, or an app shell that contains boot scripts but not the report content, stop and obtain a static HTML/export source before continuing.\n\n   When the user provides a hosted artifact URL, first determine whether it exposes a usable static export or package source. If the static export is unavailable but the validated artifact payload is still available in the current run, create the matching static HTML/export from that payload and preserve source provenance in the handoff. If neither a static export nor the artifact payload is available, stop with a blocker instead of printing the live app shell or rebuilding the report from memory.\n\n   When creating or repairing the static source, keep visible metadata reader-facing. Do not copy internal artifact runtime fields, package plumbing, or validator/debug state into the report body, header, footer, or source section. For example, omit raw labels such as snapshot status, package path, widget type, manifest path, renderer IDs, validation status, and local temp paths from the visible PDF. If a runtime detail matters for audit or troubleshooting, preserve it in support notes rather than the visible PDF. Translate data-state caveats into reader language only when they affect interpretation, such as \"synthetic demo data\" or \"partial source coverage.\"\n\n2. Generate the PDF with Chrome CLI headless print-to-PDF.\n\n   Use the platform-specific Chrome executable available in the environment. Common examples are `/Applications/Google Chrome.app/Contents/MacOS/Google Chrome` on macOS and `google-chrome`, `chromium`, or `chromium-browser` on Linux. This is the primary conversion method because it prints the static HTML with a browser rendering engine and usually preserves selectable text, layout, charts, tables, and print CSS.\n\n   ```bash\n   chrome \\\n     --headless=new \\\n     --disable-gpu \\\n     --no-first-run \\\n     --no-default-browser-check \\\n     --no-pdf-header-footer \\\n     --print-to-pdf=/absolute/path/to/report.pdf \\\n     /absolute/path/to/report.html\n   ```\n\n3. If Chrome is unavailable or cannot produce a valid PDF, use a renderer-backed fallback.\n\n   Use the next available local mechanism that renders the same static HTML/export source and prints or saves that rendered page to PDF. Keep the fallback tool-agnostic: the requirement is faithful HTML rendering followed by PDF output, not a specific implementation. Do not replace this with a model-authored PDF layout, manually redrawn charts, or a report reconstructed from memory.\n\n   A fallback is acceptable only when:\n\n   - the static HTML/export remains the source of truth\n   - the rendered output preserves the report title, narrative, charts, tables, caveats, and source details\n   - app-only controls are omitted\n   - the resulting PDF passes the same verification checks as the primary Chrome path\n\n   If no available local renderer can print the static HTML/export faithfully, stop and report the blocker with the missing capability and the source file that could not be converted.\n\n4. Verify the PDF itself.\n\n   Confirm page count and metadata with `pdfinfo` or equivalent. Extract text with `pdftotext` or equivalent when the PDF should contain selectable text. Render representative pages with `pdftoppm` or equivalent and inspect them for blank charts, clipped content, missing source details, unwanted controls, internal runtime metadata, and layout regressions. For short reports, render every page. Include a negative check for app-only control labels such as share, edit, refresh, publish, toolbar, menu, and drag affordances, plus internal artifact labels such as snapshot status, widget type, manifest path, package path, validation status, and local temp paths.\n\n5. Repair before handoff.\n\n   If the output is blank, clipped, missing charts, missing source details, or includes app-only chrome, fix the static HTML/export source, print stylesheet, or renderer invocation and regenerate. Do not hand off an unverified PDF unless the user explicitly accepts the limitation.\n\n6. Hand off the PDF.\n\n   Return the PDF path and, when useful, the source HTML path or URL. Keep routine check details in support artifacts. Do not list internal checks in the user-facing handoff unless a check failed, was unavailable, or produced a user-relevant caveat. If the static HTML/export had to be created from an artifact payload because the hosted URL did not expose one, say that briefly. If required checks could not be completed, state the gap clearly.\n\n## Standards\n\n- Preserve the reader-facing artifact content: title, narrative, charts, tables, caveats, source details, and generated-at or source freshness details when present.\n- Omit app-only controls: top bars, share menus, edit controls, refresh controls, drag handles, hover-only menus, and interactive-only affordances.\n- Omit internal artifact and conversion metadata from the visible PDF. Do not show raw runtime fields, implementation state, package labels, local paths, validator/debug labels, or status strings that exist only to operate the app or export pipeline. Keep audit-useful internals in support files, and use plain reader-facing caveats in the PDF when a data state affects interpretation.\n- Prefer a text PDF with selectable/searchable text. Use a screenshot/image PDF only when a faithful text PDF is not viable, and state that text may not be selectable or searchable.\n- Keep the static source as the PDF source of truth. Do not reconstruct the report from memory when a source HTML/export exists.\n- Do not create a model-authored PDF from scratch as a normal fallback. Direct PDF construction is acceptable only as an explicitly labeled last-resort workaround after the user accepts the quality limitation.\n- Keep generated PDF support files together when possible: static HTML source, PDF output, extracted text, page previews, and any notes about source retrieval or renderer fallback.\n\n## Verification Guidance\n\nBefore handoff, verify the PDF with the local tools available in the environment:\n\n- Confirm the PDF exists, is non-empty, and has the expected page count and page size.\n- Confirm text is selectable/searchable when a text PDF is expected.\n- Render or preview representative pages; for short reports, prefer checking every page.\n- Inspect for blank pages, clipped charts, missing tables, missing source details, unwanted app controls, and leaked internal artifact or conversion metadata.\n- If the skill file itself was edited, run the repository's normal markdown or diff checks.\n\nExamples when available: `pdfinfo`, `pdftotext`, `pdftoppm`, file-size checks, and `git diff --check`.\n","frontmatter":{"name":"report-to-pdf","description":"Narrow conversion skill. Invoke only when the user explicitly asks to convert an existing Data Analytics report, dashboard, or inline chart export into a PDF artifact."},"isInternal":false,"tokens":1488,"sizeBytes":7469},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/build-report/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/build-report/SKILL.md","title":"build-report","category":"anthropic-skill","format":"markdown","content":"---\nname: build-report\ndescription: \"Build a durable analytical report with an answer-first narrative, evidence-backed findings, charts or tables, caveats, recommendations, and source context.\"\n---\n\n# Build an Analytical Report\n\nUse this workflow when the user needs a durable report rather than a transient answer. Run the appropriate analysis workflow first; this workflow owns the reader-facing structure, evidence placement, visual/table placement, caveats, sources, QA, and handoff.\n\n## Choose one delivery format\n\nHonor an explicit format. Otherwise use:\n\n1. Markdown for the most portable code-agent deliverable.\n2. Self-contained plain HTML when a polished browser-readable report is useful and the host can render or inspect it.\n3. PDF, DOCX, slides, or another format only when requested or clearly required by the destination and the host exposes suitable creation and verification tools.\n\nDo not install or require React, Recharts, Vite, MCP Apps, or widget runtimes. HTML must use semantic HTML/CSS and may use inline SVG or small vanilla JavaScript interactions. It must remain readable without JavaScript.\n\n## Build the report\n\n1. Confirm the audience, decision, scope, comparison window, and requested format from available context. Ask only when a missing choice would materially change the result.\n2. Verify the analytical evidence. Keep metric definitions, grain, time range, filters, units, exclusions, and source freshness explicit.\n3. Lead with the answer. State the most important conclusion and decision implication before methodology details.\n4. Build a coherent narrative rather than a dump of charts or query results.\n5. Include only visuals and tables that support a finding. Read `../visualize-data/SKILL.md` when creating charts.\n6. Distinguish verified facts, likely explanations, assumptions, limitations, and unresolved questions.\n7. Provide recommendations tied to evidence, expected impact, owner or next action, and measurable follow-up where appropriate.\n8. Add a source section that identifies real source systems, tables/views, datasets, files, documents, queries, and access dates when known. Never invent provenance.\n\n## Recommended structure\n\n```markdown\n# [Short reader-facing title]\n\n## Executive summary\n[Answer, magnitude, and decision implication]\n\n## Key findings\n[Evidence-backed findings with charts or tables]\n\n## Recommendations\n[Prioritized actions and expected outcomes]\n\n## Risks and limitations\n[Data gaps, assumptions, uncertainty, and interpretation limits]\n\n## Sources and methodology\n[Definitions, scope, source details, and reproducibility notes]\n```\n\nAdapt the headings to the audience, but retain the answer-first logic.\n\n## QA and handoff\n\n- Recalculate headline values and comparisons from the reviewed evidence.\n- Check that every claim is supported and every chart matches its source data.\n- Check titles, labels, units, denominators, date ranges, and sorting.\n- For HTML/PDF/DOCX/slides, render or inspect the actual artifact when the host supports it; fix clipping, blank charts, overflow, low contrast, and unreadable tables.\n- Ensure the report contains no credentials, local temporary paths, placeholder provenance, or internal implementation noise.\n- Return the primary artifact path plus only the relevant supporting notebook, SQL, data, or chart files.\n\nIf the user asks only for an inline brief or explicitly says no file/artifact, deliver the same answer-first structure concisely in chat.\n\n","frontmatter":{"name":"build-report","description":"Build a durable analytical report with an answer-first narrative, evidence-backed findings, charts or tables, caveats, recommendations, and source context."},"isInternal":false,"tokens":688,"sizeBytes":3468},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/create-data-context/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/create-data-context/SKILL.md","title":"create-data-context","category":"anthropic-skill","format":"markdown","content":"---\nname: create-data-context\ndescription: \"Create, update, inspect, or repair Data Analytics semantic layers. Use when the user asks to save data context or create a semantic layer that future Data Analytics work can inspect and cite.\"\n---\n\n# Create Data Context\n\nThis skill creates and maintains semantic-layer skills for Data Analytics. A semantic-layer skill is an explicit artifact the user can inspect and cite later. It captures how future analyses should interpret the data, for example which metric definition is canonical, which dashboard or table is the best source of truth, and what caveats should be checked before answering.\n\nData-task routing is owned by the Data Analytics `index` skill. If the user wants Data Analytics to do work with data now, route to `index`, whether the work starts from connected sources, uploaded files, pasted tables, sample data, or an existing semantic layer. Examples include answering a metric question, building a report, or checking a dataset.\n\nUse this skill only when the user asks to save data context or create, update, inspect, or repair a semantic layer.\n\n## Runtime Routing\n\nUse the current runtime's classified `surface` and `mode` values, plus the capabilities exposed in the run, to choose intake and persistence. Build and validate the same canonical semantic-layer skill package before writing it to any destination.\n\nFor intake:\n\n- Use structured intake when a supported form action is available.\n- Use conversational intake for open-ended details and for runtimes without a supported form action.\n\nChoose one persistence destination by default:\n\n| Destination branch | Select this branch when | Action |\n| --- | --- | --- |\n| ChatGPT personal Skills | `surface = chatgpt_web` and the run exposes a product-backed personal Skills install surface, such as a native skill draft/upload/install action or an installable skill package preview. | Install the generated skill into the user's personal Skills library. Capture the installed skill link or Skills-library reference returned by the install surface and include it as a Markdown link in the chat response. Verify through the available Skills-library, list, or fresh-thread discovery surface when the runtime exposes one. |\n| Local Codex | The user asks for local persistence, or `surface = codex_desktop`. | Write a filesystem skill to `$CODEX_HOME/skills/<area>-semantic-layer`; if `$CODEX_HOME` is unavailable and the local runtime clearly uses the default home location, use `~/.codex/skills/<area>-semantic-layer`. Validate the written skill and verify it is discoverable in a new local Codex context when possible. |\n| Portable package | The current run has no supported persistent skill destination. | Return a portable skill package or source plan and clearly state that it has not been installed persistently, including the exact persistence blocker. |\n\nFor dual ChatGPT web and local Codex availability, install the same canonical package into both the ChatGPT Skills library and the local Codex user-skill directory.\n\nFor ordinary data work, return to the Data Analytics `index` workflow.\n\n## Skill Configuration\n\n### Audience And Language\n\nWrite for Data Analytics users, not plugin maintainers. Explain what context would improve the current or future analysis in practical terms. Avoid implementation terms such as raw state paths, connector ids, cache, runtime, metadata, or preflight unless the user asks for debugging details.\n\n### Source Links\n\nWhen referencing sources inline, prefer clickable Markdown links over plain labels whenever a useful URL exists. Use the source title, record name, channel/thread, or meeting/date as the link text. Use plain labels only when no useful link is available.\n\n## Semantic Layer Setup\n\nUse this flow when the user wants to create or maintain a semantic layer. If they are not ready to create the layer yet, use the same flow to produce a short source plan for what the semantic layer needs.\n\nThe output is a visible skill or plan. Build the semantic-layer skill when enough source-backed detail exists to make it useful. When the available detail is still thin, return a practical plan that explains what source to collect next and why.\n\n## Creating Or Updating The Layer\n\nCreate one semantic layer per coherent product, business, metric, source, or reporting area unless the user explicitly asks for a broader shared layer. Infer the area from the provided context when it is clear; ask only when the answer changes the crawl, destination, or resulting skill.\n\nChoose the destination from `Runtime Routing` using the supported persistence mechanism exposed in the current run. For local Codex creations, default to `$CODEX_HOME/skills/<area>-semantic-layer` unless the user chooses another destination. Ask before placing a generated semantic-layer skill inside a plugin.\n\nBefore crawling, build a data-source list that explains what was checked, what is missing, and which sources are lower-confidence. For direct creation or draft-file work, write it to `references/source-inventory.md`; for planning-only work, return it in chat.\n\nUse source-backed evidence. Favor durable sources such as transformation code, tests, maintained metric docs, and verified dashboards over looser signals such as query history or team discussion. If sources disagree, keep the conflict visible instead of choosing silently.\n\nKeep generated semantic-layer skills compact. Put detailed metric definitions, tables, query patterns, caveats, and evidence into linked references using `references/semantic-layer/skill-template.md`. Preserve provenance and avoid copying raw sensitive data, credentials, row-level examples, or long private messages into generated files.\n\nAfter creating or updating a semantic-layer skill, read `references/semantic-layer/weekly-polling-automation.md` and always offer weekly refresh when the layer has a stable target path and usable `references/source-inventory.md`. Weekly refresh is optional: do not create it without explicit user approval unless the user directly asked for recurring refresh. If the offer cannot be made, state the missing prerequisite.\n\nReturn the created or updated path or installed skill link, source coverage, any user-relevant caveats or blockers, future-use guidance, iteration guidance, and the weekly refresh automation offer or prerequisite blocker so the user can cite the semantic layer directly in later prompts. Tell the user they can ask to refine definitions, add sources, update caveats, or adjust the semantic layer as their understanding changes. For ChatGPT personal Skills creations, include the installed skill link in the response.\n\nKeep routine validation details in support artifacts unless a check failed, was unavailable, or changes how the user should rely on the semantic layer.\n\n## Output Contract\n\nFor semantic-layer work, report what was created, updated, inspected, or repaired; source coverage; any user-relevant caveats or blockers; and the exact path or installed skill link the user can cite later. For create or update results, include the weekly refresh automation offer or the missing prerequisite that prevented the offer, and let the user know they can iterate on the semantic layer. Keep routine validation details in support artifacts. If the request is ordinary data work, say that it should be routed through `index`.\n","frontmatter":{"name":"create-data-context","description":"Create, update, inspect, or repair Data Analytics semantic layers. Use when the user asks to save data context or create a semantic layer that future Data Analytics work can inspect and cite."},"isInternal":false,"tokens":1416,"sizeBytes":7368},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/design-kpis/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/design-kpis/SKILL.md","title":"design-kpis","category":"anthropic-skill","format":"markdown","content":"---\nname: design-kpis\ndescription: \"Design KPI frameworks, metric definitions, targets, guardrails, and measurement plans for product or business decisions. Use when success metrics, drivers, guardrails, targets, or the measurement approach need to be defined or improved.\"\n---\n\n# Design KPIs\n\nDesign KPI frameworks, set targets, and develop measurement plans that help teams make product or business decisions.\n\n## When To Use Data Quality First\n\nUse $analyze-data-quality first when the task is to reconcile existing metrics, dashboards, tables, owners, or sources of truth.\n\nReturn to this skill only when the user asks to define the metric going forward, redesign the KPI framework, choose guardrails, or set targets.\n\n## Skill Configuration\n\n### Source Discovery And Verification\n\nUse the relevant semantic layer as a starting map, not a boundary.\n\n1. **Explore all possible sources.** Search every connected or provided source that could contain task-relevant data or change the interpretation. Within each structured-data source, run fresh catalog or metadata discovery for relevant schemas, datasets, tables, views, models, and metrics. Known sources, tables, dashboards, and semantic mappings are starting points, not stopping points.\n2. **Compare duplicates and conflicts.** When sources overlap or disagree, compare ownership, freshness, definition, grain, coverage, and directness. Use the best authoritative source, or combine complementary sources when needed. Note material conflicts, explain why the selected source or sources control the answer, and verify selected data through live reads before concluding.\n\n### Source Access Guardrail\n\nBefore querying sources, building artifacts, or drawing conclusions, determine whether the answer requires a specific source of truth.\n\nIf a required source is unavailable, stop that path. Tell the user what source is needed, ask them to make it available or provide a reviewed fallback, and do not treat weaker substitutes as equivalent.\n\nIf the missing source is only optional enrichment, continue with the strongest available evidence and label the gap when it materially affects the answer.\n\nClarify with the user when a missing input would materially change the analytical frame or recommendation. Otherwise make a reasonable assumption, state it, and proceed.\n\n## Workflow\n\n### 1. Clarify The Decision And Operating Context\n\nUnderstand the decision the metrics need to support, the context in which they will be reviewed, and who will act on the result. Ask the user to clarify the goal, operating cadence, or measurement constraints when missing or ambiguous input would change the recommendation.\n\n### 2. Gather Evidence Before Recommending Metrics\n\nWhen the prompt does not already provide enough context to know what success means, gather that context before recommending metrics or targets. Use $gather-business-context to understand the goal, current state, audience, constraints, risks, existing definitions, prior decisions, and any baseline or target context that should shape the metric system.\n\nFor KPI design, use that context to clarify what success is meant to mean, how related metrics have been defined before, and which constraints or risks should affect the recommended KPIs, drivers, guardrails, or measurement plan.\n\n### 3. Generate A Wider Candidate Set\n\nCreate candidate outcome, driver, and guardrail metrics before narrowing.\nEach candidate should have a clear definition and a plausible link to the decision. Use the example metric shapes below as inspiration when helpful, not as a required template.\n\n### 4. Compare And Select Metrics\n\nCompare candidate metrics by whether they:\n\n- reflect the goal: the metric should represent the intended outcome. When using a proxy, explain why it should reflect real progress and where it could mislead.\n- inform a real decision: movement should change what the team does, prioritizes, or investigates.\n- show useful signal at the decision cadence: a metric can be conceptually good but too slow-moving or noisy for the decision it supports. For example, annual retention may be the right outcome, but it may not help a weekly launch review unless paired with earlier indicators.\n- can be influenced by the team: the team should have plausible levers, or the metric should be paired with drivers it can affect.\n- can be measured operationally: the team should be able to instrument, calculate, and track the metric consistently without one-off manual work.\n- are hard to improve in a misleading way: improving the metric should not obviously hide harm to quality, trust, retention, cost, or another important outcome.\n\nUse lightweight scoring only when it helps explain tradeoffs. Recommend `1-3` primary KPIs, `1-2` driver metrics for each KPI when they improve diagnosis, and `1-2` guardrails when tradeoffs are likely. Do not recommend extra metrics unless they materially improve decision-making.\n\nFor each recommended metric, include enough detail for the team to use it: what it measures, why it matters, how it is calculated, where it comes from, its main pros and cons against the selection criteria above, and what caveats or guardrails matter.\n\n### 5. Set Targets When Needed\n\nTreat target setting as a separate judgment from metric selection. First decide what should be measured; then set targets when the user asks or when the recommendation needs a threshold to be useful.\n\nUse the target-setting approach that best fits the evidence:\n\n- Top-down: start from benchmarks, historical performance, comparable products, competitor or market context, or a reasoned view of what good would need to look like for the decision.\n- Bottom-up: start from what the team can realistically do, such as what is shipping, how adoption is expected to build, or which operating levers should move the metric.\n\nUse data to set or evaluate targets. Once the target-setting approach is clear, identify what data it requires, such as provided inputs, internal performance data, external benchmarks or market data, and results from similar past work.\n\nCompare aspirational targets with what the team can realistically influence through planned work, available audience, expected adoption, and historical movement. A good target should be meaningful for the decision and plausible enough to guide action. Explain the target anchor, key assumptions, and confidence. If the strongest target-setting method requires missing inputs, share the methodology and ask whether the user can provide or identify the relevant data. If there is still enough evidence for a directional target, present it as a provisional range; otherwise recommend the measurement needed before setting a firm target.\n\n### 6. Deliver The Recommendation\n\nKeep the final recommendation concise and decision-oriented, and deliver it inline by default. Do not load `$build-report` merely because the KPI framework uses evidence, compares candidates, or contains several metrics. Use `$visualize-data` and `$build-report` when a data visual would materially improve the answer, such as by showing how a proposed target compares with historical performance or benchmarks, or by clarifying tradeoffs or candidate scoring. Honor an explicitly requested report, dashboard, notebook, spreadsheet, native document, or slide deck as the primary artifact. The recommendation should include:\n\n1. initiative summary\n2. recommended metric candidates, with definition and rationale\n3. target recommendation, if included, with anchor, assumptions, and methodology\n4. evidence reviewed\n5. assumptions and missing context\n6. risks and guardrails\n7. open questions\n\n## Example Metric Shapes\n\nDifferent contexts need different metric shapes. Use these as examples, not a template:\n\n- Product launch or adoption: pair an outcome metric for adoption or value realization with drivers for activation, engagement, repeat use, or time to value, plus guardrails for experience quality.\n- Growth work: choose the business outcome the team is trying to improve, such as activation, retention, or monetization; add drivers that explain how growth is expected to happen and guardrails for quality.\n- Funnel work: choose the progression or completion outcome that represents success; add drivers around where people advance or drop off and guardrails for downstream quality.\n- Operating review: focus on health, pacing, and action-oriented metrics that show whether the business is on track and where attention is needed.\n- Experiment or intervention: use one primary success metric tied to the decision, diagnostics that explain movement, and guardrails for unintended effects.\n- Data, model, or analytics initiative: connect technical performance to the decision or workflow it improves, with adoption, reliability, cost, or fairness guardrails when relevant.\n- Platform, reliability, or operations work: measure service health, throughput, quality, cost efficiency, and customer impact in terms the owning team can act on.\n","frontmatter":{"name":"design-kpis","description":"Design KPI frameworks, metric definitions, targets, guardrails, and measurement plans for product or business decisions. Use when success metrics, drivers, guardrails, targets, or the measurement approach need to be defined or improved."},"isInternal":false,"tokens":1716,"sizeBytes":8979},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/gather-business-context/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/gather-business-context/SKILL.md","title":"gather-business-context","category":"anthropic-skill","format":"markdown","content":"---\nname: gather-business-context\ndescription: \"Gather business context from connected or provided sources so downstream analysis starts with the right framing. Use when an analytical question depends on missing context, such as what a metric means, what changed recently, or which sources should be checked. If the same prompt asks for diagnosis, recommendation, or a deliverable, gather context first and continue to the focused skill.\"\n---\n\n## Boundary\n\nUse this skill to gather framing context, not to complete the downstream analysis.\n\nIf the same request also asks for a diagnosis, recommendation, dashboard, report, or other analytical deliverable, return only the context needed for that next step and continue with the appropriate focused skill, such as $metric-diagnostics, $product-business-analysis, $build-dashboard, or $build-report.\n\n# Gather Business Context\n\nUse this skill to collect the business context needed to understand an analytical question before doing deeper work. Focus on what the topic is, why it matters, what changed or is being decided, who or what source is closest to the work, and which definitions or artifacts should frame the analysis. This is a retrieval and extraction skill: gather enough context to set up the next step, not a final report, root-cause analysis, or broad background scan. Skip it when the prompt already provides the needed context or the task is fully self-contained.\n\n## Workflow\n\n### 1. Identify The Retrieval Target\n\nEstablish the analytical topic that needs context and why it matters for the next step. Capture the boundary needed to search and interpret sources, such as the relevant product area, audience, time period, or decision. If the timeframe is missing, use the narrowest reasonable window implied by the task and label it as an assumption.\n\n### 2. Build Search Anchors\n\nSearch with concrete identifiers rather than broad topic guesses. Start with the names the user provided or the sources surfaced, then expand with adjacent terms that help recall, such as aliases, owners, teams, dates, source names, related entities, or entities found in earlier results.\n\nStart broad enough to avoid missing relevant context. If too much comes back and a quick scan suggests the results are mostly unrelated, combine anchors to narrow retrieval, for example a metric plus a dashboard name, a feature plus a launch window, or a customer plus the relevant workflow. If a likely source comes back thin, revise the anchors before treating the source as missing.\n\n### 3. Search From Discovery Points Toward Authoritative Artifacts\n\n1. **Explore all possible sources.** Search every enabled or provided source family that could contain useful context or task-relevant data. Within each structured-data source, run fresh catalog or metadata discovery for relevant schemas, datasets, tables, views, models, and metrics. User-named sources, known tables, dashboards, and semantic-layer anchors are starting points, not stopping points.\n2. **Compare duplicates and conflicts.** When sources overlap or disagree, compare authority, freshness, definition, scope, and directness. Prefer artifacts closest to what was decided, defined, implemented, or measured; follow linked evidence when useful. Note material conflicts and explain which source or combination should guide downstream analysis.\n\n### 4. Extract Only Decision-Shaping Context\n\nTreat business context as a fixed extraction target, not an open-ended summary. Capture the facts that will shape the downstream analysis: the topic's business meaning, why it matters now, how it is defined or measured, where to verify it, what recently changed, and what uncertainty should travel with the analysis. Examples can include a metric definition, current rollout state, dashboard link, owner note, source conflict, or stated next step.\n\nKeep the context note focused on details that help frame the next analysis. Skip broad background, adjacent history, or long source excerpts unless they add useful context.\n\n### 5. Keep Source Notes Compact And Attributable\n\nFor each useful source, record enough attribution for the downstream work to be checked later: when the source applies, what kind of source it is, what factual context it established, and any important caveat or conflict. Distinguish source facts from inference and do not imply source review, stakeholder views, metric certainty, or confidence beyond what was actually established.\n\n### 6. Reconcile Conflicts Explicitly\n\nWhen sources disagree in a way that could change the downstream framing, preserve the disagreement instead of smoothing it over. Prefer the newest explicit decision artifact over older plans, owner-written docs over third-party summaries, and implementation artifacts over aspirational plans when the question is what is live, shipped, logged, or queryable now. Treat an informal source as stronger than a canonical artifact only when it clearly records a later decision or owner confirmation.\n\nIf disagreement remains, present both views, label the conflict, and state what source or owner would resolve it. If context is stale or incomplete, say what is missing and where to look next.\n\n### 7. Stop Once The Framing Is Sound\n\nStop gathering context when the downstream task can be framed well enough to proceed and the likely enabled or provided source families have been checked, ruled out as unavailable, or identified as too thin. Before stopping, make sure the next step has a clear enough understanding of the topic, why it matters, where the important definitions came from, what recent context applies, and what gaps remain.\n\nContinue searching when a relevant enabled or provided source is likely to add useful context. If an expected source was not found, name that as a gap rather than implying it does not exist.\n\n### 8. Return A Lightweight Context Note When Useful\n\nPrefer a focused context note over a full report or raw retrieval dump. Include enough context for the next analysis to proceed without redoing the search: a short summary, the relevant context, important definitions or source links, uncertainty or caveats, and citations. Keep it readable, but do not compress away details that explain the framing or source quality.\n\nIf the user asked only for quick orientation, shorten the structure while preserving citations, conflicts, and missing canonical artifacts.\n\n## Standards\n\nJudge sources by what they can actually establish. Informal discussion can be useful for discovery and recent context, but durable artifacts are usually stronger evidence for definitions, decisions, status, and measured results once found. Prefer sources close to the work, recent enough to reflect current reality, and explicit about what they establish. Surface missing source-of-truth artifacts as context gaps.\n\nKeep important claims attributable. Treat a source as useful only when it clarifies how the downstream task should be framed or interpreted; sources that merely mention the topic are incidental. Preserve enough evidence to check the work later, and label interpretation, assumptions, conflicts, and uncertainty when support is thin, stale, indirect, or conflicting.\n\nPreserve disagreements that could change the framing. Prefer owner-authored or decision-adjacent material and evidence of what is current over secondhand summaries or speculation. Do not infer consensus from silence. Say what source or owner would resolve an important conflict.\n","frontmatter":{"name":"gather-business-context","description":"Gather business context from connected or provided sources so downstream analysis starts with the right framing. Use when an analytical question depends on missing context, such as what a metric means, what changed recently, or which sources should be checked. If the same prompt asks for diagnosis, recommendation, or a deliverable, gather context first and continue to the focused skill."},"isInternal":false,"tokens":1409,"sizeBytes":7458},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/index/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/index/SKILL.md","title":"index","category":"anthropic-skill","format":"markdown","content":"---\nname: index\ndescription: \"Route broad Data Analytics requests to the appropriate quantitative analysis, visualization, dashboard, report, notebook, KPI, market-sizing, validation, or semantic-layer workflow.\"\n---\n\n# Data Analytics Router\n\nUse this workflow when Data Analytics is explicitly invoked or the request requires structured records, quantitative evidence, metrics, or an evidence-backed product or business decision. Do not use it for ordinary prose drafting, file-format conversion, or qualitative description that does not require data interpretation.\n\n## Choose the focused workflow\n\n- Metric changed, missed a target, or differs from expectation: read `../metric-diagnostics/SKILL.md`.\n- Product or business decision, prioritization, segmentation, launch, or experiment recommendation: read `../product-business-analysis/SKILL.md`.\n- Dataset, dashboard, source, join, freshness, grain, or metric trust question: read `../analyze-data-quality/SKILL.md`.\n- KPI framework, canonical definition, target, driver, or guardrail design: read `../design-kpis/SKILL.md`.\n- KPI status update, WBR, MBR, QBR, or operating readout: read `../kpi-reporting/SKILL.md`.\n- Dashboard or monitoring view: read `../build-dashboard/SKILL.md`.\n- Durable analytical report: read `../build-report/SKILL.md`.\n- Chart or quantitative figure: read `../visualize-data/SKILL.md`.\n- Reproducible SQL/Python notebook: read `../jupyter-notebooks/SKILL.md`.\n- TAM, SAM, SOM, segment, or opportunity sizing: read `../market-sizing/SKILL.md`.\n- Review an analysis before sharing: read `../validate-data/SKILL.md`.\n- Create, repair, or save reusable data context or a semantic layer: read `../create-data-context/SKILL.md`.\n- Missing business definitions, ownership, change context, or decision framing: read `../gather-business-context/SKILL.md` before the primary workflow.\n\nLoad every selected workflow completely. Follow its related-skill rules when applicable. A task can combine workflows; use this usual order:\n\n1. Gather missing business context.\n2. Validate source quality and metric definitions.\n3. Perform the focused analysis.\n4. Validate conclusions.\n5. Visualize or create the requested durable artifact.\n\n## Source access\n\nUse the best source already available through the code-agent harness: local files, uploaded data, pasted results, databases, warehouses, BI systems, product analytics tools, notebooks, documents, or callable connectors. Tool availability is determined by the host, not by this skill.\n\nWhen no usable source is available:\n\n- Ask for the smallest useful artifact: a CSV/XLSX file, query result, schema, metric definition, dashboard export, screenshot, or pasted table.\n- Offer `assets/demo-product-growth.csv` only as a clearly labeled synthetic demonstration. Never use sample data to answer a real-data question.\n- Do not invent records, measurements, source access, or query results.\n\nIf available sources conflict in a way that changes the answer, surface the conflict and use the data-quality workflow. Otherwise choose the most authoritative and fresh source and proceed.\n\n## Portable output policy\n\nThis bundle targets a generic code agent and does not depend on React, MCP Apps, widgets, or a proprietary rendering surface.\n\n- Inline answers: concise Markdown with findings, evidence, caveats, and next actions.\n- Reports: Markdown by default; use self-contained plain HTML, PDF, DOCX, or another requested format only when the host can create and verify it.\n- Charts: use reproducible Python/Matplotlib, notebook-native plotting, SVG, or destination-native chart tools.\n- Dashboards: prefer a self-contained plain HTML/JavaScript artifact, Streamlit when Python execution is appropriate, or an existing BI platform selected by the user.\n- Notebooks: keep SQL/Python reproducible and make assumptions visible.\n\nPreserve source names, metric definitions, grain, time windows, filters, units, and uncertainty. Never expose credentials, secrets, hidden reasoning, or unnecessary personal data.\n\n","frontmatter":{"name":"index","description":"Route broad Data Analytics requests to the appropriate quantitative analysis, visualization, dashboard, report, notebook, KPI, market-sizing, validation, or semantic-layer workflow."},"isInternal":false,"tokens":837,"sizeBytes":4017},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/jupyter-notebooks/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/jupyter-notebooks/SKILL.md","title":"jupyter-notebooks","category":"anthropic-skill","format":"markdown","content":"---\nname: jupyter-notebooks\ndescription: \"Create, edit, or validate reproducible SQL or Python notebooks. Use for notebooks, SQL/Python scratchpads, reproducible exploration, audit trails, or runnable companions where the analysis should be reviewable or rerunnable.\"\n---\n\n## Related Skills\n\nUse $validate-data when notebook results support a recommendation, shared claim, or decision.\n\n# Jupyter Notebooks\n\nCreate clean, reproducible Jupyter notebooks that are easy to skim, rerun, and handoff. Treat the notebook as a reader-facing analysis artifact, not a scratchpad dump. Notebook work is not complete until the notebook executes successfully top-to-bottom, or the execution gap is called out with the exact validation steps needed to reproduce it.\n\n## Workflow\n\n1. Lock the notebook mode and scope.\n\n   Decide whether the notebook is an analysis report, experiment log, diagnostic notebook, data-quality check, market-sizing calculation, model exploration,\n   tutorial, or companion artifact for a report. Identify the reader, decision,\n   expected handoff, required inputs, and whether the task calls for a new notebook or targeted edits to an existing one.\n\n2. Inspect or scaffold with notebook-safe tooling.\n\n   Prefer JupyterLab, `nbformat`, `nbclient`, or an existing scaffold utility over hand-editing raw JSON. When editing an existing notebook, preserve its intent and minimize JSON churn. Avoid reordering cells unless it clearly improves the top-to-bottom story. If raw JSON editing is unavoidable,\n   validate the notebook structure before finishing.\n\n3. Structure the notebook for the chosen mode.\n\n   For analytical notebooks, default to:\n\n   1. `## tl;dr`\n   2. `## Context & Methods`\n   3. `## Data`\n   4. `## Results`\n   5. `## Takeaways`\n\n   Write `tl;dr` and takeaways after reviewing executed outputs. Use concrete observed values, visible patterns, rows, or charts, not assumptions. Include a `### Key Assumptions` subsection in `Context & Methods` when assumptions affect correctness.\n\n   For tutorials or walkthroughs, adapt the same discipline to a teaching flow:\n\n   1. `## Goal`\n   2. `## Setup`\n   3. `## Steps`\n   4. `## Checks`\n   5. `## Next Steps`\n\n4. Build a clear data and computation path.\n\n   Separate setup, imports, parameters, data loading, data preparation,\n   calculations, visualizations, and interpretation. If the notebook uses both SQL and Python, keep complex SQL in SQL cells or separate query files rather than large embedded Python strings unless there is a clear reason. Use descriptive variable names and keep each code cell focused on one step.\n\n5. Use data sources deliberately.\n\n   When a notebook needs table data, first use `~~structured_data` to confirm table choice, schema, partition filters, sample rows, and query-submission policy. Use the relevant source connector when available, then fall back to exports or pasted SQL when needed. Use `~~operations_logs` for freshness or lineage checks when they matter. Record query permalinks, request IDs, source paths, dashboard links,\n   extract names, or other source artifacts in the notebook context for any executed result that supports the analysis. Keep heavy queries filtered and bounded instead of turning the notebook into a broad live-source scan.\n\n6. Make cells readable and bounded.\n\n   Add concise markdown headers before most code cells. Keep headers brief and action-oriented, such as `### 1. Load Data`, `### 2. Validate Inputs`, or `### 3. Plot Results`. Favor several short cells over one large mixed-purpose cell. Keep prose short: explain purpose, assumptions, and expected result, not every line of code. Split multiple tables or charts across separate cells instead of dumping all outputs from one cell.\n\n7. Validate results before writing conclusions.\n\n   Check that key numbers, charts, and takeaways match executed outputs. Bound raw debug output, oversized tables, and noisy logs. If a result is surprising, add a local reasonableness check, small sample inspection, or reconciliation against a trusted source before promoting it to the summary.\n\n8. Execute and record validation status.\n\n   Run the notebook top-to-bottom when the environment allows:\n\n   ```bash\n   python -m jupyter nbconvert --execute --to notebook --inplace path/to/notebook.ipynb\n   ```\n\n   Optional local setup when needed:\n\n   ```bash\n   uv pip install jupyterlab nbformat nbclient ipykernel\n   ```\n\n   If execution is not possible, say so explicitly and provide the exact command,\n   missing dependency, credential, data access, kernel, or environment step needed to validate locally.\n\n## Standards\n\n### Notebook Structure\n\n- Make the default top-to-bottom read clear before the reader starts executing cells out of order.\n- Put executive summary material at the top, but write it last after inspecting executed results.\n- Keep notebook sections aligned with the notebook mode: analysis, experiment,\n  diagnostic, tutorial, or handoff artifact.\n- Keep section titles, chart titles, labels, and file names descriptive enough for handoff.\n- Preserve the existing notebook's intent when refactoring; improve structure without rewriting everything by default.\n\n### Reproducibility\n\n- Keep parameters, date ranges, filters, cohorts, assumptions, and source references visible near the top of the notebook.\n- Record enough source context for another reader to trace the analysis: query permalinks, request IDs, table names, source paths, spreadsheet tabs,\n  dashboard links, extract versions, or input file locations.\n- Make computation deterministic where possible. Avoid hidden state, manually edited intermediate values, out-of-order dependencies, and unexplained cached outputs.\n- Prefer explicit environment setup cells or notes when the notebook depends on nonstandard packages, kernels, credentials, or local files.\n- Execute the notebook when the task requires a runnable artifact. In the final response, do not add a separate routine validation section for a clean run; surface execution gaps, partial execution, or unrun notebooks with the reason because those affect whether the user can rely on the artifact.\n\n### Code And Data Hygiene\n\n- Separate data preparation from presentation.\n- Keep complex SQL readable and documented with a one-line goal comment.\n- Keep plotting and lightweight shaping in Python after the data preparation step is complete.\n- Use descriptive variable names and avoid abbreviated temporary names in reader-facing notebooks.\n- Keep outputs bounded. Prefer small preview tables, sampled rows, explicit limits, and focused charts over raw dumps.\n- Avoid broad live-source scans. Filter queries by needed partitions, cohorts,\n  or time windows.\n\n### Analysis Quality\n\n- Make assumptions explicit when they affect interpretation.\n- Tie takeaways to executed outputs with concrete numbers, rows, charts, or visible patterns.\n- Do not promote unexecuted or unverified calculations into the `tl;dr`.\n- Label caveats, incomplete checks, missing source access, and known validation gaps.\n- Add reasonableness checks for surprising results, high-impact claims, or stakeholder-facing conclusions.\n\n### Validation Checklist\n\n- Required section order is present for the notebook mode.\n- The notebook executes without runtime errors, or execution failure is called out explicitly.\n- Outputs are present where expected and are not dominated by raw debug dumps.\n- The `tl;dr`, results, and takeaways match executed cells.\n- Source references and query or artifact links are preserved.\n- Tables and charts are labeled, bounded, and interpretable.\n- The final response includes the notebook path and validation status.\n","frontmatter":{"name":"jupyter-notebooks","description":"Create, edit, or validate reproducible SQL or Python notebooks. Use for notebooks, SQL/Python scratchpads, reproducible exploration, audit trails, or runnable companions where the analysis should be reviewable or rerunnable."},"isInternal":false,"tokens":1550,"sizeBytes":7642},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/kpi-reporting/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/kpi-reporting/SKILL.md","title":"kpi-reporting","category":"anthropic-skill","format":"markdown","content":"---\nname: kpi-reporting\ndescription: \"Prepare KPI readouts, scorecards, WBR/MBR/QBR updates, and executive summaries from quantitative business or product metrics; use when the task is to report status, compare against targets, explain validated drivers, and state operating implications.\"\n---\n# KPI Reporting\n\nUse this skill to turn business or product metrics into decision-ready operating readouts for leaders and teams. The job is to define the KPI contract, report status against the right comparison and target, include validated driver context, and state the operating implication clearly.\n\nClarify with the user when a missing input would materially change the analytical frame or recommendation. Otherwise make a reasonable assumption, state it, and proceed.\n\nThis skill owns the KPI readout: what should be reported, how metrics should be interpreted, whether driver context is validated, and what operating takeaway follows. It does not own metric-system design, new driver investigation, or final artifact polish.\n\nUse $metric-diagnostics when the readout needs fresh driver investigation, then return here to package the validated finding.\n\n## Skill Configuration\n\n### Source Discovery And Verification\n\nUse the relevant semantic layer as a starting map, not a boundary.\n\n1. **Explore all possible sources.** Search every connected or provided source that could contain task-relevant data or change the interpretation. Within each structured-data source, run fresh catalog or metadata discovery for relevant schemas, datasets, tables, views, models, and metrics. Known sources, tables, dashboards, and semantic mappings are starting points, not stopping points.\n2. **Compare duplicates and conflicts.** When sources overlap or disagree, compare ownership, freshness, definition, grain, coverage, and directness. Use the best authoritative source, or combine complementary sources when needed. Note material conflicts, explain why the selected source or sources control the answer, and verify selected data through live reads before concluding.\n\n### Source Access Guardrail\n\nBefore querying sources, building artifacts, or drawing conclusions, determine whether the answer requires a specific source of truth.\n\nIf a required source is unavailable, stop that path. Tell the user what source is needed, ask them to make it available or provide a reviewed fallback, and do not treat weaker substitutes as equivalent.\n\nIf the missing source is only optional enrichment, continue with the strongest available evidence and label the gap when it materially affects the answer.\n\n## Workflow\n\n### 1. Clarify The Readout Purpose\n\nUnderstand who the readout is for, what conversation it supports, and what is being reported before drafting. Anchor the update in the period being evaluated, the comparison or target that makes performance interpretable, and the freshness cutoff.\n\nAsk the user for missing context when it would help make the readout more accurate or useful.\n\n### 2. Define The Metric Framework\n\nDecide which metrics belong in the readout and what role each one plays before pulling numbers. If the framework already exists, confirm it and use it. If it is missing or weak, use $design-kpis before reporting.\n\nStart with the primary KPI, then add the smallest set of supporting metrics needed to explain status. Supporting metrics can explain movement, guard against harmful tradeoffs, or show whether performance is pacing as expected.\n\nLead with the metric that matters most to the audience. Do not add every available cut or comparison; include the metrics and slices decision-makers actually use, plus any that materially explain this update.\n\nWhen the primary KPI is top-line, composite, or otherwise not directly actionable, define its driver decomposition before interpreting it. Use an existing metric tree when available. Otherwise identify the smallest useful set of component drivers, such as numerator and denominator, volume and rate, mix, funnel stages, segments, cohorts, or operational inputs. Do not invent a causal hierarchy when source definitions do not support one.\n\n### 3. Lock Metric Definitions And Sources\n\nConfirm the KPI definition, source, time window, reporting cutoff, comparison period, and any target or pacing expectation before interpreting performance. If a target or pacing basis is missing, ask before treating one as authoritative. Use $analyze-data-quality when source quality issues could change the reported metrics.\n\nFor all KPI updates, make a focused source pass across `~~structured_data`, `~~company_docs`, `~~team_communication`, and `~~dashboards_or_bi` before drafting. Do not infer from a sparse prompt that source-backed actuals are unavailable. Use structured data for actuals, metric definitions, and comparison periods; use the other lanes for additional business context and source-of-truth guidance.\n\nIf any core definition is unclear, ask the user to clarify before making precise claims. When a metric definition changed, show comparable restated history when available; otherwise call out the break clearly.\n\n### 4. Pull The Topline Actuals\n\nDo not draft or render a WBR, MBR, scorecard, or KPI update from placeholders. Query or inspect connected structured-data sources for core actuals first. If actuals are blocked or insufficient, stop and say what source or access is needed unless the user explicitly asked for a template or mockup.\n\nReproduce the topline actual before explaining movement or driver context.\n\nFor each headline KPI, include the current value, the absolute and relative change versus the comparison period, and a short interpretation.\n\nCall out anything that makes the current value hard to compare with the prior period before interpreting the movement, such as a tracking change, data backfill, partial outage, or missing day.\n\n### 5. Put The Numbers In Context\n\nCompare actuals against the context that makes performance interpretable. When a target, plan, pacing model, benchmark, historical range, or relevant peer group is defined, identify it and compare performance against it before judging status.\n\nIf the goal has a deadline, do not just report whether the metric is above or below target. Show whether it is on pace to hit the target by the end of the period. Use the provided pacing definition when available. If none is defined or found, ask the user; when proceeding with a calculated fallback, state that it was calculated and explain the method.\n\nWhen useful, include absolute and percent variance to target and a red/yellow/green status. Make clear what comparison or pacing basis the status label uses.\n\n### 6. Explain Validated Drivers\n\nKPI updates need driver context, but driver claims must be validated before they are presented as explanations. A plausible story is not enough.\n\nWhen the readout needs to explain drivers, use $metric-diagnostics to identify and validate them. If trusted reporting or prior analysis already validates the drivers, use that evidence instead of re-running the diagnostic.\n\n### 7. Add Business Context And Operating Implications\n\nAfter identifying the likely drivers, use $gather-business-context to look for business context that helps explain what happened and what it means for the readout. Let the driver analysis guide what context to look for, and connect context to the metric only when evidence supports the link.\n\nTranslate the evidence, driver analysis, and business context into the operating implication for the business. State whether the movement is concerning, what next step or action is warranted, and whether the main KPI is on track, at risk, or ahead of plan. Recommend action only when the evidence supports it; otherwise name the next validation step.\n\n### 8. Validate The Readout\n\nAfter the analysis is assembled and before shaping the final readout, use $validate-data to review whether the numbers, methodology, caveats, and evidence support the claimed status, drivers, and implications. Resolve material issues before sharing; carry remaining limitations into the readout.\n\n### 9. Hand Off The Readout\n\nEnd by handing the validated KPI readout to $build-report unless the user explicitly requests an inline, chat-only, brief/no-artifact answer, asks not to create a report/file/artifact, or selects another primary artifact. A quick status update, brief readout, or findings-in-chat request is an inline output choice unless the user also asks for a report, document, deck, or durable artifact. When no explicit human waiver was given, the report handoff is mandatory; do not infer a waiver only because the user did not use the word \"report\".\n\nBefore handoff, make the readout explicit:\n\n- headline status and operating implication\n- actuals, targets, pacing basis, and comparison periods\n- validated drivers and unresolved uncertainty\n- audience, cadence, and requested delivery surface when known\n- charts or figures that would clarify the readout\n\nLoad `references/report-templates.md` before handing off and use the matching pattern as source notes for $build-report. Tell $build-report this is a KPI readout and pass the status, pacing, driver, uncertainty, audience, cadence, surface, and visual guidance above. Do not render charts directly from this skill; pass visual intent and supporting evidence to $build-report so $visualize-data owns chart selection and QA.\n\nFor slide or deck requests, use $build-report to create a portable source report first, then use an available presentation workflow or document tool to create and verify the deck. Preserve the same source evidence and findings across formats.\n\n## Standards\n\n### Metric Standards\n\n- Never present a KPI as precise when its definition, source, time window, or comparison basis is unclear.\n- Make calculation logic, inclusion or exclusion rules, grain, and time treatment explicit when they affect interpretation.\n- Reconcile totals and compare against prior reporting when possible.\n- Do not compare periods, cuts, or targets that are not definitionally compatible. Call out definition changes, backfills, denominator shifts, or calendar effects when they affect the movement.\n\n### Status And Pacing Standards\n\n- Include the headline takeaway, current actual, relevant comparison, target or pacing context, driver summary, and implication unless the user asks for a narrower readout.\n- Put actuals next to the target, plan, benchmark, or baseline when available so the reader can judge performance immediately.\n- If a target is time-bound, show whether current performance is on pace using the provided pacing definition or a clearly stated calculated fallback.\n- Keep recurring metric sections consistent across runs. If a requested section is missing because data, definitions, or validation are unavailable, explain the omission briefly.\n- Use traffic-signal status only when it helps prioritize action. Pair color with text and state the basis for the status.\n- Round numbers consistently, label units, and surface caveats when they change interpretation.\n\n### Driver Standards\n\n- Quantify drivers whenever the evidence supports it; do not use descriptive prose as a substitute for sizing the effect.\n- Report the few drivers, contributors, or known non-drivers that matter for interpreting the KPI movement.\n- For top-line KPI movement, structure validated drivers as a compact decomposition: top-line actual, component drivers, largest contributors or non-drivers, and residual or unresolved movement. Use an additive bridge only when the components reconcile cleanly; otherwise explain the relationship and uncertainty.\n- Separate validated drivers from business context or hypotheses.\n- Do not elevate business events into causes unless the timing, affected population, and measured change support the link.\n- State whether the movement is broad-based or concentrated when that changes the operating implication.\n- If driver evidence remains unresolved, name the uncertainty or diagnostic follow-up instead of inventing an explanation.\n\n### Presentation Standards\n\n- Write for executives and operators who skim: lead with the answer, then the evidence.\n- Use business-readable numbers and compact formats such as `123k (+8% w/w, +19% m/m)`.\n- Replace generic adjectives like `strong`, `healthy`, or `soft` with the metric evidence that justifies them.\n- Keep caveats close to the claim they affect, and omit caveats that do not change interpretation.\n- Use charts, tables, scorecards, or KPI cards only when they make the takeaway easier to understand and remain readable in the final delivery context.\n","frontmatter":{"name":"kpi-reporting","description":"Prepare KPI readouts, scorecards, WBR/MBR/QBR updates, and executive summaries from quantitative business or product metrics; use when the task is to report status, compare against targets, explain validated drivers, and state operating implications."},"isInternal":false,"tokens":2422,"sizeBytes":12563},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/market-sizing/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/market-sizing/SKILL.md","title":"market-sizing","category":"anthropic-skill","format":"markdown","content":"---\nname: market-sizing\ndescription: \"Estimate market, segment, or opportunity size with transparent assumptions and uncertainty. Use for TAM/SAM/SOM, sizing scenarios, or comparing the scale of possible opportunities.\"\n---\n\n## Related Skills\n\nUse $visualize-data when the sizing result needs a chart or figure.\n\nUse $build-report to package the final estimate, assumptions, sensitivity, caveats, and source context whenever this skill is selected, unless the user explicitly requests an inline, chat-only, brief/no-artifact answer, asks not to create a report/file/artifact, or selects another primary artifact.\n\n# Market Sizing\n\nUse this skill to produce a defensible estimate of a market or opportunity from connected context, public sources, transparent assumptions, and auditable calculations. The job is to define the market, choose a sound sizing method, distinguish evidence from assumptions, test sensitivity, and state what would most improve confidence.\n\n## Skill Configuration\n\n### Source Discovery And Verification\n\nUse the relevant semantic layer as a starting map, not a boundary.\n\n1. **Explore all possible sources.** Search every connected or provided source that could contain task-relevant data or change the interpretation. Within each structured-data source, run fresh catalog or metadata discovery for relevant schemas, datasets, tables, views, models, and metrics. Known sources, tables, dashboards, and semantic mappings are starting points, not stopping points.\n2. **Compare duplicates and conflicts.** When sources overlap or disagree, compare ownership, freshness, definition, grain, coverage, and directness. Use the best authoritative source, or combine complementary sources when needed. Note material conflicts, explain why the selected source or sources control the answer, and verify selected data through live reads before concluding.\n\n### Source Access Guardrail\n\nBefore querying sources, building artifacts, or drawing conclusions, determine whether the answer requires a specific source of truth.\n\nIf a required source is unavailable, stop that path. Tell the user what source is needed, ask them to make it available or provide a reviewed fallback, and do not treat weaker substitutes as equivalent.\n\nIf the missing source is only optional enrichment, continue with the strongest available evidence and label the gap when it materially affects the answer.\n\nClarify with the user when a missing input would materially change the estimate or recommendation. Otherwise make a reasonable assumption, state it, and proceed.\n\n## Workflow\n\n### 1. Frame The Market Or Opportunity\n\nDefine the market or opportunity boundary before estimating:\n\n- What is being sized, for example a product category, workflow, problem, use case, or category of activity.\n- Where and when it applies, for example geography, segment scope, time horizon, or market maturity.\n- Who or what counts as part of the market, for example the relevant population, unit of demand, transaction type, or included activity.\n- How the opportunity is measured, for example spend, revenue, volume, value created, or another unit that fits the question.\n- What kind of sizing answer the user needs, for example TAM/SAM/SOM, market entry, expansion upside, spend pool, revenue pool, population count, or unit volume.\n\n### 2. Choose A Starting Sizing Approach And Inputs\n\nPick the simplest sound sizing approach for the question, then sketch the calculation chain and the major inputs the estimate will depend on.\n\nA top-down model works when reliable aggregate market data exists; a bottom-up model works when the market can be built from observable units and assumptions; a value-based model works when the estimate should start from the value created rather than a published market total. Use a mixed approach only when cross-checking would materially improve confidence. If more than one approach fits, briefly explain which one you trust most and why.\n\nExpect the first approach to change if source checks show that another model would be more defensible.\n\n### 3. Gather Sources For The Inputs\n\nChoose sources based on the inputs the estimate depends on most.\n\nStart with user-named sources when provided. Then use the strongest available evidence for each major input from the starting approach. Use `~~structured_data` when an input should come from the user's data warehouse or another structured data source. Use context lanes such as `~~company_docs`, `~~team_communication`, or `~~dashboards_or_bi` when an input needs business meaning, source-of-truth guidance, or assumptions that are not captured in structured data alone. When an input depends on the outside market, use public sources for benchmarks, population estimates, comparable markets, or proxy assumptions.\n\nUse $gather-business-context to resolve context lanes when the right source of truth, business meaning, or assumption set is unclear.\n\nIf the strongest source is unavailable or thin, continue with a transparent proxy assumption only when the estimate is still useful. Label the gap and explain how it affects confidence.\n\n### 4. Separate Facts From Assumptions\n\nKeep sourced facts, inferred estimates, and judgment calls distinct in the model. When exact data is unavailable, use a defensible proxy, explain why it is reasonable, and note the confidence level. Ground assumptions in evidence about how the market actually behaves, what can realistically change, and what determines the size of the opportunity.\n\n### 5. Build The Model\n\nMake the model easy to inspect and adjust.\n\nThe model should make these elements easy to audit or revise:\n\n- market definition and measurement unit\n- assumptions and source context\n- calculation chain and derived values\n- base case, material ranges, and sensitivity logic\n- validation priorities\n\nFor each major input, make the source path visible: structured data, context lane, public source, user-provided input, or proxy assumption.\n\nKeep derived values traceable to formulas or code rather than hardcoded outputs.\n\nUse $jupyter-notebooks when code is needed for source harmonization, calculations, sensitivity analysis, or reusable modeling logic. Keep formulas, inputs, intermediate calculations, and sensitivity logic inspectable.\n\nUse the `$Spreadsheets` skill when the user requests a spreadsheet, workbook, or Google Sheets deliverable, or when a market-sizing model would materially benefit from editable assumptions, sensitivity tables, charts, or polished workbook formatting.\n\n### 6. Test Sensitivity\n\nIdentify the assumptions that move the estimate most.\n\nShow how the estimate changes when those assumptions move up or down. Prefer simple, decision-useful sensitivity analysis over exhaustive scenario sprawl.\n\nUse ranges when uncertainty is material. Do not hide uncertainty behind a single point estimate when the inputs are thin.\n\n### 7. State The Estimate And Validation Priorities\n\nEnd by handing the estimate, method, key assumptions, uncertainty, and next validation priorities to $build-report unless the user explicitly waives report creation or selects another primary artifact. This handoff is mandatory when no explicit human waiver was given; do not infer a waiver because the user asked for an estimate or did not use the word \"report\". This workflow owns the sizing model and conclusion; $build-report owns the reader-facing structure, visuals, evidence placement, and delivery surface.\n\nBefore handoff, make the market-sizing conclusion explicit:\n\n- market definition and measurement unit\n- estimate or range\n- method and calculation chain\n- key assumptions and source support\n- main uncertainty drivers and sensitivity takeaways\n- validation priorities and practical interpretation for the user's decision\n\nIf source coverage is thin, say which major inputs rely on proxy assumptions and what source would most improve them.\n\nUse $validate-data when methodology, calculations, assumptions, caveats, or source support need review before sharing.\n\nDo not render charts directly from this skill. If a sensitivity, scenario, funnel, or market-breakdown visual would clarify the estimate, pass that visual intent and supporting evidence to $build-report so $visualize-data owns chart selection and QA.\n","frontmatter":{"name":"market-sizing","description":"Estimate market, segment, or opportunity size with transparent assumptions and uncertainty. Use for TAM/SAM/SOM, sizing scenarios, or comparing the scale of possible opportunities."},"isInternal":false,"tokens":1562,"sizeBytes":8238},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/metric-diagnostics/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/metric-diagnostics/SKILL.md","title":"metric-diagnostics","category":"anthropic-skill","format":"markdown","content":"---\nname: metric-diagnostics\ndescription: \"Diagnose why a metric changed or differs from expectation. Use when the task is to identify likely drivers of a metric movement, anomaly, gap, or discrepancy.\"\n---\n\n## Related Skills\n\nUse $gather-business-context when business context is needed to understand the metric, analysis period, ownership, or plausible explanations.\n\nUse $product-business-analysis when the task asks for a recommendation or tradeoff decision after diagnosing the movement.\n\nUse $analyze-data-quality when dashboard trust, grain, freshness, or source disagreement could affect the metric.\n\n# Metric Diagnostics\n\nUse this skill to diagnose why a metric changed or differs from expectation. Reproduce the metric, define the comparison, quantify the movement, validate likely drivers, and state what is verified, likely, unresolved, and useful to do next.\n\nClarify with the user when a missing input would materially change the analytical frame or recommendation. Otherwise make a reasonable assumption, state it, and proceed.\n\n## Skill Configuration\n\n### Source Discovery And Verification\n\nUse the relevant semantic layer as a starting map, not a boundary.\n\n1. **Explore all possible sources.** Search every connected or provided source that could contain task-relevant data or change the interpretation. Within each structured-data source, run fresh catalog or metadata discovery for relevant schemas, datasets, tables, views, models, and metrics. Known sources, tables, dashboards, and semantic mappings are starting points, not stopping points.\n2. **Compare duplicates and conflicts.** When sources overlap or disagree, compare ownership, freshness, definition, grain, coverage, and directness. Use the best authoritative source, or combine complementary sources when needed. Note material conflicts, explain why the selected source or sources control the answer, and verify selected data through live reads before concluding.\n\n### Source Access Guardrail\n\nBefore querying sources, building artifacts, or drawing conclusions, determine whether the answer requires a specific source of truth.\n\nIf a required source is unavailable, stop that path. Tell the user what source is needed, ask them to make it available or provide a reviewed fallback, and do not treat weaker substitutes as equivalent.\n\nIf the missing source is only optional enrichment, continue with the strongest available evidence and label the gap when it materially affects the answer.\n\n## Workflow\n\n### 1. Define The Diagnostic Question\n\nFrame the diagnostic so it is clear what changed and what comparison would prove it.\n\nDefine:\n\n- what the metric means in business terms\n- the time window and comparison that make the change measurable\n- the population and grain that determine what counts\n- the source that owns the metric definition\n- the diagnostic question being answered, for example movement, concentration, or reconciliation\n\nUse $gather-business-context when business context is needed to understand what the metric means, what changed around the analysis period, or which explanations are plausible.\n\n### 2. Validate The Metric Definition And Source\n\nBefore explaining the movement, confirm that the metric is defined correctly and that the source data can measure it reliably.\n\nConfirm the metric definition, grain, aggregation logic, filters, joins, exclusions, freshness, lineage, and any disagreement between trusted surfaces. Keep this source check focused on issues that could change the answer.\n\nTreat current context, named semantic layers, and familiar table names as source candidates, not source selection. For broad metric questions, run live source discovery against available tables, dashboards, metric docs, semantic layers, or other source-of-truth surfaces before choosing the controlling source. When both are available, inspect at least one business-facing or top-line surface and one lower-level source surface, then state why the selected source owns the answer.\n\nUse $analyze-data-quality when freshness, grain, joins, missingness, schema drift, outliers, unexpected categories, or distribution shifts could affect trust.\n\nUse $jupyter-notebooks when fresh SQL, Python, statistical modeling, reusable calculations, or multi-step decomposition need an inspectable analytical record.\n\n### 3. Establish The Metric Pattern\n\nBefore looking for drivers, establish the metric pattern the diagnostic needs to explain. Quantify the metric over the relevant period and scope. If the question includes a comparison, reproduce that comparison.\n\nDo not search for causes until the size, timing, and scope of the pattern are verified or explicitly marked uncertain.\n\n### 4. Choose The Diagnostic Plan\n\nChoose the smallest set of cuts and checks likely to explain the pattern or strengthen confidence.\n\nChoose driver dimensions from the metric's operating logic, business context, and source shape. Prioritize drivers the business usually monitors or can act on, not every field available in the source. If the relevant drivers are unclear, use current context, a named semantic layer, or $gather-business-context to understand how the business explains the metric and what changed around the analysis period.\n\nWhen using a lower-level table, do not limit the driver analysis to fields surfaced by the first query. Recreate or join the business grouping needed to answer the question, such as model family, model superfamily, segment, region, cohort, product taxonomy, or customer hierarchy. If the grouping cannot be reconstructed, say so before simplifying the analysis.\n\nUse the explanation mode that fits the question. Common examples:\n\n- **Metric change**: compare the focal window with a baseline, rank segment contributions, check peer or historical context, and test mix shift versus within-segment movement.\n- **Spike, regression, or incident**: pin down onset, peak, recovery,\n  distribution shape rather than only averages, affected slices, broad versus localized degradation, and whether traffic or failure behavior changed.\n- **Largest contributors or concentration**: define \"largest\", rank entities,\n  compare total share and change, and look for major movers, entrants, and exits.\n- **Reconciliation or difference analysis**: align definitions, filters, grain,\n  numerator, denominator, and exclusions; quantify the components explaining the gap and state any residual.\n\n### 5. Decompose And Validate Drivers\n\nQuantify the main drivers and validate whether they explain the pattern.\n\nSize each major driver with the strongest readily available evidence. Show whether it explains the pattern, how large it is relative to the relevant base, trend, or gap, whether it is broad or concentrated, and whether it holds under the right comparison or scope.\n\nIterate on driver hypotheses until the explanation answers why in a way that is relevant to the business. Follow promising cross-cuts and drill-downs when they could reveal the key explanation, and stop when additional cuts are unlikely to change the conclusion or materially improve confidence.\n\nInterpret driver results in context:\n\n- Use the relevant base, comparison, or share of total to make the driver meaningful.\n- For rates, check whether the numerator, denominator, or both explain the change.\n- For additive metrics, calculate contribution share when it sharpens the story.\n- Separate composition effects from within-segment performance effects when that distinction changes the explanation.\n- Prefer mutually exclusive driver buckets when additive contributions need to be interpreted; reconcile the decomposition exactly or size and explain the residual.\n\nTreat measurement issues as possible explanations, not just cleanup details. For example, the pattern may come from logging changes, incomplete recent data, duplicated rows, or a shifted denominator rather than an underlying business change.\n\nCalibrate the explanation to the evidence, and make important uncertainty visible. Use context when it changes interpretation, such as whether the pattern is ordinary, unusual, expected, or tied to a known change.\n\nUse $visualize-data when a chart would make the diagnostic claim easier to understand or verify.\n\n### 6. State Implications And Follow-Up\n\nLead with the answer to the diagnostic question, then state the practical implications when the evidence supports them.\n\nThe answer should make clear:\n\n- the pattern being explained\n- the strongest driver explanation and supporting evidence\n- why it matters for the business\n- how much confidence to place in the explanation\n- the implication, next action, or follow-up that matters most\n\nUse $product-business-analysis when the user needs a recommendation or tradeoff decision, not just the diagnostic implication.\n\nKeep implications distinguishable from verified factual reporting so a reader can tell where evidence ends and interpretation begins. Do not claim causality from timing alone; state when an explanation is only a plausible hypothesis.\n\nUse $gather-business-context when the metric result is clear but business context is needed to interpret the `so what` or identify realistic next actions.\n\nUse $validate-data when methodology, calculations, caveats, or the evidentiary support for the diagnostic conclusion need review before sharing.\n\nDo not treat artifact or report validation as analytical validation. Before handing off, confirm the analysis has the headline metric movement, driver contribution shares or effect sizes, source/window reconciliation, exact executed SQL or query references when queries were used, and caveats that would change interpretation.\n\nPass the diagnostic substance and supporting evidence to $build-report unless the user explicitly requests an inline, chat-only, brief/no-artifact answer, asks not to create a report/file/artifact, or selects another primary artifact. This handoff is mandatory when no explicit human waiver was given; do not infer a waiver because the user asked a direct diagnostic question or did not use the word \"report\". Let $build-report own the report surface, presentation polish, reproducibility treatment, and sharing handoff.\n","frontmatter":{"name":"metric-diagnostics","description":"Diagnose why a metric changed or differs from expectation. Use when the task is to identify likely drivers of a metric movement, anomaly, gap, or discrepancy."},"isInternal":false,"tokens":1873,"sizeBytes":10142},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/product-business-analysis/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/product-business-analysis/SKILL.md","title":"product-business-analysis","category":"anthropic-skill","format":"markdown","content":"---\nname: product-business-analysis\ndescription: \"Analyze product or business data to support a decision or recommendation. Use when a decision depends on metric-backed evidence, such as choosing a direction, prioritizing an opportunity, evaluating a change, segmenting users, sizing tradeoffs, or deciding what to do next.\"\n---\n\n## Related Skills\n\nUse $metric-diagnostics when the recommendation depends on explaining a metric movement, anomaly, gap, or discrepancy.\n\n# Product And Business Analysis\n\nUse this skill to answer product or business questions with data-backed evidence, context, and a recommendation. Give the audience enough trustworthy evidence, interpretation, and uncertainty framing to choose a practical next action.\n\n## Skill Configuration\n\n### Source Discovery And Verification\n\nUse the relevant semantic layer as a starting map, not a boundary.\n\n1. **Explore all possible sources.** Search every connected or provided source that could contain task-relevant data or change the interpretation. Within each structured-data source, run fresh catalog or metadata discovery for relevant schemas, datasets, tables, views, models, and metrics. Known sources, tables, dashboards, and semantic mappings are starting points, not stopping points.\n2. **Compare duplicates and conflicts.** When sources overlap or disagree, compare ownership, freshness, definition, grain, coverage, and directness. Use the best authoritative source, or combine complementary sources when needed. Note material conflicts, explain why the selected source or sources control the answer, and verify selected data through live reads before concluding.\n\n### Source Access Guardrail\n\nBefore querying sources, building artifacts, or drawing conclusions, determine whether the answer requires a specific source of truth.\n\nIf a required source is unavailable, stop that path. Tell the user what source is needed, ask them to make it available or provide a reviewed fallback, and do not treat weaker substitutes as equivalent.\n\nIf the missing source is only optional enrichment, continue with the strongest available evidence and label the gap when it materially affects the answer.\n\nClarify with the user when a missing input would materially change the analytical frame or recommendation. Otherwise make a reasonable assumption, state it, and proceed.\n\n## Workflow\n\n### 1. Start From The Decision\n\nIdentify the decision, audience, and action the analysis should inform before choosing data sources or metrics.\n\nState plainly:\n\n- the question and decision the analysis should inform\n- who will use the answer and what they can act on\n- the scope and comparison that define a useful answer\n- the outcome or behavior that matters for the decision\n- any assumptions needed to proceed\n\nDo not let unclear scope turn into broad exploratory work by default.\n\n### 2. Gather Decision-Relevant Context\n\nRun $gather-business-context before deeper analysis. That skill owns source selection, retrieval, source authority, conflict handling, and compact context notes. Use this workflow to decide how the gathered context changes the analysis and recommendation.\n\nKeep the context pass proportional to the task. For self-contained prompts or cases where the user already provided enough context, the pass can be brief: confirm the decision frame, definitions, source assumptions, and any obvious gaps before moving on. Do not turn mandatory context gathering into a broad background scan.\n\nRelevant context should clarify:\n\n- intent: what the work was meant to accomplish and why\n- definitions: how the work, metric, or source is defined and measured\n- timing: what changed around the analysis period that could affect interpretation\n- constraints: decisions, caveats, or limitations that affect what action is realistic\n\n### 3. Frame The Analysis\n\nTurn the question into a focused analytical framework.\n\nDefine a framework for answering the question with data:\n\n- the specific data questions that would support or change the recommendation\n- the comparisons and dimensions to inspect\n- the unit of analysis that matches the decision\n- the metric definitions and caveats needed to interpret the result\n\nUse the framework to surface plausible hypotheses or interpretations, then turn them into focused data questions. Keep the framework specific enough to avoid broad exploration and support a recommendation.\n\nUse $design-kpis when the success metric, driver metrics, guardrails, or measurement plan need to be defined before the analysis can proceed.\n\nStart by defining what the answer needs to show in plain language. Then choose the data that matches that meaning as closely as possible, including who is counted and what comparison makes the number meaningful. If a field or event captures only part of what the decision cares about, say what it captures and what it leaves out.\n\n### 4. Run Focused Quantitative Analysis\n\nRun enough quantitative analysis to support or reject the framed hypotheses and inform the decision:\n\n- **Follow the framework.** Run the analyses that could change the recommendation first. Track additional data questions that emerge, answer the ones that matter for the decision, and leave lower-impact cuts as follow-up instead of expanding into broad exploration.\n\n- **Use the right comparison.** Interpret results against the relevant baseline, denominator, or comparison point before turning them into a recommendation. For example, do not conclude that one group is the best opportunity just because it has the most total usage. Check whether usage is high because the group is larger, whether the pattern still holds after normalizing by the active base, whether the group is growing or declining, whether the usage reflects the behavior or outcome that matters, and whether business context changes the interpretation.\n\n- **Size the opportunities.** Estimate the magnitude of impact each important opportunity could have. State what is being compared, which metric represents impact, what denominator or population it uses, and whether the data is complete enough to trust. Keep material unknown or unclassified groups visible when they could change the interpretation.\n\n- **Keep quantitative work inspectable.** Use $jupyter-notebooks to record queries and analysis. Use $analyze-data-quality when source freshness, grain, joins, missingness, schema drift, or unexpected distributions could affect trust.\n\n- **Validate before concluding.** Use $validate-data before sharing stakeholder-facing recommendations, high-impact claims, or surprising results. When dashboards and direct queries both exist, reconcile them or explain why they differ.\n\n### 5. Translate Evidence Into Decision Implications\n\nFrame the findings within the broader business context. Do not present quantitative evidence and business context as two unrelated streams.\n\nInterpret the evidence through the decision lenses that best fit the question. Choose lenses that would actually change the recommendation, and skip ones that would add noise or false precision. Common lenses include:\n\n- **Current scale:** Is the opportunity or problem large enough today to matter for the decision?\n- **Momentum:** Is the signal growing, shrinking, accelerating, or newly emerging?\n- **Breadth:** Is the pattern broad-based, or does it only appear in a narrow corner of the business?\n- **Concentration:** Does the conclusion depend on a few large entities, events, or outliers?\n- **Intensity:** Is the behavior deep enough per unit to suggest real need, value, or risk?\n- **Efficiency:** Does the option create better output, margin, conversion, productivity, or quality for the input required?\n- **Addressability:** Can the team realistically act on this option with available product, GTM, operational, policy, or technical levers?\n- **Differentiation:** Does this group or use case require a distinct motion, product experience, support model, or message?\n- **Substitution:** Is there evidence that behavior, spend, time, or workload could shift from another path?\n- **Risk or dependency:** Are there quality, trust, compliance, technical, operational, or data constraints that change the recommendation?\n- **Coverage:** Are unknown, missing, or sparsely tagged records large enough to change the answer?\n\nUse these as thinking tools, not a checklist. Explain why the chosen lenses matter for this decision, and mention omitted cuts only when they would plausibly change the interpretation or help explain the result.\n\nUse the measured opportunities to explain which differences matter for the decision and which ones call for different actions. If the business context shows that the initial sizing misses the actionable part of the opportunity, add the focused sizing cut needed to make the recommendation useful.\n\nIf evidence conflicts, say so directly and explain which interpretation is better supported. Do not smooth over disagreement between sources.\n\n### 6. Hand Off The Recommendation\n\nEnd by handing the decision-ready recommendation to $build-report unless the user explicitly requests an inline, chat-only, brief/no-artifact answer, asks not to create a report/file/artifact, or selects another primary artifact. This handoff is mandatory when no explicit human waiver was given; do not infer a waiver because the user asked a direct question or did not use the word \"report\". This workflow owns the analytical conclusion; $build-report owns the reader-facing structure, visuals, evidence placement, and delivery surface.\n\nBefore handoff, make the recommendation explicit:\n\n- what they should believe or do next\n- why the evidence supports that recommendation\n- which caveats or dependencies matter\n- what follow-up analysis would most improve confidence\n\nIf evidence is incomplete, label the recommendation as provisional and state what would change confidence. Do not overstate the conclusion just to make the answer feel decisive.\n\nUse $validate-data when methodology, calculations, caveats, or the evidentiary support for the conclusion need review before sharing.\n\nPass narrative ingredients to the report surface, not only result tables:\n\n- direct answer and recommendation\n- key evidence and how to interpret it\n- implication for the decision\n- unresolved uncertainty and caveats\n- recommended follow-up\n","frontmatter":{"name":"product-business-analysis","description":"Analyze product or business data to support a decision or recommendation. Use when a decision depends on metric-backed evidence, such as choosing a direction, prioritizing an opportunity, evaluating a change, segmenting users, sizing tradeoffs, or deciding what to do next."},"isInternal":false,"tokens":1921,"sizeBytes":10291},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/validate-data/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/validate-data/SKILL.md","title":"validate-data","category":"anthropic-skill","format":"markdown","content":"---\nname: validate-data\ndescription: \"Validate whether an analysis is accurate, well-supported, and ready to share or use for a decision. Use when reviewing methodology, calculations, comparisons, visuals, caveats, or conclusions.\"\n---\n## Related Skills\n\nUse $analyze-data-quality when validation depends on whether the underlying data is trustworthy, comparable, fresh, or at the right grain.\n\nUse $product-business-analysis when the task asks for a recommendation or decision after the validation pass.\n\n# Validate Data Analysis\n\nValidate an analysis before it is shared with stakeholders. Focus on whether the question, data, methodology, calculations, visuals, claims, caveats, and recommendations are trustworthy enough for the stated audience and decision.\nThis skill is for analysis QA, not raw dataset profiling alone. When validation depends on dataset reliability checks such as freshness, grain, missingness,\nduplicates, join coverage, or source mismatches, use $analyze-data-quality as a companion.\n\n## Workflow\n\n1. Inventory the artifact and claims.\n\n   Identify the report, notebook, spreadsheet, SQL, dashboard, chart, pasted analysis, or recommendation being validated. Inspect source artifacts when a path, link, query, notebook, spreadsheet, or dashboard is referenced. Extract the main question, audience, decision, key claims, headline numbers, data sources, time windows, populations, filters, comparison baselines, and stated caveats. Verify that every metric or KPI requested by the user appears in the analysis or is explicitly marked unavailable, not applicable, or out of scope.\n\n2. Validate the question, methodology, and assumptions.\n\n   Confirm that the analysis answers the stated business or product question,\n   not a nearby easier question. Check whether the population, eligibility rules, exclusions, sampling, metric definitions, formulas, units,\n   denominators, timezones, cohorts, comparison periods, and baselines match the stakeholder decision. Flag hidden exclusions, inconsistent definitions,\n   partial-period comparisons, and causal wording that lacks experimental or otherwise credible causal evidence.\n\n3. Validate data selection and quality risks.\n\n   Confirm that the chosen tables, files, dashboards, or extracts are appropriate and current enough for the decision. Check freshness or \"as of\"\n   date, expected partitions, segment coverage, row/category completeness, null handling, deduplication, filter logic, join coverage, and source mismatches when those risks could change the conclusion. Use `~~structured_data` for source metadata, schema checks, sample rows, query history, or SQL spot checks through the relevant source connector when available. Use `~~operations_logs` for table freshness, lineage, or pipeline context.\n\n4. Verify calculations and aggregations.\n\n   Recompute the highest-impact numbers independently when possible. Check grain, subtotals, denominators, non-zero denominators, rate bases,\n   period-over-period bases, weighted averages, units, currency, timezone handling, and whether mutually exclusive categories add to totals. For SQL,\n   inspect join types, group-by grain, filters, distinct counts, and row counts before and after joins. Use $jupyter-notebooks or `~~spreadsheet_workspace`\n   when the artifact itself is a notebook or spreadsheet, or when reproducible spot checks need code or formulas.\n\n5. Test reasonableness and common analytical traps.\n\n   Compare magnitudes against known dashboards, historical reports, prior analyses, finance sources, or expected product scale when possible. Investigate trend jumps, drops, flatlines, exact round numbers, 0% or 100% rates, segment shares that should sum to about 100%, and results that perfectly confirm the hypothesis without friction. Check edge cases such as empty segments, new entities, and boundary dates.\n\n6. Review visuals and presentation integrity.\n\n   Confirm that charts use appropriate chart types, scales, axes, intervals,\n   titles, labels, units, ordering, annotations, color, and precision. Use\n   $visualize-data for non-trivial chart review. For rendered reports,\n   dashboards, slides, docs, PDFs, HTML, or other final artifacts, inspect the rendered output for broken charts, missing tables, clipped text, bad formatting, stale placeholders, and obvious layout issues. Check whether a quick reader could walk away with a misleading interpretation, especially from truncated axes, dual axes, 3D effects, inconsistent intervals, missing date ranges, or chart titles that overstate the data.\n\n7. Evaluate narrative, conclusions, and recommendations.\n\n   Confirm each conclusion is supported by visible evidence or saved artifacts.\n   Separate verified findings from interpretation, caveats, and open questions.\n   Identify alternative explanations, uncertainty, missing context,\n   recommendations that go beyond the evidence, and any causal language that is not supported by the design.\n\n8. Produce a confidence assessment and required fixes.\n\n   Prioritize issues that materially affect the stakeholder decision. Separate blockers from caveats: do not block sharing for minor polish issues, but do block when a number, denominator, join, time window, population, comparison,\n   or conclusion is materially unreliable. Record incomplete handoff blockers separately from caveats, including missing access, unavailable source artifacts, unrun checks, broken render steps, unresolved data-quality risks,\n   or absent owner confirmation. If SQL, Python, a notebook, or a spreadsheet was used for validation, include the artifact path, query permalink, notebook path, spreadsheet tab, or dashboard link so the check is reproducible.\n\n## Standards\n\n### Validation Stance\n\n- Validate the claims the analysis actually makes, not just whether the artifact looks polished.\n- Prefer concrete evidence: recompute important numbers, inspect source data,\n  check code paths, trace records, or reconcile against trusted sources when tools and access allow it.\n- Label anything that cannot be verified, and state what would be needed to verify it.\n- Treat surprising results, stakeholder-facing recommendations, causal claims,\n  high-impact decisions, and externally shared analyses as higher-risk validation targets.\n- Select checks that match the artifact and decision. Do not run every possible check mechanically.\n\n### Methodology Checks\n\n- Question framing: the analysis answers the stated business or product question.\n- Data selection: sources are appropriate and current enough for the decision.\n- Population: inclusions, exclusions, eligibility rules, and sampling are explicit.\n- Metric definitions: formulas, units, denominators, and timezones are clear and aligned with stakeholder definitions.\n- Baselines: comparison periods, cohorts, and contexts are comparable.\n- Causality: causal wording is backed by experimental or otherwise credible causal evidence.\n\n### Data Quality Checks\n\n- Freshness: the analysis states or can recover the data \"as of\" date.\n- Completeness: no unexpected missing partitions, segments, rows, or categories.\n- Null handling: key columns have expected null rates or explicit treatment.\n- Deduplication: primary entities are not double counted.\n- Filter verification: filters and WHERE clauses do not silently exclude the population of interest.\n- Join coverage: dimensions, experiments, and reference tables do not drop or multiply important rows.\n\n### Calculation Checks\n\n- Grain: the aggregation level matches the intended analysis grain.\n- Denominators: rates and percentages use the correct population and non-zero denominators.\n- Period alignment: comparisons use equal or explicitly caveated windows.\n- Weighted metrics: averages are weighted correctly when group sizes differ.\n- Subtotals: parts add to totals where categories are mutually exclusive.\n- Units: currency, token, user, request, account, day/week/month, and timezone units are consistent.\n\n### Reasonableness Checks\n\n- Magnitudes are plausible relative to known dashboards, historical reports, or expected product scale.\n- Percentages fall in expected ranges and segment shares sum to about 100% where expected.\n- Trend jumps, drops, flatlines, exact round numbers, and 0% or 100% rates have an explanation.\n- Results do not perfectly confirm the hypothesis without friction or exceptions.\n- Edge cases such as empty segments, new entities, and boundary dates behave sensibly.\n\n### Common Pitfalls\n\n- Join explosion: many-to-many joins silently multiply rows and inflate counts or sums. Compare row counts and distinct primary entities before and after the join, and check whether the right-hand table has multiple rows per join key.\n  Aggregate the right-hand table to the intended grain before joining when needed, use `COUNT(DISTINCT primary_id)` when counting entities through joins,\n  and comment intentional one-to-many joins.\n- Survivorship bias: the analysis only includes entities that exist today and misses deleted, churned, failed, or otherwise absent entities. Ask who is not in the dataset and whether the missing population changes the conclusion.\n- Incomplete period comparison: a partial period is compared with a complete period. Use complete periods, compare the same number of elapsed days, or label the partial-period caveat prominently.\n- Denominator shifting: the eligible population changes between periods or segments. Validate that conversion, churn, activation, attach, and retention rates use stable definitions across compared groups.\n- Average of averages: pre-computed averages are averaged without weighting for group size. Aggregate from raw numerators and denominators or use a weighted average.\n- Timezone mismatch: sources use different timestamp conventions or daily cutoffs. Confirm the analysis standardizes timestamps or explicitly states the timezone and cutoff.\n- Selection bias in segmentation: segments are defined by the outcome being measured. Define comparison groups by pre-treatment characteristics when making lift, causality, or behavior-difference claims.\n- Other statistical traps: Simpson's paradox where aggregate and segment-level trends conflict, correlation presented as causation, small samples,\n  outlier-dominated averages that need medians or distribution views, multiple testing, cherry-picked time ranges, and look-ahead bias.\n\n### Spot-Check Recipes\n\n- Recompute a key metric from raw numerators and denominators.\n- Trace a few individual records through joins, filters, and final output.\n- Reconcile a key total against a trusted dashboard, prior report, or finance source.\n- Reverse engineer a headline number from component metrics, such as users times per-user revenue.\n- Run a one-day, one-segment, or one-entity boundary check to make sure filters and joins behave sensibly.\n- Compare the same metric through an alternate query path when a claim is surprising or high stakes.\n\n### Visualization Checks\n\n- Bar charts should generally start at zero; waterfall, bridge, variance, and other delta-focused charts may use a non-zero or narrowed value axis when zero would materially compress the intended movement, provided exact values, units, and the focused scale are clear.\n- Comparison charts should use consistent scales unless the scale difference is explicit and justified.\n- Axes, units, legends, and date ranges should be labeled.\n- Category ordering should match the comparison the reader should make.\n- Truncated axes, dual axes, 3D effects, and inconsistent intervals require explicit justification or redesign.\n- Chart titles and annotations should match exactly what the data supports.\n- Titles should state the finding and include date range or scope when needed.\n- Caveats should be visible near the claims they qualify.\n- Number formatting should use appropriate precision and units.\n- Rendered artifacts should be checked in their final form when available, not only in source form.\n\n### Confidence Ratings\n\n- `Ready to share`: The analysis is methodologically sound, key calculations are verified or low risk, caveats are clear, and any remaining issues are minor.\n- `Share with caveats`: The analysis is directionally usable, but specific assumptions, limitations, or unverified checks must be communicated to stakeholders.\n- `Needs revision`: There are material errors, unsupported claims, missing checks, or methodological issues that should be fixed before sharing.\n\n### Output Standards\n\nUse this structure unless the user asks for a lighter review:\n\n```markdown\n## Validation Report\n\n### Overall Assessment: [Ready to share | Share with caveats | Needs revision]\n\n### Methodology Review\n[Findings about question framing, data selection, population, definitions, comparisons, and assumptions.]\n\n### Issues Found\n1. [Severity: High/Medium/Low] [Issue description, evidence, and impact]\n2. ...\n\n### Calculation Spot-Checks\n- [Metric or claim]: [Verified / Discrepancy found / Not verified] - [brief evidence]\n\n### Visualization Review\n[Chart or presentation issues, if applicable.]\n\n### Suggested Improvements\n1. [Improvement and why it matters]\n\n### Required Caveats for Stakeholders\n- [Caveat that must be communicated]\n```\n\n- Include the question being answered, data sources and \"as of\" date, metric and segment definitions, time period and timezone, methodology steps, assumptions and limitations, SQL queries, notebook paths, spreadsheet tabs, dashboard links, or caveats required before acting when those details are relevant.\n- Preserve source references from the original artifact, including links, query IDs, notebook paths, spreadsheet tabs, dashboard URLs, cited documents, and other evidence needed to trace the analysis.\n- Verify that every section requested by the user or implied by the deliverable format is present; explain omitted sections.\n- Keep issues prioritized by decision impact, not by artifact section order.\n- Make unverified claims and remaining caveats explicit.\n- List incomplete handoff blockers separately from caveats and suggested improvements.\n","frontmatter":{"name":"validate-data","description":"Validate whether an analysis is accurate, well-supported, and ready to share or use for a decision. Use when reviewing methodology, calculations, comparisons, visuals, caveats, or conclusions."},"isInternal":false,"tokens":2698,"sizeBytes":14022},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/visualize-data/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/visualize-data/SKILL.md","title":"visualize-data","category":"anthropic-skill","format":"markdown","content":"---\nname: visualize-data\ndescription: \"Design, create, revise, or QA quantitative charts and figures for reports, dashboards, notebooks, slides, files, or inline analytical answers.\"\n---\n\n# Visualize Data\n\nCreate quantitative visuals that are analytically sound, immediately readable, and appropriate for their destination. Treat a chart as evidence for a takeaway, not decoration.\n\n## Workflow\n\n1. State the analytical question and intended takeaway.\n2. Verify the data grain, measures, dimensions, units, missing values, filters, time window, sample size, and source.\n3. Choose the chart family from the analytical relationship:\n   - Change over ordered time: line or area chart.\n   - Category comparison: bar chart.\n   - Distribution: histogram, box plot, or density plot.\n   - Relationship between numeric measures: scatter plot.\n   - Composition: stacked bar/area; use pie only for a small set of meaningful parts.\n   - Funnel progression: funnel or ordered bars with stage conversion.\n   - Contribution to change: waterfall.\n   - Exact lookup values: table, optionally with small bars or sparklines.\n4. Define explicit encodings, sorting, aggregation, grouping, scales, labels, units, colors, annotations, and uncertainty treatment.\n5. Render with the destination's native system when one is selected. Otherwise prefer reproducible Python/Matplotlib or SVG for files and inline artifacts. Notebook-native plotting is appropriate for notebooks.\n6. Inspect the final output in context when the host provides image, browser, document, or notebook inspection.\n\nDo not install or require React, Recharts, Vite, MCP widgets, or proprietary UI renderers. For self-contained HTML, use inline SVG/canvas or a static image plus semantic fallback data. Avoid remote scripts unless the user explicitly accepts the dependency.\n\n## Visual quality\n\n- Use an answer-oriented title and a subtitle only when it adds a distinct takeaway.\n- Label axes and units; show legends or direct labels for every visible group.\n- Use consistent scales for comparisons and avoid misleading truncated axes unless clearly justified.\n- Prefer direct labeling and restrained color. Reserve semantic colors for meaning such as positive, warning, or negative states.\n- Keep annotations selective and evidence-backed.\n- Make dense charts readable through aggregation, faceting, filtering, or a table rather than shrinking text.\n- Provide accessible contrast, text alternatives, and a data table when the destination supports them.\n- Put provenance in a source note rather than cluttering the title.\n\n## QA\n\n- Recompute plotted values from the reviewed rows.\n- Confirm the visual answers the stated question and does not imply unsupported causality.\n- Check ordering, scales, labels, clipping, overlap, empty states, and small-screen behavior where relevant.\n- Confirm the exported file opens and contains the expected marks and text.\n- Preserve the code or notebook needed to reproduce the chart when the user needs an auditable artifact.\n\n","frontmatter":{"name":"visualize-data","description":"Design, create, revise, or QA quantitative charts and figures for reports, dashboards, notebooks, slides, files, or inline analytical answers."},"isInternal":false,"tokens":590,"sizeBytes":3008},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/deep-research/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/deep-research/SKILL.md","title":"deep-research","category":"anthropic-skill","format":"markdown","content":"---\nname: deep-research\ndescription: Deep research on any topic using parallel sub-agents and built-in tools only (WebSearch/WebFetch + free APIs, no keys). Use when the user asks for a thorough multi-source investigation with a cited report — \"深度调研X\"、\"deep research\"、\"帮我全面研究一下\"、\"多方求证\"、\"写一份调研报告\". NOT for simple lookups (single WebSearch suffices) and NOT for academic literature surveys (use auto-research skill instead).\n---\n\n# Deep Research\n\nOrchestrate parallel research sub-agents, then write one coherent cited report. Research is parallel; writing is single-point — never let multiple agents write report sections.\n\n## Step 0 — Always first\n\n1. Run `date +%Y-%m-%d` via Bash. Never assume the current year from training data.\n2. Triage:\n   - Answerable with 1-2 searches? → STOP, just use WebSearch directly. Do not use this skill.\n   - Enumeration task (N items × M fields, e.g. \"compare 20 frameworks\")? → still this skill, but use table-oriented decomposition (one sub-agent per item batch).\n   - Open-ended investigation? → continue below.\n3. Pick depth (default **standard**; user can override with words like \"quick\"/\"exhaustive\"):\n\n| Mode | Sub-agents (round 1) | Max follow-up rounds | Sources target |\n|---|---|---|---|\n| quick | 2-3 | 0 | 8+ |\n| standard | 3-5 | 1 | 15+ |\n| deep | 5-8 | 2 | 25+ |\n\nThese are hard budgets. Reflection (Phase 4) can spend them but never exceed them.\n\n## Workspace\n\nAll state lives on disk at `./research/<slug>/` — never only in context (survives compaction):\n\n```\nresearch/<slug>/\n├── brief.md         # research brief — the single contract for all phases\n├── findings/        # F1.md, F2.md ... one per sub-agent, structured evidence\n└── REPORT.md        # final deliverable\n```\n\nOn resume: re-read `brief.md` + list `findings/`, skip completed angles, continue.\n\n## Phase 1 — Scope\n\nAsk at most one round of clarifying questions (AskUserQuestion), only if genuinely ambiguous: audience, time frame, region, decision at stake. If the user said \"just run it\" or intent is clear, skip asking and write assumptions into the brief instead.\n\nThen write `brief.md`: refined question, scope boundaries (in/out), assumptions, depth mode, today's date. This brief — not the raw conversation — is what every later phase measures against.\n\n## Phase 2 — Plan\n\nDecompose the brief into 3-8 **independent** research angles. Pull from these lenses as applicable: core facts/definitions · recent developments (last 12 months) · quantitative data/benchmarks · counter-arguments & failure cases · practitioner experience (forums, issues) · academic work · key players/alternatives.\n\nList angles in `brief.md` under `## Angles`. For deep mode or contested topics, show the angle list to the user for a quick confirm before spending budget.\n\n## Phase 3 — Parallel research\n\nSpawn one sub-agent per angle **in a single message** (parallel). Build each prompt from the locked template in [reference/subagent-prompt.md](reference/subagent-prompt.md) — reproduce it verbatim, replacing only the `{variables}`. Each sub-agent:\n\n- researches ONE angle only, using WebSearch/WebFetch and the free endpoints in [reference/sources.md](reference/sources.md)\n- writes structured findings to `findings/F<n>.md` (claim / quote / URL / date / confidence per item)\n- returns only a 3-5 line summary to you — raw page content must never enter your context\n\nIf a sub-agent fails or returns thin results, note it and move on; do not block other angles.\n\n## Phase 4 — Reflect (gap check)\n\nRead all `findings/*.md`. Against `brief.md`, ask: which parts of the brief have no evidence? Which major claims rest on a single source? Where do sources conflict?\n\n- Gaps found AND follow-up budget remains → spawn targeted sub-agents with delta-queries (same template, narrower angle). Repeat once per remaining round.\n- No budget left or coverage sufficient → proceed. Record unresolved gaps; they go in the report's \"Open questions\".\n\n## Phase 5 — Write (single-point)\n\nYou alone write `REPORT.md` in one pass, following [reference/report.md](reference/report.md). Core rules:\n\n- Every non-obvious claim carries an inline citation `[n]` mapping to a Sources section; citation URLs come only from findings files — never from memory.\n- Where sources conflict, present both sides with dates; prefer newer + primary sources.\n- Mark single-source claims with `[single source]`, speculation with `[speculative]`.\n- End with: Open questions · Sources (numbered, with access date).\n\nFor deep mode, before finalizing do one critique pass: reread the report as a skeptical reviewer (unsupported claims? stale data? missing counter-view?) and fix in place.\n\nFinally, give the user a 5-10 line summary of key conclusions and the report path.\n","frontmatter":{"name":"deep-research","description":"Deep research on any topic using parallel sub-agents and built-in tools only (WebSearch/WebFetch + free APIs, no keys). Use when the user asks for a thorough multi-source investigation with a cited report — \"深度调研X\"、\"deep research\"、\"帮我全面研究一下\"、\"多方求证\"、\"写一份调研报告\". NOT for simple lookups (single WebSearch suffices) and NOT for academic literature surveys (use auto-research skill instead)."},"isInternal":false,"tokens":1153,"sizeBytes":4855},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/docx-official/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/docx-official/SKILL.md","title":"docx-official","category":"anthropic-skill","format":"markdown","content":"---\nname: docx-official\ndescription: \"Use this skill whenever a Microsoft Word (.docx) file is being produced, opened, transformed, or read. That includes: drafting reports, letters, contracts, RFPs, technical documents, or any long-form written deliverable; extracting text or structure from an existing Word file; filling a Word template with values; converting Word to PDF or plain text; splitting or merging documents; inspecting styles, headings, sections, tables, images, comments, or tracked changes. Trigger on mentions of 'Word doc', 'DOCX', 'Office document', a filename ending in .docx, or requests like 'turn this into a Word report'.\"\nlicense: Apache-2.0 — see LICENSE for terms and third-party attributions\n---\n\n# DOCX Skill\n\nAn Apache-2.0 toolkit for producing, editing, and reading Microsoft Word (`.docx`) files. Written from scratch against the public [ECMA-376 / ISO/IEC 29500](https://www.ecma-international.org/publications-and-standards/standards/ecma-376/) specification and built on permissively-licensed tooling (`python-docx` MIT, `lxml` BSD-3-Clause, optional external binaries `pandoc` and `soffice`) so it can be reused in commercial projects without restriction.\n\n## Decision matrix\n\n| Situation | Path | Read first |\n|-----------|------|------------|\n| No source file — build a document from a prompt / data | Author from scratch with `python-docx` | [`create.md`](create.md) |\n| You have a `.docx` template to fill in or lightly modify | Placeholder replacement via `python-docx`, keeps styles | [`edit.md`](edit.md) → *Workflow A — `python-docx` in-place edit* |\n| Deep structural edits, new sections, custom XML, unusual layouts | Explode → edit XML → assemble | [`edit.md`](edit.md) → *Workflow B — Explode → edit XML → assemble* |\n| You only need the text / structure / metadata out of a `.docx` | Extraction pipeline | [`read.md`](read.md) |\n| Need a PDF preview for QA | `scripts/render_pdf.py` via LibreOffice | see *QA* below |\n\nIf the task mixes several of these, do them in this order: **read → plan → edit/create → validate**.\n\n## One-time environment setup\n\n> **Bundled runtime:** when the `MIMO_PYTHON` environment variable is set, skip `uv`/`python3` and pip installs entirely — run every command below with `uv run` replaced by `\"$MIMO_PYTHON\"` (e.g. `\"$MIMO_PYTHON\" scripts/extract_text.py input.docx`). This skill's Python dependencies are preinstalled in that interpreter; pip console scripts are unavailable, so always go through `\"$MIMO_PYTHON\" -m <module>`. A bundled LibreOffice is exposed as `MIMO_SOFFICE` and picked up automatically by the scripts here.\n\nAll scripts include [PEP 723](https://peps.python.org/pep-0723/) inline metadata, so `uv run` resolves dependencies automatically — no manual install step needed. Just run:\n\n```bash\nuv run scripts/extract_text.py input.docx\n```\n\nIf you don't use `uv`, install dependencies once:\n\n```bash\npython3 -m pip install --upgrade python-docx lxml\n# Optional but recommended:\n#   LibreOffice (for docx → pdf preview):   brew install --cask libreoffice   (macOS)\n#                                           apt-get install -y libreoffice    (Debian/Ubuntu)\n#   Poppler   (for pdf → image, QA loop):   brew install poppler\n```\n\nAlternatively, if this skill lives in a persistent workspace you can `uv init` a project, `uv add python-docx lxml`, and run scripts with `uv run scripts/...` from the project root — this gives you a lockfile and reproducible environment.\n\nAll scripts here use the standard library plus `python-docx`. No proprietary dependencies.\n\n## Common commands\n\n```bash\n# 1. Extract plain text (best for \"what does this file say?\" questions)\nuv run scripts/extract_text.py input.docx > input.txt\n\n# 2. Explode a .docx into readable XML for structural surgery\nuv run scripts/explode.py input.docx exploded/\n\n# 3. Assemble an exploded directory into a fresh .docx\nuv run scripts/assemble.py exploded/ output.docx\n\n# 4. Render a .docx as PDF (used for visual QA)\nuv run scripts/render_pdf.py output.docx           # writes output.pdf next to it\n\n# 5. Well-formedness check (ZIP integrity + parseable XML + python-docx open)\nuv run scripts/audit.py output.docx\n\n# 6. Accept every tracked change without needing Word/LibreOffice\nuv run scripts/resolve_revisions.py reviewed.docx clean.docx\n\n# 7. Add a comment to an exploded directory\nuv run scripts/annotate.py exploded/ \"Please check\" --author \"Reviewer\" --anchor \"text\"\n```\n\nEvery script is a small, self-contained Python file. Read the top of the file for full CLI options.\n\n## Authoring principles\n\nWord is a **flowing** document format, not a slide surface. Users expect it to look like something a human wrote in Word — not a design tool trying to reinvent typography. Keep that in mind:\n\n1. **Rely on named styles.** Use `Heading 1`, `Heading 2`, `Normal`, `Title`, `Quote`, `List Bullet`, `List Number`, `Caption`. They are what makes Word's ToC, navigation pane, and cross-references work.\n2. **One idea per paragraph.** Long paragraphs are fine; run-on paragraphs are not. Break at logical boundaries.\n3. **Structure first, prose second.** Draft the heading tree, then write inside it. Reviewers scan headings before words.\n4. **Tables for tabular data only.** Do not use tables to fake multi-column layouts — export to PDF and users see the borders through the layout.\n5. **Line length is set by page margins, not by hard breaks.** Never insert manual line breaks to control wrapping.\n6. **Use fields, not literal text, for things that change** — page numbers, dates, ToC, cross-references. `python-docx` supports field codes via low-level XML (see `edit.md`).\n7. **Every image needs alt text** — accessibility, and Word screams at you in review mode when it's missing.\n\n## Typography defaults (safe starting point)\n\n| Element        | Font          | Size | Weight | Notes |\n|----------------|---------------|------|--------|-------|\n| Title          | Calibri Light | 28pt | Bold   | Centered or left, one line |\n| Heading 1      | Calibri Light | 18pt | Bold   | Space before 12pt |\n| Heading 2      | Calibri Light | 14pt | Bold   | Space before 10pt |\n| Heading 3      | Calibri       | 12pt | Bold   | Space before 6pt |\n| Body           | Calibri       | 11pt | Regular| Line spacing 1.15, space after 6pt |\n| Caption        | Calibri       | 9pt  | Italic | Muted gray `#595959` |\n| Code / mono    | Consolas      | 10pt | Regular| Left-aligned, no first-line indent |\n\nChange the palette for the topic — muted navy `#1F3A5F` for legal/finance, warm charcoal `#2E2A26` for editorial. Avoid pure `#000000` for body text; `#1F1F1F` reads softer on print.\n\n## Page setup (A4 vs Letter)\n\nAsk the user which one to use. If you cannot ask, default to the region implied by the language (Chinese/European → A4, US English → Letter). Margins:\n\n| Size   | Width × Height    | Standard margins (T/B/L/R) |\n|--------|-------------------|-----------------------------|\n| A4     | 21.0 × 29.7 cm    | 2.54 / 2.54 / 3.18 / 3.18 cm |\n| Letter | 8.5 × 11.0 in     | 1.00 / 1.00 / 1.25 / 1.25 in |\n\n## QA checklist — always run before declaring done\n\n**Assume something is wrong.** Word files fail silently: a broken relationship, an unclosed `<w:p>`, a missing style — Word will still open the file but strip content or throw a \"content had problems\" warning. Verify explicitly.\n\n1. **Open cleanly** — no repair prompt.\n   ```bash\n   uv run python -c \"import docx; docx.Document('output.docx')\"   # loads without exceptions\n   ```\n2. **Text integrity** — no placeholder residue.\n   ```bash\n   uv run scripts/extract_text.py output.docx | grep -Ei \"TODO|TBD|\\{\\{|lorem|xxxx\"\n   ```\n   Grep must return nothing.\n3. **Visual sanity** — render a PDF, open the first and last pages, scan for:\n   - Widowed headings alone at the bottom of a page.\n   - Tables split awkwardly across pages.\n   - Images pushed to their own page because they exceeded content width.\n   - Missing page numbers, wrong header/footer content.\n   ```bash\n   uv run scripts/render_pdf.py output.docx\n   ```\n4. **Style hygiene** — every heading uses a real style, not just bold+large text:\n   ```bash\n   uv run python -c \"\n   import docx; d = docx.Document('output.docx')\n   for p in d.paragraphs:\n       if p.text and p.style.name == 'Normal' and p.runs and p.runs[0].bold:\n           print('possible fake heading:', p.text[:80])\"\n   ```\n\nIf any of these fail, fix and re-run — don't paper over.\n\n## What is out of scope\n\n- **`.doc` (legacy Word 97-2003)** — this skill only targets `.docx` (Office Open XML). Convert `.doc` to `.docx` with LibreOffice first: `soffice --headless --convert-to docx old.doc`.\n- **Live collaborative editing** — the Word online API is a separate concern; here we produce and modify files.\n- **Macros / VBA** — do not generate `.docm` files. If the user asks for automation, offer a Python script that regenerates the doc instead.\n\n## Where each detail lives\n\n- **Creating from scratch**: [`create.md`](create.md) — headings, paragraphs, styles, tables, images, page setup, headers/footers, tables of contents.\n- **Editing / templating**: [`edit.md`](edit.md) — placeholder replacement, section swap, raw XML surgery, tracked changes, comments.\n- **Reading / extracting**: [`read.md`](read.md) — plain-text export, structural walk, metadata, table extraction.\n- **Scripts**: [`scripts/`](scripts/) — self-contained CLI utilities used by all of the above.\n","frontmatter":{"name":"docx-official","description":"Use this skill whenever a Microsoft Word (.docx) file is being produced, opened, transformed, or read. That includes: drafting reports, letters, contracts, RFPs, technical documents, or any long-form written deliverable; extracting text or structure from an existing Word file; filling a Word template with values; converting Word to PDF or plain text; splitting or merging documents; inspecting styles, headings, sections, tables, images, comments, or tracked changes. Trigger on mentions of 'Word doc', 'DOCX', 'Office document', a filename ending in .docx, or requests like 'turn this into a Word report'.","license":"Apache-2.0 — see LICENSE for terms and third-party attributions"},"isInternal":false,"tokens":2413,"sizeBytes":9501},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/grok-build/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/grok-build/SKILL.md","title":"grok-build","category":"anthropic-skill","format":"markdown","content":"---\nname: grok-build\ndescription: Reference and workflow guidance for the Grok Build CLI (`grok`), including interactive and headless runs, authentication, sessions, worktrees, permissions, sandboxing, MCP servers, plugins, inspection, updates, and automation output. Invoke only when the user explicitly requests the `grok-build` skill, explicitly asks to use Grok Build CLI, or an already-selected workflow requires Grok Build; do not invoke for general coding, generic shell tasks, or other agent CLIs.\n---\n\n# Grok Build CLI\n\nOperate Grok Build from a terminal while keeping execution mode, permissions, sandboxing, session state, and output handling explicit.\n\n## Start with Local Evidence\n\n1. Confirm that the CLI is available:\n\n   ```bash\n   command -v grok\n   grok version\n   ```\n\n2. Inspect the installed command before giving version-sensitive advice:\n\n   ```bash\n   grok --help\n   grok <subcommand> --help\n   ```\n\n3. Inspect the configuration discovered for the target workspace when behavior depends on rules, skills, plugins, hooks, or MCP servers:\n\n   ```bash\n   grok --cwd /path/to/repo inspect\n   grok --cwd /path/to/repo inspect --json\n   ```\n\n4. Treat current official documentation and installed help as authoritative when they differ from this bundled reference.\n\n## Choose an Execution Mode\n\n- Run `grok` with no arguments for the interactive TUI.\n- Run `grok \"<initial prompt>\"` to open the TUI with an initial task.\n- Run `grok -p \"<prompt>\"` for one non-interactive turn that prints a result and exits.\n- Run `grok agent stdio` for an ACP client that communicates over stdin/stdout.\n- Run `grok dashboard` to open the Agent Dashboard.\n\nPrefer headless mode for scripts, CI, bots, and agent orchestration. Prefer ACP only when the caller implements the ACP JSON-RPC lifecycle and consumes `session/update` chunks.\n\n## Authenticate\n\nUse an interactive login on a developer machine:\n\n```bash\ngrok login\n```\n\nUse device-code authentication in headless or remote environments:\n\n```bash\ngrok login --device-auth\n```\n\nUse a locally cached login or provide `XAI_API_KEY` only to the process that needs it. Never print, persist, or commit credentials. Use `grok logout` to clear cached credentials.\n\n## Run Headlessly\n\nUse an explicit working directory and output format:\n\n```bash\ngrok --no-auto-update \\\n  --cwd /path/to/repo \\\n  --sandbox workspace \\\n  -p \"Inspect the repository and explain the failing test.\" \\\n  --output-format json\n```\n\nChoose output according to the consumer:\n\n- Use `plain` for humans.\n- Use `json` for one final machine-readable object.\n- Use `streaming-json` for newline-delimited incremental events.\n- Add `--json-schema '<schema>'` when the installed CLI supports constrained structured output.\n\nPass `--no-auto-update` in scripts and CI to suppress background update checks. Do not parse interactive TUI rendering in automation.\n\n## Control Permissions and Isolation\n\nTreat permissions and sandboxing as separate controls:\n\n- Use permission rules to decide whether a tool call may run.\n- Use a sandbox profile to limit what an approved call may access.\n- Prefer `--sandbox workspace` for normal repository changes.\n- Prefer `--sandbox read-only` for review and auditing.\n- Prefer `--sandbox strict` for an untrusted repository, then add narrow permission rules.\n- Use `--allow <RULE>` and `--deny <RULE>` for per-run policy; remember that deny rules win.\n- Use `--always-approve` only when the environment and command scope justify unattended execution. Pair it with a suitable sandbox and explicit deny rules.\n\nDo not describe `--always-approve` as equivalent to sandboxing. The sandbox is off by default unless configured or selected.\n\n## Manage Sessions and Worktrees\n\nContinue or resume intentionally:\n\n```bash\ngrok -c\ngrok --resume <session-id>\ngrok --resume\n```\n\nUse `--session-id <UUID>` for a new named session, not to resume an existing one. Add `--fork-session` when branching from a resumed session.\n\nUse a worktree when concurrent work could collide:\n\n```bash\ngrok --worktree --ref main \"Fix the flaky test\"\ngrok --worktree=feature-name \"Implement the feature\"\n```\n\nPreview removal with `grok worktree rm --dry-run <id>` before deleting a worktree. Do not assume deleting a session removes its worktree.\n\n## Diagnose Before Editing Configuration\n\nUse built-in inspection and diagnostics first:\n\n```bash\ngrok inspect --json\ngrok mcp list --json\ngrok mcp doctor\ngrok plugin list\ngrok models\n```\n\nPrefer `grok mcp add`, `grok mcp remove`, and plugin subcommands over manually editing configuration when the CLI supports the requested operation. Keep secrets in environment variables rather than command history or committed configuration.\n\n## Read the Bundled References\n\n- Read [references/cli-reference.md](references/cli-reference.md) for the subcommand and common flag index.\n- Read [references/workflows.md](references/workflows.md) for headless execution, sessions, worktrees, permissions, sandboxing, and MCP examples.\n\nVerify destructive commands such as session deletion, plugin removal, MCP removal, memory clearing, and worktree removal with the user or the governing workflow before running them.\n","frontmatter":{"name":"grok-build","description":"Reference and workflow guidance for the Grok Build CLI (`grok`), including interactive and headless runs, authentication, sessions, worktrees, permissions, sandboxing, MCP servers, plugins, inspection, updates, and automation output. Invoke only when the user explicitly requests the `grok-build` skill, explicitly asks to use Grok Build CLI, or an already-selected workflow requires Grok Build; do not invoke for general coding, generic shell tasks, or other agent CLIs."},"isInternal":false,"tokens":1163,"sizeBytes":5162},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/html-to-video-pipeline/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/html-to-video-pipeline/SKILL.md","title":"html-to-video-pipeline","category":"anthropic-skill","format":"markdown","content":"---\nname: html-to-video-pipeline\ndescription: Reliable HTML-to-MP4 rendering via headless browser recording (Playwright/Puppeteer) + ffmpeg — the ordering, gotchas, and verification steps you MUST get right or the output silently rots. Trigger whenever the user is building or debugging any pipeline that turns an HTML/CSS/JS page (single-file, multi-composition, GSAP-driven, or `@keyframes`-driven) into a video file, including headless recording, screen capture of a web page, deterministic frame-by-frame capture, multi-scene concatenation, or engine-mixed video output. Also trigger when the symptom sounds like: font swap flashing in the opening frames (FOUT), the first few seconds of the video are frozen/dead, animations play during page load and get truncated, concatenated segments produce a video whose duration is wildly wrong (e.g., 8s becomes 35s), `file://` loaded HTML fails to fetch its sub-scenes, the exported video is soft/blurry compared to the browser, or playback stutters/looks choppy despite passing a high `-r` fps to ffmpeg. Use even for one-off scripts — the failure modes here are subtle enough that starting from scratch usually reintroduces them.\n---\n\n# HTML → Video: the pipeline that actually works\n\nTurning a live HTML page into an MP4 sounds like a one-liner (\"Playwright records, ffmpeg encodes\") and the first draft always looks fine — until you play back the export and notice text flashing in a fallback font, three dead seconds at the start, or a \"10-second\" clip that clocks in at 35s. This skill captures the specific ordering, waits, and encoder flags that make the output trustworthy.\n\nThink of the pipeline as five phases with a single invariant between them:\n\n```\nlaunch  →  hold @ frame 0  →  align capture start with animation start  →  record  →  trim & encode\n```\n\nThe invariant: **no pixel of the animation should render before capture is ready, AND capture must not start before every asset that affects layout has loaded.** Every gotcha below is a violation of that invariant.\n\nQuick checklist (each item is expanded below):\n\n1. `viewport` must exactly equal `recordVideo.size` — mismatch silently rescales the output soft/blurry.\n2. Freeze CSS animations via `addInitScript` **before** `goto()`.\n3. `goto` with `domcontentloaded`, never `load`.\n4. Pre-inline `data-composition-src` sub-scenes — `file://` blocks client-side `fetch`.\n5. Font wait = stylesheet `<link>` load → `face.load()` per face → `fonts.ready` → 2 rAFs.\n6. Probe duration with infinite-iteration / `repeat: -1` guards.\n7. Unfreeze = t=0; trim `leadInMs − 120ms` with `-ss` *before* `-i`.\n8. Concat: same engine → demuxer `-c copy`; mixed engines → concat *filter* + re-encode.\n9. Verify with ffprobe duration + full decode + sampled frames. Always.\n\nThere are two capture modes, and picking the wrong one wastes a day:\n\n- **Mode A — real-time `recordVideo`** (the phases below). Simple, wall-clock = clip length. But the screencast is best-effort variable frame rate (~25fps) and competes with the animation for CPU. Good enough for previews and ≤30fps deliverables on an idle machine.\n- **Mode B — deterministic frame stepping** (pause everything, seek to `i / fps`, screenshot, encode the PNG sequence). Exact fps, every frame rendered, no lead-in trim, immune to machine load. Required when the output must be genuinely smooth ≥30fps or renders run on loaded CI. See \"Deterministic frame stepping\" below.\n\n## Prerequisites — install these first\n\nTwo hard requirements: a headless browser driver (Playwright or Puppeteer) and `ffmpeg`. Everything below assumes both are installed and on `PATH`.\n\n### 1. Headless browser driver\n\nPlaywright is the default in this skill (its `recordVideo` API is what the pipeline is written against). Puppeteer works too but you'll wire recording yourself via CDP screencast — pick Playwright unless you have a reason not to.\n\n```bash\n# Playwright (recommended) — npm / pnpm / bun all work\nnpm  install playwright\npnpm add playwright\nbun  add playwright\n\n# Then install the actual browser binaries (this is the step people forget):\nnpx playwright install chromium              # just Chromium — enough for this pipeline\nnpx playwright install --with-deps chromium  # Linux/CI: also install shared libs\n```\n\nVerify: `npx playwright --version` prints the driver version, and `node -e \"require('playwright').chromium.launch().then(b => b.close())\"` exits cleanly.\n\nPuppeteer alternative (only if you already have it in the project):\n\n```bash\nnpm install puppeteer            # bundles a matching Chromium automatically\n# or, to reuse a system Chrome:\nnpm install puppeteer-core       # no bundled browser — you supply executablePath\n```\n\n### 2. ffmpeg\n\nThe encode/trim/concat/verify steps all shell out to `ffmpeg` (and `ffprobe`, which ships in the same package). It is **not** an npm dependency — install it at the OS level.\n\n```bash\n# macOS\nbrew install ffmpeg\n\n# Debian / Ubuntu\nsudo apt-get update && sudo apt-get install -y ffmpeg\n\n# Fedora / RHEL\nsudo dnf install ffmpeg          # requires RPM Fusion enabled\n\n# Windows\nwinget install Gyan.FFmpeg       # or: choco install ffmpeg\n```\n\nVerify: `ffmpeg -version` and `ffprobe -version` both print. If a script spawns `ffmpeg` and gets `ENOENT`, the binary isn't on `PATH` — see the graceful-failure snippet in `references/ffmpeg-cheatsheet.md`.\n\nDo **not** rely on the `ffmpeg-static` / `@ffmpeg-installer/ffmpeg` npm packages for production: their bundled builds skip codecs and encoder flags you'll hit sooner or later (e.g. `libx264` presets, `tpad`). A system ffmpeg is the durable choice.\n\n### 3. Optional — ImageMagick (verification only)\n\nOnly needed if you want the \"did anything render?\" pixel-mean check from Phase 6. Skip it otherwise.\n\n```bash\nbrew install imagemagick         # macOS\nsudo apt-get install imagemagick # Debian/Ubuntu\n```\n\nVerify: `magick -version` (ImageMagick 7) or `convert -version` (ImageMagick 6).\n\n## The pipeline\n\n### Phase 1 — Launch and prepare the recorder\n\nUse `playwright.chromium.launch({ headless: true })` and a context configured with `recordVideo: { dir, size: { width, height } }`. Two sizing rules:\n\n- **`viewport` must exactly equal `recordVideo.size`.** When they differ, Playwright rescales the screencast to fit the recording size and the whole output goes soft. Derive both from the same constants.\n- `recordVideo` captures at CSS-pixel resolution; `deviceScaleFactor` does **not** raise recording resolution. For a 1080p export use a 1920×1080 viewport, not 960×540 @ 2x.\n\nRecording begins the instant the context exists — treat that timestamp as the WebM's t=0 and remember it (`tWebmStart = Date.now()`); you will need it in Phase 5 to trim the dead opening.\n\nKnow the recorder's ceiling: the screencast runs at a variable ~25fps and drops frames under CPU load. The `-r <fps>` flag in Phase 5 makes the container constant-frame-rate but only duplicates frames — it cannot add smoothness. If stutter matters, switch to frame stepping (Mode B) instead of fighting this.\n\n### Phase 2 — Freeze animations BEFORE the page parses\n\nThis is the single most-missed step. Pure-CSS `@keyframes` animations begin the moment the element is styled — there is no JS trigger to hold. If you `goto()` the HTML and then start waiting for fonts (which takes seconds), the CSS timeline has *already been running the whole time*. The recording captures the fallback font swapping to the real face mid-clip, and the opening beats of the animation are lost to the font wait.\n\nFix: inject a global freeze **via `page.addInitScript()`**, which runs before any of the document's own scripts and before CSS is applied, so the timeline is paused at frame 0 the moment it exists:\n\n```js\nawait page.addInitScript(() => {\n  const style = document.createElement('style');\n  style.id = '__freeze';\n  style.textContent =\n    '*, *::before, *::after { animation-play-state: paused !important;' +\n    ' -webkit-animation-play-state: paused !important; }';\n  const attach = () => (document.head || document.documentElement).appendChild(style);\n  if (document.head || document.documentElement) attach();\n  else document.addEventListener('DOMContentLoaded', attach, { once: true });\n  window.__unfreeze = () => document.getElementById('__freeze')?.remove();\n});\n```\n\nThis does not stop GSAP tweens driven by JS (see Phase 4 for those) — for GSAP-driven templates, register the master timeline paused and expose a `window.__playAll()` you call in Phase 4.\n\n### Phase 3 — Load with `domcontentloaded`, not `load`\n\n`waitUntil: 'load'` blocks on every external asset, including cross-origin videos with no CORS headers. Chromium will retry those for ~4s before giving up, and those 4s get burned into the recording as a frozen first scene. Use `waitUntil: 'domcontentloaded'` — the DOM + synchronous inline scripts (GSAP, your player) are ready, and you handle fonts explicitly next.\n\nIf the template is multi-composition (scenes loaded via `data-composition-src` and client-side `fetch`), you must **pre-inline** those sub-files into the entry HTML on the Node side and write it to a sibling `.tmp.html`. Chromium blocks `file://` fetch, so client-side scene loaders that work in a browser tab will silently produce an empty shell in a headless recording. See `references/multi-composition.md`.\n\n### Phase 4 — Wait for fonts properly, then release\n\n`document.fonts.ready` alone is **not enough** and this is the second most-missed step. Under `domcontentloaded`, the Google Fonts (or any external) `<link rel=\"stylesheet\">` has usually not returned yet. Until its CSS arrives, its `@font-face` rules are not in `document.fonts` at all — so `fonts.ready` sees an empty set and resolves *instantly*. Recording proceeds, the CSS lands mid-clip, faces download, and the swap happens on-camera.\n\nThe correct sequence, all inside a `page.evaluate()` with an 8s hard cap so a wedged CDN can't stall forever:\n\n1. Wait for every `<link rel=\"stylesheet\">` to `load` or `error` — that registers `@font-face` rules into `document.fonts`.\n2. For each registered face, call `face.load()` explicitly. `font-display: swap` defers the download until something paints with that face — if your first frame doesn't happen to use the face, it never fetches without this.\n3. `await fonts.ready`.\n4. Two rAFs so layout settles on the real glyph metrics before frame 0.\n\nThen, and only then:\n\n5. Drive playback: for GSAP multi-composition templates, call `window.__playAll()` to start every registered (paused) master timeline from 0. For pure-CSS templates, this is a no-op.\n6. Call `window.__unfreeze()` to remove the freeze style. **This is the true t=0 of the animation.** Record the wall-clock offset from `tWebmStart` (`leadInMs = Date.now() - tWebmStart`) — this is what you trim in Phase 5.\n\nThe full JS for Phase 4 is in `references/font-wait.md`.\n\n### Phase 5 — Probe duration, record, then trim and encode\n\n**Probe duration first** (skip this only if you know the exact intended length). The user's requested `duration` may be shorter than the animation, in which case you'd cut the animation mid-play. Take the maximum of:\n\n- The longest **non-infinite** CSS animation (`animation-duration + animation-delay` for entries where `animation-iteration-count !== 'infinite'`).\n- The longest **finite** GSAP tween. Do **not** use `gsap.globalTimeline.totalDuration()` — a `repeat: -1` tween (blinking cursor, looping background) makes it ~1e10s. Walk `globalTimeline.getChildren(true, true, true)` and skip anything with `repeat() === -1`.\n\nAdd a ~400ms settle so the last animation frame is captured, cap at 30s so a stray huge value can't run away. If your caller passed an *explicit* per-frame duration (e.g. \"each scene is exactly 4s\"), do **not** extend — treat it as a hard cap and pad the tail if the animation finished early (see below). If duration was 'auto', extend to the probed length.\n\n**Record** for `totalDuration`, then `context.close()`. Playwright drops the WebM in `recordDir`.\n\n**Encode with ffmpeg**, applying two corrections:\n\n```\nffmpeg -y \\\n  [ -ss <(leadInMs - 120) / 1000> ]  # trim dead lead-in, back off 120ms so we don't clip frame 1\n  -i input.webm \\\n  [ -vf tpad=stop_mode=clone:stop_duration=<totalDuration> ]  # pad tail only when duration is explicit\n  -t <totalDuration> \\                # trim to exact length (recordVideo sometimes overshoots)\n  -r <fps> \\\n  -c:v libx264 -pix_fmt yuv420p -preset medium -crf 20 \\\n  -movflags +faststart \\\n  out.mp4\n```\n\nThe `-ss` back-off matters: recorder start jitter and rounding can steal the first real frame if you trim to exactly `leadInMs`. A couple of extra still frames at the head are invisible; a missing opening beat is obvious.\n\n## Deterministic frame stepping (Mode B)\n\nWhen the deliverable must be genuinely smooth at an exact fps — or the render runs on a loaded CI box where real-time capture visibly stutters — don't record in real time at all. Keep Phases 1–4 (minus `recordVideo`), then: pause every timeline, seek to `i / fps`, `page.screenshot()` each frame, and encode the PNG sequence with `ffmpeg -framerate <fps>`. Duration is exact by construction, there is no lead-in to trim, and every single frame is fully rendered regardless of machine load.\n\nIt works when the page's motion is declaratively seekable — CSS `@keyframes` (via `document.getAnimations()` + `currentTime`), WAAPI, and GSAP (`gsap.globalTimeline.time(t)`). It does **not** work for `<video>` elements, `setTimeout`-choreographed scenes, or rAF-driven physics; those need real-time recording or a CDP virtual clock. Step time monotonically forward, never backwards.\n\nFull loop, the seek/suppressEvents subtleties, the \"animations created later by JS are invisible to the seek\" trap, and optional 2x supersampling are in `references/frame-stepping.md`.\n\n## Multi-segment concatenation\n\nWhen you have N per-scene MP4s and need one output, the correct ffmpeg strategy depends on whether the inputs share a codec/timebase.\n\n**Same encoder, same params (typical: all scenes rendered by the same adapter)** — use `concat` demuxer with stream copy. Fast, lossless:\n\n```\nffmpeg -y -f concat -safe 0 -i list.txt -c copy out.mp4\n```\n\nwhere `list.txt` is `file 'seg1.mp4'\\nfile 'seg2.mp4'\\n...`.\n\n**Mixed sources (e.g. scene A recorded by headless Chromium, scene B rendered by a React/Remotion pipeline)** — the concat demuxer's `-c copy` path assumes compatible timebases and PTS. When timebases differ, PTS accumulate incorrectly and an 8-second output can become 35 seconds. **Even `-vsync cfr` won't save you** — the bad PTS have already been fed in. You must re-encode via the concat **filter**, which rebuilds the timeline:\n\n```\nffmpeg -y -i seg1.mp4 -i seg2.mp4 -i seg3.mp4 \\\n  -filter_complex \"[0:v][1:v][2:v]concat=n=3:v=1:a=0[v]\" \\\n  -map \"[v]\" -c:v libx264 -pix_fmt yuv420p -r 60 \\\n  -movflags +faststart out.mp4\n```\n\nDecision rule in code: pass a `reencode: boolean` down to your concat helper. Set it to `true` whenever any segment came from a different rendering engine than the others, or when you're not sure.\n\n## Verify — always\n\nYou cannot trust \"the file was written\" as success. The failure modes above (wrong duration, FOUT, dead lead-in) all produce a playable MP4. Before declaring success:\n\n- `ffprobe -v error -show_entries format=duration -of csv=p=0 out.mp4` — actual duration matches expected within ~50ms?\n- `ffmpeg -v error -i out.mp4 -f null -` — full decode, no errors? A \"silently corrupted\" output from a bad concat will decode fine but be the wrong length; conversely, a broken concat demuxer output can throw here.\n- Sample a frame near t=0.1s and t=0.5s (`ffmpeg -ss 0.1 -i out.mp4 -frames:v 1 -y f1.png`) — text renders in the intended font? If your test rig has ImageMagick, `magick f1.png -threshold 50% -format '%[fx:100*mean]' info:` gives a rough non-background pixel percentage that catches \"recording is completely blank\" regressions.\n\nFor fonts specifically: **studio-style live iframe previews will not reproduce FOUT** because the browser tab caches faces. Only cold-headless rendering (i.e. the actual export path) reproduces it. Verify on the exported MP4, not the preview.\n\n## When to depart from this template\n\n- **Non-animated single-frame PNG export.** Skip Phases 2, 4-5-recording; goto → `fonts.ready` → `page.screenshot()` is enough. FOUT still applies for the screenshot.\n- **You own the animation timeline in JS end-to-end** (e.g. Motion Canvas / Remotion generator style). The freeze/unfreeze dance is unnecessary because *you* drive frame-by-frame rendering — use the framework's own frame API and skip Playwright recording entirely. The concat rules still apply if you're mixing engines.\n- **Interactive-page capture** (recording a real user session). Duration probing is meaningless; use manual start/stop signals and skip lead-in trim.\n\n## Reference files\n\n- `references/font-wait.md` — full JS for the Phase 4 font-wait routine, with per-link timeout and rAF-based settle.\n- `references/frame-stepping.md` — the Mode B deterministic capture loop: seek-per-frame, screenshot, PNG-sequence encode, supersampling, and its limits.\n- `references/multi-composition.md` — inlining `data-composition-src` scenes for `file://` recording, including re-executing cloned `<script>` nodes.\n- `references/duration-probe.md` — CSS + GSAP probe with the infinite-iteration guards.\n- `references/ffmpeg-cheatsheet.md` — the encode/concat/verify commands in one place.\n","isInternal":false,"tokens":4288,"sizeBytes":17609},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/learn-everything/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/learn-everything/SKILL.md","title":"learn-everything","category":"anthropic-skill","format":"markdown","content":"---\nname: learn-everything\ndescription: Turn an uploaded PDF, paper, book chapter, document, URL, or user-provided topic into a structured, interactive learning course. Use when the user wants to learn, study, understand, master, review, or practice a subject chapter by chapter; asks for a tutorial or curriculum from source material; wants exercises, quizzes, answer grading, hints, spaced review, or a final assessment; or says \"teach me this\", \"learn this PDF\", \"分章节教学\", \"带我学\", or similar; or returns to continue a previous course (\"continue my course\", \"接着上次学\") or supplies a saved course-state file or state block. Adapt explanations and practice to the learner's level, preserve page or section references for documents, and teach incrementally rather than dumping all content at once.\n---\n\n# Learn Everything\n\nConvert source material or a topic into an adaptive course that alternates explanation, retrieval, application, feedback, and review.\n\n## Core behavior\n\n- Teach in the user's language unless they request another language.\n- Optimize for durable understanding, not merely summarization.\n- Work incrementally. Present a course map, then teach one chapter or lesson at a time.\n- Do not reveal exercise solutions before the learner attempts them, unless the learner explicitly asks.\n- Persist learning state. When file tools are available, maintain `learn/<slug>/course-state.md` (course map with completion, concept mastery table, review queue, error log) and update it at chapter boundaries — not every turn. Without file tools, keep state in conversation and emit a compact copyable state block at each chapter checkpoint so the learner can save it and paste it back to resume later. See `references/session-formats.md` for both formats.\n- Prefer concrete examples, analogies, diagrams described in text, counterexamples, and worked derivations over abstract exposition alone.\n- Separate source claims from added background knowledge. Never attribute added material to the source.\n- Match depth and notation to the learner. Define unfamiliar terms before relying on them.\n\n## Determine the input mode\n\n### Document mode\n\nUse document mode for PDFs, papers, books, slides, notes, or other supplied material.\n\n1. Read the document's structure first: table of contents, headings, section lengths, and spot checks of dense sections. Fully read short sources (a paper, a chapter, roughly ≤30 pages) before finalizing the course map; for longer sources, finalize the map from structure and read full text lazily — only the chapter currently being taught, immediately before teaching it.\n2. Identify the table of contents, headings, prerequisites, central claims, definitions, examples, equations, figures, tables, and appendices.\n3. Use semantic units rather than equal page ranges. Merge short dependent sections and split dense sections.\n4. Cite page numbers and section names when teaching source-specific content.\n5. Examine relevant figures, tables, and diagrams rather than relying only on extracted text.\n6. Mark unreadable, missing, contradictory, or ambiguous source content explicitly. Do not invent a reconstruction.\n7. Treat the supplied source as the primary curriculum. Add outside material only to supply prerequisites, clarify, correct an apparent error, or provide practice; label it as supplemental.\n\n### Topic mode\n\nUse topic mode when the learner supplies a subject rather than a source.\n\n1. Define a sensible scope and end capability.\n2. Identify prerequisites and arrange concepts from foundational to advanced.\n3. For current, niche, contested, or externally verifiable topics, research authoritative sources with available web tools before constructing the curriculum.\n4. Prefer primary sources and official documentation for technical or scientific claims.\n5. Distinguish stable fundamentals from current developments.\n6. State material scope and assumptions in the course map.\n\nDo not delay progress for minor ambiguity. Choose a useful default scope and make it visible.\n\n### Resume mode\n\nUse resume mode when the learner supplies a saved course-state file or state block, or asks to continue a previous course.\n\n1. Read the state: completed chapters, concept table, review queue, error log.\n2. Run 2–4 warm-up retrieval questions before new content, weighted toward review-needed concepts and past error classes. Ask fresh questions, never the originals verbatim.\n3. Give a one-line position recap, update the state with warm-up results, then proceed with the current chapter.\n4. If the source document is needed but not re-supplied, ask for it; teach from the state's concept summaries only as a stopgap and say so.\n\n## Start the course\n\nGather only information that materially changes the lesson. If the learner's level or goal is unknown, either:\n\n- ask one compact diagnostic question, or\n- offer a 3-question diagnostic quiz and let the learner skip it.\n\nDo not ask a long questionnaire. Infer preferences from the conversation whenever possible.\n\nThen provide:\n\n1. **Target capability** — what the learner should be able to explain or do.\n2. **Course map** — 3–12 chapters, each with purpose and prerequisites.\n3. **Estimated level** — beginner, intermediate, advanced, or mixed, with a brief reason.\n4. **Learning contract** — explain that lessons proceed one at a time and answers remain hidden until attempted.\n5. **Next action** — begin the first lesson or diagnostic immediately.\n\nUse the detailed formats in `references/session-formats.md` when consistency is useful.\n\n## Build the course map\n\nCreate chapters around conceptual dependencies, not source length alone. Each chapter should have:\n\n- a concise title;\n- one observable learning objective;\n- key concepts;\n- prerequisite links;\n- source pages or sections in document mode;\n- one planned practice outcome.\n\nUse these sizing rules:\n\n- Split a chapter when it contains more than one major reasoning jump.\n- Merge sections that cannot be understood independently.\n- Create a prerequisite bridge chapter when the source assumes missing knowledge.\n- Keep advanced appendices optional unless needed for the learner's goal.\n- For sources with more than ~12 natural chapters, group chapters into parts, agree on scope with the learner, and run the course part by part rather than flattening everything into one map.\n- Reorder only when pedagogically necessary; explain the reordering in document mode.\n\n## Teach each lesson\n\nFollow this lesson loop:\n\n1. **Orientation** — state why the lesson matters and connect it to prior learning.\n2. **Objectives** — give 2–4 observable goals.\n3. **Core explanation** — explain in small sections, introducing one conceptual jump at a time.\n4. **Worked example** — demonstrate the reasoning, not only the final result.\n5. **Misconception check** — identify 1–3 likely confusions or boundary cases.\n6. **Active recall** — ask a brief check before proceeding to longer practice.\n7. **Practice** — assign exercises calibrated to current mastery.\n8. **Feedback loop** — grade the learner's response and decide whether to advance, remediate, or increase difficulty.\n\nFor dense material, pause after each major concept and ask a single check question. For straightforward material, teach the full lesson before practice.\n\n## Design practice\n\nSelect exercises from multiple cognitive levels:\n\n- **Recall:** define, list, label, reproduce.\n- **Explain:** restate in the learner's own words; compare concepts; explain why.\n- **Apply:** solve a representative problem or use the method in context.\n- **Debug:** find an error in reasoning, code, derivation, or interpretation.\n- **Transfer:** apply the idea in a novel setting.\n- **Synthesize:** connect several chapters or produce an artifact.\n\nDefault to 3–5 exercises per lesson, mixing at least two levels. Prefer one exercise at a time when grading interactively. Use larger sets only when the learner requests a worksheet or exam.\n\nConsult `references/practice-and-mastery.md` for exercise-writing rules, difficulty bands, adaptation, and grading rubrics. The cognitive levels above describe *what the learner does*; the difficulty bands in the reference describe *how much scaffolding* — they combine freely.\n\n## Grade and respond to learner answers\n\nEvaluate substance before wording. Use this sequence:\n\n1. State the verdict: correct, mostly correct, partially correct, or needs revision.\n2. Identify what was done well.\n3. Point to the first important gap or error.\n4. Explain the correction with the smallest useful amount of teaching.\n5. Ask for a revision, provide a targeted follow-up, or advance.\n\nDo not merely say “correct.” Reinforce the decisive reasoning.\n\nWhen the answer is wrong:\n\n- First provide a hint that targets the misconception.\n- Give a stronger hint after another failed attempt.\n- Reveal a worked solution after repeated attempts, an explicit request, or when further guessing has low learning value.\n- Immediately follow a revealed solution with a near-transfer question.\n\nWhen the answer is correct:\n\n- Increase difficulty gradually.\n- Ask for explanation if the learner may have guessed.\n- Use a transfer question when mastery appears strong.\n\n## Track mastery and review\n\nMaintain a concept table — one row per concept — in the course state (file or state block):\n\n- status: unseen, introduced, practicing, mastered, or review-needed;\n- evidence: strongest recent answer or error;\n- confidence: low, medium, or high;\n- next review point.\n\nUpdate it at chapter boundaries and after significant errors. Do not print the full table every turn; show a compact progress snapshot at chapter boundaries or when requested.\n\nSchedule cumulative review:\n\n- after each chapter: 2–4 retrieval questions from current and earlier material;\n- after roughly one-third and two-thirds of the course: mixed checkpoint;\n- at course end: final assessment and synthesis task;\n- revisit recurring errors more often than mastered concepts.\n\nTreat mastery as demonstrated transfer, not one correct recall answer.\n\n## Handle learner commands\n\nRecognize and act on natural commands such as:\n\n- “继续 / continue” — move to the next pending step.\n- “提示 / hint” — give the next hint without the full answer.\n- “答案 / show solution” — reveal and explain the solution, then ask a near-transfer question.\n- “更简单 / simpler” — reduce abstraction, add prerequisites and examples.\n- “更深入 / deeper” — add derivation, edge cases, and harder transfer.\n- “跳过 / skip” — mark the item skipped and continue.\n- “复习 / review” — generate retrieval practice weighted toward weak concepts.\n- “考试 / test me” — run a closed-book mixed assessment.\n- “进度 / progress” — show completed chapters, mastery, weak points, and next step.\n- “重做课程 / rebuild course” — revise scope or chaptering while preserving demonstrated mastery.\n\n## Complete the course\n\nAt the end, provide:\n\n1. a mixed final assessment without solutions shown initially;\n2. a synthesis task that uses multiple chapters;\n3. grading with concept-level feedback;\n4. a concise mastery report;\n5. a personalized review plan focused on weak concepts;\n6. a compact reference sheet created only after assessment, so it does not replace retrieval practice.\n\nFor document mode, include a source navigation index linking mastered concepts back to pages or sections.\n\n## Quality checks\n\nBefore each response, verify:\n\n- Solutions are not exposed before the learner attempts the exercise.\n- The current activity matches the course state, and the state is updated at chapter boundaries.\n- The lesson does not assume an unexplained prerequisite.\n- The response gives the learner exactly one clear next action.","frontmatter":{"name":"learn-everything","description":"Turn an uploaded PDF, paper, book chapter, document, URL, or user-provided topic into a structured, interactive learning course. Use when the user wants to learn, study, understand, master, review, or practice a subject chapter by chapter; asks for a tutorial or curriculum from source material; wants exercises, quizzes, answer grading, hints, spaced review, or a final assessment; or says \"teach me this\", \"learn this PDF\", \"分章节教学\", \"带我学\", or similar; or returns to continue a previous course (\"continue my course\", \"接着上次学\") or supplies a saved course-state file or state block. Adapt explanations and practice to the learner's level, preserve page or section references for documents, and teach incrementally rather than dumping all content at once."},"isInternal":false,"tokens":2379,"sizeBytes":11805},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/loop/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/loop/SKILL.md","title":"loop","category":"anthropic-skill","format":"markdown","content":"---\nname: loop\ndescription: Schedule a prompt to fire on a fixed cadence (recurring loop). Use when the user asks to \"run X every N minutes/hours/days\", \"loop X\", \"babysit Y\", \"be proactive about Y every N\", or invokes `/loop` directly. Parses `[interval] <prompt>`, picks a clean cron expression, registers the job via the `cron` tool, and executes the prompt once immediately so the user sees activity without waiting for the first cron tick.\n---\n\n# /loop — schedule a recurring prompt\n\nThis skill turns a free-form `[interval] <prompt>` line into a `cron` tool call and runs the prompt once right away.\n\n## 1. Parse the input\n\nThe user's text is whatever appears after `/loop `. Apply the three rules below **in order** and stop at the first match.\n\n1. **Leading interval token.** If the first whitespace-separated token matches the regex `^\\d+[smhd]$` (case-insensitive), that token is the interval. Examples: `5m`, `2h`, `1d`, `30s`. The rest of the input is the prompt.\n\n2. **Trailing `every <N><unit>` clause.** Otherwise, look for a clause at the end of the input of the form `every <N><unit>` or `every <N> <unit-word>` where `<unit>` is `s|m|h|d` and `<unit-word>` is `second(s)|minute(s)|hour(s)|day(s)`. Strip the clause; what's left is the prompt; the captured `<N><unit>` is the interval. Examples: `every 20m`, `every 5 minutes`, `every 2 hours`.\n\n3. **Default.** No interval found → interval is `10m`, the whole input is the prompt.\n\nIf the input is empty, or is *only* an interval with no prompt body, reply with a one-line usage hint (`/loop [interval] <prompt>`) and stop. Do not schedule anything.\n\n## 2. Special: empty prompt with autonomous opt-in\n\nWhen the user types `/loop <interval>` (interval only) **and** the project has explicitly opted into autonomous-loop mode (a session-level flag the runtime sets), the prompt body is the sentinel `<<autonomous-loop>>`. The scheduler expands this sentinel at fire time into a self-directed tick instruction. If autonomous mode is not enabled, treat empty as the usage-hint case above.\n\n## 3. Map interval → 5-field cron expression\n\n| Pattern | Cron expression |\n|---|---|\n| `Ns` | treat as `ceil(N/60)m`; minimum is `1m` |\n| `Nm` where `N` is 1–59 and divides cleanly (1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30) | `*/N * * * *` |\n| `Nm` where `N ≥ 60` and `N/60` divides 24 (1, 2, 3, 4, 6, 8, 12) | `0 */(N/60) * * *` |\n| `Nh` where `N` is 1–23 and divides 24 | `0 */N * * *` |\n| `Nd` where `N` divides 31 sensibly (1, 2) | `0 0 */N * *` |\n\nCron fields are UTC. These interval patterns are timezone-agnostic; the `Nd`\nrow fires at midnight UTC, not local midnight.\n\n**Rounding rule.** If `N` does not divide its wrap-around cleanly (e.g. `7m`, `90m`, `5h`, `7d`), pick the **nearest interval that does** and tell the user explicitly what you rounded to and why. Acceptable nearby values:\n\n- minutes < 60: 1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30\n- hours: 1, 2, 3, 4, 6, 8, 12\n- days: 1, 2\n\nExamples of rounding messages:\n- `7m` → \"rounding 7m to 6m so the fires stay evenly spaced; `*/7` skews at the hour wrap\"\n- `90m` → \"rounding 90m to 2h; cron's hour field can't express 1.5h\"\n\n## 4. Call the cron tool\n\nWith the parsed `cron` expression and `prompt`, invoke the `cron` tool's `schedule` verb. Use whichever call form the tool's own prompt describes — pass `cron` and `prompt` as required, leave `durable: false` (the default; only set true when the user explicitly asked the job to persist across sessions), leave it recurring (the default; one-shot is wrong for `/loop` — one-shots come from natural-language scheduling).\n\nThe cron tool returns a job id. Mention it briefly so the user can cancel with `/loops cancel <id>`.\n\n## 5. Execute the prompt once immediately\n\nAfter the cron call succeeds, **do not wait for the first scheduled tick**. Run the prompt body once right now:\n\n- If the prompt starts with `/` (e.g. `/loop 5m /standup` → prompt is `/standup`), invoke it as a slash command — load the corresponding skill or command via the `skill` tool.\n- Otherwise, act on the prompt directly in this turn.\n\nThis is the \"don't make the user wait\" rule. The cron job carries the recurring behavior; the immediate run is for responsiveness.\n\n## 6. Examples\n\n| User input | Interval | Cron | Prompt |\n|---|---|---|---|\n| `/loop 5m /babysit-prs` | `5m` (leading) | `*/5 * * * *` | `/babysit-prs` |\n| `/loop check the deploy every 20m` | `20m` (trailing) | `*/20 * * * *` | `check the deploy` |\n| `/loop /standup every 2 hours` | `2h` | `0 */2 * * *` | `/standup` |\n| `/loop tidy inbox` | `10m` (default) | `*/10 * * * *` | `tidy inbox` |\n| `/loop 30s ping` | `30s` → `1m` | `*/1 * * * *` | `ping` |\n| `/loop 7m ping` | `7m` → `6m` (rounded, explain) | `*/6 * * * *` | `ping` |\n| `/loop` | (usage hint) | — | — |\n| `/loop 5m` | autonomous-only | (if enabled) | `<<autonomous-loop>>` |\n\n## 7. Do not\n\n- Do not invent intervals the user didn't ask for. If unsure, default to `10m` and say so.\n- Do not pass `--one-shot`. This skill is for recurring loops.\n- Do not list active jobs in your reply. Use `/loops` for that.\n- Do not re-derive the cron expression in your reply unless the user asked. A one-line confirmation (\"scheduled `<prompt>` every `<interval>`; job id `<id>`\") is enough.\n","frontmatter":{"name":"loop","description":"Schedule a prompt to fire on a fixed cadence (recurring loop). Use when the user asks to \"run X every N minutes/hours/days\", \"loop X\", \"babysit Y\", \"be proactive about Y every N\", or invokes `/loop` directly. Parses `[interval] <prompt>`, picks a clean cron expression, registers the job via the `cron` tool, and executes the prompt once immediately so the user sees activity without waiting for the first cron tick."},"isInternal":false,"tokens":1596,"sizeBytes":5285},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/mate/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/mate/SKILL.md","title":"mate","category":"anthropic-skill","format":"markdown","content":"---\nname: mate\ndescription: \"Create custom desktop pet (Mate) characters with spritesheet and manifest. Use when the user asks to 'create a pet', 'make a desktop companion', 'design a mate character', 'generate a spritesheet for my pet', or wants to customize their desktop buddy. Generates a WebP spritesheet + manifest.json that can be loaded by MiMo Desktop's Mate system.\"\n---\n\n# Mate Pet Creator\n\nCreate animated desktop pet characters for MiMo Desktop's Mate (桌面伙伴) system.\n\n## Output Structure\n\nA valid custom pet lives in a folder with this structure:\n\n```\n<pet-id>/\n├── manifest.json     # Required — animation metadata\n└── spritesheet.webp  # Required — all animation frames in a grid\n```\n\nThe user places this folder in their MiMo Desktop custom pets directory (`userData/pets/<pet-id>/`), then clicks \"Refresh\" in Settings → Mate to load it.\n\n## Manifest Schema\n\n```json\n{\n  \"id\": \"my-pet\",\n  \"name\": \"My Pet\",\n  \"description\": \"A cute custom pet\",\n  \"version\": 1,\n  \"spritesheet\": \"spritesheet.webp\",\n  \"frameWidth\": 240,\n  \"frameHeight\": 240,\n  \"columns\": 8,\n  \"totalFrames\": 16,\n  \"animations\": {\n    \"idle\": { \"row\": 0, \"frames\": 8, \"fps\": 8, \"loop\": true }\n  }\n}\n```\n\n### Required Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `id` | string | Unique identifier (kebab-case) |\n| `name` | string | Display name |\n| `version` | number | Always `1` |\n| `spritesheet` | string | Filename of the spritesheet image |\n| `frameWidth` | number | Width of each frame in pixels |\n| `frameHeight` | number | Height of each frame in pixels |\n| `columns` | number | Number of columns in the spritesheet grid |\n| `totalFrames` | number | Total number of frames across all animations |\n| `animations` | object | At minimum must include `idle` |\n\n### Optional Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `description` | string | Shown in settings UI |\n| `anchorX` | number | Horizontal anchor (0–1, default 0.5) for centering |\n\n### Animation Definition\n\nEach animation entry:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `row` | number | Row index in the spritesheet (0-based) |\n| `frames` | number | Number of frames in this animation |\n| `fps` | number | Playback speed (recommended: 6–12) |\n| `loop` | boolean | Whether the animation loops |\n\nThe `idle` animation is **required** — it plays by default when the pet is loaded.\n\n## Spritesheet Layout\n\n- Frames are arranged left-to-right, top-to-bottom in a grid.\n- Each row corresponds to one animation (matched by the `row` field in the animation definition).\n- All frames must have identical dimensions (`frameWidth × frameHeight`).\n- Transparent background (alpha channel) is required — the pet window has no background.\n- Recommended frame size: 240×240 px (renders well at 1× scale on desktop).\n- Format: WebP with transparency (lossless or near-lossless for crisp pixel art).\n\n## Workflow\n\n### Step 1: Understand the Character\n\nAsk the user:\n- What animal/creature/character?\n- Art style preference (pixel art, cartoon, flat vector, kawaii)?\n- Any specific colors or features?\n\n### Step 2: Generate the Spritesheet\n\nUse the `imagegen` skill to generate the spritesheet image. Construct the prompt with these guidelines:\n- Request a **sprite sheet** with specific grid layout (e.g., \"8 frames in a single horizontal row, each frame 240×240 pixels\")\n- Specify **transparent background** (alpha channel)\n- Describe the **idle animation** motion: gentle breathing, blinking, tail wag, bobbing, etc.\n- Keep the character **centered** in each frame with consistent sizing\n- Style: match the user's preference; default to cute/kawaii if unspecified\n\nIf the generated image is already WebP, use it directly. If it is PNG or another format, convert to WebP:\n\n```bash\n# Convert to lossless WebP preserving transparency\ncwebp -lossless -q 100 spritesheet.png -o spritesheet.webp\n```\n\nIf `cwebp` is not available, check for `sips` (macOS Ventura+ supports WebP export):\n\n```bash\nsips -s format webp spritesheet.png --out spritesheet.webp\n```\n\nIf neither tool is available, instruct the user to install one:\n\n```\nbrew install webp   # provides cwebp\n```\n\nDo NOT silently rename a PNG to .webp — the file must have valid WebP encoding (RIFF/WEBP header). If conversion genuinely cannot be performed, fail explicitly and tell the user what tool to install.\n\nIf `imagegen` is unavailable (skill not enabled or image generation fails), fall back to generating pixel-art frames directly as SVG, then rasterize. Compute dimensions from the manifest:\n\n```bash\n# Calculate actual spritesheet dimensions from manifest\nWIDTH=$((frameWidth * columns))\nHEIGHT=$((frameHeight * rows))  # rows = max animation row index + 1\n\n# Rasterize SVG to PNG, then convert to WebP\nrsvg-convert -w $WIDTH -h $HEIGHT spritesheet.svg -o spritesheet.png\ncwebp -lossless spritesheet.png -o spritesheet.webp\n```\n\nAs a last resort, output the SVG file directly and instruct the user to convert it manually.\n\n### Step 3: Write the Manifest\n\nGenerate `manifest.json` with correct dimensions matching the actual spritesheet output. Verify:\n- `frameWidth × columns` = spritesheet total width\n- `frameHeight × (max animation row index + 1)` = spritesheet total height\n- `animations.idle` exists with valid `row`, `frames`, `fps`, `loop`\n- Each animation's `frames` ≤ `columns` (frames per row cannot exceed grid columns)\n\n### Step 4: Deliver\n\nWrite both files to the current working directory under a folder named with the pet ID. Tell the user to:\n1. Copy the folder to their MiMo Desktop pets directory (Settings → Mate → click \"Open Folder\" to find it)\n2. Click \"Refresh\" in Settings → Mate\n3. Select their new pet from the list\n\n## Constraints\n\n- The `idle` animation MUST exist — the system falls back to it.\n- Frame dimensions must be consistent across the entire spritesheet.\n- Keep total file size under 2MB for smooth loading.\n- Pet ID must be unique; if it conflicts with a preset (`koala`, `panda`), the preset wins.\n- Do NOT reference or depend on any external URLs — all assets must be local files.\n","frontmatter":{"name":"mate","description":"Create custom desktop pet (Mate) characters with spritesheet and manifest. Use when the user asks to 'create a pet', 'make a desktop companion', 'design a mate character', 'generate a spritesheet for my pet', or wants to customize their desktop buddy. Generates a WebP spritesheet + manifest.json that can be loaded by MiMo Desktop's Mate system."},"isInternal":false,"tokens":1512,"sizeBytes":6148},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/memory-search/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/memory-search/SKILL.md","title":"memory-search","category":"anthropic-skill","format":"markdown","content":"---\nname: \"memory-search\"\ndescription: \"Query the raw trajectory SQLite database directly when the built-in memory and history tools are insufficient. Use when you need structured analysis across sessions: finding repeated errors, grouping tool calls by pattern, verifying what was actually executed, or locating specific past commands/decisions that text search cannot surface. Provides the database schema, ready-to-use SQL query templates, and per-goal strategies.\"\n---\n\n# Memory Search: SQLite Trajectory Database\n\nDirect SQL access to mimocode's trajectory database for structured analysis that the `memory` (BM25 over curated markdown) and `history` (FTS over raw messages) tools cannot perform — aggregation, filtering by tool/status/time, cross-session pattern detection, and execution chain inspection.\n\n## When to use\n\n- You need to **aggregate or count** across sessions (e.g. \"which tool fails most often?\", \"how many sessions touched file X?\").\n- You need to **filter by structure** — tool name, status, agent_id, time range — not just text content.\n- You need to **view a complete execution chain** for a session (every tool call in order).\n- You need to **verify a memory claim** against what actually happened (the DB is the source of truth).\n- The `memory` and `history` tools returned nothing useful despite multiple query attempts.\n\n## Locating the database\n\n```bash\n# Typically at this path. MIMOCODE_DB env var overrides if set.\nsqlite3 -readonly ~/.local/share/mimocode/mimocode.db \".tables\"\n```\n\nAlways use `-readonly` or only SELECT queries — never modify the database.\n\n## Schema\n\n| Table | Purpose | Key columns |\n|-------|---------|-------------|\n| `session` | Session metadata | `id`, `project_id`, `title`, `time_created`, `parent_id` |\n| `message` | User/assistant turns | `id`, `session_id`, `agent_id`, `time_created`, `data` (JSON: `$.role`) |\n| `part` | Message parts (text, tool calls, steps) | `id`, `message_id`, `session_id`, `time_created`, `data` (JSON) |\n| `task` | Task tree | `id`, `session_id`, `summary`, `status` |\n| `task_event` | Task state transitions | `id`, `session_id`, `task_id`, `at`, `kind`, `summary` |\n| `actor_registry` | Subagent/peer history | `session_id`, `actor_id`, `agent`, `mode`, `status`, `description` |\n\n### Part types in `part.data`\n\n- `{\"type\":\"text\",\"text\":\"...\"}` — agent text output\n- `{\"type\":\"tool\",\"tool\":\"<name>\",\"callID\":\"...\",\"state\":{\"status\":\"completed\",\"input\":{...},\"output\":\"...\"}}` — completed tool call\n- `{\"type\":\"tool\",\"tool\":\"<name>\",\"callID\":\"...\",\"state\":{\"status\":\"error\",\"input\":{...},\"error\":\"...\"}}` — failed tool call (no `output` field; error message in `$.state.error`)\n- `{\"type\":\"step-start\"}` / `{\"type\":\"step-finish\",\"tokens\":...}` — step boundaries\n- `{\"type\":\"compaction\",\"auto\":true/false}` — compaction boundary\n- `{\"type\":\"checkpoint\",...}` — checkpoint/rebuild boundary\n\n### Key conventions\n\n- `agent_id = 'main'` = main agent; other values = subagent (e.g. `\"explore-1\"`, `\"general-1\"`).\n- `$.state.output` only exists when `$.state.status = \"completed\"`. Failures store the message in `$.state.error`.\n- `time_created` is Unix milliseconds.\n\n## Query templates\n\n**List recent sessions for this project:**\n\n```sql\nSELECT id, title, time_created,\n       datetime(time_created/1000, 'unixepoch', 'localtime') as created\nFROM session\nWHERE project_id = '<PROJECT_ID>'\n  AND parent_id IS NULL\nORDER BY time_created DESC\nLIMIT 20;\n```\n\n**Find user messages containing a keyword:**\n\n```sql\nSELECT m.session_id, m.id,\n       substr(json_extract(p.data, '$.text'), 1, 200) as preview\nFROM message m\nJOIN part p ON p.message_id = m.id AND p.session_id = m.session_id\nWHERE json_extract(m.data, '$.role') = 'user'\n  AND json_extract(p.data, '$.type') = 'text'\n  AND json_extract(p.data, '$.text') LIKE '%keyword%'\nORDER BY m.time_created DESC\nLIMIT 10;\n```\n\n**Find tool calls by tool name:**\n\n```sql\nSELECT m.session_id, m.id, m.agent_id,\n       json_extract(p.data, '$.tool') as tool,\n       json_extract(p.data, '$.state.status') as status,\n       substr(COALESCE(json_extract(p.data, '$.state.output'), json_extract(p.data, '$.state.error')), 1, 300) as result_preview\nFROM message m\nJOIN part p ON p.message_id = m.id AND p.session_id = m.session_id\nWHERE json_extract(m.data, '$.role') = 'assistant'\n  AND json_extract(p.data, '$.type') = 'tool'\n  AND json_extract(p.data, '$.tool') = '<TOOL_NAME>'\n  AND m.session_id = '<SESSION_ID>'\nORDER BY m.time_created DESC\nLIMIT 20;\n```\n\n**View a session's full execution chain:**\n\n```sql\nSELECT m.id, m.agent_id,\n       json_extract(p.data, '$.type') as part_type,\n       json_extract(p.data, '$.tool') as tool,\n       substr(p.data, 1, 800) as preview\nFROM message m\nJOIN part p ON p.message_id = m.id AND p.session_id = m.session_id\nWHERE m.session_id = '<SESSION_ID>'\n  AND json_extract(m.data, '$.role') = 'assistant'\nORDER BY m.time_created, p.time_created;\n```\n\n**Find repeated stdout errors (completed bash calls, last 7 days):**\n\n```sql\nSELECT substr(json_extract(p.data, '$.state.output'), 1, 200) as error_output,\n       COUNT(*) as occurrences,\n       GROUP_CONCAT(DISTINCT m.session_id) as sessions\nFROM part p\nJOIN message m ON m.id = p.message_id AND m.session_id = p.session_id\nWHERE json_extract(p.data, '$.type') = 'tool'\n  AND json_extract(p.data, '$.tool') = 'bash'\n  AND json_extract(p.data, '$.state.status') = 'completed'\n  AND json_extract(p.data, '$.state.output') LIKE '%error%'\n  AND m.time_created > (strftime('%s', 'now') - 7*86400) * 1000\nGROUP BY substr(json_extract(p.data, '$.state.output'), 1, 200)\nHAVING occurrences > 1\nORDER BY occurrences DESC\nLIMIT 10;\n```\n\n**Find actual tool failures (any tool, last 7 days):**\n\n```sql\nSELECT json_extract(p.data, '$.tool') as tool,\n       substr(json_extract(p.data, '$.state.error'), 1, 200) as error_msg,\n       COUNT(*) as occurrences,\n       GROUP_CONCAT(DISTINCT m.session_id) as sessions\nFROM part p\nJOIN message m ON m.id = p.message_id AND m.session_id = p.session_id\nWHERE json_extract(p.data, '$.type') = 'tool'\n  AND json_extract(p.data, '$.state.status') = 'error'\n  AND m.time_created > (strftime('%s', 'now') - 7*86400) * 1000\nGROUP BY json_extract(p.data, '$.tool'), substr(json_extract(p.data, '$.state.error'), 1, 200)\nHAVING occurrences > 1\nORDER BY occurrences DESC\nLIMIT 10;\n```\n\n## Search strategies\n\n| Goal | Strategy |\n|------|----------|\n| Find a user's stated rule/preference | Search user text parts for `'%always%'`, `'%never%'`, `'%remember%'`, `'%rule%'` |\n| Find a design decision | Search `'%decided%'`, `'%tradeoff%'`, `'%reason%'` in user text |\n| Find a specific file path or command | LIKE match on tool output/error |\n| Find repeated workflows | Group tool call sequences by session, look for recurring tool×N patterns |\n| Verify a memory claim | Find the session_id from the memory entry `[ses_xxx]`, then query its full execution chain |\n| Count tool usage | `GROUP BY json_extract(p.data, '$.tool')` with COUNT |\n\n## Constraints\n\n- **Read-only**: Never modify the database. Always `sqlite3 -readonly` or SELECT only.\n- **Performance**: The DB can be multi-GB. Always use LIMIT and filter by `session_id` or `time_created` range.\n- **Privacy**: Raw trajectory contains everything the user typed. Treat it with care.\n- **JSON access**: Part data is JSON-in-a-column. Always use `json_extract()` for structured field access.\n","frontmatter":{"name":"memory-search","description":"Query the raw trajectory SQLite database directly when the built-in memory and history tools are insufficient. Use when you need structured analysis across sessions: finding repeated errors, grouping tool calls by pattern, verifying what was actually executed, or locating specific past commands/decisions that text search cannot surface. Provides the database schema, ready-to-use SQL query templates, and per-goal strategies."},"isInternal":false,"tokens":1947,"sizeBytes":7405},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/mimocode-docs/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/mimocode-docs/SKILL.md","title":"mimocode-docs","category":"anthropic-skill","format":"markdown","content":"---\nname: mimocode-docs\ndescription: \"Use whenever the user asks about MiMoCode itself: features, TUI or CLI commands, keybindings, terminal compatibility, rendering glitches, TUI lag, SSH or remote rendering, agent modes (build / plan) and how to switch between them, configuration, file locations, providers, models, authentication, or custom OpenAI-compatible or Anthropic-compatible API endpoints. Especially trigger when a prompt supplies or asks to configure a base URL/baseURL, API key/apiKey, model name or ID, provider, Anthropic Messages API, or global/project mimocode.json/jsonc, or when the user asks how to enter or leave plan mode. Also trigger when a skill, task, subprocess, or external client needs to borrow this instance's models — the OpenAI-compatible /v1 chat endpoints every MiMoCode server serves, `mimo llm-server` task tokens, or how to expose a listening port for them. Use this skill to inspect existing config safely, make minimal changes, and verify them without guessing schema fields or model capabilities.\"\n---\n\n# MiMoCode\n\nYou are MiMoCode. This skill lets you explain your own features, tell users how to use them, and help configure yourself. When a user asks \"what can you do\", \"how do I set X\", \"where does Y live\", or \"how does Z work\", answer from here — don't guess.\n\n## Identity\n\nMiMoCode (CLI binary `mimo`) is an agentic coding tool with a terminal UI, built as a fork of OpenCode. Beyond OpenCode's core (multi-provider, TUI, LSP, MCP, plugins) it adds: persistent memory, intelligent context management, subagent orchestration, goal-driven autonomous loops, compose-next end-to-end delivery, Dynamic Workflows, and self-improvement via dream/distill.\n\n## Feature Map\n\n| Feature | What it is | How to reach it |\n|---------|-----------|-----------------|\n| **Agents / modes** | `build` (default, full tools), `plan` (read-only analysis), plus custom modes you define. Build and Plan can switch at any time; other custom or special modes lock once the first message is sent. Only the user enters a mode — no tool lets the agent switch into plan, and the agent does not raise plan mode unasked; from inside plan the agent can call `plan_exit` to ask for approval and hand the plan back to build | `Tab` cycles primary agents, or pick one in the agent dialog; add your own via `.mimocode/agent/<name>.md` (see @reference/guide.md) |\n| **Subagents** | Primary agent spawns `general`/`explore` helpers, parallel + background, with lifecycle/cancel | automatic; `actor` tooling |\n| **Persistent memory** | Markdown-backed memory with indexed search across `MEMORY.md`, `checkpoint.md`, `notes.md`, and `tasks/<id>/progress.md` | auto-injected on resume |\n| **Context management** | Auto-checkpoints, context reconstruction near limit, budgeted injection | automatic; tune via `checkpoint`/`compaction` config |\n| **Task tree** | `T1`, `T1.1`… tree, integrated with checkpoints | `task` tooling |\n| **Goal / stop condition** | Judge model verifies a stop condition before the agent halts | `/goal` |\n| **Compose mode** | Structured spec→ship lifecycle; entry is the `compose-next` skill — clarify, spec, implement, verify, review, finish. Do not combine it with plan mode | `/compose-next` (see @reference/guide.md) |\n| **Visual modes** | `vivid` (default: star field, meteors, logo effects, animated activity) and `minimal` (quiet visuals, stable activity indicators); independent from the animation override | `/vivid` or the visual-mode option in `ctrl+p` |\n| **Voice input** | Streaming ASR (TenVAD + MiMo ASR); needs `sox` | `/voice` |\n| **Dream** | Consolidates recent traces into project memory | `/dream` |\n| **Distill** | Packages repeated manual workflows into skills/subagents/commands | `/distill` |\n| **Scheduled prompts** | Cron/loop: inject a prompt on a schedule or repeating loop (UTC, 5-field) | `cron` tool · `/loop` · `/loops` |\n| **Dynamic Workflow** | JS scripts that orchestrate many subagents deterministically (fan-out, pipelines, nesting); built-ins include `deep-research`, `fact-check`, and `research-experiment` | `.mimocode/workflows/*.js` + `workflow` tool |\n| **Custom skills** | Add reusable task instructions under `.mimocode/skills/` | see the `skill-creator` skill |\n| **Skill discovery** | `/skill-name` slash invocation (2+ in one message auto-load with an orchestration plan); `skill_search` tool matches by exact name/alias + BM25 and auto-loads high-confidence hits; some builtins (`claude-code`, `codex`) only appear when their CLI is installed | `/` autocomplete · automatic |\n| **MCP** | Local & remote Model Context Protocol servers | `mcp` config + `mimo mcp` |\n| **Capability API** | Every session already serves this project's chat models over OpenAI-compatible `/v1` on a loopback port, so a skill or subprocess borrows a model instead of a provider key | `mimo llm-server issue` mints a scoped token and prints the base URL (see @reference/capability-api.md) |\n\n## Configuration Basics\n\nConfig file (JSON or JSONC), discovered by walking up from cwd:\n- **Project**: `.mimocode/mimocode.json` (or `.jsonc`)\n- **Global**: `~/.config/mimocode/mimocode.jsonc` (preferred for new files) or `mimocode.json`\n\nAdd `\"$schema\": \"https://mimo.xiaomi.com/mimocode/config.json\"` for editor validation. All top-level keys are optional; project config merges over global.\n\n```jsonc\n{\n  \"$schema\": \"https://mimo.xiaomi.com/mimocode/config.json\",\n  \"model\": \"provider/model\",\n  \"permission\": { \"external_directory\": { \"/tmp/**\": \"allow\" } }\n}\n```\n\n## Reference routing\n\nRead only the reference needed for the request, but read it before changing files:\n\n- Models, providers, API keys, base URLs, or OpenAI-/Anthropic-compatible endpoints: @reference/providers.md\n- Other config keys and on-disk locations: @reference/config.md\n- Task-oriented usage and setup: @reference/guide.md\n- Terminal compatibility, TUI rendering or lag, and SSH remote use: @reference/guide.md\n- CLI and slash commands: @reference/commands.md\n- Permission rules: @reference/permissions.md\n- MCP client-side sampling (servers borrowing your model, audio transcription): @reference/mcp-sampling.md\n- Lending this instance's chat models to a skill, task, or subprocess — the OpenAI-compatible `/v1` endpoints and the `mimo llm-server` tokens that reach them: @reference/capability-api.md\n- Dynamic Workflow: @reference/workflows.md\n\n## How-To Guide\n\nFor task-oriented walkthroughs — signing in & choosing a model, troubleshooting TUI rendering or lag, using MiMoCode over SSH, making memory remember project rules, writing custom slash commands, remapping keybinds, adding MCP servers, scheduling prompts (cron/loop), and using compose-next end-to-end delivery — see @reference/guide.md. For authoring and running **Dynamic Workflow** scripts (the in-script API, where to save `.js` workflow files, and the `workflow` tool) see @reference/workflows.md.\n\n**Built-in workflows** (runnable by name via the `workflow` tool, no file needed):\n- **`deep-research`** — comprehensive research report generator (brief → plan → parallel research → reflect → write → cold review). Pass `args: { dir, question, today, depth?, context? }`. Convergent/resumable.\n- **`fact-check`** — adversarial fact verification (plan → search → extract → group → 3-juror crosscheck → JSON findings). Pass the question as `args`.\n- **`research-experiment`** — autonomous metric-improvement loop with baseline, guarded iterations, audit, and report. It requires an eval command, metric extraction rule, and editable-file scope.\n\n## Where Things Live On Disk\n\nBase dirs follow `MIMOCODE_HOME` (if set, absolute) else XDG. Data typically lives at `~/.local/share/mimocode/` (memory, logs, extracted builtin skills), config at `~/.config/mimocode/`, cache at `~/.cache/mimocode/`. See @reference/config.md for the full layout and env vars.\n\n## Commands\n\n`mimo` subcommands (`mcp`, `run`, `agent`, `models`, `providers`, `upgrade`, `stats`, `export`/`import`, `github`/`pr`, `serve`, …) and slash commands (`/goal`, `/dream`, `/distill`, `/vivid`, `/voice`, `/loop`, `/connect`, `/<skill-name>`) are documented in @reference/commands.md.\n\n## Helping the User Configure\n\nWhen asked to change a behavior:\n1. Read the routed reference and identify the exact schema fields. Do not infer fields from another tool's config format.\n2. Determine scope from the request. Treat model/provider setup as global unless the user says it is project-only; use project config for explicitly repo-local behavior.\n3. Inspect only the exact config candidates. Never recursively search the user's home directory. Prefer an existing higher-precedence `.jsonc` file and preserve comments, `$schema`, unrelated providers, and other settings.\n4. Keep secrets out of tool output and the final response. When inspecting a config, redact values for keys such as `apiKey`, `token`, `secret`, and `password`; never dump the whole unredacted file merely to find its shape.\n5. Edit minimally. If the request says configure, use, or make default, also set the top-level `model`; if it only says add, leave the current selection unchanged.\n6. When persisting a newly supplied API key and model, also put that exact `provider/model` at the front of the TUI recent-model state so the user can switch to it immediately. Follow the merge procedure in @reference/providers.md; never replace favorites, variants, or unrelated recent models.\n7. Validate the parsed configuration with the narrowest relevant command and report the config and recent-model state files changed, selected provider/model, and whether a new session or re-selection is needed. Never include the credential in the summary.\n\nDon't invent config keys, model limits, context windows, output limits, modalities, reasoning support, or tool-call capabilities. Add optional model metadata only when the user supplied it or a current authoritative source verifies it. If a requested behavior has no key, say so and suggest the closest supported option.\n\n## Answering Feature Questions\n\n- Confirm the feature exists in the map above before describing it.\n- Give the trigger (command / key / config), then a one-line how.\n- For authoring reusable task instructions, use the `skill-creator` skill.\n- If unsure whether a detail is current, verify against the config schema or README rather than asserting.\n","frontmatter":{"name":"mimocode-docs","description":"Use whenever the user asks about MiMoCode itself: features, TUI or CLI commands, keybindings, terminal compatibility, rendering glitches, TUI lag, SSH or remote rendering, agent modes (build / plan) and how to switch between them, configuration, file locations, providers, models, authentication, or custom OpenAI-compatible or Anthropic-compatible API endpoints. Especially trigger when a prompt supplies or asks to configure a base URL/baseURL, API key/apiKey, model name or ID, provider, Anthropic Messages API, or global/project mimocode.json/jsonc, or when the user asks how to enter or leave plan mode. Also trigger when a skill, task, subprocess, or external client needs to borrow this instance's models — the OpenAI-compatible /v1 chat endpoints every MiMoCode server serves, `mimo llm-server` task tokens, or how to expose a listening port for them. Use this skill to inspect existing config safely, make minimal changes, and verify them without guessing schema fields or model capabilities."},"isInternal":false,"tokens":2442,"sizeBytes":10384},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/modern-python-toolchain/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/modern-python-toolchain/SKILL.md","title":"modern-python-toolchain","category":"anthropic-skill","format":"markdown","content":"---\nname: modern-python-toolchain\ndescription: \"Modern Python project setup with uv, ruff, and pyright. Use when initializing a new Python project, configuring the Python environment, setting up linting/formatting, or when a project needs uv (the fast Python package manager). Trigger on: 'set up Python', 'new Python project', 'configure uv', 'install uv', 'ruff', 'pyright', 'Python linting', 'Python formatting', or when a task requires Python and no pyproject.toml exists yet.\"\n---\n\n# Modern Python Toolchain\n\nA guide for setting up Python projects with modern, fast tooling: **uv** (package/project manager), **ruff** (linter/formatter), and **pyright** (type checker).\n\n## Installing uv\n\nuv is an extremely fast Python package and project manager. It replaces pip, pip-tools, pipx, pyenv, virtualenv, poetry, etc.\n\n```bash\n# macOS / Linux\ncurl -LsSf https://astral.sh/uv/install.sh | sh\n\n# Windows (PowerShell)\npowershell -ExecutionPolicy ByPass -c \"irm https://astral.sh/uv/install.ps1 | iex\"\n\n# Homebrew (macOS)\nbrew install uv\n```\n\nAfter installation, restart your shell or run `source $HOME/.local/bin/env` (the installer prints the exact command).\n\nFor detailed information: https://docs.astral.sh/uv/\n\n---\n\n## uv basics\n\n### Python version\n\nPin a single Python minor version. The recommended default is 3.12 (broadest ecosystem support — PyTorch, CUDA images, downstream libraries). Python 3.14 is the latest stable; prefer it for new projects unless you depend on packages that haven't added 3.14 support yet.\n\n```toml\n# pyproject.toml\nrequires-python = \"==3.12.*\"\n```\n\nInstall Python via uv (no system Python needed):\n\n```bash\nuv python install 3.12\n```\n\n### Creating a new project\n\n```bash\nuv init                       # Create new project with pyproject.toml\nuv init -p 3.12               # Specify Python version\n```\n\n### Common commands\n\n```bash\nuv add requests               # Add dependency\nuv add --dev ruff \"pyright[nodejs]\"  # Add dev dependencies\nuv remove requests            # Remove dependency\nuv sync                       # Install from lockfile\nuv run COMMAND                # Run command in project environment\nuv run script.py              # Run a script\nuv run python -c \"...\"        # Run Python one-liner\nuvx TOOL ARGS                 # Run a tool without installing it\n```\n\n### Rules\n\n- **Never use `pip`** in uv projects — always `uv add` for packages.\n- **Never run `python script.py` directly** — always `uv run script.py` to ensure the correct environment. For one-liners use `uv run python -c \"...\"`.\n- **Don't manually manage environments** with `python -m venv` or `source .venv/bin/activate` — uv handles this automatically.\n- `uvx` runs tools from PyPI by package name without installing them permanently.\n\n### Project types\n\nFor **library** projects (`uv init --lib`) or packaged apps (`uv init --package`), `uv_build` is used as the default build backend automatically:\n\n```toml\n[build-system]\n# auto-generated by uv init; version bound tracks your installed uv (here: 0.11.28)\nrequires = [\"uv_build>=0.11.28,<0.12.0\"]\nbuild-backend = \"uv_build\"\n```\n\nFor **application** projects with an entry point:\n\n```toml\n[project.scripts]\nmyapp = \"myapp.__main__:main\"\n```\n\nIf the project does not use src layout, just run `uv run main.py`.\n\n---\n\n## ruff\n\nRuff is an extremely fast Python linter and code formatter. It replaces Flake8, isort, Black, pyupgrade, autoflake, and more.\n\nFor detailed information: https://docs.astral.sh/ruff/\n\n### When to use\n\nAlways use ruff for Python linting and formatting. Prefer `uv run ruff` when ruff is a dev dependency; otherwise fall back to `uvx ruff`.\n\n### Configuration\n\nAdd to `pyproject.toml`:\n\n```toml\n[tool.ruff.lint]\nextend-select = [\n    \"UP\",  # pyupgrade\n    \"I\",   # isort\n]\n```\n\nDo not enable the full `E` category or other formatter-conflicting rules (E1xx, E501, W191, Q, COM); `ruff format` owns layout.\n\n### Post-edit workflow\n\nAfter modifying Python code, run both:\n\n```bash\nuv run ruff check --fix path/to/changed_file.py\nuv run ruff format path/to/changed_file.py\n```\n\nUse `--diff` to preview changes without applying.\n\n---\n\n## pyright\n\nPyright is a fast type checker for Python. Only use it when the project lists it as a dev dependency or explicitly uses type checking.\n\nInstall with the `nodejs` extra so Node.js is bundled automatically (no system `node` required):\n\n```bash\nuv add --dev \"pyright[nodejs]\"\n```\n\nRun type checking:\n\n```bash\nuv run pyright path/to/changed_file.py    # check specific files\nuv run pyright src/                        # check all code\n```\n\nUsually only check the files you modified. For broad changes (base classes, shared types), check the full tree.\n\n---\n\n## Coding style\n\n### Type annotations\n\nUse modern Python 3.12+ syntax:\n\n```python\n# Good — builtin generics, union syntax\ndef fetch(url: str, timeout: float = 30.0) -> list[dict[str, str | None]]:\n    ...\n\n# Bad — legacy typing imports\nfrom typing import List, Dict, Optional\ndef fetch(url: str, timeout: float = 30.0) -> List[Dict[str, Optional[str]]]:\n    ...\n```\n\nAlways annotate function parameters. Local variables can rely on inference unless the type is ambiguous:\n\n```python\nitems: list[tuple[str, int]] = []    # annotate — empty literal\nconfig: dict[str, Any] = {}          # annotate — empty literal\nresult = some_api()                  # inference is fine\n```\n\n### pydantic v2\n\nUse the modern class-based API:\n- `model_config = ConfigDict(...)` at class body level, not `class Config`.\n- `RootModel` with `root: SomeType` for single-root schemas.\n\n### typer (CLI)\n\nRecommended for CLI entry points over `argparse`:\n\n```python\nimport typer\nfrom typing import Annotated\n\ncli = typer.Typer(add_completion=False)\n\n@cli.command()\ndef main(name: Annotated[str, typer.Argument(help=\"Your name\")]) -> None:\n    typer.echo(f\"Hello {name}\")\n\nif __name__ == \"__main__\":\n    cli()\n```\n","frontmatter":{"name":"modern-python-toolchain","description":"Modern Python project setup with uv, ruff, and pyright. Use when initializing a new Python project, configuring the Python environment, setting up linting/formatting, or when a project needs uv (the fast Python package manager). Trigger on: 'set up Python', 'new Python project', 'configure uv', 'install uv', 'ruff', 'pyright', 'Python linting', 'Python formatting', or when a task requires Python and no pyproject.toml exists yet."},"isInternal":false,"tokens":1483,"sizeBytes":5889},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/pdf-official/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/pdf-official/SKILL.md","title":"pdf-official","category":"anthropic-skill","format":"markdown","content":"---\nname: pdf-official\ndescription: \"Use this skill whenever a PDF file is being produced, opened, transformed, filled, or read. That includes: extracting text or tables from an existing PDF; combining, carving, rotating, cropping, or watermarking pages; composing a fresh PDF (report, invoice, certificate); filling AcroForm fields or overlaying text onto a non-fillable scanned form; encrypting or unlocking a PDF; running OCR over a scanned document; rendering pages to PNG/JPEG for visual analysis. Trigger on mentions of 'PDF', a filename ending in .pdf, requests like 'turn this into a PDF report', or references to AcroForm / form fields.\"\nlicense: Apache-2.0 — see LICENSE for terms and third-party attributions\n---\n\n# PDF skill\n\nAn Apache-2.0 toolkit for reading, composing, transforming, and filling PDF\nfiles. Written from scratch on top of permissively-licensed open-source\nlibraries (pypdf, pdfplumber, pypdfium2, reportlab, pdf-lib, qpdf) so this\ncan be embedded in commercial projects without special agreement.\n\n## Route the task\n\nPick the sub-guide by the *verb* of the request.\n\n| Task | Path | Read |\n|------|------|------|\n| Pull text / tables / metadata / images out of an existing PDF | Extract | [`extract.md`](extract.md) |\n| Combine, carve, rotate, crop, watermark, encrypt, or shrink | Transform | [`transform.md`](transform.md) |\n| Build a PDF that doesn't exist yet (report, invoice, certificate) | Compose | [`compose.md`](compose.md) |\n| Fill a form (AcroForm or scanned) | Interactive | [`interactive.md`](interactive.md) |\n| Scanned / image-only PDF (no selectable text) | Extract → *OCR* | [`extract.md`](extract.md) §5 |\n\nIf a task mixes several of these, follow the order:\n**probe → plan → extract or compose → validate.**\n\nEvery path starts with a probe. `scripts/survey.py` returns page count,\nwhether the file is encrypted, whether it has an AcroForm, and whether\npage 1 looks like a scan.\n\n## First install\n\n> **Bundled runtime:** when the `MIMO_PYTHON` environment variable is set, skip the installs below — run every command with `python3`/`uv run` replaced by `\"$MIMO_PYTHON\"` (pypdf/pypdfium2/reportlab/Pillow preinstalled; pip console scripts unavailable, use `\"$MIMO_PYTHON\" -m <module>`). A bundled qpdf is exposed as `MIMO_QPDF` (picked up automatically by the scripts here); invoke it directly as `\"$MIMO_QPDF\" --check file.pdf`.\n\nPython-only path (all BSD / MIT / Apache) — covers 95% of tasks:\n\n```bash\npython3 -m pip install --upgrade pypdf pdfplumber pypdfium2 reportlab Pillow\n```\n\nAdd these external binaries only when you actually need them:\n\n```bash\n# qpdf — merge/split/encrypt/repair, Apache-2.0\nbrew install qpdf                # macOS\napt-get install -y qpdf          # Debian / Ubuntu\n\n# Tesseract — OCR for scanned PDFs, Apache-2.0\nbrew install tesseract\npython3 -m pip install pytesseract pdf2image\napt-get install -y tesseract-ocr\n\n# Poppler — pdftotext / pdftoppm / pdfimages, GPL-2.0\n# Optional. Only install if you accept a GPL dependency at CLI level.\nbrew install poppler\napt-get install -y poppler-utils\n```\n\nEvery script under `scripts/` uses argparse. Exit codes:\n`0` OK · `1` runtime failure · `2` bad arguments · `3` validation failure\n(`apply_values.py` / `overlay_text.py`; `sanity_check.py` reports findings\nwith exit `1`).\nAny single script can be lifted into another project — none imports from a\nshared framework.\n\n## One-command triage\n\n```bash\nscripts/survey.py path/to/file.pdf --pretty\n```\n\nSample output:\n\n```json\n{\n  \"path\": \"/abs/path/file.pdf\",\n  \"page_count\": 12,\n  \"is_locked\": false,\n  \"form_field_count\": 34,\n  \"looks_scanned\": false,\n  \"metadata\": {\"Title\": \"...\", \"Author\": \"...\", \"Producer\": \"...\"}\n}\n```\n\nRoute by the flags:\n\n- `is_locked: true` → unlock first (`qpdf --password=… --decrypt`). Almost\n  every reader library refuses locked files.\n- `form_field_count > 0` → widgets path in [`interactive.md`](interactive.md) §1.\n- `form_field_count == 0` AND you need to fill it → overlay path\n  in [`interactive.md`](interactive.md) §2.\n- `looks_scanned: true` → skip pypdf text extraction, go straight to OCR\n  ([`extract.md`](extract.md) §5).\n\n## Which library for which task\n\n| Task | Preferred | Reason | Fallback |\n|------|-----------|--------|----------|\n| Plain text | `pdftotext -layout` | fastest, keeps columns | `pypdf` |\n| Positioned text | `pdfplumber` | char-level bboxes | `pypdfium2.get_text` |\n| Tables | `pdfplumber` | tunable `table_settings` | pandas over manual CSV |\n| Page → image | `pypdfium2` | Apache/BSD, no GPL | `pdftoppm` (GPL) |\n| Merge / carve / rotate | `pypdf` | pure Python | `qpdf --pages` (faster on huge files) |\n| Encrypt / repair / linearise | `qpdf` | handles broken input | pypdf (basic encrypt only) |\n| Compose from scratch | `reportlab` | mature, BSD | `pdf-lib` in Node |\n| Fill AcroForm | `pypdf.update_page_form_field_values` | preserves widget appearances | `pdf-lib` in Node |\n| Overlay on non-fillable | reportlab + `pypdf.merge_page` | two-layer merge, see interactive.md | — |\n\n## Common gotchas\n\n1. **PDF origin is bottom-left**, image origin is top-left. Every \"off by a\n   few points\" bug is one of these two systems misapplied. Coordinate\n   conversion is in one place: [`interactive.md`](interactive.md) §2.c.\n2. **`pypdf.extract_text()` returns nothing for scans.** That's not a bug —\n   there's no text stream. Use the `looks_scanned` flag and route to OCR.\n3. **Unicode subscripts / superscripts render as black rectangles in\n   reportlab** because Helvetica/Times/Courier don't ship those glyphs. Use\n   `<sub>` / `<super>` XML in `Paragraph`, or move the pen manually on canvas.\n   See [`compose.md`](compose.md) §5.\n4. **CJK text renders as black boxes when the font never registered.**\n   reportlab does not consult the OS font system; a bad font name/path (思源黑体,\n   PingFang, Noto on machines that lack it) plus a swallowed exception means a\n   silent Helvetica fallback — and Helvetica has no CJK glyphs. Resolve fonts\n   with the ladder in [`compose.md`](compose.md) §4 (`resolve_cjk_font()`);\n   the terminal fallback is the built-in CID font, never Helvetica.\n5. **XFA forms are not AcroForms.** If `probe_fields.py` returns `[]` on a\n   PDF that clearly has widgets in Adobe Reader, it's XFA — flatten it in\n   Acrobat first.\n6. **`writer.encrypt(pw)` in pypdf uses RC4 by default**. For real AES-256,\n   pass `algorithm=\"AES-256\"`, or use `qpdf --encrypt … 256 --`.\n\n## What's next\n\nOpen the sub-guide from the routing table and work through it end to end.\nEach sub-guide has a Validation section at the bottom describing how to\nconfirm the result.\n","frontmatter":{"name":"pdf-official","description":"Use this skill whenever a PDF file is being produced, opened, transformed, filled, or read. That includes: extracting text or tables from an existing PDF; combining, carving, rotating, cropping, or watermarking pages; composing a fresh PDF (report, invoice, certificate); filling AcroForm fields or overlaying text onto a non-fillable scanned form; encrypting or unlocking a PDF; running OCR over a scanned document; rendering pages to PNG/JPEG for visual analysis. Trigger on mentions of 'PDF', a filename ending in .pdf, requests like 'turn this into a PDF report', or references to AcroForm / form fields.","license":"Apache-2.0 — see LICENSE for terms and third-party attributions"},"isInternal":false,"tokens":1756,"sizeBytes":6679},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/playwright/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/playwright/SKILL.md","title":"playwright","category":"anthropic-skill","format":"markdown","content":"---\nname: \"playwright\"\ndescription: \"Use when the task requires automating a real browser from the terminal (navigation, form filling, snapshots, screenshots, data extraction, UI-flow debugging) via `playwright-cli` or the bundled wrapper script.\"\n---\n\n\n# Playwright CLI Skill\n\nDrive a real browser from the terminal using `playwright-cli`. Prefer the bundled wrapper script so the CLI works even when it is not globally installed.\nTreat this skill as CLI-first automation. Do not pivot to `@playwright/test` unless the user explicitly asks for test files.\n\n## Prerequisite check (required)\n\nBefore proposing commands, check whether `npx` is available (the wrapper depends on it):\n\n```bash\ncommand -v npx >/dev/null 2>&1\n```\n\nIf it is not available, pause and ask the user to install Node.js/npm (which provides `npx`). Provide these steps verbatim:\n\n```bash\n# Verify Node/npm are installed\nnode --version\nnpm --version\n\n# If missing, install Node.js/npm, then:\nnpm install -g @playwright/cli@latest\nplaywright-cli --help\n```\n\nOnce `npx` is present, proceed with the wrapper script. A global install of `playwright-cli` is optional.\n\n## Skill path (set once)\n\n```bash\nexport CODEX_HOME=\"${CODEX_HOME:-$HOME/.codex}\"\nexport PWCLI=\"$CODEX_HOME/skills/playwright/scripts/playwright_cli.sh\"\n```\n\nUser-scoped skills install under `$CODEX_HOME/skills` (default: `~/.codex/skills`).\n\n## Quick start\n\nUse the wrapper script:\n\n```bash\n\"$PWCLI\" open https://playwright.dev --headed\n\"$PWCLI\" snapshot\n\"$PWCLI\" click e15\n\"$PWCLI\" type \"Playwright\"\n\"$PWCLI\" press Enter\n\"$PWCLI\" screenshot\n```\n\nIf the user prefers a global install, this is also valid:\n\n```bash\nnpm install -g @playwright/cli@latest\nplaywright-cli --help\n```\n\n## Core workflow\n\n1. Open the page.\n2. Snapshot to get stable element refs.\n3. Interact using refs from the latest snapshot.\n4. Re-snapshot after navigation or significant DOM changes.\n5. Capture artifacts (screenshot, pdf, traces) when useful.\n\nMinimal loop:\n\n```bash\n\"$PWCLI\" open https://example.com\n\"$PWCLI\" snapshot\n\"$PWCLI\" click e3\n\"$PWCLI\" snapshot\n```\n\n## When to snapshot again\n\nSnapshot again after:\n\n- navigation\n- clicking elements that change the UI substantially\n- opening/closing modals or menus\n- tab switches\n\nRefs can go stale. When a command fails due to a missing ref, snapshot again.\n\n## Recommended patterns\n\n### Form fill and submit\n\n```bash\n\"$PWCLI\" open https://example.com/form\n\"$PWCLI\" snapshot\n\"$PWCLI\" fill e1 \"user@example.com\"\n\"$PWCLI\" fill e2 \"password123\"\n\"$PWCLI\" click e3\n\"$PWCLI\" snapshot\n```\n\n### Debug a UI flow with traces\n\n```bash\n\"$PWCLI\" open https://example.com --headed\n\"$PWCLI\" tracing-start\n# ...interactions...\n\"$PWCLI\" tracing-stop\n```\n\n### Multi-tab work\n\n```bash\n\"$PWCLI\" tab-new https://example.com\n\"$PWCLI\" tab-list\n\"$PWCLI\" tab-select 0\n\"$PWCLI\" snapshot\n```\n\n## Wrapper script\n\nThe wrapper script uses `npx --package @playwright/cli playwright-cli` so the CLI can run without a global install:\n\n```bash\n\"$PWCLI\" --help\n```\n\nPrefer the wrapper unless the repository already standardizes on a global install.\n\n## References\n\nOpen only what you need:\n\n- CLI command reference: `references/cli.md`\n- Practical workflows and troubleshooting: `references/workflows.md`\n\n## Guardrails\n\n- Always snapshot before referencing element ids like `e12`.\n- Re-snapshot when refs seem stale.\n- Prefer explicit commands over `eval` and `run-code` unless needed.\n- When you do not have a fresh snapshot, use placeholder refs like `eX` and say why; do not bypass refs with `run-code`.\n- Use `--headed` when a visual check will help.\n- When capturing artifacts in this repo, use `output/playwright/` and avoid introducing new top-level artifact folders.\n- Default to CLI commands and workflows, not Playwright test specs.\n","frontmatter":{"name":"playwright","description":"Use when the task requires automating a real browser from the terminal (navigation, form filling, snapshots, screenshots, data extraction, UI-flow debugging) via `playwright-cli` or the bundled wrapper script."},"isInternal":false,"tokens":947,"sizeBytes":3771},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/pptx-official/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/pptx-official/SKILL.md","title":"pptx-official","category":"anthropic-skill","format":"markdown","content":"---\nname: pptx-official\ndescription: \"Use this skill whenever a Microsoft PowerPoint (.pptx) file is being produced, opened, transformed, or read. That includes: authoring slide decks, pitch decks, executive readouts, training material, or any presentation deliverable; extracting text or structure from an existing .pptx; filling a .pptx template with values; converting a deck to PDF or images; splitting or merging decks; inspecting slides, layouts, masters, tables, images, charts, speaker notes, or comments. Trigger on words like 'deck', 'slides', 'presentation', 'pitch deck', 'keynote' (when a .pptx is expected as output), or any filename ending in .pptx. Do NOT trigger when the primary deliverable is a Word document, spreadsheet, PDF report, HTML site, or Google Slides API call, even if presentation-shaped content appears along the way.\"\nlicense: Apache-2.0 — see LICENSE for terms and third-party attributions\n---\n\n# PPTX Skill\n\nAn Apache-2.0 toolkit for producing, editing, and reading Microsoft PowerPoint\n(`.pptx`) files. Written from scratch against the public\n[ECMA-376 / ISO/IEC 29500 (PresentationML)](https://www.ecma-international.org/publications-and-standards/standards/ecma-376/)\nspecification and built on permissively-licensed tooling (`python-pptx` MIT,\n`pptxgenjs` MIT, `lxml` BSD-3-Clause, `Pillow` MIT-CMU, optional external\nbinaries `soffice` MPL 2.0 and `pdftoppm` GPL) so it can be reused in\ncommercial projects without restriction.\n\n## Decision matrix\n\n| Situation | Path | Read first |\n|-----------|------|------------|\n| Build a deck from a prompt or dataset — no source file to start from | Author with `python-pptx` (structured / repeatable) or PptxGenJS (design-heavy, JS) | [`create.md`](create.md) |\n| You have a `.pptx` template to fill in — keep its master, layouts, look | Placeholder replacement via `python-pptx` | [`edit.md`](edit.md) → *Template fill* |\n| Deep structural edits — reorder slides, splice XML, add unusual objects | Explode → edit XML parts → assemble | [`edit.md`](edit.md) → *Raw XML workflow* |\n| Only need the text / speaker notes / structure out of a `.pptx` | Extraction pipeline | [`read.md`](read.md) |\n| Turn a deck into PDF or PNG images (visual QA, publishing) | `scripts/render_pdf.py` / `scripts/render_slides.py` via LibreOffice | see *QA* below |\n| Grid of slide thumbnails for previewing a template | `scripts/contact_sheet.py` (Pillow) | [`read.md`](read.md) → *Thumbnails* |\n\nIf the task mixes several of these, do them in this order:\n**read → plan slide-by-slide → edit/create → validate → visual QA.**\n\n## One-time environment setup\n\n> **Bundled runtime:** when the `MIMO_PYTHON` environment variable is set, skip `uv`/pip installs — run every Python command below with `uv run` replaced by `\"$MIMO_PYTHON\"` (python-pptx/Pillow/lxml preinstalled; pip console scripts unavailable, use `\"$MIMO_PYTHON\" -m <module>`). A bundled LibreOffice is exposed as `MIMO_SOFFICE` (picked up automatically by `soffice_bridge.py`/`render_pdf.py`), and slide rasterisation automatically falls back to pypdfium2 in that interpreter when Poppler (`pdftoppm`) is absent. For the PptxGenJS authoring path, bundled Node.js is exposed as `MIMO_NODE`, with pptxgenjs/react/react-dom/sharp/react-icons/mathjax-full preinstalled in `MIMO_NODE_MODULES` — run scripts as `NODE_PATH=\"$MIMO_NODE_MODULES\" \"$MIMO_NODE\" <script.js>` instead of `npm install`.\n\n### Prerequisites\n\nIf `uv` or `bun` are not yet installed:\n\n```bash\n# Install uv (Python package/project manager)\n# macOS / Linux\ncurl -LsSf https://astral.sh/uv/install.sh | sh\n# Windows: powershell -ExecutionPolicy ByPass -c \"irm https://astral.sh/uv/install.ps1 | iex\"\n\n# Install bun (TypeScript runtime, replaces Node.js for this workflow)\n# macOS / Linux\ncurl -fsSL https://bun.sh/install | bash\n# Windows: powershell -c \"irm bun.sh/install.ps1|iex\"\n```\n\nOnly if the user explicitly refuses `uv` / `bun`, substitute `pip` (in a venv you manage yourself) for `uv`, and `npm`/`pnpm` + `npx tsx` for `bun` — everything else in this skill stays the same.\n\n### Python (uv)\n\nPython dependencies are managed by `uv`. Do not use `pip` directly.\n\n```bash\n# Initialize project (if no pyproject.toml exists)\nuv init -p 3.12\n\n# Add dependencies\nuv add python-pptx lxml Pillow\nuv add defusedxml                  # safe XML parsing (recommended for manual XML edits)\n```\n\n**Rules:**\n- Never use `pip` — always `uv add` for packages.\n- Never run `python scripts/...` directly — always `uv run scripts/...`.\n- Don't manually manage environments with `python -m venv` or `source .venv/bin/activate`.\n\n### TypeScript (bun)\n\nFor PptxGenJS creation, use `bun` (project-local, not global installs):\n\n```bash\n# Initialize (if no package.json exists)\nbun init -y\n\n# Add dependencies\nbun add pptxgenjs                  # core PPTX creation library\nbun add react react-dom sharp      # rasterization (icons + formulas)\nbun add react-icons                # icon library (FA, MD, etc.)\nbun add mathjax-full               # LaTeX formula rendering\n\n# Type definitions (including Bun runtime types)\nbun add -d @types/bun @types/react @types/react-dom\n```\n\nCreate a `tsconfig.json` if one doesn't exist:\n```json\n{\n  \"compilerOptions\": {\n    \"lib\": [\"ESNext\"],\n    \"target\": \"ESNext\",\n    \"module\": \"Preserve\",\n    \"moduleResolution\": \"bundler\",\n    \"allowImportingTsExtensions\": true,\n    \"noEmit\": true,\n    \"jsx\": \"react-jsx\",\n    \"strict\": true,\n    \"skipLibCheck\": true,\n    \"types\": [\"bun\"]\n  }\n}\n```\n\nRun scripts directly as TypeScript — no transpilation needed:\n```bash\nbun run create-ppt.ts\n```\n\n**Always run type checking after writing or modifying TS code:**\n```bash\nbun tsc --noEmit\n```\nModels may inadvertently use outdated PptxGenJS API signatures or\ndeprecated syntax without realizing it. A type check catches these\nmismatches before runtime.\n\n### System dependencies (PDF/PNG rendering)\n\n```bash\n# macOS\nbrew install --cask libreoffice\nbrew install poppler\n\n# Debian/Ubuntu\nsudo apt-get install -y libreoffice poppler-utils\n```\n\nEvery script under `scripts/` uses only the standard library plus\n`python-pptx`, `lxml`, and `Pillow`. No proprietary dependencies. External\nbinaries (`soffice`, `pdftoppm`) are invoked as subprocesses; nothing is\nbundled or statically linked.\n\n## Common commands\n\n```bash\n# 1. Extract text from every slide (title, body, notes) — the \"what does it say?\" query\nuv run scripts/dump_text.py input.pptx --notes > input.txt\n\n# 2. Convert a deck to PDF for review\nuv run scripts/render_pdf.py input.pptx                     # writes input.pdf next to it\n\n# 3. Convert every slide to a PNG (visual QA)\nuv run scripts/render_slides.py input.pptx --out slides/       # writes slides/slide-1.png, ...\n\n# 4. Grid thumbnail preview (planning which template slide to reuse)\nuv run scripts/contact_sheet.py input.pptx --cols 3         # writes input.contact-sheet.jpg\n\n# 5. Explode a .pptx into readable XML for surgical edits\nuv run scripts/explode.py input.pptx unpacked/\n\n# 6. Reassemble an exploded tree\nuv run scripts/assemble.py unpacked/ output.pptx\n\n# 7. Drop orphaned slides and unused media before reassembly\nuv run scripts/prune.py unpacked/\n\n# 8. Duplicate slide 3, or spin up a new slide from layout 5\nuv run scripts/insert_slide.py unpacked/ --clone slide3.xml\nuv run scripts/insert_slide.py unpacked/ --blank-from slideLayout5.xml\n\n# 9. Well-formedness check (ZIP + XML + python-pptx round-trip)\nuv run scripts/diagnose.py output.pptx\n```\n\nEvery script is a small Python CLI. Some scripts (e.g. `render_pdf.py`,\n`render_slides.py`, `contact_sheet.py`) import from a shared helper\n(`soffice_bridge.py`) in the same directory — copy them together. Read the top\nof each file for its full CLI options.\n\n## Live preview\n\nA live preview server is available for real-time slide feedback.\n**Not started by default.** When multi-slide work begins, ask the user\nif they want live preview enabled.\n\n**Only offer this in a pure command-line environment.** This server is\nfor the MiMoCode CLI. If you are running inside a host that embeds\nMiMoCode via the SDK — a web UI, a desktop app, an IDE plugin, etc. —\nthat host almost certainly has its own native preview / file-open\nmechanism; use it instead and do NOT start this server.\n\nIf yes, and this is a CLI environment:\n\n```bash\n# `scripts/preview.ts` lives in this skill's bundle directory, not in\n# your cwd. Prefix it with the absolute path shown in this skill's\n# location header (the folder that contains SKILL.md) — refer to it\n# as <SKILL_DIR> below.\n\n# Start (spawns background server, prints URL, exits immediately)\nbun run <SKILL_DIR>/scripts/preview.ts /path/to/output.pptx\nbun run <SKILL_DIR>/scripts/preview.ts /path/to/output.pptx --port 5000\n\n# Stop\nbun run <SKILL_DIR>/scripts/preview.ts --stop /path/to/output.pptx\n```\n\nIf the server is already running, `preview.ts` detects this via PID file\nand prints the existing URL instead of spawning a duplicate.\n\nThe background server watches the `.pptx` file, debounces (800ms),\nconverts to PDF via LibreOffice, and pushes a WebSocket reload to the\nbrowser. The browser's native PDF viewer provides scroll, thumbnails,\nzoom, and search. Preview output goes to `.pptx-preview/` (separate\nfrom `qa/`, no conflict with other scripts).\n\nGive the user the printed URL to open in their browser.\n\n**Live preview is for humans only — it does NOT replace visual QA.**\nThe preview server lets the user watch progress. You must still run\nthe visual QA subagent (render PNGs to `qa/`, spawn a vision model to\ninspect them) as described in the \"Visual QA execution model\" section.\nThese are independent workflows:\n- Preview server → user sees live updates in browser\n- Visual QA subagent → automated inspection, catches issues you can't\n\n**When to regenerate the .pptx during multi-slide work:** If the user\nhas the preview server running, regenerate the `.pptx` (re-run the\ncreation script) after completing each logical module — e.g. after\nfinishing a section's slides, not after every single shape placement.\nThis gives the user meaningful visual checkpoints without excessive\nintermediate renders.\n\n## Authoring principles\n\nSlides are a **visual surface**. Users read the deck at 40 feet from the back\nof a room, or in a browser tab three inches wide on a phone. Both have to\nwork. Keep these in mind:\n\n1. **One idea per slide.** If you can't summarize the slide in a five-word\n   title, split it in two. Long-form reasoning belongs in the doc that\n   accompanies the deck, not on the slide itself.\n2. **Title, not label.** The title is the thesis of the slide. \"Revenue\" is a\n   label. \"Revenue grew 34% on 22% headcount\" is a title. Titles carry the\n   argument; bodies carry the evidence.\n3. **Every slide earns its visuals.** A slide without a chart, image, icon,\n   or shape is usually a bullet dump. Turn it into a comparison, a stat\n   callout, a diagram, or delete it. **A \"visual\" is not necessarily a\n   picture** — a stat callout, a comparison shape, or a well-typeset quote\n   is already a visual. When you do need a picture, see *Image sourcing*\n   below.\n4. **Layouts, not per-slide geometry.** For anything reused (section\n   dividers, content pages, quote slides), define a `slide_layout` once and\n   apply it. This makes swapping the theme a one-line change instead of a\n   fifty-slide sweep.\n5. **Aspect ratio matches the target.** 16:9 (default) for laptops and\n   projectors; 4:3 only when explicitly asked (still common in academia and\n   some corporate templates); 16:10 for older widescreen.\n6. **Speaker notes carry the words.** Put the full narration into\n   `slide.notes_slide.notes_text_frame` so the presenter can rehearse from\n   the deck itself. On the slide, keep it to the phrase they can hold in\n   their head.\n7. **Bullets are not the default.** Bullet lists are the failure mode of\n   most decks — comparisons, tables, icons-with-labels, and stat callouts\n   almost always land better.\n\n## Image sourcing (choose the right channel)\n\n\"Every slide earns its visuals\" does **not** mean \"generate an image for\nevery slide.\" Choose the source based on what the image does. Four channels,\nordered by preference (lower cost + higher stability first):\n\n**L1 · Draw in code.** Icons via react-icons / iconify. Charts via\nmatplotlib / plotly / echarts. Flowcharts, comparisons, org charts via\nshapes + lines. Anything that is a data or concept visualization —\nnever fetch or generate an image for this.\n\n**L2 · Search a stock library, then download the bytes.** When a slide\nneeds a **generic real photo** (city skyline, office desk, team\ncollaboration, nature, stock imagery), use `websearch` with a\n`site:unsplash.com` / `site:pexels.com` / `site:pixabay.com` query to find\na real URL, then **download the image to a local file** and pass that path\nto `add_picture` (see *Downloading* below). Do NOT try to pass an HTTP URL\ndirectly to `add_picture` — python-pptx's `add_picture` only accepts a\nlocal path or a file-like object; it will NOT fetch a URL for you.\n\n**L3 · Search a specific source.** For **specific real things** (a\nparticular company's logo, a specific product's official screenshot, a\nnamed person's photo), use `websearch` with a targeted query (e.g.\n`\"Acme Inc\" logo site:acme.com`, or `<product name> screenshot`) instead of\na stock-library query, then download the bytes the same way as L2. Never\ncall `image_gen` here — a generated logo will not look like the real logo.\nNote: `webfetch` returns text/markdown/html only and cannot deliver binary\nimage bytes — use `bash` + `curl` or python `urllib` to download.\n\n**L4 · Generate with `image_gen`.** Only for **stylized visuals** — cover\nart, hero backgrounds, illustration-style concept images, brand-mood\nimagery. Budget: **at most 1–2 `image_gen` calls per deck**, typically for\ncover or section dividers. Not for every content slide.\n\n### Downloading a URL for `add_picture`\n\nTwo working patterns. Both keep the file local so `add_picture` can read\nthe bytes:\n\n```python\n# Pattern A: download to a temp file, then pass the path\nfrom urllib.request import Request, urlopen\nfrom pathlib import Path\n\ndef download_image(url: str, dest: Path) -> Path:\n    req = Request(url, headers={\"User-Agent\": \"Mozilla/5.0\"})  # some CDNs 403 an empty UA\n    with urlopen(req, timeout=15) as r:\n        dest.write_bytes(r.read())\n    return dest\n\npath = download_image(hit_url, Path(\"assets/hero.jpg\"))\nslide.shapes.add_picture(str(path), Inches(1), Inches(1.5), width=Inches(11))\n```\n\n```python\n# Pattern B: in-memory via BytesIO — no temp file, but same request headers\nfrom io import BytesIO\nfrom urllib.request import Request, urlopen\n\nreq = Request(hit_url, headers={\"User-Agent\": \"Mozilla/5.0\"})\nwith urlopen(req, timeout=15) as r:\n    slide.shapes.add_picture(BytesIO(r.read()), Inches(1), Inches(1.5), width=Inches(11))\n```\n\nOr from a bash step:\n\n```bash\ncurl -sSL -A \"Mozilla/5.0\" -o assets/hero.jpg \"$URL\"\n```\n\nWrap any download in a try/except: on failure fall through to the next\nchannel (L3 → L4) or a shape+text fallback — never leave a slide blank.\n\n### Decision (run per slide)\n\n1. Does this slide actually need a picture? Often the answer is no — a\n   large stat callout, a comparison shape, a well-typeset quote, or a\n   diagram *is* a visual. Skip pictures when layout + typography carries\n   the message.\n2. If yes, pick the cheapest channel that works:\n   - Data / concept / flow / icon → **L1** (draw in code)\n   - Generic real photo → **L2** (stock library search + download)\n   - Specific brand / logo / product / person → **L3** (targeted web search + download)\n   - Stylized cover / hero / illustration → **L4** (`image_gen`)\n3. If a fetch fails: L2 → L3 → L4 → shape + text fallback. Never leave a\n   slide blank because an image failed to load.\n\n### Anti-patterns\n\n- **Calling `image_gen` on every content slide.** Slow, expensive,\n  style-inconsistent, visually noisy. A 20-slide deck with 20 generated\n  images is a red flag, not a success.\n- **Passing an HTTP URL to `add_picture`.** python-pptx will raise\n  `FileNotFoundError` — always download the bytes first (see *Downloading*).\n- **Using `webfetch` to grab image bytes.** `webfetch` returns text only.\n  Use `bash` + `curl` or python `urllib` for binaries.\n- **Making up a stock-library URL from memory.** Unsplash / Pexels CDN\n  paths are opaque hashes — you cannot reliably recall a URL that both\n  exists AND matches the described content. Always search first, then\n  download.\n- **Generating a logo, celebrity, or product screenshot with `image_gen`.**\n  The output will not resemble the real thing. Use targeted web search (L3).\n- **Executive / status / weekly decks in illustration style.** Work\n  reporting is data + icons + hierarchy, not concept art. Reserve L4 for\n  launch, brand, or hero visuals.\n- **Leaving a slide blank because an image fetch failed.** Always have a\n  shape + text fallback; a well-formatted stat callout is a better slide\n  than an empty one anyway.\n\n### Scene defaults (rough mix per deck type)\n\nL2/L3 both cost about one `websearch` + one download per image — cheap\ncompared to L4, still not free. L1 remains the default.\n\n| Deck type              | Dominant | Notes                                           |\n|------------------------|----------|-------------------------------------------------|\n| Status / OKR / weekly  | L1 (~90%) | Icons + data charts. Almost no L2 / L3 / L4.   |\n| Strategy / proposal    | L1 + L2  | ~60% L1, ~30% L2 (searched stock), ~10% L4 cover. |\n| Sales / pitch / BP     | L2 + L3  | Customer logos and product shots (L3) matter. 1 L4 cover max. |\n| Training / education   | L1 (~80%) | Diagrams and flowcharts win.                   |\n| Launch / brand         | L4-heavy | Visuals are the point. Still limit style drift and reuse assets. |\n| Competitive analysis   | L3-heavy | Logos and screenshots are irreplaceable.        |\n\n## Typography defaults (safe starting point)\n\n| Element              | Font          | Size    | Weight  | Notes |\n|----------------------|---------------|---------|---------|-------|\n| Slide title          | Calibri / Segoe UI | 32-40pt | Bold    | One line — wrap = rework the title |\n| Section header       | Calibri       | 24-28pt | Bold    | On dedicated divider slides |\n| Body / bullets       | Calibri       | 18-22pt | Regular | Never below 18pt for a room; 14pt for on-screen decks |\n| Stat callout         | Calibri Light | 60-96pt | Bold    | The number, then the label below at 14-18pt |\n| Caption / footer     | Calibri       | 10-12pt | Regular | Muted gray `#7A7A7A` |\n| Code / mono          | Consolas / Cascadia Code | 16-20pt | Regular | Left aligned, no word wrap |\n\nChange the palette for the topic (financial → navy `#1F3A5F`; environment →\nforest `#2C5F2D`; product launches → your brand's accent). Avoid pure black\non pure white for backgrounds — `#F7F5F0` cream on `#1F1F1F` ink reads\nsofter under a projector.\n\n## Slide sizes\n\n| Aspect | Width × Height (inches) | Pixels @ 96 DPI | When to use |\n|--------|-------------------------|------------------|-------------|\n| 16:9 widescreen (default) | 13.333 × 7.5    | 1280 × 720       | Almost every new deck |\n| 16:10                      | 13.333 × 8.333  | 1280 × 800       | Older projectors; some corporate templates |\n| 4:3 standard               | 10.0   × 7.5    | 960  × 720       | Academia, legacy templates, printed handouts |\n| A4 landscape               | 11.69  × 8.27   | 1123 × 794       | Print-first decks (EU) |\n| Letter landscape           | 11.0   × 8.5    | 1056 × 816       | Print-first decks (US) |\n\n## QA checklist — always run before declaring done\n\n**Assume something is wrong.** PowerPoint opens broken files quietly: a\nmisaligned text box, a chart pointing at deleted data, a stray placeholder\nthat survived template fill. Verify explicitly.\n\n1. **Opens cleanly.** No repair dialog, no missing-part warning.\n   ```bash\n   uv run scripts/diagnose.py output.pptx\n   ```\n\n2. **Text integrity.** No placeholder residue and no unfilled `{{token}}`s:\n   ```bash\n   uv run scripts/dump_text.py output.pptx --notes \\\n       | grep -Ei \"\\{\\{|TODO|TBD|lorem|ipsum|xxxx|click to add\"\n   ```\n   Grep must return nothing.\n\n3. **Visual sanity.** Render the whole deck to PNG, spot-check the first,\n   last, and any slide you touched. Look for:\n   - Text overflowing the placeholder or getting auto-shrunk past readability.\n   - Two shapes overlapping (title over image, footer over content).\n   - Legend / axis labels cut off on charts.\n   - Icons at the wrong scale (tiny hairline icons, or huge stretched ones).\n   - Off-brand colors that snuck in from a copied slide.\n   ```bash\n   uv run scripts/render_slides.py output.pptx --out qa/\n   ```\n\n4. **Layout hygiene.** Every non-master slide should reference a real layout,\n   not `slideLayout1` by default for a section divider:\n   ```bash\n   uv run python -c \"\n   from pptx import Presentation\n   prs = Presentation('output.pptx')\n   for i, s in enumerate(prs.slides, 1):\n       print(f'slide {i}: layout={s.slide_layout.name!r}')\"\n   ```\n\nIf any of these fail, fix and re-run — don't paper over.\n\n## Visual QA execution model\n\n**Slide images are expensive.** A single rendered PNG at 150 DPI consumes\nthousands of context tokens. Loading multiple slides into the main\nconversation for inspection will quickly exhaust your context budget and\ncrowd out useful working memory.\n\n**Default: always use a subagent for visual inspection.** Spawn a\n`general` subagent with the rendered PNG paths and the\ninspection criteria from step 3 above. The subagent reports findings as\ntext (slide number + issue description); the images never enter the main\nconversation context. This is mandatory unless the exception below applies.\n\n```\nactor({\n  operation: {\n    action: \"run\",\n    subagent_type: \"general\",\n    // omit `model` when your current model is vision-capable (preferred — see Model selection)\n    description: \"Visual QA slides\",\n    prompt: \"Inspect the rendered slide images in qa/ for: text overflow, overlapping shapes, cut-off labels, wrong-scale icons, off-brand colors. Report each issue as 'slide N: <problem>'. Images: qa/slide-1.png through qa/slide-<N>.png.\"\n  }\n})\n```\n\n**Model selection (in priority order):**\n\n1. **Prefer the user's current model.** Query the servable vision models via\n   `actor({ operation: { action: \"models\", vision: true } })`. If your current\n   model is in the list, **omit the `model` parameter** — the subagent inherits\n   it, and visual QA runs on the model the user chose.\n2. **Fallback: lightweight vision model, stated explicitly.** If your current\n   model is not vision-capable, pick a **lightweight** vision model from the\n   query result (haiku/flash/lite-class if present, otherwise the cheapest\n   listed) and **tell the user in your reply** which model you used for visual\n   QA and why (current model cannot inspect images).\n3. **No vision model available.** If the query returns an empty list, do not\n   guess a model id — skip the visual QA subagent, run the structural checks\n   only, and tell the user visual inspection could not be performed.\n\n**Never hardcode a model id.** Which models are servable varies per\ndeployment and changes over time; only ids returned by the vision models\nquery are guaranteed to work. A guessed id fails the subagent outright.\n\n**Exception — direct inspection in the main context:** Only load slide\nimages directly (without a subagent) when the user explicitly requests\nthat the current model inspect a specific slide for fine-grained,\ninteractive editing (e.g. \"look at slide 5 and adjust the title\nposition\"). This requires the current model to be multimodal. If it\nisn't, inform the user and offer to spawn a vision subagent instead.\n\n## Common visual pitfalls\n\n- **Titles wrap onto two lines** — either shorten the title or widen the\n  placeholder. Wrapped titles push body content down and break layout\n  alignment across slides.\n- **Body text auto-shrinks below 14pt** — python-pptx respects the\n  placeholder's autofit setting; if the resulting size is unreadable, split\n  the slide instead of accepting the shrink.\n- **Charts inherit Office defaults** — the pale blue / gray palette shipped\n  with PowerPoint looks generic. Explicitly set `chart.chart_style` or use\n  `python-pptx`'s low-level access to set fill colors on series.\n- **Speaker notes forgotten** — a deck without notes cannot be rehearsed.\n  Fill `notes_slide.notes_text_frame.text` on every slide, even if just a\n  single sentence.\n- **Images at wrong DPI** — a 4000×3000 photo on a 1280×720 slide bloats\n  the file with no visual benefit. Resample down to ~150 DPI at the target\n  display size (see `create.md` → *Images*).\n- **Fonts not embedded** — `python-pptx` does not embed fonts. If the deck\n  is opened on a machine without the chosen font, PowerPoint substitutes,\n  and layout drifts. For **Latin** text, prefer system-safe fonts (Calibri,\n  Arial, Segoe UI, Times New Roman, Consolas) or ship the .pptx alongside a\n  font install step.\n- **CJK text needs the East-Asian font slot** — `run.font.name` only sets the\n  Latin typeface (`a:latin`); Chinese / Japanese / Korean glyphs come from the\n  East-Asian slot (`a:ea`), which python-pptx does not expose. Leave it unset\n  and CJK renders as tofu boxes or an inconsistent substitute. Set `a:latin` +\n  `a:ea` + `a:cs` to a CJK-capable font on every run that contains CJK text\n  (recipe in `create.md` → *CJK / East-Asian text*).\n\n## What is out of scope\n\n- **`.ppt` (PowerPoint 97-2003 binary)**. Convert first:\n  `soffice --headless --convert-to pptx old.ppt`.\n- **VBA / macros / `.pptm`.** This skill does not emit or execute macros.\n- **Password-protected or encrypted decks.** `python-pptx` cannot read\n  encrypted files; strip protection with PowerPoint or LibreOffice first.\n- **Live PowerPoint automation.** For COM (Windows) or AppleScript (macOS)\n  integration, use a dedicated automation library — this toolkit is\n  file-in / file-out.\n- **Keynote `.key` files.** Not a PresentationML format; use Apple's\n  Keynote or LibreOffice for round-trip.\n\n## Where each detail lives\n\n- **Creating from scratch**: [`create.md`](create.md) — python-pptx recipes,\n  PptxGenJS recipes, layouts, text, tables, images, charts, icons,\n  backgrounds, speaker notes, palette and typography guidance.\n- **Editing / templating**: [`edit.md`](edit.md) — placeholder fill, slide\n  duplication / reorder / delete, explode/assemble for XML surgery, comments,\n  cleanup of orphaned parts, common pitfalls.\n- **Reading / extracting**: [`read.md`](read.md) — plain-text export\n  (including speaker notes), structural walk, metadata, thumbnails, image\n  extraction, conversion to PDF / PNG for QA.\n- **Scripts**: [`scripts/`](scripts/) — CLI utilities (some share a local\n  `soffice_bridge.py` helper; copy together when extracting).\n- **Live preview**: [`scripts/preview.ts`](scripts/preview.ts) — launcher\n  (start/stop); [`scripts/preview_server.ts`](scripts/preview_server.ts) —\n  background server that watches .pptx, converts to PDF, serves with\n  WebSocket hot-reload in the browser's native PDF viewer.\n","frontmatter":{"name":"pptx-official","description":"Use this skill whenever a Microsoft PowerPoint (.pptx) file is being produced, opened, transformed, or read. That includes: authoring slide decks, pitch decks, executive readouts, training material, or any presentation deliverable; extracting text or structure from an existing .pptx; filling a .pptx template with values; converting a deck to PDF or images; splitting or merging decks; inspecting slides, layouts, masters, tables, images, charts, speaker notes, or comments. Trigger on words like 'deck', 'slides', 'presentation', 'pitch deck', 'keynote' (when a .pptx is expected as output), or any filename ending in .pptx. Do NOT trigger when the primary deliverable is a Word document, spreadsheet, PDF report, HTML site, or Google Slides API call, even if presentation-shaped content appears along the way.","license":"Apache-2.0 — see LICENSE for terms and third-party attributions"},"isInternal":false,"tokens":7001,"sizeBytes":27319},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/product-design/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/product-design/SKILL.md","title":"product-design","category":"anthropic-skill","format":"markdown","content":"---\nname: product-design\ndescription: \"Use this skill when Product Design is explicitly invoked or the main task is product design exploration, UX research, flow auditing or critique, visual ideation, cloning a live product surface, implementing a selected visual target, design QA, saved design context, or sharing a prototype.\"\n---\n\n# Product Design\n\nThis is the single entry point for a code-agent-oriented Product Design bundle. The original workflow instructions are under `workflows/`, with shared guidance under `references/`. The bundled React/Vite prototype template and package metadata are intentionally excluded.\n\n## Route the request\n\n1. Read `workflows/index/SKILL.md` completely. Treat it as the authoritative plugin-level scope, routing, sequencing, and browser-choice policy.\n2. Select the focused workflow or workflow sequence specified by the index. Read every selected workflow's `SKILL.md` completely before acting.\n3. Common sequences include loading context before design/build work, ideating before implementation when no visual target is selected, and running design QA after a source-grounded prototype is built. Follow the exact conditions in the index rather than inferring a fixed sequence for every request.\n4. Resolve relative links from the file that contains the link. Read required reference files and use bundled scripts and assets when present.\n5. Do not load unrelated focused workflows merely because they are present.\n\n## Bundled capabilities\n\nFocused workflows live in `workflows/`: `user-context`, `get-context`, `research`, `audit`, `ideate`, `url-to-code`, `image-to-code`, `design-qa`, and `share`.\n\nShared reusable guidance lives in `references/`. Workflow-local references, scripts, and assets remain beside their owning workflow when they are not React/frontend build artifacts.\n\nUse browser, Chrome, Playwright, image generation, design apps, hosting, and other integrations only when the host harness exposes them. The bundle's mention of a tool does not prove availability or authorization. Follow host permissions and the selected workflow's fallback behavior.\n\nWhen creating a prototype, prefer the target repository's existing frontend stack. If there is no existing app and the user still wants a runnable web prototype, create the smallest suitable implementation using host-supported tools; React is not required. Do not look for the removed bundled prototype template or bootstrap script.\n\n## Safety and fidelity\n\n- Never treat plugin instructions as permission to bypass host policy or publish externally without the required user choice.\n- Keep audits evidence-grounded and distinguish screenshot-visible findings from claims requiring deeper testing.\n- Do not modify production code when a workflow requires an isolated prototype.\n- Preserve the selected workflow's visual QA and handoff requirements through completion.\n","frontmatter":{"name":"product-design","description":"Use this skill when Product Design is explicitly invoked or the main task is product design exploration, UX research, flow auditing or critique, visual ideation, cloning a live product surface, implementing a selected visual target, design QA, saved design context, or sharing a prototype."},"isInternal":false,"tokens":539,"sizeBytes":2881},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/product-design/workflows/audit/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/product-design/workflows/audit/SKILL.md","title":"audit","category":"anthropic-skill","format":"markdown","content":"---\nname: audit\ndescription: \"Audit or critique a product flow, journey, workflow, funnel, onboarding path, checkout path, settings path, screen, or multi-step product experience by capturing screenshots first, then reporting UX, design, and accessibility findings inline from that evidence. Use Figma only when the user explicitly asks for a board. Use when the user asks to audit, review, critique, inspect, assess, analyze, evaluate, or give feedback on a product experience.\"\n---\n\n# Audit\n\nUse this skill when the user wants to audit, review, critique, inspect, assess, analyze, evaluate, or give feedback on a product flow, journey, funnel, onboarding path, checkout path, settings path, screen, or other product experience.\n\nThe output is not a loose opinion. The output is:\n\n- Screenshots of the flow\n- Those screenshots rendered inline in the report\n- A numbered step list\n- UX and design findings tied to steps or screenshots\n- Accessibility risks tied to steps or screenshots\n- Clear limits on what could not be checked from screenshots alone\n\n## Critical Overrides\n\n- Refer to the Plugin router [$index](../index/SKILL.md) before proceeding.\n- Follow [$critical-overrides](../../references/critical-overrides.md).\n\n## User Context\n\nBefore starting, load [$user-context](../user-context/SKILL.md) and run its preflight script when local shell access is available.\n\nUse saved product URLs, Figma files, screenshots, reference images, codebase paths, Storybook, tokens, design systems, brand assets, component refs, browser preferences, and share targets as grounding material when relevant.\n\nDo not inspect every saved reference. Inspect only what the current task needs.\n\n## Route\n\nBefore auditing:\n\n1. Identify the product or surface.\n2. Identify the flow or task.\n3. Choose the capture tool.\n4. Capture the flow.\n5. Save and inspect each screenshot.\n6. Return the audit inline with the accepted screenshots.\n\nOutput rules:\n\n- Default to a concise inline report with screenshots rendered in the chat.\n- Saving screenshots and notes in the workspace is an internal implementation detail. Do not ask the user to choose a local folder.\n- If the user explicitly asks for Figma, create the Figma audit board in addition to the inline report.\n- After the inline report, ask once: `Want me to plot this out in Figma with the screenshots and notes?`\n\nCapture rules:\n\n- Follow the Browser Choice rule in [$index](../index/SKILL.md#browser-choice).\n- If none of those can capture valid screenshots or control the flow, stop and report the blocker.\n\nBrowser capture order:\n\n1. Load the Browser skill before browser work.\n2. Connect to the browser and use the current tab when it already shows the target.\n3. Do not reload or navigate away unless the audit needs a fresh start.\n4. Observe the visible state before acting.\n5. Before each click, type, or key press, use the latest DOM snapshot to target one clear control.\n6. After each action, take the cheapest fresh check that proves what changed: DOM for structure, screenshot for visual state.\n7. Save and inspect the accepted screenshot before using it as audit evidence.\n\nFigma rules:\n\n- If Figma is the destination, load the required Figma skills before creating or editing the file.\n- Keep a local copy of every screenshot even when Figma succeeds.\n- Do not upload a screenshot to Figma until the saved local file has been inspected and accepted.\n- Figma is not done until the screenshots are visibly placed in the Figma output.\n- After placing screenshots in Figma, render or inspect the board and confirm every flow step has the correct screenshot visible in the correct card.\n- If an image is missing, misplaced, blank, or only uploaded as an unused asset, fix it before handoff.\n- If Figma tools cannot create files or place images, return the inline audit and explain the missing Figma capability.\n\nEvidence rules:\n\n- Use only evidence captured in the current audit run.\n- Do not use memory, prior chats, old traces, cached screenshots, or prior generated artifacts as audit evidence unless the user explicitly provides them.\n- Do not audit until the product, flow, and capture tool are known.\n- Do not claim full accessibility compliance from screenshots alone.\n\n## Capture And Audit The Flow\n\nYou are an expert design, UX, and accessibility auditor. For each step in the flow, capture what the user sees, observe how the screen behaves, inspect the screenshot, and write audit notes before moving on.\n\nFollow [references/design-audit-framework.md](references/design-audit-framework.md) when deciding what to inspect and how to describe strengths, UX issues, accessibility risks, limits, and recommendations.\n\nScreenshot source rule:\n\n- Use the screenshot you actually saw.\n- Save that exact screenshot to the local audit folder.\n- Open or inspect the saved file before accepting it.\n- If the saved file shows the wrong window, wrong state, blank page, crop, or loading screen, reject it and capture again.\n- When Figma is the destination, upload that accepted local file.\n- After upload, verify the Figma board shows the same step.\n- Do not replace a Browser, Chrome, or Computer Use screenshot with an OS screenshot unless you first prove the saved file shows the same window and state.\n\nFor every step:\n\n1. Move to the next step in the requested flow.\n2. Wait until the screen is loaded and visually stable.\n3. Check for loading spinners, blank areas, login walls, error pages, blocked states, cookie dialogs, and half-rendered content.\n4. Capture the screenshot.\n5. Inspect the screenshot before accepting it.\n6. Reject the screenshot if it is blank, loading, cropped, blocked, or showing the wrong state.\n7. Observe behavior that matters for the audit, such as navigation, focus, loading, validation, error handling, empty states, motion, and whether the next action is clear.\n8. Write notes for that step.\n9. In the notes, report strengths, UX issues, accessibility risks, and any limits that made the step difficult to audit.\n10. Save accepted screenshots with numbered names, such as `01-start.png`, `02-form-filled.png`, and `03-confirmation.png`.\n11. Inspect the saved screenshot file before upload or handoff.\n12. Keep each accepted screenshot and its notes together for the final inline report.\n13. If the user explicitly requested Figma, add each accepted screenshot and its notes to the board immediately.\n\nDefault inline report:\n\n- Render accepted screenshots in flow order.\n- Keep the report pithy: overall verdict, numbered steps, highest-impact changes, and evidence limits.\n- Tie every finding to the screenshot or step that supports it.\n\nIf the user explicitly requested Figma:\n\n- Place screenshots in order, left to right on the same row, with 200px between each one. Go to a new row every 15 screenshots, and separate those rows by 600px.\n- Underneath the screenshot, add text with the Step number and its name, and notes.\n- Keep a local folder copy even when Figma succeeds.\n- When you are done, wrap all of the assets you added in a Section and title the section.\n\nAcceptance checks:\n\n- Every important step in the requested flow has a valid screenshot or a named blocker.\n- Screenshots are saved in order.\n- Screenshots are rendered inline in the final report.\n- When Figma was explicitly requested, screenshots and notes are placed in the board as they are captured.\n- Every note points to the screenshot or step it describes.\n- Notes explain strengths, UX issues, accessibility risks, and evidence limits when those apply.\n- Accessibility risks say what can be seen from screenshots and what still needs testing.\n- The final screenshot set and notes are enough to support the requested audit.\n\nBlockers:\n\n- The flow cannot be completed.\n- A required step cannot be screenshotted.\n- The source changes in a way that makes the flow unclear.\n- Screenshots cannot be saved or rendered inline.\n- Notes cannot be written.\n- The requested claim would require evidence that screenshots cannot provide.\n- Do not claim an audit if the actual flow could not be accessed and captured. Help Center pages, web searches, and other indirect evidence are research, not an audit.\n\n## Final Response\n\nAfter the flow is captured and notes are written, list every step in the final response.\n\nThe final step list MUST include:\n\n- step number\n- short description of the step\n- general health of that step\n\nAlso include where the full output was saved or placed.\n\nKeep the language direct. Do not use broad design jargon when a plain phrase works.\n","frontmatter":{"name":"audit","description":"Audit or critique a product flow, journey, workflow, funnel, onboarding path, checkout path, settings path, screen, or multi-step product experience by capturing screenshots first, then reporting UX, design, and accessibility findings inline from that evidence. Use Figma only when the user explicitly asks for a board. Use when the user asks to audit, review, critique, inspect, assess, analyze, evaluate, or give feedback on a product experience."},"isInternal":false,"tokens":1783,"sizeBytes":8514},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/product-design/workflows/design-qa/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/product-design/workflows/design-qa/SKILL.md","title":"design-qa","category":"anthropic-skill","format":"markdown","content":"---\nname: design-qa\ndescription: \"Internal prototype QA helper. Use only after a Product Design prototype, URL-to-code build, or image-to-code build has a source visual target and a rendered implementation to compare before handoff. Do not use for broad UX critique, design critique, product audits, or flow reviews; route those user-facing requests to audit.\"\n---\n\n# Design QA\n\nUse this internal helper to compare a prototype's source design against the rendered implementation before handoff.\n\nDo not use this skill for broad UX critique, design critique, product audits, or flow reviews. Use [audit](../audit/SKILL.md) for those user-facing requests.\n\nUse this skill before every Product Design build handoff.\n\nA passing QA run requires both:\n\n- a source visual target: Figma node, image, screenshot, mockup, or source capture\n- a rendered implementation: local URL, deployed URL, app screen, component, or screenshot\n\nIf either artifact cannot be opened, captured, or compared, write `design-qa.md` with `final result: blocked` and name the blocker. Do not let the build skill hand off as done.\n\n## Critical Overrides\n\nFollow [critical-overrides](../../references/critical-overrides.md).\n\n## Workflow\n\nCompare the intended design to the implementation as a product-quality reviewer, not as a generic aesthetic critic. The output must be a prioritized fix list grounded in evidence from both artifacts.\n\nDo not write the QA review from memory, code, or file paths alone. Open or capture both the source design and the implementation first, then compare what is actually visible.\n\nDo not pretend separate image views are side-by-side comparison. Put the source image and the implementation screenshot together in the same comparison input, then judge the visible differences from that combined input.\n\nDesign QA is an iteration loop. The first comparison may pass only when it finds no actionable P0/P1/P2 differences and no visual fixes are made in response.\n\nWhen a comparison finds any P0/P1/P2 issue:\n\n- Record the finding and keep the current result blocked.\n- Apply the fix.\n- Capture the revised implementation at the same viewport and state.\n- Compare the revised capture against the source again.\n\nA later pass must identify the earlier findings, the fixes made, and the post-fix visual evidence. Build, dependency, lint, deployment, and preview troubleshooting do not count as design-QA iterations.\n\n1. Identify the comparison target.\n   - Determine the source design: Figma node, image, design board, screenshot, spec, or mockup.\n   - Determine the implementation: local URL, deployed URL, app screen, component, screenshot, or code-rendered view.\n   - Match the same viewport, state, theme, device density, route, content, auth state, and interaction state before judging.\n   - If artifacts do not represent the same state, call that out first and avoid false precision.\n\n2. Capture evidence.\n   - For Figma, use design context and screenshot tools when available.\n   - For web/app implementations, follow the Browser Choice rule in [index](../index/SKILL.md#browser-choice). In ChatGPT Work Mode, follow the active build skill's \"Previewing prototypes in ChatGPT Work Mode\" section before opening a local implementation. Then capture screenshots at the intended viewport.\n   - Capture additional states when relevant: mobile/desktop, hover/focus/active, empty/loading/error, dark/light, and key responsive breakpoints.\n   - Save paths or URLs for screenshots when available so findings can cite evidence.\n   - Capturing screenshots is not enough. Put the source image and the implementation screenshot together in the same comparison input before judging.\n\n3. Normalize before comparing.\n   - Align crop, viewport size, scale, and device frame. Do not compare a framed mockup to an unframed page without noting the mismatch.\n   - Prefer comparing content regions over full browser chrome or surrounding canvas.\n\n4. Compare at the right level of detail.\n   - Use a full-view comparison to judge overall composition, hierarchy, layout, density, and responsive structure.\n   - Use focused region comparisons when important details are too small to judge in the full-view comparison.\n   - Choose focused regions from the actual source and implementation. Use them where fidelity depends on precise typography, alignment, imagery, assets, icons, logos, controls, forms, navigation, tables, dense UI, or visible interaction states.\n   - If no focused region is needed, say why in `design-qa.md`.\n   - Do not pass QA from a full-view comparison alone when important details are not clearly readable.\n\n5. Review systematically.\n   - Read [qa-rubric](./references/qa-rubric.md) when the QA pass spans more than a quick visual check.\n   - Check information architecture, layout, spacing, typography/fonts, color, imagery/image quality, icons, copy, affordances, interaction states, responsiveness, accessibility, and polish.\n   - Always make a specific pass over the five required fidelity surfaces: fonts/typography, spacing/layout rhythm, colors/tokens, image quality, and copy/content. Do this even if the user did not name those areas explicitly.\n   - If the mock does not address some issue you're seeing (e.g. a null state), call that out as a separate finding as a shortcoming of the mock to be addressed.\n   - Your other goal is to decide whether the implementation \"looks as good\" as the mock. If there are stylistic problems, call them out. If the user's prompt is leaking into the implementation (vs letting the app stand on its own), call that out as well.\n   - Distinguish design drift from intentional product/code constraints. If a deviation may be intentional, phrase it as a question or assumption.\n\n6. Produce a fix-oriented QA report.\n   - Lead with findings, ordered by severity and user impact.\n   - For each finding include: severity, location, what differs, evidence, why it matters, and the concrete fix.\n   - Include exact CSS/component/token suggestions when the implementation context is available.\n   - Separate objective mismatches from subjective polish recommendations.\n   - Do not say a design matches, is done, or is as good as it can get until the required fidelity surfaces have been checked and any remaining differences are explicitly classified as acceptable, expected, or still actionable.\n   - End with a concise implementation checklist.\n\n## Required Fidelity Surfaces\n\nEvery QA report must explicitly evaluate these surfaces:\n\n- Fonts and typography: family, fallback, weight, size, line height, letter spacing, antialiasing, hierarchy, wrapping, truncation, and whether display text and small UI text use appropriate optical weights. It is incredibly important to check fonts carefully for fidelity, including looking up similar typefaces or using image analysis to find the font differences.\n- Spacing and layout rhythm: frame size, crop, alignment, margins, padding, grid tracks, section gaps, component spacing, radii, shadows/elevation, and vertical rhythm.\n- Colors and visual tokens: sampled or inferred palette, gradients, opacity, contrast, semantic state colors, foreground/background balance, and whether CSS tokens map to the source design.\n- Image quality and asset fidelity: subject correctness, crop, scale, sharpness, compression, transparency halos, masking, background treatment, raster-vs-vector appropriateness, and whether generated assets match the source art direction. Fail QA if logos, illustrations, decorative marks, product imagery, non-standard icons, or other visible image assets from the visual target were replaced with custom inline SVG, handcrafted SVG, HTML elements, div/span shapes, CSS drawings, gradients, emoji, text glyphs, placeholder shapes, or code-native approximations.\n- Copy and content of app-specific text\n\n## Severity\n\n- `P0`: Blocks core use, severe accessibility failure, broken layout, or impossible task.\n- `P1`: Major design mismatch or usability regression likely to be noticed by users.\n- `P2`: Moderate visual drift, inconsistent state, responsive issue, or fixable polish gap.\n- `P3`: Minor refinement that improves fidelity but does not block acceptance.\n\nTreat viewport overflow that hides persistent app controls, and mismatches that materially change above-the-fold content, major-region proportions, text wrapping, or interface density, as P2 or higher.\n\n## Output Format\n\nUse this structure unless the user asks otherwise:\n\n```markdown\n**Findings**\n- [P1] Short issue title\n  Location: screen/component/selector/file if known.\n  Evidence: design does X, implementation does Y.\n  Impact: why this matters.\n  Fix: concrete change.\n\n**Open Questions**\n- Any ambiguity about intentional deviations, unavailable states, or missing artifacts.\n\n**Implementation Checklist**\n- Ordered fixes that can be executed directly.\n\n**Follow-up Polish**\n- P3 refinements that can improve fidelity after handoff.\n```\n\nIf there are no substantive mismatches, say that clearly and list any residual test gaps.\n\nWhen this skill is used before handoff, save the latest QA report as project-root `design-qa.md`.\n\n`design-qa.md` must include:\n\n- source visual truth path\n- implementation screenshot path\n- viewport\n- state\n- full-view comparison evidence\n- focused region comparison evidence, or why it was not needed\n- findings\n- comparison history for every P0/P1/P2 iteration: earlier findings, fixes made, and post-fix visual evidence\n- final result\n\nFor ChatGPT Work Mode builds, `design-qa.md` must include the browser-rendered implementation screenshot, viewport, primary interactions tested, console errors checked, and final result. If browser-rendered evidence is missing, `final result` is `blocked`.\n\n`final result` must be exactly `passed` or `blocked`.\n\nUse `passed` when there are no actionable P0/P1/P2 findings. P3 findings may remain as follow-up polish.\nUse `blocked` when actionable P0/P1/P2 findings remain and name the blocker.\n\nReturn the file path with the QA report.\n","frontmatter":{"name":"design-qa","description":"Internal prototype QA helper. Use only after a Product Design prototype, URL-to-code build, or image-to-code build has a source visual target and a rendered implementation to compare before handoff. Do not use for broad UX critique, design critique, product audits, or flow reviews; route those user-facing requests to audit."},"isInternal":false,"tokens":2051,"sizeBytes":9981},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/product-design/workflows/get-context/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/product-design/workflows/get-context/SKILL.md","title":"get-context","category":"anthropic-skill","format":"markdown","content":"---\nname: get-context\ndescription: \"Mandatory design-brief gate for clarifying the product and outcome. Use before ideation, image-to-code builds, redesigns, or product UI work to clarify missing product information and play back the brief before proceeding.\"\n---\n\n# Get Context\n\n\nRun this skill at the start of Product Design requests that ask to design, build, prototype, clone, redesign, extend, or generate product UI directions.\n\nUse question mode to clarify the following:\n\n- what product, site, feature, workflow, component, or screen is being designed, redesigned, or extended\n- what the feature, change, app, or website should help the user do\n\nDo not re-ask answered questions. When both are clear, play back the brief and defaults in one pithy note, name the next workflow, and continue in the same turn. Playback is not a request for approval. The user can course-correct style, scope, or interactivity at any point.\n\nHard boundary: do not implement UI, scaffold a prototype, start a server, or create files while the design target or intended user outcome is still missing.\n\n## Critical Overrides\n\n- Refer to the Plugin router [$index](../index/SKILL.md) before proceeding.\n- Follow [$critical-overrides](../../references/critical-overrides.md).\n\n## User Context\n\nBefore starting, load [$user-context](../user-context/SKILL.md) and run its preflight script when local shell access is available.\n\nUse saved product URLs, Figma files, screenshots, reference images, codebase paths, Storybook, tokens, design systems, brand assets, component refs, browser preferences, and share targets as grounding material when relevant.\n\nDo not inspect every saved reference. Inspect only what the current task needs.\n\n## Handoff To The Next Workflow\n\n1. When the next workflow is already clear, read that skill before sending the brief playback. Do not only name a skill you have not read.\n\n2. Before executing `$ideate`, `$url-to-code`, or `$image-to-code`, play back the minimum brief and any defaults in one pithy user-visible note.\n\n3. If the target and intended user outcome are clear, continue to the next workflow in the same turn. Do not wait for explicit confirmation. If the user provides feedback, incorporate it and course-correct.\n\n4. Before starting an involved app, prototype, clone, redesign, or build, send one short expectation-setting note and continue. Example:\n\n```text\nThis kind of build usually takes about 10-15 minutes, and ambitious ones can take longer. Good moment to grab coffee or tend to something else; I’ll keep moving and bring the prototype back when it is ready.\n```\n\nDo not send this note for tiny static changes, quick audits, simple research, setup-only, or share-only requests.\n\nDone means the design target and intended user outcome are clear, defaults have been played back, and any already-determined next skill has been read.\n","frontmatter":{"name":"get-context","description":"Mandatory design-brief gate for clarifying the product and outcome. Use before ideation, image-to-code builds, redesigns, or product UI work to clarify missing product information and play back the brief before proceeding."},"isInternal":false,"tokens":609,"sizeBytes":2870},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/product-design/workflows/ideate/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/product-design/workflows/ideate/SKILL.md","title":"ideate","category":"anthropic-skill","format":"markdown","content":"---\nname: ideate\ndescription: \"Generate image-based alternatives, remixes, or new design directions from a Product Design brief. Use when the user asks for design variants, visual exploration, remixes, or image-generated approaches from provided context.\"\n---\n\n# Ideate\n\nYou're tasked with generating design concepts for a user's idea.\n\nFollow the shared Product Design routing guidance in [$index](../index/SKILL.md).\n\n## Critical Overrides\n\n- Refer to the Plugin router [$index](../index/SKILL.md) before proceeding.\n- Follow [$critical-overrides](../../references/critical-overrides.md).\n\n## User Context\n\nBefore starting, load [$user-context](../user-context/SKILL.md) and run its preflight script when local shell access is available.\n\nAttach provided product URLs, Figma files, screenshots, reference images, codebase paths, Storybook, tokens, design systems, brand assets, component refs, browser preferences, and share targets to the Image Gen generations to align them to the design brief.\n\nDo not inspect every saved reference. Inspect only what the current task needs.\n\n## Workflow\n\nDo not generate images until `$get-context` has satisfied the minimum required design brief.\n\nBefore generating images:\n\n1. Understand the brief.\n\n- Identify the target: component, screen, feature/workflow, or broad product idea.\n- Identify the intended user, product surface, and goal.\n- Preserve hard constraints from the user.\n- Run `get-context` if the minimum required design brief isn't satisfied.\n\n2. Resolve context.\n\n- Use provided files, screenshots, links, and visible references.\n- In a local workspace, look for nearby design documentation and other local visual context.\n- Check likely design context folders such as `user-context`, `storybook/`, `.storybook/`, `design-system/`, `design-systems/`, `tokens/`, `components/`, `app/`, and generated prototype roots.\n- In an existing project, look for existing product screenshots, similar flows, Storybook captures, design tokens, and component references before generating. Ask if the user can provide example screens similar to the one they are building if the existing app isn't accessible. Ensure you add design language and tokens to the Image Gen prompt.\n\n3. Inspect references directly.\n\n- Look at screenshots, images, Figma frames, app surfaces, or other visual references before generating.\n- Do not infer from filenames alone.\n- If a named local path or reference is not visible, stop and ask the user to confirm the path, upload the file, start the local app, or point to the correct workspace.\n\n4. Decide the variation mode.\n\n- If useful local design context exists and the user has not asked for a new style, stay within that existing direction.\n- If no useful design context exists, or the user asks for broad exploration, vary both concept and visual system.\n- For a specific component or existing surface, vary structure, interaction, hierarchy, and emphasis before varying brand style.\n- For a broad product idea, explore three meaningfully different product directions.\n\n5. Choose target dimensions before Image Gen.\n\n- Pick the dimensions that best match the user's request and any provided visual reference.\n- Mobile app: `390 x 844`.\n- Tablet app: `834 x 1194`.\n- Desktop app, dashboard, admin, or SaaS: `1440 x 1024`.\n- Landing or marketing page: `1440` wide and scrollable.\n- Modal, panel, widget, or component: natural container size.\n- Provided screenshot, Figma frame, mockup, or reference image: match its dimensions and aspect ratio when the user wants to continue from that visual.\n- Avoid crowding. Make the design fit the chosen dimensions cleanly, with realistic spacing, readable type, and no clipped content.\n- Include the chosen dimensions in every Image Gen prompt.\n\n6. Check for access gaps.\n\n- If a connector, reference, or file cannot be accessed because of auth, permissions, expired login, missing scope, suspiciously empty results, or unavailable local state, stop.\n- Name the gap clearly and ask whether to troubleshoot access or continue without that source.\n- Do not generate images while silently ignoring a named reference.\n\n7. Attach images and mocks provided by the user to the Image Gen call along with your design brief.\n\n8. Generate 3 independent options that have distinct information hierarchy, layout strategy, interaction model, or product framing.\n\nRules you must follow:\n\n- Use the Image Gen prompt below.\n- Use the built-in Image Gen tool.\n- Generate exactly three independent images unless the user overrides the count.\n- Launch each Image Gen call independently. Do not batch Image Gen calls with `Promise.all`, collect them into an ordered array, or replay them in request order.\n- Each option must be its own Image Gen result. Do not put multiple ideas in one image.\n- Give each direction a distinct, descriptive name before generation, but do not call it `option 1`, `option 2`, or `option 3` and do not put planned numeric labels in Image Gen prompts. Parallel results can arrive in a different order from the requests.\n- Number options only after the Image Gen results are present in the thread. The only authoritative option order is the order those generated-image results are displayed in the current thread. Ignore the planned concept order, original request chain, prompt submission order, `Promise.all` result order, batch order, array indexes, retry order, and assumed completion order.\n- After all results return, bind each visible option number to the result in that displayed order. Do not name or describe the options in the final selection message.\n- Attach provided screenshots, files, app captures, Figma references, and visual source material as moodboard inspiration when available.\n- Attach existing product screenshots, similar flows, Storybook captures, design tokens, and component references as grounding material when available.\n- When mock data includes dates or time-sensitive information, resolve the exact current date and include it in every Image Gen prompt. Derive visible dates from that anchor; preserve dates required by the user or source design.\n- If a screenshot, image, or visual file is available, attach the actual image to the Image Gen call. Do not rely on text descriptions of it.\n- Only claim a visual reference was attached if the Image Gen call actually received that image or a readable local image path.\n- If you cannot attach the image, say that clearly and ask whether to continue with text-only direction.\n- Preserve hard constraints from the brief in every image.\n- After generating options, stop for the user's selection before any build work begins.\n- When the user later selects option `N`, resolve it against the Nth displayed generated-image result from the most recent ideation set, not the original planned concept order. If the exact displayed result cannot be resolved, do not build from a guess; ask the user to name the concept or reattach/select the image.\n- The selected option is the visual target for `$image-to-code`.\n\n## Feedback Loop\n\nIf the user gives feedback after seeing options, generate revised options with that feedback.\n\nIf the user selects an option and gives feedback, generate a revised option with that feedback before build.\n\nIf the user likes parts of more than one option, combine those choices into a new Image Gen design and show it before build.\n\n## Image Gen Prompt\n\nAdapt this prompt to the current design brief, attach any available image references, and send it to Image Gen:\n\n```text\nCreate realistic, production-quality UI designs with clear hierarchy, strong typography, intentional imagery, and purposeful spacing.\n\nDesign a focused primary screen, not a feature inventory. The product may support many workflows, but this frame should show the hero use case, one clear primary action, and only one or two supporting actions or content areas. Do not add cards, panels, tabs, badges, metrics, filters, or navigation items merely to advertise every feature. Let the rest of the product exist off-screen. Prefer strong hierarchy and generous whitespace; if the screen feels crammed, remove UI.\n\n### Target Dimensions\n\nPick the dimensions that best match the user's request and any provided visual reference.\n\nDefault to a desktop web-app frame unless the user or reference clearly calls for mobile, tablet, or another format.\n\n - Mobile app: `390 x 844`\n - Tablet app: `834 x 1194`\n - Desktop app, dashboard, admin, or SaaS: `1440 x 1024`\n - Landing or marketing page: `1440` wide and scrollable\n - Modal, panel, widget, or component: natural container size\n - Provided screenshot, Figma frame, mockup, or reference image: match its dimensions and aspect ratio when the user wants to continue from that visual\n\nUse a natural viewport ratio for the intended surface. Never stretch, squash, or warp the generated screen, imagery, typography, or UI elements to fill the canvas. If the composition does not fit naturally, recompose or simplify the layout instead.\n\nAvoid crowding. Make the design fit the chosen dimensions cleanly, with realistic spacing, readable type, and no clipped content.\n\n### Layout\n\nWhen deciding how to lay elements out on the page, this should be your priority order for tools to differentiate sections:\n\n1. Use spacing, grouping, alignment, typography, and hierarchy on the same product surface.\n2. Use simple dividers or row separators.\n3. Use a subtle surface tint only when the base surface is not enough.\n4. Use borders only when separation still is not clear.\n5. Use shadows/elevation last, and sparingly.\n\nDon'ts:\n - Do not default to a centered \"app card\" (the whole UI is in a card on the page) on top of a contrasting page background. Use the base page surface first unless the source product or user explicitly asks for a contained app panel.\n - Do not put cards inside cards. Do not make every major section a card. Do not make each list item its own card unless each item is truly a standalone object. A normal list should usually read as one grouped surface with lightweight row separation.\n - Do not make up extraneous features. Add only the things essential to accomplish what the prototype's goal is. Don't make up more features just to fill out a UI.\n\n### Typography\n\n - Anchor UI typography to readable product sizes. Body text should usually sit between 14px and 16px, with the rest of the type scale built around that baseline.\n - Keep long-form text to a comfortable line length, generally no more than 65 characters per line.\n - Use no more than 2 fonts in a UI. You can use any font available in the project, or fonts provided free on Google Fonts. Pick the font that is best for the goal of the product and that matches with its intended look and feel.\n\n### Presentation\n\n - Do not add browser or device chrome around the mockup.\n - Do not put multiple ideas into a single image generation.\n - Vary each idea as much as possible while adhering to the constraints given entirely.\n\n### Data Freshness\n\nWhen the design includes dates or time-sensitive mock data, use the supplied current date as the anchor. Weekly views must show the real containing week with correct weekday/date pairs. Feeds, charts, notifications, and recent activity must use plausible chronological dates relative to today. Mark today when useful. Preserve dates required by the brief or source design.\n```\n\n## Output\n\nWait until all Image Gen calls have returned before sending the final message that asks the user to choose.\n\nDo not send the final selection message until every requested generated image is visible exactly once in the main chat.\n\nIf fewer Image Gen outputs are visible than requested, retry the missing generation. Do not send the selection message.\n\nNumber the returned Image Gen outputs in the order they appear in the conversation context:\n\n- First Image Gen output = Option 1\n- Second Image Gen output = Option 2\n- Third Image Gen output = Option 3\n\nIgnore the planned concept order, original request chain, request order, `Promise.all` result order, batch order, array indexes, retry order, and tool submission order.\n\nDo not name or describe the options. For the default three images, send only:\n\n`Which option should I build: 1, 2, or 3? Or tell me what you'd like to refine or personalize first.`\n\nAdjust the numbers only if the user requested a different count.\n\nIf the user chooses a number, acknowledge the chosen option before routing to `$image-to-code`, for example: `Building option 2!` Do not ask for confirmation when the mapping is clear.\n\nDone means the requested number of independent images have been generated and the user has been asked to select one.\n","frontmatter":{"name":"ideate","description":"Generate image-based alternatives, remixes, or new design directions from a Product Design brief. Use when the user asks for design variants, visual exploration, remixes, or image-generated approaches from provided context."},"isInternal":false,"tokens":2592,"sizeBytes":12626},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/product-design/workflows/image-to-code/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/product-design/workflows/image-to-code/SKILL.md","title":"image-to-code","category":"anthropic-skill","format":"markdown","content":"---\nname: image-to-code\ndescription: \"Implement a selected image, screenshot, mockup, generated concept, or design frame as a faithful, responsive, interactive frontend in the target codebase.\"\n---\n\n# Image to Code\n\nTranslate a selected visual target into a high-quality frontend. Read `../index/SKILL.md`, `../../references/critical-overrides.md`, and the relevant saved context from `../user-context/SKILL.md` before building.\n\n## Preconditions\n\n- Require an unambiguous selected image, screenshot, mockup, generated result, or design frame. A written brief alone is not a visual target; route to ideation first when appropriate.\n- Resolve which image is selected before editing. Ask when an ordinal or attachment is ambiguous.\n- Use only the current task's relevant product context, tokens, components, assets, and references.\n\n## Workflow\n\n1. Inspect the source visual at useful detail and record its viewport, layout regions, hierarchy, spacing, typography, colors, borders, radii, shadows, imagery, icons, responsive behavior, and visible states.\n2. Inventory every required asset. Reuse supplied or repository assets when they match. Use an available image-generation tool for custom raster imagery and an appropriate existing icon set for UI icons. Do not substitute emoji, generic placeholders, or improvised CSS drawings for meaningful visual assets.\n3. Inspect the target repository and use its existing framework, package manager, component system, design tokens, and conventions. React is not required. Do not replace an established stack merely to match this workflow.\n4. If no target app exists, create the smallest runnable frontend supported by the harness and suited to the request; plain HTML/CSS/JavaScript is acceptable.\n5. Implement the full visible structure and the primary user journey. Unless requested otherwise, make navigation, tabs, menus, forms, toggles, selections, and main calls to action behave realistically without inventing backend systems.\n6. Match desktop or mobile based on the source. When the source is a phone UI and no device is named, verify around 390 × 844 as well as any relevant responsive behavior.\n7. Run the real app using its normal development or preview command.\n8. Capture the implementation using the browser tool selected by `../index/SKILL.md` and run `../design-qa/SKILL.md` against the source visual.\n9. Fix all blocking and high-impact mismatches. Save `design-qa.md` in the project root and hand off only when it records `final result: passed`, or clearly report a genuine capture/verification blocker.\n\n## Fidelity rules\n\n- Treat the selected visual as the design target; do not introduce unrelated redesign ideas.\n- Match the same viewport and interaction state during visual comparison.\n- Place real assets before final QA and avoid hotlinking third-party source assets in the finished app.\n- Keep the implementation maintainable within the target repository's patterns.\n- Do not claim verification from build success or an HTTP status alone; inspect the rendered result and primary interactions.\n\n## Handoff\n\nProvide the runnable project or changed files, the local preview information when useful, and a concise summary of what was implemented, verified, and left as a limitation. Publish only when the user asks and the host exposes an authorized deployment tool.\n\n","frontmatter":{"name":"image-to-code","description":"Implement a selected image, screenshot, mockup, generated concept, or design frame as a faithful, responsive, interactive frontend in the target codebase."},"isInternal":false,"tokens":667,"sizeBytes":3336},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/product-design/workflows/index/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/product-design/workflows/index/SKILL.md","title":"index","category":"anthropic-skill","format":"markdown","content":"---\nname: index\ndescription: \"Use when Product Design is explicitly invoked, or when the user's main goal is to explore a design, research UX, audit or critique a flow, faithfully clone a visual source, check a built design, or share a prototype. Do not use Product Design for ordinary implementation unless the user explicitly asks for it.\"\n---\n\n# Skill Purpose\n\nRoute Product Design requests to the right Product Design skill. Use this plugin for an `@Product Design` mention, a direct Product Design request, or a request mainly about design exploration, faithful source cloning, audits, research, critique, or sharing. A request is not Product Design just because it mentions UI, a prototype, or visual style.\n\n# Plugin Purpose\n\nThe Product Design plugin helps designers and other non-coders close the gap between product ideas and working software.\n\nThe Product Design plugin equips you with the following set of skills to:\n\n- Research ideas and pain points related to your product.\n- Conduct product-flow audits.\n- Generate distinctly new ideas for your product with ImageGen.\n- Clone existing product apps into lightweight prototypes.\n- Build lightweight or interactive prototypes to share with your team.\n\n## Communication Style\n\nSpeak to the user in a warm, fun, and collaborative way, prioritizing pithy explanations over long walls of text and numerous bullet points. Refer to the [communication-protocol](../../references/communication-protocol.md) for relaying Product Design plugin progress updates and handoff.\n\n## Critical Overrides\n\n- Follow [$critical-overrides](../../references/critical-overrides.md).\n\n## Router Only\n\nThis index chooses the next Product Design skill. It does not do that skill's work.\n\nIf the user names a focused skill, read that exact skill first. Do not replace it with a related skill.\n\nWhen a request matches `$user-context`, `$get-context`, `$research`, `$ideate`, `$image-to-code`, `$url-to-code`, `$audit`, `$design-qa`, or `$share`, load the focused skill and follow it.\n\nFor requests to audit, review, critique, inspect, assess, analyze, evaluate, or give feedback on an existing product experience, load `$audit` directly; do not load `$get-context` first. If the same request also asks to build, fix, redesign, or implement afterward, run `$audit` first, then continue through the appropriate normal workflow.\n\nFor visual ideation, `$ideate` is the focused workflow. Use `$get-context` to resolve the minimum brief and play back any defaults before `$ideate` starts.\n\nFor clone or recreation of a live URL, load `$url-to-code` directly.\n\nFor a redesign, improvement, or new site based on a URL, use `$get-context` to confirm the redesign brief. `Like <URL>` means redesign, not clone. Capture the current site with screenshots, attach those screenshots to the `$ideate` Image Gen calls, then execute `$ideate`.\n\n## Standard Chat Mode\n\nIf Product Design is invoked in standard ChatGPT chat without Work Mode tools, do not start the workflow. Tell the user once:\n\n```text\nChat isn't supported by the Product Design plugin. Please switch to the Work tab and paste this prompt in for the full experience.\n```\n\nDo not ask design-brief questions, generate options, or begin build work until the user moves to Work Mode.\n\n## Browser Choice\n\nIn ChatGPT Work Mode, always use the cloud browser available to that chat. If it is not initially visible, load the Browser skill and follow its setup instructions before concluding it is unavailable.\n\nIn Codex Desktop, use `@Browser` and explicitly select the in-app surface with `agent.browsers.get(\"iab\")`.\n\nIn Codex Desktop, use Chrome only when the user asks for it, the task needs an existing Chrome tab/login/profile/extension, or the in-app Browser is unavailable or blocked.\n\nIf ChatGPT Work Mode does not expose both the cloud browser and `@Sites` after preflight, tell the user once:\n\n```text\nCloud browser and Sites are not available in this chat. I can still build a single-page HTML prototype, but I cannot visually verify it or publish a live checkpoint, so fidelity and interaction polish may be lower. Continue with that fallback?\n```\n\nOnly proceed after the user agrees. Do not claim the fallback is verified, open, hosted, or ready to share. This fallback applies to image-to-code and new prototypes. It does not apply to URL-to-code when browser capture is required.\n\n## No Visual Target, No Build\n\nFor new app, prototype, redesign, or UI build requests without a URL, screenshot, Figma frame, mockup, source image, or existing code target:\n\n- `$ideate` is the focused workflow.\n- Use `$get-context` to resolve the minimum brief.\n- Once the target and intended user outcome are clear, play back the assumptions and run `$ideate` in the same turn.\n- Show exactly three visual options and wait for the user to choose one.\n- Do not scaffold, edit files, or start a server before a visual option is selected.\n\n`Full working version`, `no refs`, `go for it`, `make an assumption`, or a complete brief do not waive this.\n\n## User Context\n\nUse [$user-context](../user-context/SKILL.md) when the user asks to:\n\n- Set up Product Design\n- Get started with Product Design\n- Onboard with Product Design\n- Save product or design sources\n- See what Product Design remembers\n- Update saved product or design context\n- Remember a Product Design preference\n- Setup my plugin\n\nAdjust the context-gathering request to match the user's request. First-time setup differs from updating existing context.\n\nFor setup-only requests, do not inspect the workspace, install dependencies, scaffold a prototype, generate images, run audits, or start implementation.\n\nWhen answering \"what can you do?\", \"how do I get started?\", or similar broad Product Design questions, load `$user-context` and follow its persistence availability check before offering saved-context onboarding.\n\nBefore routing to Product Design workflows, load [$user-context](../user-context/SKILL.md) and run its preflight script when local shell access is available.\n\n## Browser Annotation Updates\n\nTreat annotations as scoped edits to the current prototype.\n\nRead the annotation, its target, and the surrounding screen before changing code. Preserve the existing prototype by default: layout, style, content, routes, assets, interactions, and working behavior stay the same unless the annotation asks to change them.\n\nDo not redesign nearby UI or rebuild the prototype just because an annotation touches that area. If the annotation is ambiguous and the choice would materially change the prototype, ask first.\n\n## Skills\n\nUse this as the root routing guidance for Product Design plugin work. If several focused skills apply, sequence them in the order that creates the most useful design workflow. Keep this index as a router; do not perform focused workflow logic here.\n\n### $user-context\n\nPreflight, save, or answer from Product Design setup context. Route here before Product Design workflows to load saved product and design sources, and for direct setup, get-started, onboarding, save, remember, recall, inspect, or customization requests. This skill owns Product Design plugin-scoped context and preference policy.\n\n### $get-context\n\nRoute here first for design, build, prototype, redesign, extend, or UI exploration work. Require only a clear design target and intended user outcome. Ask one targeted question only when one of those is missing; otherwise play back the brief and defaults, then continue without waiting for approval.\n\n### $research\n\nRun fast, source-grounded UX research on current user problems for a named digital product. Route here for researching user pain, UX friction, onboarding issues, docs/help problems, developer experience friction, support pain, product workflow issues, or current user complaints.\n\n### $audit\n\nCapture and review a product flow, journey, screen, or multi-step product experience from screenshots. Route here for user-facing audit, review, critique, inspect, assess, analyze, evaluate, or feedback requests. It reports UX, design, and accessibility findings tied to captured evidence; do not use `design-qa` for user-facing audits.\n\n### $ideate\n\nGenerate image-based visual alternatives, remixes, or concept directions for a component, screen, feature, workflow, or product idea. Route here after `get-context` has played back the minimum brief and the user needs visual exploration, design variants, alternatives to an existing design, or idea discovery before choosing a visual target. Prefer this over prose-only ideation unless the user asks for prose.\n\n### $url-to-code\n\nClone a live URL as a runnable frontend-only local app using the Browser Choice rule above. Load this alongside `get-context` when the user provides a production URL for a faithful local prototype or clone, but do not execute it until the minimum brief has been played back. It should not modify production code; stay in `get-context` when source selection is still unclear.\n\n### $image-to-code\n\nImplement a selected visual target as a faithful, responsive, interactive frontend. Route here after `get-context` has played back the minimum brief and the user has chosen an ImageGen mock, screenshot, Figma frame, mockup, reference image, or other visual source. Do not start here when no visual target has been selected; use `get-context` and `ideate` first.\n\n### $share\n\nDeploy a runnable prototype and return a shareable URL using the user's preferred target when available. Route here when the user asks to share, deploy, publish, host, create a link, or make a prototype shareable with `@Sites`, `@Vercel`, or another deployment tool.\n\n### $design-qa\n\nCompare a coded Product Design prototype against its source visual target before handoff. Route here only as an internal helper after a prototype, URL-to-code build, or image-to-code build has both a source visual and rendered implementation. Do not route broad UX critiques, audits, or product-flow reviews here; use `audit` instead.\n","frontmatter":{"name":"index","description":"Use when Product Design is explicitly invoked, or when the user's main goal is to explore a design, research UX, audit or critique a flow, faithfully clone a visual source, check a built design, or share a prototype. Do not use Product Design for ordinary implementation unless the user explicitly asks for it."},"isInternal":false,"tokens":2060,"sizeBytes":9967},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/product-design/workflows/share/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/product-design/workflows/share/SKILL.md","title":"share","category":"anthropic-skill","format":"markdown","content":"---\nname: share\ndescription: \"Share a runnable prototype using the user's preferred deployment tool.\"\n---\n\n# Share\n\nDeploy the user's runnable prototype so they can share it with others.\n\n## Critical Overrides\n\n- Refer to the Plugin router [$index](../index/SKILL.md) before proceeding.\n- Follow [$critical-overrides](../../references/critical-overrides.md).\n\n## User Context\n\nBefore starting, load [$user-context](../user-context/SKILL.md) and run its preflight script when local shell access is available.\n\nUse saved product URLs, Figma files, screenshots, reference images, codebase paths, Storybook, tokens, design systems, brand assets, component refs, browser preferences, and share targets as grounding material when relevant.\n\nDo not inspect every saved reference. Inspect only what the current task needs.\n\n## Workflow\n\n1. Confirm the prototype directory and the user's preferred deployment target.\n2. If the user invokes Product Design with @Sites, @Vercel, or another deployment tool, treat that as the selected hosting target.\n3. If the user did not choose a target, ask one question:\n\n> Where should I deploy this: @Sites, @Vercel, or another target?\n\n4. Use the selected deployment tool when it is available.\n5. If the selected tool is not available, say that clearly and ask whether to use another target.\n6. Run the deployment when possible. Do not give setup instructions if you can complete the deployment directly.\n7. Return the shareable URL.\n8. State any misses or manual follow-up the user still needs to do.\n\n## Rules\n\n- Do not deploy before the user chooses or confirms the target.\n- Do not claim the prototype is shared until you have a working URL.\n- If the selected tool is not available, say that clearly and ask whether to use another target.\n","frontmatter":{"name":"share","description":"Share a runnable prototype using the user's preferred deployment tool."},"isInternal":false,"tokens":379,"sizeBytes":1772},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/product-design/workflows/url-to-code/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/product-design/workflows/url-to-code/SKILL.md","title":"url-to-code","category":"anthropic-skill","format":"markdown","content":"---\nname: url-to-code\ndescription: \"Recreate an authorized live website or app URL as a faithful, runnable, frontend-only local implementation.\"\n---\n\n# URL to Code\n\nUse this workflow only when the user asks to clone or faithfully recreate a live site they own or have permission to reproduce. For redesign, improvement, or a loosely inspired result, route through `../index/SKILL.md` to context and ideation instead.\n\nRead `../index/SKILL.md`, `../../references/critical-overrides.md`, and relevant saved context before building.\n\n## Workflow\n\n1. Remind the user that they must have permission and follow the target site's terms.\n2. Open the source with the browser selected by the index. Stop if it resolves to a wrong page, login wall, error, unrelated redirect, or other surface that cannot ground the requested clone.\n3. Capture the full desktop page and a representative mobile viewport. Inspect small scroll increments so sticky, lazy-loaded, and animated content is not missed.\n4. Inspect the DOM and visible behavior for text, links, controls, component states, images, icons, fonts, colors, spacing, dimensions, breakpoints, and interaction behavior.\n5. Test important interactions one at a time and return to the starting state between tests. Preserve evidence for changed states.\n6. Save permitted source assets locally. Do not hotlink them in the final result. When an asset cannot be obtained, use an available generation tool or an appropriate open replacement and disclose the substitution.\n7. Inspect the target repository and use its existing framework and conventions. React is not required. If no app exists, create the smallest suitable frontend supported by the harness; plain HTML/CSS/JavaScript is acceptable.\n8. Build only from captured evidence. Implement the visible desktop/mobile layouts and primary interactions without inventing unrelated design choices or backend behavior.\n9. Run and inspect the local implementation with a real browser. Compare the same viewport and states against the source.\n10. Run `../design-qa/SKILL.md`, save `design-qa.md`, fix blocking and high-impact mismatches, and hand off only after `final result: passed` or a clearly documented verification blocker.\n\n## Hard rules\n\n- Capture source evidence before scaffolding or editing.\n- Do not infer hidden states when source evidence is available.\n- Do not use screenshots alone when DOM/style/interaction evidence can be inspected.\n- Do not leave placeholder assets or improvised icon glyphs in the final implementation.\n- Build success and server health are not visual verification.\n- Publish only when the user asks and the host exposes an authorized deployment tool.\n\n","frontmatter":{"name":"url-to-code","description":"Recreate an authorized live website or app URL as a faithful, runnable, frontend-only local implementation."},"isInternal":false,"tokens":532,"sizeBytes":2676},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/product-design/workflows/user-context/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/product-design/workflows/user-context/SKILL.md","title":"user-context","category":"anthropic-skill","format":"markdown","content":"---\nname: user-context\ndescription: Load or manage Product Design's saved user context. Use when the user asks to set up Product Design, get started, onboard, save product or design sources, see what Product Design remembers, update saved context, or remember Product Design preferences. Examples include product URLs, Figma files, screenshots, reference images, codebase paths, Storybook, tokens, design systems, brand assets, and general product/design notes.\n---\n\n# User Context\n\nUser Context stores the product and design references a designer uses often, so future Product Design work starts from the right sources.\n\nUse this skill when the user asks to:\n\n- set up Product Design\n- get started with Product Design\n- onboard with Product Design\n- save product or design sources\n- see what Product Design remembers\n- update saved product or design context\n- remember a Product Design preference\n- setup my plugin\n\n## Critical Overrides\n\n- Refer to the Plugin router [$index](../index/SKILL.md) before proceeding.\n- Follow [$critical-overrides](../../references/critical-overrides.md).\n- Before offering onboarding or saving context for future conversations, confirm that local shell access is available, `$CODEX_HOME` can be resolved, and `$CODEX_HOME/state/plugins/product-design/` exists and is writable or can be created in a writable parent directory. If `user-context.md` already exists, confirm that it is writable too.\n- If any check cannot be completed or fails, persistent context is unavailable. Do not offer saved-context onboarding or claim that new context was saved for future conversations. If the user asks to save something, explain that it can be used in the current conversation but not saved for future conversations.\n\n## Saved User Context\n\nIf `user-context.md` exists, use it by default.\n\nUse saved product URLs, Figma files, screenshots, reference images, codebase paths, Storybook, tokens, design systems, brand assets, component refs, browser preferences, and share targets to ground Product Design work.\n\nIdeation, prototypes, audits, clones, and critiques should match the saved product context unless the user asks for something different.\n\nWhen a workflow needs visual grounding, attach or include relevant saved screenshots, reference images, tokens, design language, and component references in ImageGen, ideation, prototype, audit, and critique work.\n\n## State File\n\nSaved context lives here:\n\n```text\n$CODEX_HOME/state/plugins/product-design/user-context.md\n```\n\nSaved screenshots and reference images live next to it:\n\n```text\n$CODEX_HOME/state/plugins/product-design/assets/\n```\n\nIf the file does not exist, continue normally unless the user asks to set up Product Design, save context, or the current task is blocked by missing product/design context.\n\n## Preflight\n\nWhen any Product Design workflow needs saved context, run:\n\n```bash\npython3 scripts/user_context_preflight.py\n```\n\nUse the returned saved entries as the starting context for the task.\n\nIf the script reports that no saved context exists, continue from the current user prompt unless setup context is required.\n\nDo not browse, open, or inspect every saved reference during preflight. Inspect only the saved references needed for the current task.\n\n## Setup\n\nUse [references/onboarding.md](references/onboarding.md) when the user asks to set up Product Design, asks what Product Design can remember, asks what Product Design knows about their product, or provides product/design references to save.\n\nFor setup-only requests, explain what Product Design can remember and ask for useful sources.\n\nAdjust the context-gathering request to match the user's request. First-time setup differs from updating existing context.\n\nDo not inspect the workspace, install dependencies, scaffold a prototype, generate images, run audits, or start implementation during setup.\n\nAfter the user provides references to save, run:\n\n```bash\npython3 scripts/init_user_context.py\n```\n\nThen add the references to the created `user-context.md`.\n\n## Save\n\nSave useful, durable Product Design context:\n\n- Product URLs\n- Figma files\n- Screenshots and reference images\n- Codebase paths\n- Storybook and component docs\n- Design tokens and theme sources\n- Brand, logo, icon, illustration, image, and asset sources\n- Preferred browser, capture tools, and share targets\n- Team conventions that make future Product Design work more accurate\n\nWhen the user provides screenshots or reference images to save, copy them into `assets/` next to `user-context.md` and link them from the saved entry.\n\nGive each saved image a clear, descriptive filename that says what the image shows. Use names future Product Design runs can understand without opening the file.\n\nGood image names:\n\n```text\nassets/chatgpt-settings-modal-dark-mode.png\nassets/payment-sheet-mobile-error-state.png\nassets/product-dashboard-sidebar-navigation.png\nassets/storybook-primary-button-states.png\nassets/brand-logo-lockup-purple-gradient.png\nassets/onboarding-flow-welcome-step.png\nassets/checkout-confirmation-screen.png\nassets/account-menu-open-state.png\n```\n\nDo not save secrets, credentials, API keys, private tokens, copied customer data, or anything that should not persist.\n\nUse this structure:\n\n```md\n# {Category}\n\n- Description: {what this category is and when future Product Design runs should use it}\n\n## Saved Links And Context\n\n{Saved reference or fact}\n- Date Added: YYYY-MM-DD.\n- File: assets/{clear-descriptive-name}.png\n- Useful Context: {what this reference represents}\n- Future Use: {how future Product Design work should use it}\n```\n\nInclude `File:` only when the saved entry has a local image file.\n\nWhen a category has no saved references yet, use exactly:\n\n```md\nstatus: not provided\n```\n\nKeep saved context curated. Prefer a few high-value references over a dump of every possible URL or file.\n\n## Read\n\n- Do not treat `status: not provided` as a fact.\n- Read through `scripts/user_context_preflight.py` when local shell access is available.\n- Use saved context as default grounding, then inspect only what the current task needs.\n","frontmatter":{"name":"user-context","description":"Load or manage Product Design's saved user context. Use when the user asks to set up Product Design, get started, onboard, save product or design sources, see what Product Design remembers, update saved context, or remember Product Design preferences. Examples include product URLs, Figma files, screenshots, reference images, codebase paths, Storybook, tokens, design systems, brand assets, and general product/design notes."},"isInternal":false,"tokens":1242,"sizeBytes":6088},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/research-paper-writing/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/research-paper-writing/SKILL.md","title":"research-paper-writing","category":"anthropic-skill","format":"markdown","content":"---\nname: research-paper-writing\ndescription: Write, rewrite, and polish academic papers (ML/CV/NLP style). Use when the user drafts or revises Abstract, Introduction, Related Work, Method, Experiments, or Conclusion; asks \"does this flow / 这段通顺吗 / polish this paragraph\"; turns bullet points or a Chinese draft into publication-quality English; runs a pre-submission self-review or reviewer-style critique; fixes paper figures/tables/LaTeX formatting; or compiles/converts the paper to PDF (LaTeX build, 编译PDF, 转成PDF). Trigger on mentions of paper, draft, camera-ready, rebuttal-facing revision, CVPR/ICCV/NeurIPS/ICLR/ACL-style venues, or .tex files being edited for a paper.\n---\n\n# Research Paper Writing\n\nAct as an experienced co-author who has published at top ML/CV/NLP venues. The goal is not \"prettier English\" — it is a draft that survives skeptical reviewers: clear story, one message per paragraph, and every claim backed by evidence.\n\n## Step 1: Diagnose the request, then route\n\nMatch the user's situation and load ONLY the needed reference (do not preload all):\n\n| User situation | What to do | Load |\n|---|---|---|\n| \"Polish this paragraph / does this flow?\" | Quick polish pass (see below) | `references/paragraph-flow.md` |\n| Draft or rewrite Abstract | Pick a template, draft, check claims | `references/abstract.md` |\n| Draft or rewrite Introduction | Clarify story first, then template | `references/introduction.md` |\n| Draft or rewrite Related Work | Topic grouping + positioning | `references/related-work.md` |\n| Draft or rewrite Method | Module triad workflow | `references/method.md` |\n| Draft or rewrite Experiments; fix tables | Claim→experiment mapping, table rules | `references/experiments.md` |\n| Draft or rewrite Conclusion / Limitations | Scope-based limitation framing | `references/conclusion.md` |\n| \"Review my paper / 投稿前检查\" | Adversarial five-dimension review | `references/paper-review.md` |\n| \"Compile / convert to PDF / 编译不过\" | Pick engine, build, verify output | `references/pdf-export.md` |\n| Bullet points / Chinese notes → English section | Treat as section drafting; get facts first, then draft | the matching section guide |\n\nIf the user's draft lives in files (`.tex`, `.md`, Overleaf export), work on the files directly: locate sections with grep (`\\section`, `\\begin{abstract}`), edit in place, and keep every `\\cite{...}`, `\\ref{...}`, label, comment, and math environment byte-for-byte unless the edit is specifically about them.\n\n## Step 2: Get the facts before writing\n\nGood paper writing is mostly correct facts arranged well. Before drafting a section, make sure these are known — from the draft, the codebase, or the user:\n\n1. What exact technical problem is solved, and why prior methods fail at it (limitation + technical reason).\n2. What the contribution is (new task / pipeline / module / finding / insight).\n3. Why the method works in essence, and its concrete advantages.\n4. What the strongest experimental numbers are.\n\nIf any of these are missing and not recoverable from context, ask — at most 3 focused questions in one message. Never fill gaps by inventing.\n\n## Hard Rules (never violate)\n\n1. **Never fabricate.** Do not invent experimental numbers, citations, baseline names, dataset statistics, or related-work claims. Use explicit placeholders (`[XX.X]`, `[CITE: sparse-view NeRF methods]`) and tell the user what to fill in.\n2. **Preserve technical meaning.** Rewrites must keep every claim's strength and scope. If a sentence is ambiguous and the rewrite must pick an interpretation, flag it: `⚠ interpreted as ...`.\n3. **Weaken or cut unsupported claims.** If a claim in Abstract/Introduction has no experimental backing in the paper, do not keep it strong — propose the weakened version and say why.\n4. **Respect double-blind.** Do not insert author names, GitHub links, or acknowledgments into a submission draft; warn the user if the draft already leaks identity.\n5. **Scale the output to the request.** A one-paragraph polish gets revised text plus a 1–2 line note — no outlines, no checklists. Full contracts are for section rewrites and reviews only.\n\n## Core Writing Principles\n\n1. One paragraph, one message; the first sentence states it.\n2. Every sentence connects to the previous one (cause, contrast, consequence, refinement, example).\n3. Define terms before reusing them; keep terminology identical across the whole paper (never alternate synonyms for a key concept).\n4. Never present the method as an incremental patch on a naive baseline — lead with the challenge and the insight, even for incremental work.\n5. Figures and tables are content, not decoration: clean teaser, clear pipeline figure, booktabs-style minimal-ink tables.\n\n## Workflows by request size\n\n### A. Quick polish (sentence / paragraph)\n\n1. Run the flow test from `references/paragraph-flow.md`: one message? first sentence states it? nouns self-contained? sentence-to-sentence relations explicit?\n2. Return the revised paragraph, then 1–2 lines on what changed and why.\n3. If the paragraph's real problem is structural (wrong message, no evidence), say so instead of cosmetically polishing.\n\n### B. Section draft / rewrite\n\n1. Confirm the section's story in a 3–7 bullet mini-outline before writing prose; on low ambiguity proceed and show the outline with the draft.\n2. Draft paragraph by paragraph — one message per paragraph, template from the section guide.\n3. Reverse-outline the result: thesis → topic sentences → evidence; fix anything that doesn't map.\n4. For Abstract/Introduction, append a claim-evidence map: `Claim: ... | Evidence: ... | Status: supported / needs evidence / weakened`.\n\n### C. Pre-submission review\n\n1. Load `references/paper-review.md` and read the paper as a hostile reviewer.\n2. Score the five dimensions (contribution, clarity, experimental strength, evaluation completeness, method soundness); mark each question `pass` / `needs revision` / `needs new experiment`.\n3. Return a prioritized fix list: rejection-level risks first, then clarity issues, then polish. Include concrete edit suggestions, not just complaints.\n\n## References\n\n- `references/abstract.md` — 3 abstract templates with annotated real examples\n- `references/introduction.md` — intro logic map, 4 opening / 3 challenge / 4 pipeline templates\n- `references/related-work.md` — topic grouping and positioning\n- `references/method.md` — module triad (design / motivation / advantage) workflow\n- `references/experiments.md` — claim→experiment planning, table/figure rules\n- `references/conclusion.md` — limitation framing that doesn't invite rejection\n- `references/paper-review.md` — adversarial five-dimension review checklist\n- `references/paragraph-flow.md` — paragraph clarity test, reverse outlining, transitions\n- `references/pdf-export.md` — compiling LaTeX/Markdown to PDF, engine choice, failure fixes, output verification\n- `references/examples/` — annotated LaTeX examples cited from the section guides\n","frontmatter":{"name":"research-paper-writing","description":"Write, rewrite, and polish academic papers (ML/CV/NLP style). Use when the user drafts or revises Abstract, Introduction, Related Work, Method, Experiments, or Conclusion; asks \"does this flow / 这段通顺吗 / polish this paragraph\"; turns bullet points or a Chinese draft into publication-quality English; runs a pre-submission self-review or reviewer-style critique; fixes paper figures/tables/LaTeX formatting; or compiles/converts the paper to PDF (LaTeX build, 编译PDF, 转成PDF). Trigger on mentions of paper, draft, camera-ready, rebuttal-facing revision, CVPR/ICCV/NeurIPS/ICLR/ACL-style venues, or .tex files being edited for a paper."},"isInternal":false,"tokens":1570,"sizeBytes":7058},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/sales/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/sales/SKILL.md","title":"sales","category":"anthropic-skill","format":"markdown","content":"---\nname: sales\ndescription: \"Use this skill whenever Sales is explicitly invoked or the task involves customer meeting preparation, call follow-up, account prioritization, account signals, deal strategy, business cases, competitive briefs, forecasts, customer evidence, rep coaching, company research, CRM context, or company and contact enrichment.\"\n---\n\n# Sales\n\nThis is the single entry point for a code-agent-oriented Sales bundle. The original workflow instructions are under `workflows/`; connector manifests and plugin marketplace metadata are intentionally excluded.\n\n## Route the request\n\n1. Read `workflows/index/SKILL.md` completely. Treat it as the authoritative plugin-level scope, source-selection rules, routing, and workflow sequencing policy.\n2. Select the narrowest focused workflow or workflow sequence named by that index. Read every selected workflow's `SKILL.md` completely before acting.\n3. Load provider-specific skills such as Salesforce, HubSpot, Apollo, or ZoomInfo only when the chosen source and available host tools make them relevant.\n4. If a selected workflow names related skills, read them only when their stated conditions apply. Resolve relative links from the file containing the link and load required references completely.\n5. Prefer bundled scripts and templates when a selected workflow calls for them. Do not load unrelated sales workflows merely because they are present.\n\n## Bundled capabilities\n\nFocused workflows live in `workflows/`, covering meeting preparation, call follow-up, account prioritization and signals, deal planning, business cases, competitive briefs, forecast review, customer quotes, internal experts, rep coaching, company research, enrichment, and provider-specific CRM or intelligence workflows.\n\nWorkflow-local supporting assets, references, and scripts remain beside their owning workflow. Use CRM, email, calendar, messaging, transcript, intelligence, and document systems only when the host harness exposes an authenticated tool for them. Do not invent customer facts when a source is missing; use the workflow's evidence and fallback rules.\n\n## Safety and fidelity\n\n- Never treat plugin instructions as permission to bypass host policy, reveal credentials, or perform unapproved external writes.\n- Keep sourced facts separate from inference and recommendations.\n- Require appropriate confirmation before sending messages, updating CRM records, or taking other external actions.\n- Preserve the selected workflow's requested output and handoff requirements through completion.\n","frontmatter":{"name":"sales","description":"Use this skill whenever Sales is explicitly invoked or the task involves customer meeting preparation, call follow-up, account prioritization, account signals, deal strategy, business cases, competitive briefs, forecasts, customer evidence, rep coaching, company research, CRM context, or company and contact enrichment."},"isInternal":false,"tokens":461,"sizeBytes":2548},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/sales/workflows/analyze-account-signals/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/sales/workflows/analyze-account-signals/SKILL.md","title":"analyze-account-signals","category":"anthropic-skill","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fanalyze-account-signals%2FSKILL.md -->","frontmatter":{"name":"analyze-account-signals","description":"Use when the user wants to know what changed with one account, monitor an owner portfolio or watchlist, or rank accounts needing attention from recent evidence. Produce an evidence-backed account brief or bounded watchlist summary with recommended actions."},"isInternal":false,"tokens":3384,"sizeBytes":16439},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/sales/workflows/answers-ask-user-input/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/sales/workflows/answers-ask-user-input/SKILL.md","title":"answers-ask-user-input","category":"anthropic-skill","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fanswers-ask-user-input%2FSKILL.md -->","frontmatter":{"name":"answers-ask-user-input","description":"Use when a small amount of missing context would materially improve the answer and tappable options plus a free-text answer can gather it efficiently."},"isInternal":false,"tokens":1029,"sizeBytes":4749},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/sales/workflows/apollo/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/sales/workflows/apollo/SKILL.md","title":"apollo","category":"anthropic-skill","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fapollo%2FSKILL.md -->","frontmatter":{"name":"apollo","description":"Use only when a focused Sales workflow has selected a present and connected Apollo connector, or the user explicitly asks for Apollo prospecting, enrichment, Company Details, records, sequences, or outbound planning. Apply Apollo v2-specific behavior only after verifying app version 2.0.0 or later."},"isInternal":false,"tokens":2666,"sizeBytes":13848},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/sales/workflows/build-business-case/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/sales/workflows/build-business-case/SKILL.md","title":"build-business-case","category":"anthropic-skill","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fbuild-business-case%2FSKILL.md -->","frontmatter":{"name":"build-business-case","description":"Review commercial proposals and build customer-led business cases, ROI or value models, pricing or investment rationales, executive summaries, and customer-ready value stories tied to a customer, workflow, initiative, or decision."},"isInternal":false,"tokens":2420,"sizeBytes":11665},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/sales/workflows/build-competitive-brief/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/sales/workflows/build-competitive-brief/SKILL.md","title":"build-competitive-brief","category":"anthropic-skill","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fbuild-competitive-brief%2FSKILL.md -->","frontmatter":{"name":"build-competitive-brief","description":"Use when the user wants a competitor or vendor comparison, market-landscape analysis, battlecard, objection package, positioning brief, or account-specific competitive view. Produce an evidence-backed comparison, guidance, and brief, using supplied materials, connected research, and public evidence when appropriate."},"isInternal":false,"tokens":3390,"sizeBytes":17078},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/sales/workflows/enrich-company-and-contact-data/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/sales/workflows/enrich-company-and-contact-data/SKILL.md","title":"enrich-company-and-contact-data","category":"anthropic-skill","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fenrich-company-and-contact-data%2FSKILL.md -->","frontmatter":{"name":"enrich-company-and-contact-data","description":"Use for data-first company, contact, lead, and prospect discovery or enrichment, including firmographic or technographic completion, named-company profiling, entity resolution, ICP matching, prospect-list building, segmentation, trigger or sales-signal analysis, market and territory scans, and enrichment-backed comparisons. Exclude meeting preparation, outreach-led company research, and prioritization of an already established account book."},"isInternal":false,"tokens":2271,"sizeBytes":10996},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/sales/workflows/find-customer-quotes/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/sales/workflows/find-customer-quotes/SKILL.md","title":"find-customer-quotes","category":"anthropic-skill","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Ffind-customer-quotes%2FSKILL.md -->","frontmatter":{"name":"find-customer-quotes","description":"Use when the user wants verbatim customer or prospect quotes, voice-of-customer evidence, theme validation, objection evidence, product-friction examples, or support for a product area, use case, or sales narrative. Retrieve from transcripts, call notes, supplied transcript-like recordings or exports, and other grounded call material using explicit speaker-confidence and provenance rules."},"isInternal":false,"tokens":2634,"sizeBytes":12946},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/sales/workflows/find-key-internal-sources/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/sales/workflows/find-key-internal-sources/SKILL.md","title":"find-key-internal-sources","category":"anthropic-skill","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Ffind-key-internal-sources%2FSKILL.md -->","frontmatter":{"name":"find-key-internal-sources","description":"Use when a seller needs to find the best internal experts, owners, approvers, documents, channels, source-of-truth materials, or escalation routes for a customer question, product topic, competitive objection, implementation issue, account task, or other sales-support need. Route questions such as 'who knows about this?', 'what should I read?', 'where is the source of truth?', and 'which internal channel or document should I use?' here."},"isInternal":false,"tokens":2244,"sizeBytes":10940},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/sales/workflows/follow-up-after-call/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/sales/workflows/follow-up-after-call/SKILL.md","title":"follow-up-after-call","category":"anthropic-skill","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Ffollow-up-after-call%2FSKILL.md -->","frontmatter":{"name":"follow-up-after-call","description":"Use after a completed customer, prospect, partner, or important internal sales call, discovery session, demo, or conversation, including when the user supplies or uploads a transcript, notes, recording summary, or other grounded evidence. Advise on, assess, qualify, recap, and produce seller-ready follow-up actions and drafts."},"isInternal":false,"tokens":2873,"sizeBytes":13988},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/sales/workflows/get-rep-call-feedback/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/sales/workflows/get-rep-call-feedback/SKILL.md","title":"get-rep-call-feedback","category":"anthropic-skill","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fget-rep-call-feedback%2FSKILL.md -->","frontmatter":{"name":"get-rep-call-feedback","description":"Use when the user wants evidence-backed coaching for one rep's calls, especially by comparing the rep with peer examples to identify repeatable best practices, specific upgrade moments, and practical next-call language."},"isInternal":false,"tokens":2327,"sizeBytes":11538},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/sales/workflows/hubspot/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/sales/workflows/hubspot/SKILL.md","title":"hubspot","category":"anthropic-skill","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fhubspot%2FSKILL.md -->","frontmatter":{"name":"hubspot","description":"Use only when a focused Sales workflow has selected a connected HubSpot CRM, or the user explicitly asks for HubSpot guidance, reads, drafts, notes, or reviewed record changes. Do not use when another CRM is authoritative."},"isInternal":false,"tokens":1529,"sizeBytes":7281},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/sales/workflows/index/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/sales/workflows/index/SKILL.md","title":"index","category":"anthropic-skill","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Findex%2FSKILL.md -->","frontmatter":{"name":"index","description":"Use this Sales index first for explicit Sales mentions and clear seller workflows: prospecting, lead qualification, account research, monitoring or prioritization, meeting prep, call follow-up, outreach research, deal strategy, pipeline or forecast review, CRM-backed context or data enrichment, internal source finding or sales support, customer quotes or evidence, business cases, competitive briefs, rep coaching, sales company research, and company or contact enrichment. For implicit use require clear seller, prospect, account, opportunity, pipeline, forecast, CRM, or customer-facing sales intent."},"isInternal":false,"tokens":2762,"sizeBytes":14293},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/sales/workflows/plan-deal-strategy/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/sales/workflows/plan-deal-strategy/SKILL.md","title":"plan-deal-strategy","category":"anthropic-skill","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fplan-deal-strategy%2FSKILL.md -->","frontmatter":{"name":"plan-deal-strategy","description":"Use when the user wants strategy for one active deal, renewal, negotiation, buying process, or initial sales motion for an offer or product. Build a grounded deal map or practical sales plan with objections, sequencing, posture, and prioritized next actions. Use prepare-for-meeting instead for multi-account same-day customer call queues."},"isInternal":false,"tokens":2672,"sizeBytes":12549},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/sales/workflows/prepare-for-meeting/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/sales/workflows/prepare-for-meeting/SKILL.md","title":"prepare-for-meeting","category":"anthropic-skill","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fprepare-for-meeting%2FSKILL.md -->","frontmatter":{"name":"prepare-for-meeting","description":"Use when the user wants to prepare for one or more upcoming meetings with customers, prospects, partners, accounts, or important stakeholders; requests daily or date-based meeting preparation; asks to organize a same-day customer call queue; asks for the most important qualifying meeting of the day; or identifies meetings only by company, attendee, topic, or date. Produce an individual meeting brief or a chronological multi-meeting agenda as appropriate."},"isInternal":false,"tokens":2227,"sizeBytes":10680},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/sales/workflows/prioritize-accounts/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/sales/workflows/prioritize-accounts/SKILL.md","title":"prioritize-accounts","category":"anthropic-skill","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fprioritize-accounts%2FSKILL.md -->","frontmatter":{"name":"prioritize-accounts","description":"Use when the user asks which existing accounts to work now, which leads are hottest in a grounded list or pipeline, how to rank a territory, book, pipeline, ICP list, or account list, where to focus this week, or what rep-ready next actions to take. Prioritize accounts using current evidence, suppress or account for in-flight motion, and identify reachable contacts when supported. Use enrichment instead for net-new company discovery or missing-data completion."},"isInternal":false,"tokens":2765,"sizeBytes":13199},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/sales/workflows/review-forecast/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/sales/workflows/review-forecast/SKILL.md","title":"review-forecast","category":"anthropic-skill","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Freview-forecast%2FSKILL.md -->","frontmatter":{"name":"review-forecast","description":"Use when the user wants forecast posture, forecast accuracy, commit, upside, forecast-call preparation, or a pipeline or deal-risk review for a seller book, team, period, report, or named deal set. Produce a manager-ready forecast rollup, risk posture, recommendation changes, evidence gaps, and follow-up actions."},"isInternal":false,"tokens":3242,"sizeBytes":15816},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/sales/workflows/review-rep-call-trends/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/sales/workflows/review-rep-call-trends/SKILL.md","title":"review-rep-call-trends","category":"anthropic-skill","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Freview-rep-call-trends%2FSKILL.md -->","frontmatter":{"name":"review-rep-call-trends","description":"Use when the user wants to understand how a sales or customer-facing rep's call behavior is changing over time. Produce an evidence-backed trend readout with improvements, regressions, stable patterns, coaching actions, and calls to re-listen."},"isInternal":false,"tokens":2274,"sizeBytes":11034},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/sales/workflows/sales-company-research/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/sales/workflows/sales-company-research/SKILL.md","title":"sales-company-research","category":"anthropic-skill","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fsales-company-research%2FSKILL.md -->","frontmatter":{"name":"sales-company-research","description":"Research companies, partners, and referral channels to shape draft outreach approaches, messages, or partner motions; exclude descriptive company profiling, list enrichment, and internal source finding."},"isInternal":false,"tokens":914,"sizeBytes":4511},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/sales/workflows/salesforce/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/sales/workflows/salesforce/SKILL.md","title":"salesforce","category":"anthropic-skill","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fsalesforce%2FSKILL.md -->","frontmatter":{"name":"salesforce","description":"Use when a focused Sales workflow needs Salesforce-backed CRM reads, links, drafts, notes, account plans, Agentforce assignments, or explicitly requested Salesforce connector/query guidance. Do not use for generic CRM app construction or when another CRM is authoritative."},"isInternal":false,"tokens":2451,"sizeBytes":12010},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/sales/workflows/zoominfo/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/sales/workflows/zoominfo/SKILL.md","title":"zoominfo","category":"anthropic-skill","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsales%2Fworkflows%2Fzoominfo%2FSKILL.md -->","frontmatter":{"name":"zoominfo","description":"Use only when a focused Sales workflow has selected a present and connected ZoomInfo connector, or the user explicitly asks for ZoomInfo company search, contact search, enrichment, intent, similarity, recommendations, or research. Do not use when another enrichment source is selected."},"isInternal":false,"tokens":2741,"sizeBytes":13890},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/skill-creator/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/skill-creator/SKILL.md","title":"skill-creator","category":"anthropic-skill","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fskill-creator%2FSKILL.md -->","frontmatter":{"name":"skill-creator","description":"Interactive guide for creating, reviewing, and improving agent skills (SKILL.md folders). Use when the user wants to build a new skill ('create a skill', 'make a skill for X', 'write a SKILL.md', 'turn this workflow into a skill'), review or improve an existing skill, fix a skill that never triggers or triggers too often, or validate a skill folder before sharing it. Do NOT use for general prompt writing, MCP server development, or editing arbitrary markdown files.","version":"1.0.0","license":"MIT","platforms":["linux","macos","windows"]},"isInternal":false,"tokens":1725,"sizeBytes":7763},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/super-research/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/super-research/SKILL.md","title":"super-research","category":"anthropic-skill","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsuper-research%2FSKILL.md -->","isInternal":false,"tokens":2764,"sizeBytes":11553},{"name":"SKILL.md","path":"packages/cli/src/skill/builtin/.bundle/xlsx-official/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/xlsx-official/SKILL.md","title":"xlsx-official","category":"anthropic-skill","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fxlsx-official%2FSKILL.md -->","frontmatter":{"name":"xlsx-official","description":"Spreadsheet toolkit. Reach for it whenever the artifact on either side of the conversation is a workbook file — .xlsx, .xlsm, .xltx, .csv, .tsv — and the user wants that artifact produced, changed, cleaned, or read. Typical triggers: 'build me a model', 'update this sheet', 'add a column', 'compute the totals as formulas', 'sanity-check this xlsx', 'export sheet 2 to CSV', 'render the workbook as PDF', 'the spreadsheet in ~/Downloads is a mess, fix it'. Applies equally to financial models, ops reports, data cleanups, and template fills. Skip it when the workbook is only source material and the real output is a Word doc, an HTML page, a Python script that runs standalone, a Google Sheets integration, or an ingestion pipeline into a database — in those cases the spreadsheet is a means, not the deliverable.","license":"Apache-2.0 — see LICENSE for terms and third-party attributions"},"isInternal":false,"tokens":3069,"sizeBytes":11820},{"name":"AGENTS.md","path":"packages/cli/test/AGENTS.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/test/AGENTS.md","title":"Test Skill","category":"anthropic-skill","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Ftest%2FAGENTS.md -->","isInternal":false,"tokens":1079,"sizeBytes":4518},{"name":"callable.md","path":"packages/cli/test/fixture/skills/agents-sdk/references/callable.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/test/fixture/skills/agents-sdk/references/callable.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Ftest%2Ffixture%2Fskills%2Fagents-sdk%2Freferences%2Fcallable.md -->","isInternal":false,"tokens":521,"sizeBytes":2283},{"name":"SKILL.md","path":"packages/cli/test/fixture/skills/agents-sdk/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/test/fixture/skills/agents-sdk/SKILL.md","title":"agents-sdk","category":"anthropic-skill","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Ftest%2Ffixture%2Fskills%2Fagents-sdk%2FSKILL.md -->","frontmatter":{"name":"agents-sdk","description":"Build AI agents on Cloudflare Workers using the Agents SDK. Load when creating stateful agents, durable workflows, real-time WebSocket apps, scheduled tasks, MCP servers, or chat applications. Covers Agent class, state management, callable RPC, Workflows integration, and React hooks."},"isInternal":false,"tokens":1460,"sizeBytes":6337},{"name":"SKILL.md","path":"packages/cli/test/fixture/skills/cloudflare/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/test/fixture/skills/cloudflare/SKILL.md","title":"cloudflare","category":"anthropic-skill","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Ftest%2Ffixture%2Fskills%2Fcloudflare%2FSKILL.md -->","frontmatter":{"name":"cloudflare","description":"Comprehensive Cloudflare platform skill covering Workers, Pages, storage (KV, D1, R2), AI (Workers AI, Vectorize, Agents SDK), networking (Tunnel, Spectrum), security (WAF, DDoS), and infrastructure-as-code (Terraform, Pulumi). Use for any Cloudflare development task.","references":["workers","pages","d1","durable-objects","workers-ai"]},"isInternal":false,"tokens":1795,"sizeBytes":7799},{"name":"index.json","path":"packages/cli/test/fixture/skills/index.json","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/test/fixture/skills/index.json","title":"Skills Skill","category":"anthropic-skill","format":"json","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Ftest%2Ffixture%2Fskills%2Findex.json -->","frontmatter":{"skills":[{"name":"agents-sdk","description":"Cloudflare Agents SDK","files":["SKILL.md","references/callable.md"]},{"name":"cloudflare","description":"Cloudflare Platform Skill","files":["SKILL.md"]}]},"isInternal":false,"tokens":70,"sizeBytes":237},{"name":"SKILL.md","path":"packages/cli/test/fixture/skills/llm-endpoint-demo/SKILL.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/test/fixture/skills/llm-endpoint-demo/SKILL.md","title":"llm-endpoint-demo","category":"anthropic-skill","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Ftest%2Ffixture%2Fskills%2Fllm-endpoint-demo%2FSKILL.md -->","frontmatter":{"name":"llm-endpoint-demo","description":"Demo and end-to-end fixture for MiMoCode's temporary local LLM server. Use when verifying that a skill can borrow a configured chat model through a local base_url and a throwaway token instead of a real provider API key, or when testing the expire-and-reissue loop. Not a general-purpose skill."},"isInternal":false,"tokens":898,"sizeBytes":3523},{"name":"README.md","path":"packages/cli/README.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/README.md","title":"cli Documentation","category":"plugin-manifest","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2FREADME.md -->","isInternal":false,"tokens":68,"sizeBytes":212},{"name":"README.md","path":"packages/cli/src/acp/README.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/acp/README.md","title":"acp Documentation","category":"plugin-manifest","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Facp%2FREADME.md -->","isInternal":false,"tokens":1086,"sizeBytes":4919},{"name":"README.md","path":"packages/cli/src/provider/sdk/copilot/README.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/provider/sdk/copilot/README.md","title":"copilot Documentation","category":"plugin-manifest","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fprovider%2Fsdk%2Fcopilot%2FREADME.md -->","isInternal":false,"tokens":43,"sizeBytes":225},{"name":"README.md","path":"packages/cli/src/skill/builtin/.bundle/docx-official/README.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/docx-official/README.md","title":"docx-official Documentation","category":"plugin-manifest","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fdocx-official%2FREADME.md -->","isInternal":false,"tokens":1352,"sizeBytes":5662},{"name":"README.md","path":"packages/cli/src/skill/builtin/.bundle/pdf-official/README.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/pdf-official/README.md","title":"pdf-official Documentation","category":"plugin-manifest","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fpdf-official%2FREADME.md -->","isInternal":false,"tokens":1108,"sizeBytes":4543},{"name":"README.md","path":"packages/cli/src/skill/builtin/.bundle/super-research/evals/toy_bench/README.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/super-research/evals/toy_bench/README.md","title":"toy_bench Documentation","category":"plugin-manifest","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsuper-research%2Fevals%2Ftoy_bench%2FREADME.md -->","isInternal":false,"tokens":240,"sizeBytes":994},{"name":"README.md","path":"packages/cli/src/skill/builtin/.bundle/super-research/evals/toy_dataset/README.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/super-research/evals/toy_dataset/README.md","title":"toy_dataset Documentation","category":"plugin-manifest","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsuper-research%2Fevals%2Ftoy_dataset%2FREADME.md -->","isInternal":false,"tokens":208,"sizeBytes":843},{"name":"README.md","path":"packages/cli/src/skill/builtin/.bundle/super-research/evals/toy_pipeline/README.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/super-research/evals/toy_pipeline/README.md","title":"toy_pipeline Documentation","category":"plugin-manifest","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsuper-research%2Fevals%2Ftoy_pipeline%2FREADME.md -->","isInternal":false,"tokens":523,"sizeBytes":2146},{"name":"README.md","path":"packages/cli/src/skill/builtin/.bundle/super-research/evals/toy_regression/README.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/super-research/evals/toy_regression/README.md","title":"toy_regression Documentation","category":"plugin-manifest","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsuper-research%2Fevals%2Ftoy_regression%2FREADME.md -->","isInternal":false,"tokens":400,"sizeBytes":1474},{"name":"README.md","path":"packages/cli/src/skill/builtin/.bundle/super-research/evals/toy_repo/README.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/super-research/evals/toy_repo/README.md","title":"toy_repo Documentation","category":"plugin-manifest","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsuper-research%2Fevals%2Ftoy_repo%2FREADME.md -->","isInternal":false,"tokens":123,"sizeBytes":449},{"name":"README.md","path":"packages/cli/src/skill/builtin/.bundle/super-research/README.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/super-research/README.md","title":"super-research Documentation","category":"plugin-manifest","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fsuper-research%2FREADME.md -->","isInternal":false,"tokens":2896,"sizeBytes":8465},{"name":"README.md","path":"packages/cli/src/skill/builtin/.bundle/xlsx-official/README.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/skill/builtin/.bundle/xlsx-official/README.md","title":"xlsx-official Documentation","category":"plugin-manifest","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fskill%2Fbuiltin%2F.bundle%2Fxlsx-official%2FREADME.md -->","isInternal":false,"tokens":1051,"sizeBytes":4376},{"name":"README.md","path":"packages/cli/src/sync/README.md","rawUrl":"https://raw.githubusercontent.com/XiaomiMiMo/MiMo-Code/HEAD/packages/cli/src/sync/README.md","title":"sync Documentation","category":"plugin-manifest","format":"markdown","content":"<!-- Skill available on-demand via /api/skills/XiaomiMiMo/MiMo-Code?path=packages%2Fcli%2Fsrc%2Fsync%2FREADME.md -->","isInternal":false,"tokens":2058,"sizeBytes":9230}],"systemPromptSnippet":"<yakaai_skills repo=\"XiaomiMiMo/MiMo-Code\">\n<!-- File: AGENTS.md (Tokens: ~906 | Category: root-instruction) -->\n# MiMo-Code\n\n## Conventions\n\n- Use MiMoCode Compose skills when available, otherwise use superpowers skill if installed.\n- To regenerate the JavaScript SDK, run `./packages/sdk/script/build.ts`.\n- ALWAYS USE PARALLEL TOOLS WHEN APPLICABLE.\n- The default branch in this repo is `main`.\n- CI triggers on `main`.\n- Prefer automation: execute requested actions without confirmation unless blocked by missing info or safety/irreversibility.\n- Install deps with `bun ci` (= `bun install --frozen-lockfile`) — install per `bun.lock`, don't mutate the lockfile. ⛔ Do NOT use `bun install`/`npm install`.\n- Comments, docs, shipped skill content and test assertions use synthetic values, never machine-specific ones — `/tmp/example` for paths, `test/model` for model refs, `feat/example` for branches.\n- Do not edit `packages/cli/migration/*/migration.sql` that already shipped — engines have applied those journals; new schema changes get a **new** migration directory under `packages/cli/migration/`.\n\n## Style Guide\n\nMatch the style of the surrounding code. The rules below apply across the repository.\n\n### Types and errors\n\n- Avoid using the `any` type\n- Inside Effect code, express failures through the Effect error channel (`Effect.try`, `Effect.tryPromise`, `Effect.catchTag`, typed errors) rather than `try`/`catch`; plain scripts and non-Effect code may use `try`/`catch`\n\n### Bun and Node runtimes\n\n- Use Bun APIs where the runtime is Bun-only, like `Bun.file()` in the TUI (`src/cli/cmd/tui/`); build-time macros are fine anywhere, as they never reach the shipped runtime\n- In core code reachable from `src/node.ts`, prefer the Node equivalent when one exists — `createHash` over `Bun.CryptoHasher`, `prepare()` over bun:sqlite's `query()` — as that code also ships through `script/build-node.ts` and must run on plain Node\n- Bun-only calls in core escape both `typecheck` and `bun test`, which run on Bun; existing usage needs no urgent removal, and APIs with no Node equivalent may stay until a runtime seam exists\n\n### Config modules\n\nIn `src/config`, follow the existing self-export pattern at the top of the file (for example `export * as ConfigAgent from \"./agent\"`) when adding a new config module.\n\n### Schema Definitions (Drizzle)\n\nUse snake_case for field names so column names don't need to be redefined as strings.\n\n```ts\n// Good\nconst table = sqliteTable(\"session\", {\n  id: text().primaryKey(),\n  project_id: text().notNull(),\n  created_at: integer().notNull(),\n})\n\n// Bad\nconst table = sqliteTable(\"session\", {\n  id: text(\"id\").primaryKey(),\n  projectID: text(\"project_id\").notNull(),\n  createdAt: integer(\"created_at\").notNull(),\n})\n```\n\n### Reading a nullable column\n\nTwo independent absences meet in one expression, and only one of them is\n`undefined`. `.get()` yields `undefined` when no row matches — Drizzle normalises\nthe driver's `null` there — while a nullable column's SQL `NULL` arrives as\n`null`. So `row?.some_column` is `T | null | undefined`.\n\nWhen a caller only asks \"is there a value\", flatten to `undefined`, and write the\nflattening as an annotation rather than an `as` cast:\n\n```ts\n// Good — the compiler enforces it; deleting the `?? undefined` is a type error\nconst boundary: MessageID | undefined = row?.last_checkpoint_message_id ?? undefined\n\n// Bad — the cast removes `null` from the union without converting anything,\n// so the declared type is untrue at runtime\nreturn row?.last_checkpoint_message_id as MessageID | undefined\n```\n\nDiscriminate a possibly-absent value with truthiness or `== null`, never with\n`=== undefined` / `!== undefined`. Because `null !== undefined` is `true`, such a\nguard typechecks, reads correctly in review, and does nothing.\n\n## Testing\n\n- Avoid mocks as much as possible\n- Test actual implementation, do not duplicate logic into tests\n\n<!-- File: .agents/skills/drive-mimo/SKILL.md (Tokens: ~4923 | Category: anthropic-skill) -->\n---\nname: drive-mimo\ndescription: Use when developing or testing the MiMoCode repository and you need to programmatically drive another MiMoCode (mimo) process. Supports headless `mimo run` with JSON events and interactive TUI via tmux for behavior, integration, and visual regression testing. Covers an installed `mimo` binary or a dev build launched from source with `bun dev`; do not use it for ordinary MiMoCode task execution.\n---\n\n# Drive MiMo\n\n## Overview\n\nTwo **interfaces** for driving a separate mimo process:\n\n| Interface | Command | Use when |\n|------|---------|----------|\n| **Headless** | `mimo run --format json` | Scripted tasks, CI, event validation |\n| **TUI** | `mimo` in tmux | Interactive flow, permission dialogs, keybindings, visual regression |\n\n**Core principle:** Every run produces parseable evidence. No eyeballing.\n\nAlways drive an *isolated* instance: give each run a fresh `MIMOCODE_HOME` and a throwaway workspace so it never touches your own config, memory, or session DB.\n\n### Two ways to launch — orthogonal to interface\n\nThe interface (headless vs TUI, above) is *what you drive*. How the process is\n**launched** is a separate axis — either can be launched either way:\n\n| Launcher | Command | Use when |\n|----------|---------|----------|\n| **Installed binary** | `mimo …` | Testing a released/installed build |\n| **Dev (from source)** | `bun dev …` | Debugging mimocode itself — runs `src/index.ts` directly, no build step, picks up local code changes |\n\nEverything below uses `mimo` for brevity. To drive a **dev build** instead,\nsubstitute `bun dev` for `mimo` and run from the repo root — every flag,\nJSON event, and tmux technique is identical. See the Dev Mode section.\n\n## Prerequisites\n\n```bash\n# mimo binary must be on PATH (installed-binary launcher)\nwhich mimo || echo \"mimo not found on PATH\"\n\n# OR: dev launcher — run from the mimocode repo root, needs bun\nwhich bun || echo \"bun not found — needed for dev mode\"\n\n# tmux (for TUI interface)\nwhich tmux || echo \"tmux not found — install it for TUI mode\"\n```\n\n> **Running the `wait-for-text.sh` helper:** invoke it as\n> `./scripts/wait-for-text.sh …` from this skill's directory. The repository copy\n> is executable and can be called directly.\n\n---\n\n## Dev Mode (debugging mimocode itself)\n\nWhen the goal is to debug **mimocode's own code**, launch from source with\n`bun dev` instead of the installed `mimo` binary. It runs\n`packages/cli/src/index.ts` directly — no build step — so local edits take\neffect on the next launch.\n\n**Key facts:**\n\n- Run from the **repo root**. `bun dev` == `bun run dev`.\n- It is the dev equivalent of the `mimo` command: same CLI, same subcommands\n  and flags. `bun dev --help`, `bun dev run …`, `bun dev serve`, etc.\n- Args pass straight through, so **both interfaces work under dev**:\n  - Headless: `bun dev run --format json --dangerously-skip-permissions …`\n  - TUI:      `bun dev <workspace>` (positional workspace arg, as with `mimo`)\n- If `MIMOCODE_HOME` is not set, dev defaults it to a repo-local `.dev-home`\n  dir. For an isolated driven run, set `MIMOCODE_HOME=$(mktemp -d)` explicitly\n  just like with the binary.\n\n**Substitution rule:** anywhere Part 1 / Part 2 / Part 3 below say `mimo`,\nreplace it with `bun dev` (invoked from the repo root) to drive a dev build.\n\n```bash\n# Headless, dev build (from repo root)\nREPO=/path/to/mimocode/checkout   # your local mimocode repo root\nMIMOCODE_HOME=$(mktemp -d) bun --cwd \"$REPO\" dev run \\\n  --format json --dangerously-skip-permissions --dir \"$WORKSPACE\" \\\n  < \"$PROMPT\" > /tmp/mimo-dev.jsonl 2>&1\n\n# TUI, dev build in tmux (from repo root)\ntmux new-session -d -s \"$SESSION\" -x 120 -y 30 \\\n  \"cd $REPO && MIMOCODE_HOME=$(mktemp -d) MIMOCODE_PURE=true bun dev $WORKSPACE; sleep 999\"\n```\n\n---\n\n## Part 1: Headless Mode (`mimo run`)\n\n### Launch\n\n```bash\nPROMPT=$(mktemp -t mimo-drive.XXXXXX)\ncat >\"$PROMPT\" <<'EOF'\nYour task here.\nEOF\n\nMIMOCODE_HOME=$(mktemp -d) mimo run \\\n  --format json \\\n  --dangerously-skip-permissions \\\n  --dir \"$WORKSPACE\" \\\n  < \"$PROMPT\" > /tmp/mimo-out.jsonl 2>&1\n\nEXIT=$?\n```\n\n### Key flags\n\n| Flag | Purpose |\n|------|---------|\n| `--format json` | Structured JSONL events to stdout |\n| `--dangerously-skip-permissions` | Auto-approve all permissions |\n| `--model provider/model` | Override model |\n| `--session SID` | Continue existing session |\n| `--continue` | Continue last session |\n| `--file path` | Attach file to message |\n| `--dir path` | Working directory |\n\n### JSON event types\n\n`--format json` writes one JSON object per line. **Every** event has the shape\n`{\"type\": ..., \"timestamp\": <ms>, \"sessionID\": \"ses_...\", ...payload}` — the\n`sessionID` is a field on each event, not a standalone event. The payload for\nmost events is nested under `part`.\n\nEmitted event types (from the run event stream):\n\n```\n{\"type\":\"step_start\",\"timestamp\":...,\"sessionID\":\"ses_abc\",\"part\":{...}}\n{\"type\":\"text\",\"timestamp\":...,\"sessionID\":\"ses_abc\",\"part\":{\"type\":\"text\",\"text\":\"I'll create the file...\",\"time\":{...}}}\n{\"type\":\"reasoning\",\"timestamp\":...,\"sessionID\":\"ses_abc\",\"part\":{\"type\":\"reasoning\",\"text\":\"The user wants...\"}}\n{\"type\":\"tool_use\",\"timestamp\":...,\"sessionID\":\"ses_abc\",\"part\":{\"type\":\"tool\",\"tool\":\"write\",\"state\":{\"status\":\"completed\",...}}}\n{\"type\":\"step_finish\",\"timestamp\":...,\"sessionID\":\"ses_abc\",\"part\":{...}}\n{\"type\":\"error\",\"timestamp\":...,\"sessionID\":\"ses_abc\",\"error\":{...}}\n```\n\nNotes that matter for parsing:\n\n- **No `session.id`, no `tool_result`, no `session.status` event.** A `tool_use`\n  is emitted **once** per tool part when it reaches `completed` or `error` — the\n  result/output is inside `part.state`, there is no separate result event.\n- **`tool_use` identifies the tool via `part.tool`** (a bare string, e.g.\n  `\"tool\":\"write\"`) — there is no `.tool.name` and no top-level `.name`.\n- **`text` / `reasoning` text lives at `part.text`**, not top-level `.text`.\n- **`reasoning` is only emitted when `--thinking` is passed.** Without it, no\n  reasoning events appear.\n- **Completion is not a stream event.** The process finishes when the run\n  completes; the reliable completion signal is **process exit** (exit code 0),\n  not any line in the JSONL.\n\n### Validation patterns\n\n```bash\n# Completion — the real signal is the exit code, not a stream event\n[ $EXIT -eq 0 ] || echo \"FAIL: exit $EXIT\"\n\n# No errors\ngrep -q '\"type\":\"error\"' /tmp/mimo-out.jsonl && echo \"FAIL: errors found\"\n\n# A specific tool was used (match part.tool, the bare string)\ngrep -q '\"tool\":\"write\"' /tmp/mimo-out.jsonl || echo \"FAIL: write tool not called\"\n\n# Text output contains expected string (text is at .part.text)\ngrep '\"type\":\"text\"' /tmp/mimo-out.jsonl | jq -r '.part.text' | grep -q \"expected\"\n\n# Robust tool check via jq (works regardless of key ordering)\njq -e 'select(.type==\"tool_use\") | .part.tool==\"write\"' /tmp/mimo-out.jsonl >/dev/null \\\n  || echo \"FAIL: write tool not called\"\n```\n\n\n### Timeout\n\n```bash\ntimeout 120 mimo run --format json --dangerously-skip-permissions < \"$PROMPT\"\n[ $? -eq 124 ] && echo \"FAIL: timed out\"\n```\n\n---\n\n## Part 2: TUI Mode (tmux)\n\n### Isolation variables\n\n| Variable | Purpose |\n|---|---|\n| `MIMOCODE_HOME` | **Required.** Fresh `mktemp -d` per run. Sandboxes DB, config, cache. |\n| `MIMOCODE_PURE=true` | Disable external plugins. |\n| `MIMOCODE_DISABLE_GIT=true` | Skip git ops if workspace isn't a real repo. |\n\n### Launch TUI in tmux\n\n```bash\n# Create isolated environment\nMHOME=$(mktemp -d)\nWORKSPACE=$(mktemp -d)\nSESSION=\"mimo-drive-$$\"\n\n# Launch mimo TUI in tmux (workspace is a positional arg, NOT --dir)\ntmux new-session -d -s \"$SESSION\" -x 120 -y 30 \\\n  \"MIMOCODE_HOME=$MHOME MIMOCODE_PURE=true mimo $WORKSPACE; sleep 999\"\n\n# Wait for the TUI to render its input prompt\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"$PROMPT_RE\" -T 15\n```\n\nWhere `PROMPT_RE` is a language-neutral pattern for the input prompt. The\nprompt placeholder is localized, so match on the stable markers rather than a\nlocalized string:\n\n```bash\n# Matches the prompt line regardless of UI language:\n#   the \">\" input caret, the \"Ask\" English placeholder, or a \"/\" command hint\nPROMPT_RE='>|Ask|/[a-z]'\n```\n\nIf a run's UI language is known and fixed, you may match its literal\nplaceholder instead — but prefer the neutral pattern for portability.\n\n### Send input\n\n```bash\n# Type a message (literal text, then Enter)\ntmux send-keys -t \"$SESSION:0.0\" -l -- \"Create a file called hello.txt with content 'world'\"\ntmux send-keys -t \"$SESSION:0.0\" Enter\n\n# Special keys\ntmux send-keys -t \"$SESSION:0.0\" C-c          # Cancel\ntmux send-keys -t \"$SESSION:0.0\" C-d          # EOF\ntmux send-keys -t \"$SESSION:0.0\" Escape       # Escape\ntmux send-keys -t \"$SESSION:0.0\" Tab          # Tab completion\ntmux send-keys -t \"$SESSION:0.0\" Up           # History up\ntmux send-keys -t \"$SESSION:0.0\" Down         # History down\ntmux send-keys -t \"$SESSION:0.0\" Enter        # Submit\n```\n\n### Capture output\n\n```bash\n# Current screen\ntmux capture-pane -t \"$SESSION:0.0\" -p\n\n# Full scrollback\ntmux capture-pane -t \"$SESSION:0.0\" -p -S -\n\n# Last 50 lines\ntmux capture-pane -t \"$SESSION:0.0\" -p -S -50\n```\n\n### Wait for state changes\n\n```bash\n# Wait for agent to start processing\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"thinking\\|reading\\|writing\" -T 30\n\n# Wait for tool permission prompt\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"Allow\\|Deny\\|permission\\|approve\" -T 30\n\n# Wait for completion\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"completed\\|done\\|finished\\|idle\" -T 120\n\n# Wait for error\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"error\\|failed\\|Error\" -T 30\n\n# Custom regex\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"hello\\.txt.*world\" -T 30\n```\n\n### Handle permission dialogs\n\n```bash\n# Wait for permission prompt, then approve\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"Allow\\|approve\" -T 30\ntmux send-keys -t \"$SESSION:0.0\" -l -- \"y\"\ntmux send-keys -t \"$SESSION:0.0\" Enter\n\n# Or deny\ntmux send-keys -t \"$SESSION:0.0\" -l -- \"n\"\ntmux send-keys -t \"$SESSION:0.0\" Enter\n```\n\n### Multi-turn interaction\n\n```bash\n# Turn 1: send initial message\ntmux send-keys -t \"$SESSION:0.0\" -l -- \"Create a TypeScript file that adds two numbers\"\ntmux send-keys -t \"$SESSION:0.0\" Enter\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"completed\\|done\" -T 120\n\n# Turn 2: follow-up\ntmux send-keys -t \"$SESSION:0.0\" -l -- \"Now add a test for it\"\ntmux send-keys -t \"$SESSION:0.0\" Enter\nbash scripts/wait-for-text.sh -t \"$SESSION:0.0\" -p \"completed\\|done\" -T 120\n\n# Verify result\ntmux capture-pane -t \"$SESSION:0.0\" -p -S - | grep -i \"pass\\|fail\"\n```\n\n### Cleanup\n\n```bash\ntmux kill-session -t \"$SESSION\" 2>/dev/null\nrm -rf \"$MHOME\" \"$WORKSPACE\"\n```\n\n---\n\n## Part 3: Scenarios\n\n### S1: Smoke (headless)\n\n```bash\ntest_smoke() {\n  local P=$(mktemp) MHOME=$(mktemp -d)\n  echo \"Say hello\" > \"$P\"\n  MIMOCODE_HOME=$MHOME mimo run --format json --dangerously-skip-permissions \\\n    < \"$P\" > /tmp/s1.jsonl 2>&1\n  local E=$?\n  rm -rf \"$MHOME\" \"$P\"\n  [ $E -eq 0 ] && grep -q '\"type\":\"text\"' /tmp/s1.jsonl && echo \"PASS\" || echo \"FAIL\"\n}\n```\n\n### S2: Tool use (headless)\n\n```bash\ntest_tool_use() {\n  local P=$(mktemp) MHOME=$(mktemp -d) WS=$(mktemp -d)\n  echo 'Create file test.txt with content \"hello\"' > \"$P\"\n  MIMOCODE_HOME=$MHOME mimo run --format json --dangerously-skip-permissions --dir \"$WS\" \\\n    < \"$P\" > /tmp/s2.jsonl 2>&1\n  local E=$?\n  local OK=true\n  [ $E -ne 0 ] && OK=false\n  ! grep -q '\"tool\":\"write\"' /tmp/s2.jsonl && OK=false\n  [ ! -f \"$WS/test.txt\" ] && OK=false\n  rm -rf \"$MHOME\" \"$WS\" \"$P\"\n  $OK && echo \"PASS\" || echo \"FAIL\"\n}\n```\n\n### S3: TUI interactive flow\n\n```bash\ntest_tui_interactive() {\n  local MHOME=$(mktemp -d) WS=$(mktemp -d) SID=\"mimo-s3-$$\"\n  local PROMPT_RE='>|Ask|/[a-z]'\n  tmux new-session -d -s \"$SID\" -x 120 -y 30 \"MIMOCODE_HOME=$MHOME MIMOCODE_PURE=true mimo $WS; sleep 999\"\n\n  # Wait for prompt\n  bash scripts/wait-for-text.sh -t \"$SID:0.0\" -p \"$PROMPT_RE\" -T 15 || { echo \"FAIL: no prompt\"; tmux kill-session -t $SID; return 1; }\n\n  # Send task\n  tmux send-keys -t \"$SID:0.0\" -l -- \"Create hello.txt with content 'world'\"\n  tmux send-keys -t \"$SID:0.0\" Enter\n\n  # Wait for completion (agent shows elapsed time like \"· 9.8s\")\n  bash scripts/wait-for-text.sh -t \"$SID:0.0\" -p \"· [0-9]\" -T 120 || { echo \"FAIL: no completion\"; tmux kill-session -t $SID; return 1; }\n\n  # Verify file\n  [ -f \"$WS/hello.txt\" ] && echo \"PASS\" || echo \"FAIL\"\n  tmux kill-session -t \"$SID\" 2>/dev/null\n  rm -rf \"$MHOME\" \"$WS\"\n}\n```\n\n### S4: TUI permission handling\n\n```bash\ntest_tui_permission() {\n  local MHOME=$(mktemp -d) WS=$(mktemp -d) SID=\"mimo-s4-$$\"\n  local PROMPT_RE='>|Ask|/[a-z]'\n  tmux new-session -d -s \"$SID\" -x 120 -y 30 \"MIMOCODE_HOME=$MHOME MIMOCODE_PURE=true mimo $WS; sleep 999\"\n\n  bash scripts/wait-for-text.sh -t \"$SID:0.0\" -p \"$PROMPT_RE\" -T 15\n\n  # Ask for something that needs permission (no --dangerously-skip-permissions in TUI)\n  tmux send-keys -t \"$SID:0.0\" -l -- \"Run the command: echo hello\"\n  tmux send-keys -t \"$SID:0.0\" Enter\n\n  # Wait for permission prompt\n  bash scripts/wait-for-text.sh -t \"$SID:0.0\" -p \"Allow\\|approve\\|permission\\|y/n\" -T 30 || { echo \"FAIL: no permission prompt\"; tmux kill-session -t $SID; return 1; }\n\n  # Approve\n  tmux send-keys -t \"$SID:0.0\" -l -- \"y\"\n  tmux send-keys -t \"$SID:0.0\" Enter\n\n  # Wait for completion\n  bash scripts/wait-for-text.sh -t \"$SID:0.0\" -p \"· [0-9]\" -T 60\n\n  tmux capture-pane -t \"$SID:0.0\" -p | grep -q \"hello\" && echo \"PASS\" || echo \"FAIL\"\n  tmux kill-session -t \"$SID\" 2>/dev/null\n  rm -rf \"$MHOME\" \"$WS\"\n}\n```\n\n### S5: TUI keybindings\n\n```bash\ntest_tui_keybindings() {\n  local MHOME=$(mktemp -d) WS=$(mktemp -d) SID=\"mimo-s5-$$\"\n  local PROMPT_RE='>|Ask|/[a-z]'\n  tmux new-session -d -s \"$SID\" -x 120 -y 30 \"MIMOCODE_HOME=$MHOME MIMOCODE_PURE=true mimo $WS; sleep 999\"\n\n  bash scripts/wait-for-text.sh -t \"$SID:0.0\" -p \"$PROMPT_RE\" -T 15\n\n  # Test Ctrl+C cancels input\n  tmux send-keys -t \"$SID:0.0\" -l -- \"some partial input\"\n  tmux send-keys -t \"$SID:0.0\" C-c\n\n  # Screen should still show prompt (not exit)\n  sleep 1\n  tmux capture-pane -t \"$SID:0.0\" -p | grep -qE \"$PROMPT_RE\" && echo \"PASS: Ctrl+C didn't exit\" || echo \"FAIL: Ctrl+C exited\"\n\n  # Test Escape\n  tmux send-keys -t \"$SID:0.0\" Escape\n  sleep 0.5\n\n  tmux kill-session -t \"$SID\" 2>/dev/null\n  rm -rf \"$MHOME\" \"$WS\"\n}\n```\n\n---\n\n## Batch Runner\n\n```bash\nrun_all() {\n  local PASS=0 FAIL=0 RESULTS=()\n  for fn in test_smoke test_tool_use test_tui_interactive test_tui_permission test_tui_keybindings; do\n    echo \"--- $fn ---\"\n    if $fn 2>/dev/null; then PASS=$((PASS+1)); else FAIL=$((FAIL+1)); RESULTS+=(\"$fn: FAIL\"); fi\n  done\n  echo \"=== $PASS passed, $FAIL failed ===\"\n  [ ${#RESULTS[@]} -gt 0 ] && printf '  %s\\n' \"${RESULTS[@]}\"\n  [ $FAIL -eq 0 ]\n}\n```\n\n---\n\n## Quick Reference\n\n| Task | Command |\n|------|---------|\n| Headless run | `MIMOCODE_HOME=$(mktemp -d) mimo run --format json --dangerously-skip-permissions \"prompt\"` |\n| TUI launch | `tmux new-session -d -s test -x 120 -y 30 \"MIMOCODE_HOME=$(mktemp -d) mimo $WORKSPACE; sleep 999\"` |\n| Send text | `tmux send-keys -t test:0.0 -l -- \"text\" && tmux send-keys -t test:0.0 Enter` |\n| Capture screen | `tmux capture-pane -t test:0.0 -p -S -` |\n| Wait for text | `bash scripts/wait-for-text.sh -t test:0.0 -p \"pattern\" -T 30` |\n| Send Ctrl+C | `tmux send-keys -t test:0.0 C-c` |\n| Approve permission | `tmux send-keys -t test:0.0 -l -- \"y\" && tmux send-keys -t test:0.0 Enter` |\n| Cleanup | `tmux kill-session -t test && rm -rf $MHOME` |\n\n<!-- File: .agents/skills/effect/SKILL.md (Tokens: ~161 | Category: anthropic-skill) -->\n---\nname: effect\ndescription: Answer questions about the Effect framework\n---\n\n# Effect\n\nThis codebase uses Effect, a framework for writing typescript.\n\n## How to Answer Effect Questions\n\n1. Clone the Effect repository: `https://github.com/Effect-TS/effect-smol` to\n   `.opencode/references/effect-smol` in this project NOT the skill folder.\n2. Use the explore agent to search the codebase for answers about Effect patterns, APIs, and concepts\n3. Provide responses based on the actual Effect source code and documentation\n\n## Guidelines\n\n- Always use the explore agent with the cloned repository when answering Effect-related questions\n- Reference specific files and patterns found in the Effect codebase\n- Do not answer from memory - always verify against the source\n\n<!-- File: packages/cli/src/skill/builtin/.bundle/arxiv/SKILL.md (Tokens: ~1655 | Category: anthropic-skill) -->\n---\nname: arxiv\ndescription: \"Use this skill whenever the user wants to find, read, cite, track, download, or analyze academic papers on arXiv. That includes: searching papers by topic, author, category, or arXiv ID; fetching abstracts or full metadata; generating BibTeX citations; downloading PDFs; listing the latest submissions in a field (e.g. cs.AI daily digest); checking a paper's citation impact; finding who cites a paper, what it references, or related-paper recommendations. Trigger on mentions of 'arXiv', an arXiv ID (e.g. 2601.02780 or hep-th/0601001), an arxiv.org URL, 'paper search', 'literature review', 'find papers about X', 'cite this paper', or 'what's new in cs.LG'.\"\nversion: 2.0.0\nlicense: MIT\nplatforms: [linux, macos, windows]\n---\n\n# arXiv Research\n\nSearch, read, cite, and analyze academic papers using the free arXiv API and Semantic Scholar API. No API keys, no dependencies — the bundled script uses only the Python stdlib.\n\n## Quick Start: the `arxiv.py` script\n\nPrefer `scripts/arxiv.py` over raw `curl` — it handles Atom XML parsing, versioned IDs, withdrawn-paper detection, and produces clean readable (or `--json`) output.\n\n| Goal | Command |\n|------|---------|\n| Search papers | `python scripts/arxiv.py search \"GRPO reinforcement learning\" --max 10 --sort date` |\n| Filtered search | `python scripts/arxiv.py search \"attention\" --author vaswani --category cs.CL` |\n| Full metadata + abstract | `python scripts/arxiv.py get 2601.02780,1706.03762` |\n| BibTeX citation | `python scripts/arxiv.py bibtex 2601.02780` |\n| Download PDF | `python scripts/arxiv.py download 2601.02780 --dest ./papers` |\n| Latest in a category | `python scripts/arxiv.py new cs.CL --max 10` |\n| Who cites this paper | `python scripts/arxiv.py cites 2601.02780 --max 20` |\n| What this paper cites | `python scripts/arxiv.py refs 2601.02780` |\n| Related-paper recommendations | `python scripts/arxiv.py similar 2601.02780` |\n| Machine-readable output | append `--json` to any command |\n\nCommon flags: `--max N` (result count), `--sort relevance|date|updated`, `--start N` (pagination offset, search only), `--json`.\n\n## Reading Paper Content\n\nAfter finding a paper, read it with the `webfetch` tool:\n\n- Abstract page (fast, metadata + abstract): `https://arxiv.org/abs/2601.02780`\n- Full paper as HTML (best for reading, when available): `https://arxiv.org/html/2601.02780`\n- PDF: `https://arxiv.org/pdf/2601.02780`\n\nIf HTML is unavailable and the PDF must be processed locally, `download` it first, then use a PDF-processing skill.\n\n## Recommended Research Workflows\n\n**Literature review on a topic**\n1. `search \"topic\" --sort date --max 15` — recent work\n2. `search \"topic\" --max 15` — seminal work (relevance-sorted)\n3. Cross-check impact: `python scripts/arxiv.py get ID` then `cites ID --max 5` for citation counts\n4. Read the top candidates via `webfetch` on the abs/html URLs\n5. `bibtex ID1,ID2,...` for the papers you keep\n\n**Deep-dive a single paper**\n1. `get ID` — full abstract, versions, journal ref, DOI\n2. `refs ID` — what it builds on\n3. `cites ID` — follow-up work (sorted by citation count)\n4. `similar ID` — related papers you might have missed\n5. `webfetch` the HTML/PDF for full text\n\n**Stay current in a field**\n- `new cs.AI --max 20` — latest submissions in a category\n- Category taxonomy: https://arxiv.org/category_taxonomy — common ones: `cs.AI`, `cs.CL` (NLP), `cs.CV`, `cs.LG`, `cs.CR`, `stat.ML`, `math.OC`\n\n## Raw API Reference (when the script isn't enough)\n\nThe script covers most needs; use the raw APIs for advanced queries.\n\n### arXiv API (Atom XML)\n\n```bash\ncurl -s \"https://export.arxiv.org/api/query?search_query=all:transformer&max_results=5\"\n```\n\nField prefixes: `all:` (everything), `ti:` (title), `au:` (author), `abs:` (abstract), `cat:` (category), `co:` (comment, e.g. `co:accepted+NeurIPS`).\n\nBoolean syntax (URL-encode spaces as `+`):\n\n```\nall:GPT+OR+all:BERT              # OR\nall:language+model+ANDNOT+all:vision   # AND NOT\nti:\"chain+of+thought\"            # exact phrase\nau:hinton+AND+cat:cs.LG          # combined\n```\n\nParameters: `sortBy` (`relevance`|`lastUpdatedDate`|`submittedDate`), `sortOrder`, `start`, `max_results`, `id_list` (comma-separated IDs).\n\n### Semantic Scholar API (JSON)\n\narXiv has no citation data — Semantic Scholar fills that gap (free, ~1 req/sec unauthenticated).\n\n```bash\n# Paper details with citation counts\ncurl -s \"https://api.semanticscholar.org/graph/v1/paper/arXiv:2601.02780?fields=title,citationCount,influentialCitationCount,tldr\"\n\n# Author profile\ncurl -s \"https://api.semanticscholar.org/graph/v1/author/search?query=Yann+LeCun&fields=name,hIndex,citationCount,paperCount\"\n\n# Keyword search returning JSON (alternative to arXiv search)\ncurl -s \"https://api.semanticscholar.org/graph/v1/paper/search?query=GRPO&limit=5&fields=title,year,citationCount,externalIds\"\n```\n\nUseful fields: `title`, `authors`, `year`, `abstract`, `tldr` (AI summary), `citationCount`, `influentialCitationCount`, `isOpenAccess`, `openAccessPdf`, `fieldsOfStudy`, `publicationVenue`, `externalIds` (arXiv ID, DOI).\n\n## Important Details\n\n**Rate limits** — arXiv: ~1 request / 3 seconds; Semantic Scholar: ~1 request / second. Space out consecutive calls; the script exits with a clear message on HTTP 429.\n\n**ID formats** — new style `2402.03300`, old style `hep-th/0601001`. Both work everywhere.\n\n**Versioning** — `arxiv.org/abs/2601.02780` resolves to the latest version; `...v2` is a specific immutable version. `bibtex` and `download` preserve the version suffix so citations match the content you actually read (later versions can change substantially).\n\n**Withdrawn papers** — the script flags entries whose abstract indicates withdrawal/retraction with `[WITHDRAWN]`. Don't cite these without noting the status.\n\n**Listings caveat** — `new CATEGORY` sorts by submission date via the search API; the official \"new today\" listing at `https://arxiv.org/list/cs.AI/new` may group slightly differently (cross-lists, replacements).\n\n<!-- File: packages/cli/src/skill/builtin/.bundle/claude-code/SKILL.md (Tokens: ~1340 | Category: anthropic-skill) -->\n---\nname: claude-code\ndescription: \"Operate Claude Code CLI (v2.1+) via the terminal only when the user explicitly requests Claude Code or names this skill. Covers print mode (-p), interactive tmux sessions, and background (--bg) orchestration.\"\nversion: 2.0.0\nlicense: MIT\nplatforms: [linux, macos, windows]\n---\n\n# Claude Code Delegation\n\nDelegate coding work to Claude Code, Anthropic's autonomous coding agent CLI.\n\n**Setup (once):** `npm install -g @anthropic-ai/claude-code && claude auth login` · verify with `claude auth status` / `claude doctor`. CI token: `claude setup-token`. Full auth/install variants → `references/flags.md`.\n\n**Platform check (before running anything):** detect the OS first. All shell examples in this skill are POSIX (bash). Linux/macOS run them as-is. On **Windows**, run Claude Code natively in PowerShell/Git Bash for print and background modes, but interactive tmux orchestration requires **WSL**. Shell-syntax translation table (quoting, env vars, piping, paths) → `references/platforms.md`.\n\n## Mode Selection (decide FIRST)\n\n| Task shape | Mode | Why |\n|---|---|---|\n| One-shot task: fix bug, add feature, review diff, extract data | **Print `-p`** ← default | No PTY, no dialogs, structured output |\n| Multi-turn iterate: refactor → review → fix → test; needs slash commands | **Interactive tmux** → `references/interactive-tmux.md` | Full REPL, requires dialog handling |\n| Long-running, shouldn't block; large fan-out supervision | **Background `--bg`** | Native supervision via `claude agents` |\n| High-stakes PR review | **`claude ultrareview [pr#]`** | Cloud multi-agent, exit-code driven (uploads diff to cloud — never on branches with secrets) |\n\nDo NOT hand-roll tmux fan-outs for parallel work — prefer `--bg` + `claude agents --json --all`.\n\n## Print Mode (the 90% path)\n\n```\nterminal(command=\"claude -p 'Fix the auth bug in src/auth.py' \\\n  --allowedTools 'Read,Edit' --max-turns 10 --output-format json\",\n  workdir=\"/path/to/project\", timeout=180)\n```\n\n**Always set:** `workdir` · `--max-turns` (5–10; print-mode only) · `--allowedTools` (least privilege: `Read,Edit,Write,Bash`, patterns like `Bash(git *)`).\n\n**JSON result fields:** `result` (text) · `session_id` (for resume) · `subtype` (`success` | `error_max_turns` | `error_budget`) · `total_cost_usd` · `num_turns` · `structured_output` (with `--json-schema`).\n\n**Common variants:**\n\n```bash\ngit diff main... | claude -p 'Review for bugs' --max-turns 1     # pipe input, cheapest review\nclaude -p 'Continue: add pooling' --resume <session_id>          # resume; --continue = latest in cwd; --fork-session = branch\nclaude -p 'List functions' --output-format json --json-schema '<schema>' --max-turns 5   # structured extraction (needs turns to read files)\nclaude --bare -p 'task' --settings ci.json                       # CI: skips hooks/plugins/CLAUDE.md; auth = ANTHROPIC_API_KEY only\nclaude -p 'task' --max-budget-usd 0.50 --fallback-model haiku    # cost cap (min ~$0.05) + overload fallback\n```\n\nStreaming, stream-json events, bidirectional input, cache-reuse (`--exclude-dynamic-system-prompt-sections`) → `references/print-mode.md`.\n\n## Background Mode\n\n```bash\nclaude --bg 'investigate flaky test in tests/api.test.ts'   # NOT compatible with -p\nclaude agents --json --all                                   # list/inspect\nclaude attach <id> | logs <id> | stop <id> | respawn <id> | rm <id>\n```\n\n## Guardrails & Gotchas (violations break agents)\n\n1. **`-p` auto-skips trust/permission dialogs** (any non-TTY does) — only run in trusted directories.\n2. **Interactive mode = tmux required** (Windows: only inside WSL — never attempt tmux in PowerShell/cmd; fall back to `-p` or `--bg`); two startup dialogs, and the `--dangerously-skip-permissions` dialog defaults to **\"No, exit\"** (must send `Down` then `Enter`). Full patterns → `references/interactive-tmux.md`.\n3. **Session resume is per-directory** — `--continue` only finds sessions from the same cwd.\n4. **Slash commands don't work in `-p`** — describe the task in natural language instead.\n5. **Context >70% degrades quality** — in interactive sessions monitor `/context`, use `/compact`.\n6. **Clean up**: kill tmux sessions and `claude stop/rm` background sessions when done.\n7. **Don't kill slow sessions** — capture progress first (`tmux capture-pane` / `claude logs`).\n8. **Report back**: after completion, summarize what changed (use the JSON `result` + `git diff`).\n\n## References (read on demand)\n\n| File | Read when |\n|---|---|\n| `references/print-mode.md` | Streaming output, stream-json events, piping, schemas, session mgmt, cache reuse |\n| `references/interactive-tmux.md` | Any tmux/PTY session: dialogs, send-keys, monitoring, slash commands, shortcuts |\n| `references/flags.md` | Full CLI flag & subcommand tables, auth variants, env vars, model/effort selection |\n| `references/config.md` | CLAUDE.md/memory, settings hierarchy, custom agents, hooks, MCP, plugins, project purge |\n| `references/platforms.md` | Running on Windows (PowerShell/Git Bash/WSL) or macOS: shell translation, paths, per-OS gotchas |\n\n<!-- File: packages/cli/src/skill/builtin/.bundle/codex/SKILL.md (Tokens: ~2370 | Category: anthropic-skill) -->\n---\nname: codex\ndescription: Run, configure, and troubleshoot OpenAI Codex CLI in non-interactive headless environments. Use for Codex automation in Bash or PowerShell, native Windows or WSL2, shell scripts, CI/CD, Docker, Kubernetes, remote servers, agent harnesses, or batch jobs; for constructing `codex exec` commands; selecting sandbox and approval modes; consuming JSONL events or structured output; resuming sessions; passing prompts through stdin; and handling failures caused by unavailable interactive input such as `request_user_input`.\n---\n\n# Codex CLI\n\nUse Codex CLI as a deterministic, non-interactive worker suitable for automation and agent orchestration.\n\n## Operating Rules\n\n1. Use `codex exec`, not the interactive `codex` TUI.\n2. Pass the task as the positional `PROMPT` argument. Do not use `-p` for the prompt; `-p` selects a profile.\n3. For ordinary unattended code changes, prefer:\n\n```bash\ncodex exec \\\n  -C /path/to/repo \\\n  --sandbox workspace-write \\\n  --ask-for-approval never \\\n  \"<TASK>\"\n```\n\n4. Use `--yolo` only inside an externally hardened and disposable runner. It disables Codex approvals and sandboxing.\n5. For harnesses and CI, prefer `--json` plus `--output-last-message`.\n6. Do not make the run depend on a human answering questions. Resolve ambiguity using repository evidence and conservative defaults.\n7. Treat credentials as secrets. Inject `CODEX_API_KEY` only into the single `codex exec` process when possible.\n8. Before giving version-sensitive advice, inspect `codex exec --help` or current official Codex documentation if available.\n9. On Windows, choose one execution environment per task: native PowerShell for Windows toolchains or WSL2 for Linux toolchains. Do not casually mix paths, installations, or authentication across them.\n\n## Choose the Execution Mode\n\n### Read-only analysis\n\nUse when the task must not modify files:\n\n```bash\ncodex exec \\\n  -C /path/to/repo \\\n  --sandbox read-only \\\n  --ask-for-approval never \\\n  \"Analyze the repository and report risks. Do not modify files.\"\n```\n\n### Workspace-scoped implementation\n\nUse as the default for autonomous repository work:\n\n```bash\ncodex exec \\\n  -C /path/to/repo \\\n  --sandbox workspace-write \\\n  --ask-for-approval never \\\n  \"Implement the task, run relevant tests, and report unresolved blockers.\"\n```\n\n### Externally isolated unrestricted execution\n\nUse only when the enclosing container, VM, or sandbox enforces the real security boundary:\n\n```bash\ncodex exec \\\n  -C /workspace/repo \\\n  --yolo \\\n  \"Implement the task and validate the result.\"\n```\n\nNever recommend `--yolo` on a normal developer machine or a runner containing unrelated secrets, host mounts, SSH keys, cloud credentials, or a Docker socket.\n\n## Construct an Autonomous Prompt\n\nWhen headless execution could encounter choices, prepend these instructions:\n\n```text\nWork fully autonomously.\n\nDo not ask the user questions and do not request interactive input.\nInspect the repository and available context before making assumptions.\nWhen several valid approaches exist, choose the option that:\n1. minimizes unrelated changes,\n2. preserves backward compatibility,\n3. introduces the fewest new dependencies,\n4. avoids destructive or irreversible actions.\n\nContinue until the task is complete or a concrete blocking error is reached.\nRecord assumptions, validation performed, and unresolved blockers in the final response.\n```\n\nDo not simulate \"always select the first option.\" Option ordering is not a safety or quality policy. Apply the explicit decision rules above instead.\n\n## Handle `request_user_input` Failures\n\nWhen Codex reports that `request_user_input` is unavailable in Default mode or non-interactive mode:\n\n1. Confirm the invocation uses `codex exec` and is intentionally headless.\n2. Add the autonomous prompt policy above.\n3. Supply missing decisions in the task prompt or `AGENTS.md` when they are known in advance.\n4. Replace open-ended requests such as \"ask me which approach\" with deterministic selection criteria.\n5. If the choice is safety-critical, destructive, or impossible to infer, make the run fail clearly rather than selecting randomly.\n6. Do not attempt to emulate terminal keystrokes unless the subprocess itself, rather than Codex, requires input and the workflow explicitly defines the safe answer.\n\n## Pass Prompts and Context\n\nUse a direct positional prompt:\n\n```bash\ncodex exec \"Summarize the repository structure.\"\n```\n\nRead the prompt from stdin:\n\n```bash\ncodex exec - < prompt.md\n```\n\nPipe dynamic context while retaining an explicit task:\n\n```bash\nnpm test 2>&1 | codex exec \"Analyze this test output and fix the repository.\"\n```\n\nUse `--skip-git-repo-check` only for intentional one-off directories outside Git:\n\n```bash\ncodex exec \\\n  --skip-git-repo-check \\\n  -C /tmp/task \\\n  \"Analyze the files in this directory.\"\n```\n\n## Produce Harness-Friendly Output\n\n### Capture only the final message\n\n```bash\ncodex exec \\\n  -C /workspace/repo \\\n  --output-last-message /output/final.md \\\n  \"Review the codebase.\"\n```\n\n### Stream JSONL events\n\n```bash\ncodex exec \\\n  -C /workspace/repo \\\n  --json \\\n  --sandbox workspace-write \\\n  --ask-for-approval never \\\n  \"Run tests and fix failures.\" \\\n  > /output/events.jsonl\n```\n\nExpect event families such as `thread.started`, `turn.started`, `turn.completed`, `turn.failed`, `item.*`, and `error`.\n\n### Capture events and the final answer together\n\n```bash\ncodex exec \\\n  -C /workspace/repo \\\n  --json \\\n  --sandbox workspace-write \\\n  --ask-for-approval never \\\n  --output-last-message /output/final.md \\\n  \"Complete the task autonomously.\" \\\n  | tee /output/events.jsonl\n```\n\nDo not parse human-readable progress text when `--json` is available.\n\n## Require Structured Final Output\n\nCreate a JSON Schema and pass it with `--output-schema`:\n\n```bash\ncodex exec \\\n  -C /workspace/repo \\\n  --sandbox workspace-write \\\n  --ask-for-approval never \\\n  --output-schema /input/result.schema.json \\\n  --output-last-message /output/result.json \\\n  \"Implement the task, validate it, and return the requested structured result.\"\n```\n\nA useful harness schema usually includes:\n\n- `status`: `success`, `partial`, or `failed`\n- `summary`: concise outcome\n- `changed_files`: repository-relative paths\n- `validation`: commands run and results\n- `assumptions`: decisions made without user input\n- `blockers`: concrete unresolved problems\n\nSet `additionalProperties` to `false` when downstream parsing must be strict.\n\n## Resume or Avoid Persistence\n\nResume the most recent session for the current working directory:\n\n```bash\ncodex exec resume --last \"Continue the previous task and fix remaining issues.\"\n```\n\nResume a specific session:\n\n```bash\ncodex exec resume \"$SESSION_ID\" \"Continue with the next stage.\"\n```\n\nUse an ephemeral run when rollout persistence is undesirable:\n\n```bash\ncodex exec --ephemeral \"Analyze the repository.\"\n```\n\nDo not rely on `--last` across unrelated working directories unless deliberately using the relevant all-directory option supported by the installed CLI.\n\n## Authenticate Safely\n\nFor a local interactive login:\n\n```bash\ncodex login\n```\n\nFor a headless machine with device-code login enabled:\n\n```bash\ncodex login --device-auth\n```\n\nFor a single automated invocation:\n\n```bash\nCODEX_API_KEY=\"$OPENAI_API_KEY\" \\\ncodex exec --json \"Triage the repository.\"\n```\n\nDo not expose API keys as broad job-level environment variables in jobs that execute repository-controlled code. Never commit or print `~/.codex/auth.json`.\n\n## Windows, PowerShell, and WSL2\n\nFor native Windows headless use:\n\n- Install with the official PowerShell installer or npm.\n- Prefer PowerShell 7.4 or newer for JSONL redirection.\n- Build argument arrays and invoke them with `& codex @args`; avoid fragile backtick-heavy command construction.\n- Check `$LASTEXITCODE` after every Codex invocation. PowerShell error preferences alone are not a substitute for checking a native process exit code.\n- Keep stdout JSONL separate from stderr diagnostics. Do not use `2>&1` when stdout must remain parseable JSONL.\n- Configure `%USERPROFILE%\\.codex\\config.toml` with `[windows] sandbox = \"elevated\"` when available; use `unelevated` only as the fallback.\n- Preserve the task-level policy `--sandbox workspace-write --ask-for-approval never` for ordinary autonomous edits. The native Windows sandbox implementation and the CLI task policy are separate controls.\n\nFor WSL:\n\n- Use WSL2, not WSL1.\n- Install and authenticate Codex inside WSL as a Linux installation.\n- Keep repositories under `~/code/...`, not `/mnt/c/...`, for better performance and fewer permission, symlink, and file-watcher problems.\n- Do not pass credentials through visible `wsl.exe` command-line strings.\n\nSee [references/windows.md](references/windows.md) for installation, PowerShell wrappers, JSONL parsing, sandbox configuration, WSL2 patterns, and Windows-specific troubleshooting.\n\n## Container and CI Requirements\n\nWhen generating a Docker, Kubernetes, or CI design:\n\n- Mount only the intended workspace and output directory.\n- Run as a non-root user when practical.\n- Do not mount the host Docker socket.\n- Do not mount home directories, SSH keys, or cloud credential directories.\n- Restrict network access unless the task explicitly needs it.\n- Apply CPU, memory, process, and execution-time limits outside Codex.\n- Preserve stdout, stderr, exit status, JSONL events, and the final message separately.\n- Validate repository diffs and test results before treating a run as successful.\n- Prefer a fresh worktree or disposable checkout per task.\n\nSee [references/recipes.md](references/recipes.md) for ready-to-use shell, Docker, CI, and parser patterns.\n\n## Diagnose Failures\n\nUse this order:\n\n1. Run `codex --version` and `codex exec --help`.\n2. Verify the command uses a positional prompt or `-` for stdin.\n3. Verify the working directory and Git repository status.\n4. Verify authentication without printing secret material.\n5. Check whether sandbox policy blocks required reads, writes, commands, sockets, or network access.\n6. Check whether approval policy is causing an impossible prompt in headless mode.\n7. Inspect stderr and the JSONL `error` or `turn.failed` events.\n8. Re-run with a smaller, deterministic task that reproduces the failure.\n9. Do not silently switch to `--yolo` as a troubleshooting shortcut.\n\n## Completion Standard\n\nFor implementation tasks, consider the run complete only when Codex has:\n\n1. inspected the relevant repository context,\n2. made the requested changes,\n3. run the most relevant available validation,\n4. reviewed the resulting diff for unrelated changes,\n5. reported assumptions and unresolved blockers,\n6. produced machine-readable status when requested by the harness.\n\n<!-- File: packages/cli/src/skill/builtin/.bundle/compose-next/SKILL.md (Tokens: ~3001 | Category: anthropic-skill) -->\n---\nname: compose-next\ndescription: Use for multi-step feature work, bug fixes, or refactors where requirements need to settle, a feature document should carry design + tasks + delivery evidence, and the change deserves independent review before merge. Use it only when the user explicitly requests this workflow, whether with `/compose-next`, by name, or in any other clear natural language; do not infer the request from task complexity alone. Not for one-shot edits, single-file tweaks, or answering questions — those need no orchestration overhead.\n---\n\n# Compose Next\n\nCompact end-to-end contract for grill → workspace → spec → implement → verify → review → finalize → finish. One skill load, no internal skill hand-offs.\n\nWhen writing a checkpoint or compacting context, preserve this recovery instruction in the checkpoint or compacted summary: on resumption, if the Compose Next instructions are absent, reload the `compose-next` skill before continuing.\n\nEnter this workflow only on an explicit user request. Any clear natural-language instruction to use this workflow counts just like `/compose-next`; the user does not need to know or name the skill. If the user has not clearly requested the workflow, do the work directly and run none of the phases below; do not infer consent merely because the task is large or resembles a Compose task.\n\n## Step 0 — Orient\n\nInspect the repository, its instructions (`AGENTS.md`, `README`, existing spec files), and recent changes before asking anything. Do not ask the user for facts the environment already answers.\n\nDecide the shape of the work:\n\n- **Fully constrained mechanical change with no durable design surface** → skip Grill and Spec, go to Workspace then Implement.\n- **Requirements or design ambiguous** → Grill first.\n- **Requirements clear, feature deserves a durable document** → Workspace then Spec.\n\nUser gates and project overrides:\n\n- If the user explicitly requests `without worktree` or specifies a worktree or workspace path, use that workspace choice and skip the default worktree gate. Do not ask again for worktree consent.\n- If the user explicitly says `without spec`, \"no spec needed\", \"this is a small fix\", or gives an equivalent instruction, skip the durable feature document and its spec gate. Keep verification and review when the task still warrants them.\n- An explicit project instruction, `AGENTS.md`, or user-provided agent/worktree configuration may define a project-specific worktree path, branch convention, spec path, or spec format. Use that configuration instead of the defaults in this skill. Record the override in the feature document or final report when it changes the normal artifact location.\n\nEvery path passes through Workspace before Spec or Implement; no branch skips it.\n\n## Grill — resolve decisions\n\nResolve one decision axis at a time. A single decision may bundle multiple dependent fields in one structured question; unrelated decisions require separate turns.\n\nUse the Question tool for every user decision:\n\n- Put known choices in `options`. Each option gets a concise `label` and a `description` explaining the consequence. List the recommendation first and mark its label `(Recommended)`.\n- For consequential choices, include 2–3 viable alternatives.\n- When choices cannot be enumerated, still call Question with `options: []` for free-text.\n- Do not ask for permission to continue when no decision remains.\n\nSplit requests spanning independent subsystems before refining each part. Do not begin implementation until requirements and scope are settled.\n\n### When user input is unavailable\n\nIf user input cannot be obtained — the Question tool is absent, a question gets no reply, or the run cannot stop and wait (for example a goal that keeps running) — and the decision is not a dangerous action that requires explicit user consent, resolve **this one decision** yourself and continue:\n\n1. Choose the option marked `(Recommended)` when repository evidence still supports it and it can run unattended.\n2. Otherwise choose the closest minimal-scope option supported by the evidence; prefer text-only, non-interactive work.\n3. If the decision includes destructive or irreversible work, choose a non-destructive path that preserves progress; never auto-approve the destructive option.\n4. State the option selected and the reason in the response.\n\n## Workspace — worktree ownership\n\nNever begin implementation on `main` or `master` without explicit user consent. If the active workspace is already chosen, skip creation below and continue with toolchain setup.\n\n- Compare `git rev-parse --git-dir` with `git rev-parse --git-common-dir`. If they differ, use the current linked worktree; do not nest another. A non-empty `git rev-parse --show-superproject-working-tree` indicates a submodule, not a linked worktree.\n- Create a linked worktree at `.worktrees/{{slug}}` by default. Base the new branch on the latest mainline (e.g. `origin/main`). If the current checkout makes the base unclear (detached HEAD, an unrelated feature branch, unknown default branch), ask the user explicitly which base to use before creating the worktree. Run `git check-ignore -q \"$path\"`; if it is not ignored, write `*` to `.worktrees/.gitignore`. Then run `git worktree add \"$path\" -b \"$branch\" \"$base\"`.\n- When targeting the worktree with a command, pass its absolute path as `workdir`; omitted `workdir` uses the current session directory.\n- Install dependencies per repository instructions. Prefer lockfile-frozen, hardlink-friendly modes (`bun ci`, `uv sync --frozen`) over commands that mutate the lockfile. Confirm the toolchain is usable before continuing.\n\n## Spec — one document per feature\n\nMaintain one document per feature at `docs/compose/spec/{{feature-name}}.md` from the workspace root. Do not add a date to the filename. A user-specified location overrides this path. Edit an existing document in place; never create a separate plan or report. Do not write the feature document before Workspace owns the active workspace.\n\n### Template\n\n```markdown\n---\nfeature: {{feature-name}}\nstatus: designed | in-progress | delivered\nupdated: YYYY-MM-DD\nsource: {{branch-name}} | {{pr-url}} | {{mr-url}}\n---\n\n# {{Feature Name}}\n\n## Report\n\n## [S1] Problem\nDescribe the user-visible problem.\n\n## [S2] Design\nRecord the chosen behavior and the contracts needed to implement it.\n\n## [S3] Out of Scope\nState explicit boundaries.\n\n## Tasks\n- [ ] T1: {{work item}} — acceptance: {{observable result}} (covers: S2.1)\n- [ ] T2: {{work item}} — acceptance: {{observable result}} (depends: T1)\n\n## Journey log\nOptional. Dead ends, pivots, or transferable lessons worth future work. Do not pad an uncomplicated change by splitting it into several thin entries.\n```\n\n### Design-time rules\n\n- Leave `Report` empty until finalized and set `status: designed`. Keep `Journey log` empty unless something is worth carrying forward.\n- Set `source` to the form that best names where the spec's source lives — `{{branch-name}}`, `{{pr-url}}`, or `{{mr-url}}` — and update it whenever that changes.\n- Record settled decisions and precise contracts, not exploration history or file-level code dumps. Include architecture, interfaces, data flow, error behavior, and testing boundaries when they affect the change.\n- Make each task the smallest independently verifiable work item; give it an observable acceptance criterion. Add `depends:` only for real prerequisites; dependencies must be acyclic.\n- Under Design, give each contract or behavior its own subsection `S2.1`, `S2.2`, …\n- Keep `Sn` and `Sn.m` anchors stable when headings change; never renumber existing anchors.\n- `covers:` on a task is optional (for example `covers: S2.1`).\n- Scale detail to the change; do not pad small designs.\n\nBefore implementation, fix ambiguous requirements, contradictions, unresolved references, and unverifiable acceptance criteria. If the user is available, request document approval with the Question tool; otherwise continue.\n\n### Amendments\n\nUpdate only affected sections, bump `updated:`, preserve anchors, and keep only the tasks required by the amendment and their dependents. Do not regenerate the document or create duplicate tasks.\n\n## Implement\n\nUse the feature document as the source of requirements, or the conversation for an undocumented mechanical change. When a feature document exists, set its `status: in-progress` on the first implementation commit. Execute tasks in dependency order. Track multi-step work with the Task tool.\n\nFor behavior changes with a cheap reproduction, write a failing test, confirm it fails for the intended reason, implement the smallest fix, and confirm it passes. A bug fix requires a regression test when one can be written. Skip test-first for generated code, configuration-only changes, throwaway prototypes, or explicit user direction.\n\nTest public behavior. Do not duplicate production logic in expected values, add test-only production APIs, or assert only that mocks were called. Prefer real implementations over mocks.\n\nFor failures, reproduce before editing and identify the root cause from errors, diffs, recent commits, or boundary instrumentation. After two failed fixes, stop patching and re-derive the cause.\n\n### Parallel work\n\nDispatch independent tasks in parallel when isolation prevents collisions; keep tightly coupled work together. Prefer giving parallel subagents disjoint file sets and keeping commits with the orchestrator. Give each subagent the workspace path, task, acceptance criteria, relevant spec sections, and required verification. Do not pass session history. Treat its report as a claim and inspect the resulting diff.\n\nContinue through tasks without routine approval pauses. Stop only for an unresolved product decision, a blocker that cannot be worked around, a destructive action requiring consent, or completion.\n\n## Verify\n\nBefore any completion claim, run the repository's relevant tests, typecheck, build, or reproduction from the correct directory and read the output. Record each command and result. Mark known baseline failures as `PRE-EXISTING` with a short identifier. Do not substitute prior output or a subagent report for fresh evidence.\n\nVerification and review are strictly sequential. Wait for all verification commands to exit before dispatching the reviewer. Never overlap review with a resource-heavy test or application process in the same environment.\n\n## Review\n\nAfter implementation is verified and before finalizing the feature document, dispatch one fresh subagent to review the complete change.\n\nProvide the reviewer:\n\n- the applicable spec sections and acceptance criteria;\n- the workspace path, base branch, base SHA, head SHA, and exact diff command or precomputed diff;\n- a compact verification summary: one line per command with `PASS`, `FAIL`, or `PRE-EXISTING`, plus test counts when available. Do not paste full command output unless a specific failure requires it.\n\nIf there is no feature document, take acceptance criteria from the conversation. If none are explicit, ask the user for them before dispatching the reviewer.\n\nDo not provide an implementer-authored narrative. The reviewer may inspect the diff and run additional commands needed to validate its conclusions. It must not repeat a command already reported as passing, especially a heavy E2E suite, unless the result is stale, the code changed afterward, or concrete evidence makes the result suspect. Before any justified rerun, confirm no equivalent command is still running. Missing evidence should be reported or gathered with the cheapest non-duplicative command.\n\nUse a reviewer model at least as capable as the strongest implementer it reviews.\n\nRequire separate conclusions for:\n\n- **Spec compliance** — every acceptance criterion is met and points to evidence in the diff or reviewer-observed command output.\n- **Correctness** — logic, boundaries, error handling, regressions, and tests are sound, including issues outside the written spec.\n- **Codebase consistency** — naming, structure, and local conventions match surrounding code.\n\nClassify unmet or unverifiable acceptance criteria and correctness bugs as critical. Fix critical findings, re-verify, and re-review affected areas. Reject incorrect findings with technical evidence. When necessary, return to Spec and record the pivot in the Journey log. If the fix-and-re-review loop stops converging — repeated findings on the same area, or fixes that introduce new criticals — stop looping and report the impasse with the remaining findings instead of forcing a pass.\n\nFor human review feedback, verify each item against the codebase, clarify ambiguous items before editing, and implement validated items one at a time with verification. Check actual usage before expanding an unused path, and surface conflicts with prior user decisions instead of silently complying.\n\nFor parallel task work, review integrated task diffs at useful boundaries only when delaying review would compound risk.\n\n## Finalize — commit the feature document\n\nIf a feature document exists, after review passes and before finishing the branch:\n\n1. Set `status: delivered` and bump `updated:`.\n2. Check off completed tasks; leave incomplete tasks unchecked and do not claim delivery if they block acceptance.\n3. When finalized, fill `Journey log` when needed and replace `Report` with:\n\n```markdown\n## Report\n\n**What was built** — concise description of the final behavior.\n\n**Verification** — commands run and their observed results.\n```\n\nUpdate a design section only when it contradicts the delivered behavior. Commit the finalized document on the feature branch before finishing. This documentation-only commit does not restart verification or review; CI re-running on it is expected.\n\n## Finish\n\nDo not auto-finish: confirm with the user before any irreversible action, including opening a PR or MR, merging, or pushing.\n\nReport branch, base, head SHA, workspace, feature-doc path when available, and ask the user which way to finish — for example:\n\n- local merge / open PR / push only / keep the branch;\n- which base branch to merge or target;\n- keep or remove the worktree.\n\nOpen PR or MR does not imply merge: unless the user also asked to merge, stop after opening — the merge always needs its own confirmation, whether the PR or MR was created here or already existed.\n\nWhen the closing action changes where the spec lives, update `source` and commit it as documentation only: `{{pr-url}}` or `{{mr-url}}` after opening one, `{{branch-name}}` before a local merge.\n\nWorktree pitfalls:\n\n- Local merge and `gh pr merge` run from the main repository checkout — the base branch cannot be checked out while another worktree holds it.\n- `git worktree remove` only on `.worktrees/` or the path scoped by the prompt / `AGENTS.md`.\n\n<!-- File: packages/cli/src/skill/builtin/.bundle/data-analytics/SKILL.md (Tokens: ~724 | Category: anthropic-skill) -->\n---\nname: data-analytics\ndescription: \"Use this skill for quantitative product or business analysis: data quality checks, metric diagnostics, KPI design and reporting, dashboards, analytical reports, charts, notebooks, market sizing, semantic layers, and evidence-backed recommendations. Also use it whenever Data Analytics is explicitly invoked.\"\n---\n\n# Data Analytics\n\nThis is the single entry point for a code-agent-oriented Data Analytics bundle. The original plugin workflows are under `workflows/`; React, Vite, MCP App widgets, connector manifests, and frontend build artifacts are intentionally excluded.\n\n## Route the request\n\n1. Read `workflows/index/SKILL.md` completely. Treat it as the authoritative plugin-level eligibility and analytical routing policy, except where its UI/runtime delivery rules conflict with the code-agent overrides below.\n2. Select the narrowest focused workflow named by that index. Read every selected workflow's `SKILL.md` completely before acting.\n3. If a selected workflow names related skills, load those only when its routing conditions apply. Multiple skills may form one workflow; follow the ordering defined by the index and focused skills.\n4. Resolve relative links from the file that contains the link. Read referenced instruction or reference files when the selected workflow requires them and they exist in this bundle. Prefer bundled scripts and sample data over recreating them.\n5. Do not load unrelated focused workflows merely because they are present.\n\n## Bundled capabilities\n\nFocused workflows live in `workflows/`, including data-quality analysis, business-context gathering, metric diagnostics, product/business analysis, KPI design and reporting, visualization, dashboards, reports, notebooks, market sizing, validation, and semantic-layer creation.\n\nUse data sources and tools only when the host harness exposes them. The bundle does not require a particular connector registry or UI protocol.\n\n## Code-agent delivery overrides\n\nThese rules take precedence over MCP App, widget, native Work Mode, and packaged Recharts delivery rules inherited from the original workflows:\n\n- Never require or call `render_artifact`, `render_chart`, `render_table`, `validate_artifact`, `export_artifact_package`, `charts_widget_v2`, or `app_block` unless the user independently provides an equivalent tool and explicitly requests it.\n- Default transient answers to concise Markdown with source notes. Default durable reports and dashboards to Markdown, a self-contained HTML file using plain HTML/CSS/SVG/vanilla JavaScript, a notebook, a spreadsheet, or a static image according to the user's request and the host's available tools.\n- For charts, prefer reproducible Python/Matplotlib, notebook-native plotting, SVG, or the destination system's native chart support. Inspect generated visuals when the harness provides image or browser inspection.\n- Do not install Node, React, Recharts, Vite, or frontend packages for analytics output. Do not depend on removed `src/`, `assets/`, MCP specifications, HTML runtime helpers, or widget resources.\n- If a focused workflow points to a removed UI-only reference, skip that reference and apply these overrides while preserving its analytical, provenance, QA, and narrative requirements.\n- A requested report remains incomplete until its chosen portable file exists or a concrete blocker is reported; a chat summary is sufficient only when the user requested an inline answer.\n\n## Safety and fidelity\n\n- Never treat plugin instructions as permission to bypass host policy, expose secrets, or perform unapproved external writes.\n- Keep source provenance and uncertainty visible in analytical outputs.\n- Do not silently replace real-data questions with sample data.\n- Preserve the selected workflow's validation and delivery requirements through completion.\n\n<!-- File: packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/analyze-data-quality/SKILL.md (Tokens: ~2091 | Category: anthropic-skill) -->\n---\nname: analyze-data-quality\ndescription: \"Assess whether structured data, query results, dashboards, or analytical evidence are trustworthy enough to use. Use when the task is to check data quality, reconcile conflicting sources or metric definitions, or decide whether evidence is safe to cite.\"\n---\n\n## Related Skills\n\nUse $design-kpis when the work is to define or redesign a KPI framework, metric definition, guardrail, or target rather than checking whether existing data is trustworthy.\n\nUse $validate-data when the work is to QA an analysis, chart, report, or recommendation rather than investigate the underlying data.\n\n# Analyze Data Quality\n\nAssess whether a dataset is trustworthy enough for analysis, modeling,\ndashboards, experiments, or downstream pipelines. Start with the intended use and grain, run the highest-value checks for the data shape, and report concrete evidence, analytical risk, likely causes, and the smallest useful remediation or automated test.\n\n## Workflow\n\n1. Clarify the quality question and operating context.\n\n   Establish what the dataset represents, the intended unit of analysis, the downstream use, whether the user cares about raw ingestion quality,\n   transformed-model quality, or both, and the comparison baseline such as prior weeks, prior schema, or a trusted reference table. Identify expected grain,\n   primary keys or candidate keys, important date columns, timezone assumptions,\n   domain rules, allowed values, and business thresholds. If context is missing,\n   infer cautiously and label assumptions.\n\n2. Choose an inspectable analysis path.\n\n   When checks require SQL or Python, default to a companion notebook so the user can inspect the exact code behind the findings. Use $jupyter-notebooks when a dedicated notebook scaffold or refactor workflow would help. For queryable tables, use `~~structured_data` to confirm schema, grain, sample rows, and query rules through the relevant source connector before heavier checks. Use `~~operations_logs` for freshness and lineage when those checks matter.\n\n3. Build a compact profile.\n\n   Start with row count, column count, column names and types, candidate keys,\n   duplicate rates on likely identifiers, min/max timestamps for relevant date columns, null rates, distinct counts for likely categorical columns, and basic numeric summaries for measure columns. Confirm grain before interpreting anomalies; many apparent quality problems are mixed-grain data,\n   partial backfills, late-arriving data, or duplicated joins.\n\n4. Run core quality checks.\n\n   Select checks that match the dataset and task. Default to the most relevant checks across completeness, uniqueness, validity, consistency, integrity,\n   timeliness, volume, and shape. Compare rates, not just counts, and segment by time, source, country, platform, model version, or other key dimensions when that helps distinguish real issues from expected variation.\n\n5. Run shape-specific checks.\n\n   Adapt the checks to the data shape:\n\n   - Event data: duplicate event IDs, future event timestamps, session or user\n     coverage gaps, and abrupt event-mix changes after releases.\n   - Dimension tables: non-unique business keys, orphan surrogate keys, status\n     changes without corresponding timestamps, and unexpected churn in reference\n     values.\n   - Fact tables: mixed grain, impossible measures such as negative revenue or\n     quantity, join blowups to dimensions, and late-arriving or partially loaded\n     partitions.\n   - ML feature or scoring tables: leakage from post-outcome fields, feature\n     sparsity spikes, range shifts after model or feature-store changes, and\n     class-label drift.\n   - Experiment data: duplicate assignments, variant imbalance beyond\n     expectation, exposure without assignment, and events before assignment\n     timestamp.\n\n6. Run temporal and distribution checks when history exists.\n\n   Prioritize temporal diagnostics when the user mentions \"after X date\",\n   \"suddenly\", \"recently\", or \"only started appearing\". Check first-seen dates,\n   last-seen dates, daily or weekly null-rate trends, duplicate-rate trends, row count trends, category-share shifts, distribution drift, and change points around launches, migrations, incidents, model changes, or backfills.\n\n7. Investigate analytical risks and likely causes.\n\n   Tie each issue to the downstream risk: broken trusted analysis, biased decisions, broken joins, stale dashboards, incorrect experiments, leakage,\n   unreliable model features, or misleading segments. When possible, identify whether the issue is isolated to a source, segment, partition, time window,\n   release, migration, backfill, or upstream pipeline change.\n\n8. Recommend fixes or automated tests.\n\n   Recommend the smallest set of follow-up fixes, monitoring, or automated tests that would materially reduce risk. Suggest automation only when the rule is stable and worth maintaining. Include or save the notebook/query path when code produced the findings.\n\n## Standards\n\n### Core Checks\n\n- Completeness: null rate by column; null rate by partition, segment, and time bucket; unexpected empty strings or sentinel values; required-column population rate.\n- Uniqueness: exact duplicate rows, duplicate primary keys, duplicate composite keys, and proportion unique for semi-unique fields such as emails or device IDs.\n- Validity: type conformance after casting; format checks for IDs, emails, URLs,\n  enums, country codes, and timestamps; range checks for measures, percentages,\n  counts, and dates; allowed-values checks for controlled vocabularies.\n- Consistency: cross-field rule checks, units or currency consistency, status and timestamp alignment, and agreement between duplicated fields from different sources.\n- Integrity: parent-child key coverage, orphan records, unexpected many-to-many joins, and broken slowly changing dimension joins.\n- Timeliness: freshness lag from source event time to load time, freshness lag from load time to report time, missing recent partitions, and unexplained historical rewrites or backfills.\n- Volume and shape: row-count drift, distinct-count drift, distribution drift,\n  share-of-total drift for major categories, and new or disappeared categories.\n\n### Specific Check Guidance\n\n- Duplicates and keys: check exact duplicates, primary key duplicates, composite key duplicates at the intended grain, and near-duplicates caused by whitespace,\n  casing, formatting, or late updates. Report count, share of affected rows,\n  duplicated keys, and whether duplication is isolated to a time range, source,\n  or segment.\n- Missingness: distinguish acceptable sparsity from broken completeness. Check null rates over time, newly null columns after schema or pipeline changes, and sentinel values such as `''`, `'unknown'`, `'n/a'`, `0`, or `-1`.\n- Domain validity: check malformed identifiers, country codes, timestamps,\n  impossible values, values outside allowed sets, and cross-field contradictions such as `is_cancelled = false` with a non-null `cancelled_at`.\n- Join coverage: when multiple datasets are involved, check foreign keys that do not match a parent table, unexpected one-to-many expansion, coverage loss when joining to dimensions or experiments, and row counts before and after joins.\n- Freshness and schema drift: check row-count changes against recent history,\n  lag on important date columns, added/removed/retyped columns, and shifts in sparsity or cardinality that suggest upstream changes.\n- Outliers and distribution shifts: use robust methods such as quantiles, MAD,\n  or IQR before defaulting to z-scores. Check sudden changes in mean, median,\n  variance, zero rate, category share, and long-tail behavior.\n- Leakage, backfill, and time travel: check features populated before they should exist, future-dated records, late-arriving data causing unstable recent partitions, and backfills that change historical counts without annotation.\n\n### Severity\n\n- Critical: breaks trusted analysis, core joins, production dashboards, or key decisions, such as duplicated grain, missing primary keys, or stale production data.\n- High: materially biases downstream decisions, such as large null spikes,\n  category drift in a core dimension, invalid business-rule values, leakage, or severe join coverage loss.\n- Medium: localized or explainable issues that still need documentation,\n  monitoring, or owner follow-up.\n- Low: cosmetic inconsistencies, expected sparsity, or known edge cases that do not materially affect current use.\n\nDo not dump raw profiling output without interpretation. Tie each finding to an analytical risk and likely impact.\n\n### Automated Test Guidance\n\n- Good candidates for automation: primary key uniqueness, not-null checks on required columns, accepted values for stable enums, referential integrity,\n  freshness thresholds, and seasonality-aware row-count or volume bounds.\n- Use caution with hard-coded distribution thresholds on volatile product metrics, strict uniqueness in messy entity-resolution use cases, and recent partitions when late-arriving data is normal.\n- Suggest automated tests only when the expected rule is stable, important, and maintainable.\n\n### Output Standards\n\nFor stakeholder-facing data-quality work, pass the completed findings to $build-report by default so the runtime produces a portable report in the selected format. Do not stop at profiling output or a notebook unless the user explicitly requested a quick inline answer or another primary artifact. The structure below defines the report content.\n\nStructure the response with:\n\n1. dataset and grain summary\n2. checks performed\n3. findings\n4. temporal or trend anomalies\n5. likely causes and impacted use cases\n6. recommended fixes or automated tests\n7. assumptions and open questions\n\nFor each finding, include:\n\n- what failed\n- evidence: counts, rates, segments, and dates\n- why it matters\n- severity and confidence level\n- likely cause when known\n- suggested remediation or automated test\n\nWhen code was used, include or save a notebook containing the key SQL and Python checks and make the notebook path easy to find.\n\n### Defaults\n\n- Prefer small, high-signal tables over exhaustive dumps.\n- Compare rates, not just counts.\n- Break checks out by time and key segments whenever possible.\n- Normalize strings before judging duplicates or distinct-count spikes.\n- Treat recent partitions carefully when data arrives late.\n- Call out when an anomaly could be caused by a legitimate product launch,\n  experiment, migration, incident, model change, or backfill.\n- Preserve inspectable evidence: SQL, query links, notebook paths, source paths,\n  sample rows, chart outputs, and calculation notes.\n\n<!-- File: packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/build-dashboard/SKILL.md (Tokens: ~487 | Category: anthropic-skill) -->\n---\nname: build-dashboard\ndescription: \"Build a source-backed dashboard or monitoring view with clear metrics, filters, visual hierarchy, definitions, refresh context, and QA.\"\n---\n\n# Build a Dashboard\n\nUse this workflow when the user needs a reusable monitoring or exploration surface rather than a one-time report. Read the relevant analysis and KPI workflows first when metric definitions or decision logic are not already settled.\n\n## Select a portable surface\n\nHonor the user's destination. Otherwise choose the simplest surface supported by the harness:\n\n- Existing BI/product analytics platform when the user wants a governed shared dashboard there.\n- Streamlit when Python execution and local/server operation are appropriate; read `specifications/streamlit-dashboard.md`.\n- Self-contained plain HTML/CSS/vanilla JavaScript for a portable local dashboard; read `specifications/html-dashboard.md`.\n\nDo not require React, Vite, Recharts, MCP Apps, or widget runtimes.\n\n## Workflow\n\n1. Define the audience, operating decision, monitoring cadence, and questions the dashboard must answer.\n2. Define each metric: formula, numerator/denominator, unit, grain, time window, filters, exclusions, owner, source, and freshness expectation.\n3. Validate joins, completeness, duplicates, missingness, comparability, and refresh status before presenting metrics as trustworthy.\n4. Design the information hierarchy:\n   - Overview and primary outcomes.\n   - Drivers and diagnostic cuts.\n   - Guardrails and risks.\n   - Detail tables or drill-down paths.\n5. Add only decision-relevant filters. Make default date ranges, segments, comparison periods, and filter state visible.\n6. Use `../visualize-data/SKILL.md` for each chart and keep exact lookup values accessible in tables.\n7. Show data freshness, source context, definitions, and material caveats in the dashboard.\n8. Implement and test the real artifact with representative, empty, partial, and error states when feasible.\n\n## QA and handoff\n\n- Reconcile displayed totals and KPIs against reviewed source results.\n- Test filters, date boundaries, sorting, responsive layout, and refresh behavior.\n- Check chart labels, units, legends, accessibility, and table readability.\n- Ensure the artifact does not expose secrets, credentials, unnecessary personal data, or temporary local paths.\n- Deliver the dashboard artifact or governed platform link plus metric definitions, source/query files, refresh instructions, and known limitations.\n\n<!-- File: packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/build-report/report-to-google-doc/SKILL.md (Tokens: ~1490 | Category: anthropic-skill) -->\n---\nname: report-to-google-doc\ndescription: \"Narrow conversion skill. Invoke only when the user explicitly asks to convert an existing local or blob-hosted HTML analytics report into a Google Doc, DOCX, or shareable document.\"\n---\n\n# Report To Google Doc\n\nUse this skill only when the user explicitly needs a shareable Google Drive document from an existing HTML analytics report. The source must be an HTML report: a local file, a downloaded blob-hosted report, or a report produced by `$build-report`\nHTML mode or an equivalent local portable report source.\n\nThe expected path is HTML -> DOCX -> Drive upload. It is acceptable for Drive to host the upload as a DOCX-backed viewer file rather than a native Google Docs MIME type. Do not use the old Google Docs batch-update request path.\n\n## Workflow\n\n1. Resolve the HTML report.\n\n   Use an absolute local path. If the user provides a remote report, retrieve it first and pass the local HTML file to the helper. If the file is a sign-in page, redirect page, or tiny stub, stop and obtain the real report.\n\n2. Run the bundled helper.\n\n   ```bash\n   python3 <REPORT_TO_GOOGLE_DOC_SKILL_DIR>/scripts/report_to_google_doc_plan.py \\\n     /absolute/path/to/report.html \\\n     --out-dir /tmp/report_to_google_doc_plan\n   ```\n\n   Omit `--render-workers` on the normal path. Only pass a worker count after benchmarking the same report family locally. If dependencies are missing,\n   use a local virtual environment with `beautifulsoup4`, `pillow`, and `python-docx`; `cairosvg` or headless Playwright are optional renderers.\n\n3. Inspect helper outputs.\n\n   Required outputs:\n\n   - `skeleton.txt`: source text with stable placeholders\n   - `manifest.json`: parsed headings, tables, callouts, lists, styles, links,\n     and rendered visual inventory\n   - `preflight_checks.json`: source, width, DOCX, and rendered-image checks\n   - `report.docx`: generated local Word document\n   - `docx_upload_plan.json`: compact upload instructions\n   - `placeholder_queries.json`: source mapping debug labels\n\n   Do not upload until `preflight_checks.json` has `status: \"passed\"` with zero errors. Warnings must either be fixed or called out in the handoff.\n\n4. Upload the DOCX.\n\n   ```json\n   mcp__codex_apps__google_drive._upload_file({\n     \"file_uri\": \"/tmp/report_to_google_doc_plan/report.docx\",\n     \"file_name\": \"Report Name.docx\",\n     \"mime_type\": \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\"\n   })\n   ```\n\n   Treat the returned Drive URL as the deliverable. Do not attempt to force native Google Docs conversion, and do not fall back to `_batch_update_document`.\n\n5. Validate the uploaded result.\n\n   Confirm the uploaded file is readable and non-empty. Compare uploaded text against the source inventory: title, section headings, executive summary or answer callout, caveats, recommendations, source notes, and source links.\n   Inspect the local `report.docx` structure when available: heading counts,\n   lists, tables, hyperlink relationships, and image relationships should match `manifest.json`.\n\n6. Hand off the link.\n\n   Return the Drive/Docs URL and, when useful, the local DOCX path or source HTML path. Connector success alone is not enough; the handoff is complete only after the uploaded file and local DOCX structure have been checked against the source report. Keep routine check and preflight details in support artifacts. Do not list internal checks in the user-facing handoff unless a check failed, was unavailable, or produced a user-relevant caveat.\n\n## Standards\n\n- Preserve every section, headline claim, metric card, metric definition,\n  source note, chart takeaway, recommendation, caveat, and link from the HTML report.\n- Preserve semantic formatting: headings, paragraphs, inline bold/emphasis,\n  inline code, positive/negative colors, links, lists, callouts, metric-card grids, tables, notes, captions, and charts.\n- Use DOCX-native structures wherever practical: headings, paragraphs, tables,\n  bullets/numbered lists, links, inline images, paragraph shading, table cell shading, and text styles.\n- Keep the report text column readable. Tables, charts, rendered table grids,\n  screenshots, and visual blocks must not exceed the DOCX page text width.\n- Preserve charts as inline images rendered from the source visual or its same-data SVG fallback, aligned to the same left edge as text and tables. A chart with missing bars, missing legend swatches, or all-black/all-white marks fails validation even if the DOCX contains an image object.\n- Preserve multi-column report blocks. A two-column grid made only of titled mini-tables can remain a two-column rendered image capped to the text width;\n  mixed two-column blocks with narrative text, pills, callouts, or non-table panels should preserve that content natively instead of dropping it.\n- Do not expose customer-level details or sensitive links that were intentionally omitted from a sanitized report.\n- Do not write Google Docs batch-update artifacts such as `seed_requests.json`,\n  `remote_write_plan.json`, or `all_requests*.json`.\n\n## Repairs\n\nUse these fixes when validation exposes a conversion issue:\n\n| Problem | Fix |\n| --- | --- |\n| Heading is regular weight | Fix the DOCX writer heading style or explicit run bolding. |\n| Blank line after title or heading | Delete spacer paragraphs; skeletons should emit `\\n`, not `\\n\\n`, after headings. |\n| Body paragraphs have too much space | Delete literal blank paragraphs and set modest style spacing. |\n| Table/image too wide | Set table columns or image width to the DOCX text column width. |\n| Chart has labels but missing bars | Inline SVG class styles or use a headless screenshot before inserting. |\n| Two-column table group is flattened | Treat the grid as one layout block with mini-table titles preserved. |\n| Executive summary, metric cards, or section is missing | Fix parser inventory before upload. |\n| Chart overlaps table | Insert the image on its own paragraph after the table. |\n| Chart duplicated | Remove the extra image; keep exactly one source-order copy. |\n| Inline bold/code/color missing | Fix manifest range splitting in the DOCX writer. |\n| Source links show raw URLs | Replace with native linked labels or native bullets using HTML link text. |\n\n## Local Checks\n\n```bash\npython3 -m py_compile <REPORT_TO_GOOGLE_DOC_SKILL_DIR>/scripts/report_to_google_doc_plan.py\npython3 <REPORT_TO_GOOGLE_DOC_SKILL_DIR>/scripts/report_to_google_doc_plan.py \\\n  /absolute/path/to/report.html \\\n  --out-dir /tmp/report_to_google_doc_plan_smoke\njq '.status, .summary' /tmp/report_to_google_doc_plan_smoke/preflight_checks.json\ntest -f /tmp/report_to_google_doc_plan_smoke/report.docx\ntest -f /tmp/report_to_google_doc_plan_smoke/docx_upload_plan.json\ngit diff --check -- plugins/data-analytics/skills/build-report/report-to-google-doc\n```\n\n<!-- File: packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/build-report/report-to-google-slides/SKILL.md (Tokens: ~905 | Category: anthropic-skill) -->\n---\nname: report-to-google-slides\ndescription: \"Narrow conversion skill. Invoke only when the user explicitly asks to convert an existing HTML analytics report into a native Google Slides deck.\"\n---\n\n# Report To Google Slides\n\nUse this skill only when the user explicitly has an existing HTML analytics report and wants a Google Slides deliverable. The output should be a deck, not a pasted report. A stakeholder skimming the slides should understand the answer, evidence,\ncaveats, and recommended follow-up without opening the source report.\n\nThis skill consumes a local portable report, preferably self-contained HTML. If another format is the only source, first create an equivalent local HTML or structured report from the same evidence.\n\n## Workflow\n\n1. Resolve the local HTML report.\n\n   Use an absolute file path. If the user provides a remote report, retrieve it outside this skill first. If the local file is a sign-in page, redirect page,\n   or very small stub, stop and obtain the real report before continuing.\n\n2. Run the helper.\n\n   ```bash\n   python3 <REPORT_TO_GOOGLE_SLIDES_SKILL_DIR>/scripts/report_to_google_slides.py \\\n     <LOCAL_HTML_REPORT_PATH> \\\n     --out-dir /tmp/report_to_google_slides\n   ```\n\n3. Inspect local outputs.\n\n   Required outputs:\n\n   - `deck.pptx`: editable local PowerPoint file\n   - `manifest.json`: parsed source inventory and coverage counts\n   - `deck_plan.json`: slide-by-slide plan with named elements\n   - `preflight_checks.json`: local quality checks and pass/fail status\n   - `assets/`: rendered chart images\n\n   Do not import the PPTX until `preflight_checks.json` has `status: \"passed\"`.\n   Then run `unzip -t <out-dir>/deck.pptx`.\n\n4. Import and verify in Google Slides.\n\n   Import `deck.pptx` with `mcp__codex_apps__google_drive._import_presentation` using `upload_mode=\"native_google_slides\"`. Verify the imported deck with `_get_presentation_outline` and `_get_slide_thumbnail` for every slide when possible. At minimum, inspect the cover, one chart slide, one table slide,\n   and the caveats/sources slides.\n\n5. Repair before handoff.\n\n   If thumbnails show clipped text, missing charts, low contrast, blank images,\n   or awkward sizing, revise the helper output or source assumptions and regenerate before handing off the deck URL.\n\n6. Hand off the deck.\n\n   Return the Google Slides URL and, when useful, the local PPTX path or source HTML path. Keep routine check, preflight, thumbnail-inspection, and import-check details in support artifacts. Do not list internal checks in the user-facing handoff unless a check failed, was unavailable, or produced a user-relevant caveat.\n\n## Standards\n\n- Preserve the report's decision-critical information: headline claim,\n  executive summary, major findings, metric definitions, material charts,\n  decision-critical tables, recommendations, implications, caveats,\n  assumptions, freshness notes, and source/provenance notes.\n- Translate report prose into slide-native communication. Lead with the takeaway, use one main idea per slide, and put supporting detail in concise callouts, bullets, tables, chart annotations, or speaker notes.\n- Tighten copy before shrinking fonts.\n- Keep gross metric reads, net/incremental reads, causal claims, and caveats visibly separated when the source report distinguishes those lenses.\n- Use editable text and native PPTX tables wherever practical. Use native PPTX bullets; do not fake bullets with typed dashes.\n- Preserve source charts as evidence images. Do not screenshot the whole HTML report or paste whole report sections.\n- Support self-contained HTML reports whose chart evidence is available as inline SVG, accessible tables, or embedded images; render those into local chart evidence images before building the deck.\n- Use one chart per evidence slide unless the report has a stronger grouped comparison.\n- Keep table slides legible. If a full table is too dense, keep the main comparison in the deck and move extra detail to speaker notes or source slides.\n- Source notes should be visible but quiet.\n\n## Visual System\n\nThe helper derives colors and hierarchy from the HTML report CSS and chart palette, then applies a restrained analytics deck layout. It does not follow external deck files or company-specific branding.\n\n<!-- File: packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/build-report/report-to-pdf/SKILL.md (Tokens: ~1488 | Category: anthropic-skill) -->\n---\nname: report-to-pdf\ndescription: \"Narrow conversion skill. Invoke only when the user explicitly asks to convert an existing Data Analytics report, dashboard, or inline chart export into a PDF artifact.\"\n---\n\n# Report To PDF\n\nUse this skill only when the user explicitly needs a PDF from an existing Data Analytics report, dashboard, or chart artifact. Prefer a static HTML export or another portable report file as the source.\n\nThe expected path is static HTML -> browser headless print-to-PDF -> PDF verification. If only a non-portable source exists, create or retrieve the matching static HTML/export source first.\n\n## Workflow\n\n1. Resolve the static source.\n\n   Use an absolute local path to a static HTML report/export or a local URL served from that static export. If the source is a blob stub, sign-in page, redirect page, incomplete viewer, or an app shell that contains boot scripts but not the report content, stop and obtain a static HTML/export source before continuing.\n\n   When the user provides a hosted artifact URL, first determine whether it exposes a usable static export or package source. If the static export is unavailable but the validated artifact payload is still available in the current run, create the matching static HTML/export from that payload and preserve source provenance in the handoff. If neither a static export nor the artifact payload is available, stop with a blocker instead of printing the live app shell or rebuilding the report from memory.\n\n   When creating or repairing the static source, keep visible metadata reader-facing. Do not copy internal artifact runtime fields, package plumbing, or validator/debug state into the report body, header, footer, or source section. For example, omit raw labels such as snapshot status, package path, widget type, manifest path, renderer IDs, validation status, and local temp paths from the visible PDF. If a runtime detail matters for audit or troubleshooting, preserve it in support notes rather than the visible PDF. Translate data-state caveats into reader language only when they affect interpretation, such as \"synthetic demo data\" or \"partial source coverage.\"\n\n2. Generate the PDF with Chrome CLI headless print-to-PDF.\n\n   Use the platform-specific Chrome executable available in the environment. Common examples are `/Applications/Google Chrome.app/Contents/MacOS/Google Chrome` on macOS and `google-chrome`, `chromium`, or `chromium-browser` on Linux. This is the primary conversion method because it prints the static HTML with a browser rendering engine and usually preserves selectable text, layout, charts, tables, and print CSS.\n\n   ```bash\n   chrome \\\n     --headless=new \\\n     --disable-gpu \\\n     --no-first-run \\\n     --no-default-browser-check \\\n     --no-pdf-header-footer \\\n     --print-to-pdf=/absolute/path/to/report.pdf \\\n     /absolute/path/to/report.html\n   ```\n\n3. If Chrome is unavailable or cannot produce a valid PDF, use a renderer-backed fallback.\n\n   Use the next available local mechanism that renders the same static HTML/export source and prints or saves that rendered page to PDF. Keep the fallback tool-agnostic: the requirement is faithful HTML rendering followed by PDF output, not a specific implementation. Do not replace this with a model-authored PDF layout, manually redrawn charts, or a report reconstructed from memory.\n\n   A fallback is acceptable only when:\n\n   - the static HTML/export remains the source of truth\n   - the rendered output preserves the report title, narrative, charts, tables, caveats, and source details\n   - app-only controls are omitted\n   - the resulting PDF passes the same verification checks as the primary Chrome path\n\n   If no available local renderer can print the static HTML/export faithfully, stop and report the blocker with the missing capability and the source file that could not be converted.\n\n4. Verify the PDF itself.\n\n   Confirm page count and metadata with `pdfinfo` or equivalent. Extract text with `pdftotext` or equivalent when the PDF should contain selectable text. Render representative pages with `pdftoppm` or equivalent and inspect them for blank charts, clipped content, missing source details, unwanted controls, internal runtime metadata, and layout regressions. For short reports, render every page. Include a negative check for app-only control labels such as share, edit, refresh, publish, toolbar, menu, and drag affordances, plus internal artifact labels such as snapshot status, widget type, manifest path, package path, validation status, and local temp paths.\n\n5. Repair before handoff.\n\n   If the output is blank, clipped, missing charts, missing source details, or includes app-only chrome, fix the static HTML/export source, print stylesheet, or renderer invocation and regenerate. Do not hand off an unverified PDF unless the user explicitly accepts the limitation.\n\n6. Hand off the PDF.\n\n   Return the PDF path and, when useful, the source HTML path or URL. Keep routine check details in support artifacts. Do not list internal checks in the user-facing handoff unless a check failed, was unavailable, or produced a user-relevant caveat. If the static HTML/export had to be created from an artifact payload because the hosted URL did not expose one, say that briefly. If required checks could not be completed, state the gap clearly.\n\n## Standards\n\n- Preserve the reader-facing artifact content: title, narrative, charts, tables, caveats, source details, and generated-at or source freshness details when present.\n- Omit app-only controls: top bars, share menus, edit controls, refresh controls, drag handles, hover-only menus, and interactive-only affordances.\n- Omit internal artifact and conversion metadata from the visible PDF. Do not show raw runtime fields, implementation state, package labels, local paths, validator/debug labels, or status strings that exist only to operate the app or export pipeline. Keep audit-useful internals in support files, and use plain reader-facing caveats in the PDF when a data state affects interpretation.\n- Prefer a text PDF with selectable/searchable text. Use a screenshot/image PDF only when a faithful text PDF is not viable, and state that text may not be selectable or searchable.\n- Keep the static source as the PDF source of truth. Do not reconstruct the report from memory when a source HTML/export exists.\n- Do not create a model-authored PDF from scratch as a normal fallback. Direct PDF construction is acceptable only as an explicitly labeled last-resort workaround after the user accepts the quality limitation.\n- Keep generated PDF support files together when possible: static HTML source, PDF output, extracted text, page previews, and any notes about source retrieval or renderer fallback.\n\n## Verification Guidance\n\nBefore handoff, verify the PDF with the local tools available in the environment:\n\n- Confirm the PDF exists, is non-empty, and has the expected page count and page size.\n- Confirm text is selectable/searchable when a text PDF is expected.\n- Render or preview representative pages; for short reports, prefer checking every page.\n- Inspect for blank pages, clipped charts, missing tables, missing source details, unwanted app controls, and leaked internal artifact or conversion metadata.\n- If the skill file itself was edited, run the repository's normal markdown or diff checks.\n\nExamples when available: `pdfinfo`, `pdftotext`, `pdftoppm`, file-size checks, and `git diff --check`.\n\n<!-- File: packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/build-report/SKILL.md (Tokens: ~688 | Category: anthropic-skill) -->\n---\nname: build-report\ndescription: \"Build a durable analytical report with an answer-first narrative, evidence-backed findings, charts or tables, caveats, recommendations, and source context.\"\n---\n\n# Build an Analytical Report\n\nUse this workflow when the user needs a durable report rather than a transient answer. Run the appropriate analysis workflow first; this workflow owns the reader-facing structure, evidence placement, visual/table placement, caveats, sources, QA, and handoff.\n\n## Choose one delivery format\n\nHonor an explicit format. Otherwise use:\n\n1. Markdown for the most portable code-agent deliverable.\n2. Self-contained plain HTML when a polished browser-readable report is useful and the host can render or inspect it.\n3. PDF, DOCX, slides, or another format only when requested or clearly required by the destination and the host exposes suitable creation and verification tools.\n\nDo not install or require React, Recharts, Vite, MCP Apps, or widget runtimes. HTML must use semantic HTML/CSS and may use inline SVG or small vanilla JavaScript interactions. It must remain readable without JavaScript.\n\n## Build the report\n\n1. Confirm the audience, decision, scope, comparison window, and requested format from available context. Ask only when a missing choice would materially change the result.\n2. Verify the analytical evidence. Keep metric definitions, grain, time range, filters, units, exclusions, and source freshness explicit.\n3. Lead with the answer. State the most important conclusion and decision implication before methodology details.\n4. Build a coherent narrative rather than a dump of charts or query results.\n5. Include only visuals and tables that support a finding. Read `../visualize-data/SKILL.md` when creating charts.\n6. Distinguish verified facts, likely explanations, assumptions, limitations, and unresolved questions.\n7. Provide recommendations tied to evidence, expected impact, owner or next action, and measurable follow-up where appropriate.\n8. Add a source section that identifies real source systems, tables/views, datasets, files, documents, queries, and access dates when known. Never invent provenance.\n\n## Recommended structure\n\n```markdown\n# [Short reader-facing title]\n\n## Executive summary\n[Answer, magnitude, and decision implication]\n\n## Key findings\n[Evidence-backed findings with charts or tables]\n\n## Recommendations\n[Prioritized actions and expected outcomes]\n\n## Risks and limitations\n[Data gaps, assumptions, uncertainty, and interpretation limits]\n\n## Sources and methodology\n[Definitions, scope, source details, and reproducibility notes]\n```\n\nAdapt the headings to the audience, but retain the answer-first logic.\n\n## QA and handoff\n\n- Recalculate headline values and comparisons from the reviewed evidence.\n- Check that every claim is supported and every chart matches its source data.\n- Check titles, labels, units, denominators, date ranges, and sorting.\n- For HTML/PDF/DOCX/slides, render or inspect the actual artifact when the host supports it; fix clipping, blank charts, overflow, low contrast, and unreadable tables.\n- Ensure the report contains no credentials, local temporary paths, placeholder provenance, or internal implementation noise.\n- Return the primary artifact path plus only the relevant supporting notebook, SQL, data, or chart files.\n\nIf the user asks only for an inline brief or explicitly says no file/artifact, deliver the same answer-first structure concisely in chat.\n\n<!-- File: packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/create-data-context/SKILL.md (Tokens: ~1416 | Category: anthropic-skill) -->\n---\nname: create-data-context\ndescription: \"Create, update, inspect, or repair Data Analytics semantic layers. Use when the user asks to save data context or create a semantic layer that future Data Analytics work can inspect and cite.\"\n---\n\n# Create Data Context\n\nThis skill creates and maintains semantic-layer skills for Data Analytics. A semantic-layer skill is an explicit artifact the user can inspect and cite later. It captures how future analyses should interpret the data, for example which metric definition is canonical, which dashboard or table is the best source of truth, and what caveats should be checked before answering.\n\nData-task routing is owned by the Data Analytics `index` skill. If the user wants Data Analytics to do work with data now, route to `index`, whether the work starts from connected sources, uploaded files, pasted tables, sample data, or an existing semantic layer. Examples include answering a metric question, building a report, or checking a dataset.\n\nUse this skill only when the user asks to save data context or create, update, inspect, or repair a semantic layer.\n\n## Runtime Routing\n\nUse the current runtime's classified `surface` and `mode` values, plus the capabilities exposed in the run, to choose intake and persistence. Build and validate the same canonical semantic-layer skill package before writing it to any destination.\n\nFor intake:\n\n- Use structured intake when a supported form action is available.\n- Use conversational intake for open-ended details and for runtimes without a supported form action.\n\nChoose one persistence destination by default:\n\n| Destination branch | Select this branch when | Action |\n| --- | --- | --- |\n| ChatGPT personal Skills | `surface = chatgpt_web` and the run exposes a product-backed personal Skills install surface, such as a native skill draft/upload/install action or an installable skill package preview. | Install the generated skill into the user's personal Skills library. Capture the installed skill link or Skills-library reference returned by the install surface and include it as a Markdown link in the chat response. Verify through the available Skills-library, list, or fresh-thread discovery surface when the runtime exposes one. |\n| Local Codex | The user asks for local persistence, or `surface = codex_desktop`. | Write a filesystem skill to `$CODEX_HOME/skills/<area>-semantic-layer`; if `$CODEX_HOME` is unavailable and the local runtime clearly uses the default home location, use `~/.codex/skills/<area>-semantic-layer`. Validate the written skill and verify it is discoverable in a new local Codex context when possible. |\n| Portable package | The current run has no supported persistent skill destination. | Return a portable skill package or source plan and clearly state that it has not been installed persistently, including the exact persistence blocker. |\n\nFor dual ChatGPT web and local Codex availability, install the same canonical package into both the ChatGPT Skills library and the local Codex user-skill directory.\n\nFor ordinary data work, return to the Data Analytics `index` workflow.\n\n## Skill Configuration\n\n### Audience And Language\n\nWrite for Data Analytics users, not plugin maintainers. Explain what context would improve the current or future analysis in practical terms. Avoid implementation terms such as raw state paths, connector ids, cache, runtime, metadata, or preflight unless the user asks for debugging details.\n\n### Source Links\n\nWhen referencing sources inline, prefer clickable Markdown links over plain labels whenever a useful URL exists. Use the source title, record name, channel/thread, or meeting/date as the link text. Use plain labels only when no useful link is available.\n\n## Semantic Layer Setup\n\nUse this flow when the user wants to create or maintain a semantic layer. If they are not ready to create the layer yet, use the same flow to produce a short source plan for what the semantic layer needs.\n\nThe output is a visible skill or plan. Build the semantic-layer skill when enough source-backed detail exists to make it useful. When the available detail is still thin, return a practical plan that explains what source to collect next and why.\n\n## Creating Or Updating The Layer\n\nCreate one semantic layer per coherent product, business, metric, source, or reporting area unless the user explicitly asks for a broader shared layer. Infer the area from the provided context when it is clear; ask only when the answer changes the crawl, destination, or resulting skill.\n\nChoose the destination from `Runtime Routing` using the supported persistence mechanism exposed in the current run. For local Codex creations, default to `$CODEX_HOME/skills/<area>-semantic-layer` unless the user chooses another destination. Ask before placing a generated semantic-layer skill inside a plugin.\n\nBefore crawling, build a data-source list that explains what was checked, what is missing, and which sources are lower-confidence. For direct creation or draft-file work, write it to `references/source-inventory.md`; for planning-only work, return it in chat.\n\nUse source-backed evidence. Favor durable sources such as transformation code, tests, maintained metric docs, and verified dashboards over looser signals such as query history or team discussion. If sources disagree, keep the conflict visible instead of choosing silently.\n\nKeep generated semantic-layer skills compact. Put detailed metric definitions, tables, query patterns, caveats, and evidence into linked references using `references/semantic-layer/skill-template.md`. Preserve provenance and avoid copying raw sensitive data, credentials, row-level examples, or long private messages into generated files.\n\nAfter creating or updating a semantic-layer skill, read `references/semantic-layer/weekly-polling-automation.md` and always offer weekly refresh when the layer has a stable target path and usable `references/source-inventory.md`. Weekly refresh is optional: do not create it without explicit user approval unless the user directly asked for recurring refresh. If the offer cannot be made, state the missing prerequisite.\n\nReturn the created or updated path or installed skill link, source coverage, any user-relevant caveats or blockers, future-use guidance, iteration guidance, and the weekly refresh automation offer or prerequisite blocker so the user can cite the semantic layer directly in later prompts. Tell the user they can ask to refine definitions, add sources, update caveats, or adjust the semantic layer as their understanding changes. For ChatGPT personal Skills creations, include the installed skill link in the response.\n\nKeep routine validation details in support artifacts unless a check failed, was unavailable, or changes how the user should rely on the semantic layer.\n\n## Output Contract\n\nFor semantic-layer work, report what was created, updated, inspected, or repaired; source coverage; any user-relevant caveats or blockers; and the exact path or installed skill link the user can cite later. For create or update results, include the weekly refresh automation offer or the missing prerequisite that prevented the offer, and let the user know they can iterate on the semantic layer. Keep routine validation details in support artifacts. If the request is ordinary data work, say that it should be routed through `index`.\n\n<!-- File: packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/design-kpis/SKILL.md (Tokens: ~1716 | Category: anthropic-skill) -->\n---\nname: design-kpis\ndescription: \"Design KPI frameworks, metric definitions, targets, guardrails, and measurement plans for product or business decisions. Use when success metrics, drivers, guardrails, targets, or the measurement approach need to be defined or improved.\"\n---\n\n# Design KPIs\n\nDesign KPI frameworks, set targets, and develop measurement plans that help teams make product or business decisions.\n\n## When To Use Data Quality First\n\nUse $analyze-data-quality first when the task is to reconcile existing metrics, dashboards, tables, owners, or sources of truth.\n\nReturn to this skill only when the user asks to define the metric going forward, redesign the KPI framework, choose guardrails, or set targets.\n\n## Skill Configuration\n\n### Source Discovery And Verification\n\nUse the relevant semantic layer as a starting map, not a boundary.\n\n1. **Explore all possible sources.** Search every connected or provided source that could contain task-relevant data or change the interpretation. Within each structured-data source, run fresh catalog or metadata discovery for relevant schemas, datasets, tables, views, models, and metrics. Known sources, tables, dashboards, and semantic mappings are starting points, not stopping points.\n2. **Compare duplicates and conflicts.** When sources overlap or disagree, compare ownership, freshness, definition, grain, coverage, and directness. Use the best authoritative source, or combine complementary sources when needed. Note material conflicts, explain why the selected source or sources control the answer, and verify selected data through live reads before concluding.\n\n### Source Access Guardrail\n\nBefore querying sources, building artifacts, or drawing conclusions, determine whether the answer requires a specific source of truth.\n\nIf a required source is unavailable, stop that path. Tell the user what source is needed, ask them to make it available or provide a reviewed fallback, and do not treat weaker substitutes as equivalent.\n\nIf the missing source is only optional enrichment, continue with the strongest available evidence and label the gap when it materially affects the answer.\n\nClarify with the user when a missing input would materially change the analytical frame or recommendation. Otherwise make a reasonable assumption, state it, and proceed.\n\n## Workflow\n\n### 1. Clarify The Decision And Operating Context\n\nUnderstand the decision the metrics need to support, the context in which they will be reviewed, and who will act on the result. Ask the user to clarify the goal, operating cadence, or measurement constraints when missing or ambiguous input would change the recommendation.\n\n### 2. Gather Evidence Before Recommending Metrics\n\nWhen the prompt does not already provide enough context to know what success means, gather that context before recommending metrics or targets. Use $gather-business-context to understand the goal, current state, audience, constraints, risks, existing definitions, prior decisions, and any baseline or target context that should shape the metric system.\n\nFor KPI design, use that context to clarify what success is meant to mean, how related metrics have been defined before, and which constraints or risks should affect the recommended KPIs, drivers, guardrails, or measurement plan.\n\n### 3. Generate A Wider Candidate Set\n\nCreate candidate outcome, driver, and guardrail metrics before narrowing.\nEach candidate should have a clear definition and a plausible link to the decision. Use the example metric shapes below as inspiration when helpful, not as a required template.\n\n### 4. Compare And Select Metrics\n\nCompare candidate metrics by whether they:\n\n- reflect the goal: the metric should represent the intended outcome. When using a proxy, explain why it should reflect real progress and where it could mislead.\n- inform a real decision: movement should change what the team does, prioritizes, or investigates.\n- show useful signal at the decision cadence: a metric can be conceptually good but too slow-moving or noisy for the decision it supports. For example, annual retention may be the right outcome, but it may not help a weekly launch review unless paired with earlier indicators.\n- can be influenced by the team: the team should have plausible levers, or the metric should be paired with drivers it can affect.\n- can be measured operationally: the team should be able to instrument, calculate, and track the metric consistently without one-off manual work.\n- are hard to improve in a misleading way: improving the metric should not obviously hide harm to quality, trust, retention, cost, or another important outcome.\n\nUse lightweight scoring only when it helps explain tradeoffs. Recommend `1-3` primary KPIs, `1-2` driver metrics for each KPI when they improve diagnosis, and `1-2` guardrails when tradeoffs are likely. Do not recommend extra metrics unless they materially improve decision-making.\n\nFor each recommended metric, include enough detail for the team to use it: what it measures, why it matters, how it is calculated, where it comes from, its main pros and cons against the selection criteria above, and what caveats or guardrails matter.\n\n### 5. Set Targets When Needed\n\nTreat target setting as a separate judgment from metric selection. First decide what should be measured; then set targets when the user asks or when the recommendation needs a threshold to be useful.\n\nUse the target-setting approach that best fits the evidence:\n\n- Top-down: start from benchmarks, historical performance, comparable products, competitor or market context, or a reasoned view of what good would need to look like for the decision.\n- Bottom-up: start from what the team can realistically do, such as what is shipping, how adoption is expected to build, or which operating levers should move the metric.\n\nUse data to set or evaluate targets. Once the target-setting approach is clear, identify what data it requires, such as provided inputs, internal performance data, external benchmarks or market data, and results from similar past work.\n\nCompare aspirational targets with what the team can realistically influence through planned work, available audience, expected adoption, and historical movement. A good target should be meaningful for the decision and plausible enough to guide action. Explain the target anchor, key assumptions, and confidence. If the strongest target-setting method requires missing inputs, share the methodology and ask whether the user can provide or identify the relevant data. If there is still enough evidence for a directional target, present it as a provisional range; otherwise recommend the measurement needed before setting a firm target.\n\n### 6. Deliver The Recommendation\n\nKeep the final recommendation concise and decision-oriented, and deliver it inline by default. Do not load `$build-report` merely because the KPI framework uses evidence, compares candidates, or contains several metrics. Use `$visualize-data` and `$build-report` when a data visual would materially improve the answer, such as by showing how a proposed target compares with historical performance or benchmarks, or by clarifying tradeoffs or candidate scoring. Honor an explicitly requested report, dashboard, notebook, spreadsheet, native document, or slide deck as the primary artifact. The recommendation should include:\n\n1. initiative summary\n2. recommended metric candidates, with definition and rationale\n3. target recommendation, if included, with anchor, assumptions, and methodology\n4. evidence reviewed\n5. assumptions and missing context\n6. risks and guardrails\n7. open questions\n\n## Example Metric Shapes\n\nDifferent contexts need different metric shapes. Use these as examples, not a template:\n\n- Product launch or adoption: pair an outcome metric for adoption or value realization with drivers for activation, engagement, repeat use, or time to value, plus guardrails for experience quality.\n- Growth work: choose the business outcome the team is trying to improve, such as activation, retention, or monetization; add drivers that explain how growth is expected to happen and guardrails for quality.\n- Funnel work: choose the progression or completion outcome that represents success; add drivers around where people advance or drop off and guardrails for downstream quality.\n- Operating review: focus on health, pacing, and action-oriented metrics that show whether the business is on track and where attention is needed.\n- Experiment or intervention: use one primary success metric tied to the decision, diagnostics that explain movement, and guardrails for unintended effects.\n- Data, model, or analytics initiative: connect technical performance to the decision or workflow it improves, with adoption, reliability, cost, or fairness guardrails when relevant.\n- Platform, reliability, or operations work: measure service health, throughput, quality, cost efficiency, and customer impact in terms the owning team can act on.\n\n<!-- File: packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/gather-business-context/SKILL.md (Tokens: ~1409 | Category: anthropic-skill) -->\n---\nname: gather-business-context\ndescription: \"Gather business context from connected or provided sources so downstream analysis starts with the right framing. Use when an analytical question depends on missing context, such as what a metric means, what changed recently, or which sources should be checked. If the same prompt asks for diagnosis, recommendation, or a deliverable, gather context first and continue to the focused skill.\"\n---\n\n## Boundary\n\nUse this skill to gather framing context, not to complete the downstream analysis.\n\nIf the same request also asks for a diagnosis, recommendation, dashboard, report, or other analytical deliverable, return only the context needed for that next step and continue with the appropriate focused skill, such as $metric-diagnostics, $product-business-analysis, $build-dashboard, or $build-report.\n\n# Gather Business Context\n\nUse this skill to collect the business context needed to understand an analytical question before doing deeper work. Focus on what the topic is, why it matters, what changed or is being decided, who or what source is closest to the work, and which definitions or artifacts should frame the analysis. This is a retrieval and extraction skill: gather enough context to set up the next step, not a final report, root-cause analysis, or broad background scan. Skip it when the prompt already provides the needed context or the task is fully self-contained.\n\n## Workflow\n\n### 1. Identify The Retrieval Target\n\nEstablish the analytical topic that needs context and why it matters for the next step. Capture the boundary needed to search and interpret sources, such as the relevant product area, audience, time period, or decision. If the timeframe is missing, use the narrowest reasonable window implied by the task and label it as an assumption.\n\n### 2. Build Search Anchors\n\nSearch with concrete identifiers rather than broad topic guesses. Start with the names the user provided or the sources surfaced, then expand with adjacent terms that help recall, such as aliases, owners, teams, dates, source names, related entities, or entities found in earlier results.\n\nStart broad enough to avoid missing relevant context. If too much comes back and a quick scan suggests the results are mostly unrelated, combine anchors to narrow retrieval, for example a metric plus a dashboard name, a feature plus a launch window, or a customer plus the relevant workflow. If a likely source comes back thin, revise the anchors before treating the source as missing.\n\n### 3. Search From Discovery Points Toward Authoritative Artifacts\n\n1. **Explore all possible sources.** Search every enabled or provided source family that could contain useful context or task-relevant data. Within each structured-data source, run fresh catalog or metadata discovery for relevant schemas, datasets, tables, views, models, and metrics. User-named sources, known tables, dashboards, and semantic-layer anchors are starting points, not stopping points.\n2. **Compare duplicates and conflicts.** When sources overlap or disagree, compare authority, freshness, definition, scope, and directness. Prefer artifacts closest to what was decided, defined, implemented, or measured; follow linked evidence when useful. Note material conflicts and explain which source or combination should guide downstream analysis.\n\n### 4. Extract Only Decision-Shaping Context\n\nTreat business context as a fixed extraction target, not an open-ended summary. Capture the facts that will shape the downstream analysis: the topic's business meaning, why it matters now, how it is defined or measured, where to verify it, what recently changed, and what uncertainty should travel with the analysis. Examples can include a metric definition, current rollout state, dashboard link, owner note, source conflict, or stated next step.\n\nKeep the context note focused on details that help frame the next analysis. Skip broad background, adjacent history, or long source excerpts unless they add useful context.\n\n### 5. Keep Source Notes Compact And Attributable\n\nFor each useful source, record enough attribution for the downstream work to be checked later: when the source applies, what kind of source it is, what factual context it established, and any important caveat or conflict. Distinguish source facts from inference and do not imply source review, stakeholder views, metric certainty, or confidence beyond what was actually established.\n\n### 6. Reconcile Conflicts Explicitly\n\nWhen sources disagree in a way that could change the downstream framing, preserve the disagreement instead of smoothing it over. Prefer the newest explicit decision artifact over older plans, owner-written docs over third-party summaries, and implementation artifacts over aspirational plans when the question is what is live, shipped, logged, or queryable now. Treat an informal source as stronger than a canonical artifact only when it clearly records a later decision or owner confirmation.\n\nIf disagreement remains, present both views, label the conflict, and state what source or owner would resolve it. If context is stale or incomplete, say what is missing and where to look next.\n\n### 7. Stop Once The Framing Is Sound\n\nStop gathering context when the downstream task can be framed well enough to proceed and the likely enabled or provided source families have been checked, ruled out as unavailable, or identified as too thin. Before stopping, make sure the next step has a clear enough understanding of the topic, why it matters, where the important definitions came from, what recent context applies, and what gaps remain.\n\nContinue searching when a relevant enabled or provided source is likely to add useful context. If an expected source was not found, name that as a gap rather than implying it does not exist.\n\n### 8. Return A Lightweight Context Note When Useful\n\nPrefer a focused context note over a full report or raw retrieval dump. Include enough context for the next analysis to proceed without redoing the search: a short summary, the relevant context, important definitions or source links, uncertainty or caveats, and citations. Keep it readable, but do not compress away details that explain the framing or source quality.\n\nIf the user asked only for quick orientation, shorten the structure while preserving citations, conflicts, and missing canonical artifacts.\n\n## Standards\n\nJudge sources by what they can actually establish. Informal discussion can be useful for discovery and recent context, but durable artifacts are usually stronger evidence for definitions, decisions, status, and measured results once found. Prefer sources close to the work, recent enough to reflect current reality, and explicit about what they establish. Surface missing source-of-truth artifacts as context gaps.\n\nKeep important claims attributable. Treat a source as useful only when it clarifies how the downstream task should be framed or interpreted; sources that merely mention the topic are incidental. Preserve enough evidence to check the work later, and label interpretation, assumptions, conflicts, and uncertainty when support is thin, stale, indirect, or conflicting.\n\nPreserve disagreements that could change the framing. Prefer owner-authored or decision-adjacent material and evidence of what is current over secondhand summaries or speculation. Do not infer consensus from silence. Say what source or owner would resolve an important conflict.\n\n<!-- File: packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/index/SKILL.md (Tokens: ~837 | Category: anthropic-skill) -->\n---\nname: index\ndescription: \"Route broad Data Analytics requests to the appropriate quantitative analysis, visualization, dashboard, report, notebook, KPI, market-sizing, validation, or semantic-layer workflow.\"\n---\n\n# Data Analytics Router\n\nUse this workflow when Data Analytics is explicitly invoked or the request requires structured records, quantitative evidence, metrics, or an evidence-backed product or business decision. Do not use it for ordinary prose drafting, file-format conversion, or qualitative description that does not require data interpretation.\n\n## Choose the focused workflow\n\n- Metric changed, missed a target, or differs from expectation: read `../metric-diagnostics/SKILL.md`.\n- Product or business decision, prioritization, segmentation, launch, or experiment recommendation: read `../product-business-analysis/SKILL.md`.\n- Dataset, dashboard, source, join, freshness, grain, or metric trust question: read `../analyze-data-quality/SKILL.md`.\n- KPI framework, canonical definition, target, driver, or guardrail design: read `../design-kpis/SKILL.md`.\n- KPI status update, WBR, MBR, QBR, or operating readout: read `../kpi-reporting/SKILL.md`.\n- Dashboard or monitoring view: read `../build-dashboard/SKILL.md`.\n- Durable analytical report: read `../build-report/SKILL.md`.\n- Chart or quantitative figure: read `../visualize-data/SKILL.md`.\n- Reproducible SQL/Python notebook: read `../jupyter-notebooks/SKILL.md`.\n- TAM, SAM, SOM, segment, or opportunity sizing: read `../market-sizing/SKILL.md`.\n- Review an analysis before sharing: read `../validate-data/SKILL.md`.\n- Create, repair, or save reusable data context or a semantic layer: read `../create-data-context/SKILL.md`.\n- Missing business definitions, ownership, change context, or decision framing: read `../gather-business-context/SKILL.md` before the primary workflow.\n\nLoad every selected workflow completely. Follow its related-skill rules when applicable. A task can combine workflows; use this usual order:\n\n1. Gather missing business context.\n2. Validate source quality and metric definitions.\n3. Perform the focused analysis.\n4. Validate conclusions.\n5. Visualize or create the requested durable artifact.\n\n## Source access\n\nUse the best source already available through the code-agent harness: local files, uploaded data, pasted results, databases, warehouses, BI systems, product analytics tools, notebooks, documents, or callable connectors. Tool availability is determined by the host, not by this skill.\n\nWhen no usable source is available:\n\n- Ask for the smallest useful artifact: a CSV/XLSX file, query result, schema, metric definition, dashboard export, screenshot, or pasted table.\n- Offer `assets/demo-product-growth.csv` only as a clearly labeled synthetic demonstration. Never use sample data to answer a real-data question.\n- Do not invent records, measurements, source access, or query results.\n\nIf available sources conflict in a way that changes the answer, surface the conflict and use the data-quality workflow. Otherwise choose the most authoritative and fresh source and proceed.\n\n## Portable output policy\n\nThis bundle targets a generic code agent and does not depend on React, MCP Apps, widgets, or a proprietary rendering surface.\n\n- Inline answers: concise Markdown with findings, evidence, caveats, and next actions.\n- Reports: Markdown by default; use self-contained plain HTML, PDF, DOCX, or another requested format only when the host can create and verify it.\n- Charts: use reproducible Python/Matplotlib, notebook-native plotting, SVG, or destination-native chart tools.\n- Dashboards: prefer a self-contained plain HTML/JavaScript artifact, Streamlit when Python execution is appropriate, or an existing BI platform selected by the user.\n- Notebooks: keep SQL/Python reproducible and make assumptions visible.\n\nPreserve source names, metric definitions, grain, time windows, filters, units, and uncertainty. Never expose credentials, secrets, hidden reasoning, or unnecessary personal data.\n\n<!-- File: packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/jupyter-notebooks/SKILL.md (Tokens: ~1550 | Category: anthropic-skill) -->\n---\nname: jupyter-notebooks\ndescription: \"Create, edit, or validate reproducible SQL or Python notebooks. Use for notebooks, SQL/Python scratchpads, reproducible exploration, audit trails, or runnable companions where the analysis should be reviewable or rerunnable.\"\n---\n\n## Related Skills\n\nUse $validate-data when notebook results support a recommendation, shared claim, or decision.\n\n# Jupyter Notebooks\n\nCreate clean, reproducible Jupyter notebooks that are easy to skim, rerun, and handoff. Treat the notebook as a reader-facing analysis artifact, not a scratchpad dump. Notebook work is not complete until the notebook executes successfully top-to-bottom, or the execution gap is called out with the exact validation steps needed to reproduce it.\n\n## Workflow\n\n1. Lock the notebook mode and scope.\n\n   Decide whether the notebook is an analysis report, experiment log, diagnostic notebook, data-quality check, market-sizing calculation, model exploration,\n   tutorial, or companion artifact for a report. Identify the reader, decision,\n   expected handoff, required inputs, and whether the task calls for a new notebook or targeted edits to an existing one.\n\n2. Inspect or scaffold with notebook-safe tooling.\n\n   Prefer JupyterLab, `nbformat`, `nbclient`, or an existing scaffold utility over hand-editing raw JSON. When editing an existing notebook, preserve its intent and minimize JSON churn. Avoid reordering cells unless it clearly improves the top-to-bottom story. If raw JSON editing is unavoidable,\n   validate the notebook structure before finishing.\n\n3. Structure the notebook for the chosen mode.\n\n   For analytical notebooks, default to:\n\n   1. `## tl;dr`\n   2. `## Context & Methods`\n   3. `## Data`\n   4. `## Results`\n   5. `## Takeaways`\n\n   Write `tl;dr` and takeaways after reviewing executed outputs. Use concrete observed values, visible patterns, rows, or charts, not assumptions. Include a `### Key Assumptions` subsection in `Context & Methods` when assumptions affect correctness.\n\n   For tutorials or walkthroughs, adapt the same discipline to a teaching flow:\n\n   1. `## Goal`\n   2. `## Setup`\n   3. `## Steps`\n   4. `## Checks`\n   5. `## Next Steps`\n\n4. Build a clear data and computation path.\n\n   Separate setup, imports, parameters, data loading, data preparation,\n   calculations, visualizations, and interpretation. If the notebook uses both SQL and Python, keep complex SQL in SQL cells or separate query files rather than large embedded Python strings unless there is a clear reason. Use descriptive variable names and keep each code cell focused on one step.\n\n5. Use data sources deliberately.\n\n   When a notebook needs table data, first use `~~structured_data` to confirm table choice, schema, partition filters, sample rows, and query-submission policy. Use the relevant source connector when available, then fall back to exports or pasted SQL when needed. Use `~~operations_logs` for freshness or lineage checks when they matter. Record query permalinks, request IDs, source paths, dashboard links,\n   extract names, or other source artifacts in the notebook context for any executed result that supports the analysis. Keep heavy queries filtered and bounded instead of turning the notebook into a broad live-source scan.\n\n6. Make cells readable and bounded.\n\n   Add concise markdown headers before most code cells. Keep headers brief and action-oriented, such as `### 1. Load Data`, `### 2. Validate Inputs`, or `### 3. Plot Results`. Favor several short cells over one large mixed-purpose cell. Keep prose short: explain purpose, assumptions, and expected result, not every line of code. Split multiple tables or charts across separate cells instead of dumping all outputs from one cell.\n\n7. Validate results before writing conclusions.\n\n   Check that key numbers, charts, and takeaways match executed outputs. Bound raw debug output, oversized tables, and noisy logs. If a result is surprising, add a local reasonableness check, small sample inspection, or reconciliation against a trusted source before promoting it to the summary.\n\n8. Execute and record validation status.\n\n   Run the notebook top-to-bottom when the environment allows:\n\n   ```bash\n   python -m jupyter nbconvert --execute --to notebook --inplace path/to/notebook.ipynb\n   ```\n\n   Optional local setup when needed:\n\n   ```bash\n   uv pip install jupyterlab nbformat nbclient ipykernel\n   ```\n\n   If execution is not possible, say so explicitly and provide the exact command,\n   missing dependency, credential, data access, kernel, or environment step needed to validate locally.\n\n## Standards\n\n### Notebook Structure\n\n- Make the default top-to-bottom read clear before the reader starts executing cells out of order.\n- Put executive summary material at the top, but write it last after inspecting executed results.\n- Keep notebook sections aligned with the notebook mode: analysis, experiment,\n  diagnostic, tutorial, or handoff artifact.\n- Keep section titles, chart titles, labels, and file names descriptive enough for handoff.\n- Preserve the existing notebook's intent when refactoring; improve structure without rewriting everything by default.\n\n### Reproducibility\n\n- Keep parameters, date ranges, filters, cohorts, assumptions, and source references visible near the top of the notebook.\n- Record enough source context for another reader to trace the analysis: query permalinks, request IDs, table names, source paths, spreadsheet tabs,\n  dashboard links, extract versions, or input file locations.\n- Make computation deterministic where possible. Avoid hidden state, manually edited intermediate values, out-of-order dependencies, and unexplained cached outputs.\n- Prefer explicit environment setup cells or notes when the notebook depends on nonstandard packages, kernels, credentials, or local files.\n- Execute the notebook when the task requires a runnable artifact. In the final response, do not add a separate routine validation section for a clean run; surface execution gaps, partial execution, or unrun notebooks with the reason because those affect whether the user can rely on the artifact.\n\n### Code And Data Hygiene\n\n- Separate data preparation from presentation.\n- Keep complex SQL readable and documented with a one-line goal comment.\n- Keep plotting and lightweight shaping in Python after the data preparation step is complete.\n- Use descriptive variable names and avoid abbreviated temporary names in reader-facing notebooks.\n- Keep outputs bounded. Prefer small preview tables, sampled rows, explicit limits, and focused charts over raw dumps.\n- Avoid broad live-source scans. Filter queries by needed partitions, cohorts,\n  or time windows.\n\n### Analysis Quality\n\n- Make assumptions explicit when they affect interpretation.\n- Tie takeaways to executed outputs with concrete numbers, rows, charts, or visible patterns.\n- Do not promote unexecuted or unverified calculations into the `tl;dr`.\n- Label caveats, incomplete checks, missing source access, and known validation gaps.\n- Add reasonableness checks for surprising results, high-impact claims, or stakeholder-facing conclusions.\n\n### Validation Checklist\n\n- Required section order is present for the notebook mode.\n- The notebook executes without runtime errors, or execution failure is called out explicitly.\n- Outputs are present where expected and are not dominated by raw debug dumps.\n- The `tl;dr`, results, and takeaways match executed cells.\n- Source references and query or artifact links are preserved.\n- Tables and charts are labeled, bounded, and interpretable.\n- The final response includes the notebook path and validation status.\n\n<!-- File: packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/kpi-reporting/SKILL.md (Tokens: ~2422 | Category: anthropic-skill) -->\n---\nname: kpi-reporting\ndescription: \"Prepare KPI readouts, scorecards, WBR/MBR/QBR updates, and executive summaries from quantitative business or product metrics; use when the task is to report status, compare against targets, explain validated drivers, and state operating implications.\"\n---\n# KPI Reporting\n\nUse this skill to turn business or product metrics into decision-ready operating readouts for leaders and teams. The job is to define the KPI contract, report status against the right comparison and target, include validated driver context, and state the operating implication clearly.\n\nClarify with the user when a missing input would materially change the analytical frame or recommendation. Otherwise make a reasonable assumption, state it, and proceed.\n\nThis skill owns the KPI readout: what should be reported, how metrics should be interpreted, whether driver context is validated, and what operating takeaway follows. It does not own metric-system design, new driver investigation, or final artifact polish.\n\nUse $metric-diagnostics when the readout needs fresh driver investigation, then return here to package the validated finding.\n\n## Skill Configuration\n\n### Source Discovery And Verification\n\nUse the relevant semantic layer as a starting map, not a boundary.\n\n1. **Explore all possible sources.** Search every connected or provided source that could contain task-relevant data or change the interpretation. Within each structured-data source, run fresh catalog or metadata discovery for relevant schemas, datasets, tables, views, models, and metrics. Known sources, tables, dashboards, and semantic mappings are starting points, not stopping points.\n2. **Compare duplicates and conflicts.** When sources overlap or disagree, compare ownership, freshness, definition, grain, coverage, and directness. Use the best authoritative source, or combine complementary sources when needed. Note material conflicts, explain why the selected source or sources control the answer, and verify selected data through live reads before concluding.\n\n### Source Access Guardrail\n\nBefore querying sources, building artifacts, or drawing conclusions, determine whether the answer requires a specific source of truth.\n\nIf a required source is unavailable, stop that path. Tell the user what source is needed, ask them to make it available or provide a reviewed fallback, and do not treat weaker substitutes as equivalent.\n\nIf the missing source is only optional enrichment, continue with the strongest available evidence and label the gap when it materially affects the answer.\n\n## Workflow\n\n### 1. Clarify The Readout Purpose\n\nUnderstand who the readout is for, what conversation it supports, and what is being reported before drafting. Anchor the update in the period being evaluated, the comparison or target that makes performance interpretable, and the freshness cutoff.\n\nAsk the user for missing context when it would help make the readout more accurate or useful.\n\n### 2. Define The Metric Framework\n\nDecide which metrics belong in the readout and what role each one plays before pulling numbers. If the framework already exists, confirm it and use it. If it is missing or weak, use $design-kpis before reporting.\n\nStart with the primary KPI, then add the smallest set of supporting metrics needed to explain status. Supporting metrics can explain movement, guard against harmful tradeoffs, or show whether performance is pacing as expected.\n\nLead with the metric that matters most to the audience. Do not add every available cut or comparison; include the metrics and slices decision-makers actually use, plus any that materially explain this update.\n\nWhen the primary KPI is top-line, composite, or otherwise not directly actionable, define its driver decomposition before interpreting it. Use an existing metric tree when available. Otherwise identify the smallest useful set of component drivers, such as numerator and denominator, volume and rate, mix, funnel stages, segments, cohorts, or operational inputs. Do not invent a causal hierarchy when source definitions do not support one.\n\n### 3. Lock Metric Definitions And Sources\n\nConfirm the KPI definition, source, time window, reporting cutoff, comparison period, and any target or pacing expectation before interpreting performance. If a target or pacing basis is missing, ask before treating one as authoritative. Use $analyze-data-quality when source quality issues could change the reported metrics.\n\nFor all KPI updates, make a focused source pass across `~~structured_data`, `~~company_docs`, `~~team_communication`, and `~~dashboards_or_bi` before drafting. Do not infer from a sparse prompt that source-backed actuals are unavailable. Use structured data for actuals, metric definitions, and comparison periods; use the other lanes for additional business context and source-of-truth guidance.\n\nIf any core definition is unclear, ask the user to clarify before making precise claims. When a metric definition changed, show comparable restated history when available; otherwise call out the break clearly.\n\n### 4. Pull The Topline Actuals\n\nDo not draft or render a WBR, MBR, scorecard, or KPI update from placeholders. Query or inspect connected structured-data sources for core actuals first. If actuals are blocked or insufficient, stop and say what source or access is needed unless the user explicitly asked for a template or mockup.\n\nReproduce the topline actual before explaining movement or driver context.\n\nFor each headline KPI, include the current value, the absolute and relative change versus the comparison period, and a short interpretation.\n\nCall out anything that makes the current value hard to compare with the prior period before interpreting the movement, such as a tracking change, data backfill, partial outage, or missing day.\n\n### 5. Put The Numbers In Context\n\nCompare actuals against the context that makes performance interpretable. When a target, plan, pacing model, benchmark, historical range, or relevant peer group is defined, identify it and compare performance against it before judging status.\n\nIf the goal has a deadline, do not just report whether the metric is above or below target. Show whether it is on pace to hit the target by the end of the period. Use the provided pacing definition when available. If none is defined or found, ask the user; when proceeding with a calculated fallback, state that it was calculated and explain the method.\n\nWhen useful, include absolute and percent variance to target and a red/yellow/green status. Make clear what comparison or pacing basis the status label uses.\n\n### 6. Explain Validated Drivers\n\nKPI updates need driver context, but driver claims must be validated before they are presented as explanations. A plausible story is not enough.\n\nWhen the readout needs to explain drivers, use $metric-diagnostics to identify and validate them. If trusted reporting or prior analysis already validates the drivers, use that evidence instead of re-running the diagnostic.\n\n### 7. Add Business Context And Operating Implications\n\nAfter identifying the likely drivers, use $gather-business-context to look for business context that helps explain what happened and what it means for the readout. Let the driver analysis guide what context to look for, and connect context to the metric only when evidence supports the link.\n\nTranslate the evidence, driver analysis, and business context into the operating implication for the business. State whether the movement is concerning, what next step or action is warranted, and whether the main KPI is on track, at risk, or ahead of plan. Recommend action only when the evidence supports it; otherwise name the next validation step.\n\n### 8. Validate The Readout\n\nAfter the analysis is assembled and before shaping the final readout, use $validate-data to review whether the numbers, methodology, caveats, and evidence support the claimed status, drivers, and implications. Resolve material issues before sharing; carry remaining limitations into the readout.\n\n### 9. Hand Off The Readout\n\nEnd by handing the validated KPI readout to $build-report unless the user explicitly requests an inline, chat-only, brief/no-artifact answer, asks not to create a report/file/artifact, or selects another primary artifact. A quick status update, brief readout, or findings-in-chat request is an inline output choice unless the user also asks for a report, document, deck, or durable artifact. When no explicit human waiver was given, the report handoff is mandatory; do not infer a waiver only because the user did not use the word \"report\".\n\nBefore handoff, make the readout explicit:\n\n- headline status and operating implication\n- actuals, targets, pacing basis, and comparison periods\n- validated drivers and unresolved uncertainty\n- audience, cadence, and requested delivery surface when known\n- charts or figures that would clarify the readout\n\nLoad `references/report-templates.md` before handing off and use the matching pattern as source notes for $build-report. Tell $build-report this is a KPI readout and pass the status, pacing, driver, uncertainty, audience, cadence, surface, and visual guidance above. Do not render charts directly from this skill; pass visual intent and supporting evidence to $build-report so $visualize-data owns chart selection and QA.\n\nFor slide or deck requests, use $build-report to create a portable source report first, then use an available presentation workflow or document tool to create and verify the deck. Preserve the same source evidence and findings across formats.\n\n## Standards\n\n### Metric Standards\n\n- Never present a KPI as precise when its definition, source, time window, or comparison basis is unclear.\n- Make calculation logic, inclusion or exclusion rules, grain, and time treatment explicit when they affect interpretation.\n- Reconcile totals and compare against prior reporting when possible.\n- Do not compare periods, cuts, or targets that are not definitionally compatible. Call out definition changes, backfills, denominator shifts, or calendar effects when they affect the movement.\n\n### Status And Pacing Standards\n\n- Include the headline takeaway, current actual, relevant comparison, target or pacing context, driver summary, and implication unless the user asks for a narrower readout.\n- Put actuals next to the target, plan, benchmark, or baseline when available so the reader can judge performance immediately.\n- If a target is time-bound, show whether current performance is on pace using the provided pacing definition or a clearly stated calculated fallback.\n- Keep recurring metric sections consistent across runs. If a requested section is missing because data, definitions, or validation are unavailable, explain the omission briefly.\n- Use traffic-signal status only when it helps prioritize action. Pair color with text and state the basis for the status.\n- Round numbers consistently, label units, and surface caveats when they change interpretation.\n\n### Driver Standards\n\n- Quantify drivers whenever the evidence supports it; do not use descriptive prose as a substitute for sizing the effect.\n- Report the few drivers, contributors, or known non-drivers that matter for interpreting the KPI movement.\n- For top-line KPI movement, structure validated drivers as a compact decomposition: top-line actual, component drivers, largest contributors or non-drivers, and residual or unresolved movement. Use an additive bridge only when the components reconcile cleanly; otherwise explain the relationship and uncertainty.\n- Separate validated drivers from business context or hypotheses.\n- Do not elevate business events into causes unless the timing, affected population, and measured change support the link.\n- State whether the movement is broad-based or concentrated when that changes the operating implication.\n- If driver evidence remains unresolved, name the uncertainty or diagnostic follow-up instead of inventing an explanation.\n\n### Presentation Standards\n\n- Write for executives and operators who skim: lead with the answer, then the evidence.\n- Use business-readable numbers and compact formats such as `123k (+8% w/w, +19% m/m)`.\n- Replace generic adjectives like `strong`, `healthy`, or `soft` with the metric evidence that justifies them.\n- Keep caveats close to the claim they affect, and omit caveats that do not change interpretation.\n- Use charts, tables, scorecards, or KPI cards only when they make the takeaway easier to understand and remain readable in the final delivery context.\n\n<!-- File: packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/market-sizing/SKILL.md (Tokens: ~1562 | Category: anthropic-skill) -->\n---\nname: market-sizing\ndescription: \"Estimate market, segment, or opportunity size with transparent assumptions and uncertainty. Use for TAM/SAM/SOM, sizing scenarios, or comparing the scale of possible opportunities.\"\n---\n\n## Related Skills\n\nUse $visualize-data when the sizing result needs a chart or figure.\n\nUse $build-report to package the final estimate, assumptions, sensitivity, caveats, and source context whenever this skill is selected, unless the user explicitly requests an inline, chat-only, brief/no-artifact answer, asks not to create a report/file/artifact, or selects another primary artifact.\n\n# Market Sizing\n\nUse this skill to produce a defensible estimate of a market or opportunity from connected context, public sources, transparent assumptions, and auditable calculations. The job is to define the market, choose a sound sizing method, distinguish evidence from assumptions, test sensitivity, and state what would most improve confidence.\n\n## Skill Configuration\n\n### Source Discovery And Verification\n\nUse the relevant semantic layer as a starting map, not a boundary.\n\n1. **Explore all possible sources.** Search every connected or provided source that could contain task-relevant data or change the interpretation. Within each structured-data source, run fresh catalog or metadata discovery for relevant schemas, datasets, tables, views, models, and metrics. Known sources, tables, dashboards, and semantic mappings are starting points, not stopping points.\n2. **Compare duplicates and conflicts.** When sources overlap or disagree, compare ownership, freshness, definition, grain, coverage, and directness. Use the best authoritative source, or combine complementary sources when needed. Note material conflicts, explain why the selected source or sources control the answer, and verify selected data through live reads before concluding.\n\n### Source Access Guardrail\n\nBefore querying sources, building artifacts, or drawing conclusions, determine whether the answer requires a specific source of truth.\n\nIf a required source is unavailable, stop that path. Tell the user what source is needed, ask them to make it available or provide a reviewed fallback, and do not treat weaker substitutes as equivalent.\n\nIf the missing source is only optional enrichment, continue with the strongest available evidence and label the gap when it materially affects the answer.\n\nClarify with the user when a missing input would materially change the estimate or recommendation. Otherwise make a reasonable assumption, state it, and proceed.\n\n## Workflow\n\n### 1. Frame The Market Or Opportunity\n\nDefine the market or opportunity boundary before estimating:\n\n- What is being sized, for example a product category, workflow, problem, use case, or category of activity.\n- Where and when it applies, for example geography, segment scope, time horizon, or market maturity.\n- Who or what counts as part of the market, for example the relevant population, unit of demand, transaction type, or included activity.\n- How the opportunity is measured, for example spend, revenue, volume, value created, or another unit that fits the question.\n- What kind of sizing answer the user needs, for example TAM/SAM/SOM, market entry, expansion upside, spend pool, revenue pool, population count, or unit volume.\n\n### 2. Choose A Starting Sizing Approach And Inputs\n\nPick the simplest sound sizing approach for the question, then sketch the calculation chain and the major inputs the estimate will depend on.\n\nA top-down model works when reliable aggregate market data exists; a bottom-up model works when the market can be built from observable units and assumptions; a value-based model works when the estimate should start from the value created rather than a published market total. Use a mixed approach only when cross-checking would materially improve confidence. If more than one approach fits, briefly explain which one you trust most and why.\n\nExpect the first approach to change if source checks show that another model would be more defensible.\n\n### 3. Gather Sources For The Inputs\n\nChoose sources based on the inputs the estimate depends on most.\n\nStart with user-named sources when provided. Then use the strongest available evidence for each major input from the starting approach. Use `~~structured_data` when an input should come from the user's data warehouse or another structured data source. Use context lanes such as `~~company_docs`, `~~team_communication`, or `~~dashboards_or_bi` when an input needs business meaning, source-of-truth guidance, or assumptions that are not captured in structured data alone. When an input depends on the outside market, use public sources for benchmarks, population estimates, comparable markets, or proxy assumptions.\n\nUse $gather-business-context to resolve context lanes when the right source of truth, business meaning, or assumption set is unclear.\n\nIf the strongest source is unavailable or thin, continue with a transparent proxy assumption only when the estimate is still useful. Label the gap and explain how it affects confidence.\n\n### 4. Separate Facts From Assumptions\n\nKeep sourced facts, inferred estimates, and judgment calls distinct in the model. When exact data is unavailable, use a defensible proxy, explain why it is reasonable, and note the confidence level. Ground assumptions in evidence about how the market actually behaves, what can realistically change, and what determines the size of the opportunity.\n\n### 5. Build The Model\n\nMake the model easy to inspect and adjust.\n\nThe model should make these elements easy to audit or revise:\n\n- market definition and measurement unit\n- assumptions and source context\n- calculation chain and derived values\n- base case, material ranges, and sensitivity logic\n- validation priorities\n\nFor each major input, make the source path visible: structured data, context lane, public source, user-provided input, or proxy assumption.\n\nKeep derived values traceable to formulas or code rather than hardcoded outputs.\n\nUse $jupyter-notebooks when code is needed for source harmonization, calculations, sensitivity analysis, or reusable modeling logic. Keep formulas, inputs, intermediate calculations, and sensitivity logic inspectable.\n\nUse the `$Spreadsheets` skill when the user requests a spreadsheet, workbook, or Google Sheets deliverable, or when a market-sizing model would materially benefit from editable assumptions, sensitivity tables, charts, or polished workbook formatting.\n\n### 6. Test Sensitivity\n\nIdentify the assumptions that move the estimate most.\n\nShow how the estimate changes when those assumptions move up or down. Prefer simple, decision-useful sensitivity analysis over exhaustive scenario sprawl.\n\nUse ranges when uncertainty is material. Do not hide uncertainty behind a single point estimate when the inputs are thin.\n\n### 7. State The Estimate And Validation Priorities\n\nEnd by handing the estimate, method, key assumptions, uncertainty, and next validation priorities to $build-report unless the user explicitly waives report creation or selects another primary artifact. This handoff is mandatory when no explicit human waiver was given; do not infer a waiver because the user asked for an estimate or did not use the word \"report\". This workflow owns the sizing model and conclusion; $build-report owns the reader-facing structure, visuals, evidence placement, and delivery surface.\n\nBefore handoff, make the market-sizing conclusion explicit:\n\n- market definition and measurement unit\n- estimate or range\n- method and calculation chain\n- key assumptions and source support\n- main uncertainty drivers and sensitivity takeaways\n- validation priorities and practical interpretation for the user's decision\n\nIf source coverage is thin, say which major inputs rely on proxy assumptions and what source would most improve them.\n\nUse $validate-data when methodology, calculations, assumptions, caveats, or source support need review before sharing.\n\nDo not render charts directly from this skill. If a sensitivity, scenario, funnel, or market-breakdown visual would clarify the estimate, pass that visual intent and supporting evidence to $build-report so $visualize-data owns chart selection and QA.\n\n<!-- File: packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/metric-diagnostics/SKILL.md (Tokens: ~1873 | Category: anthropic-skill) -->\n---\nname: metric-diagnostics\ndescription: \"Diagnose why a metric changed or differs from expectation. Use when the task is to identify likely drivers of a metric movement, anomaly, gap, or discrepancy.\"\n---\n\n## Related Skills\n\nUse $gather-business-context when business context is needed to understand the metric, analysis period, ownership, or plausible explanations.\n\nUse $product-business-analysis when the task asks for a recommendation or tradeoff decision after diagnosing the movement.\n\nUse $analyze-data-quality when dashboard trust, grain, freshness, or source disagreement could affect the metric.\n\n# Metric Diagnostics\n\nUse this skill to diagnose why a metric changed or differs from expectation. Reproduce the metric, define the comparison, quantify the movement, validate likely drivers, and state what is verified, likely, unresolved, and useful to do next.\n\nClarify with the user when a missing input would materially change the analytical frame or recommendation. Otherwise make a reasonable assumption, state it, and proceed.\n\n## Skill Configuration\n\n### Source Discovery And Verification\n\nUse the relevant semantic layer as a starting map, not a boundary.\n\n1. **Explore all possible sources.** Search every connected or provided source that could contain task-relevant data or change the interpretation. Within each structured-data source, run fresh catalog or metadata discovery for relevant schemas, datasets, tables, views, models, and metrics. Known sources, tables, dashboards, and semantic mappings are starting points, not stopping points.\n2. **Compare duplicates and conflicts.** When sources overlap or disagree, compare ownership, freshness, definition, grain, coverage, and directness. Use the best authoritative source, or combine complementary sources when needed. Note material conflicts, explain why the selected source or sources control the answer, and verify selected data through live reads before concluding.\n\n### Source Access Guardrail\n\nBefore querying sources, building artifacts, or drawing conclusions, determine whether the answer requires a specific source of truth.\n\nIf a required source is unavailable, stop that path. Tell the user what source is needed, ask them to make it available or provide a reviewed fallback, and do not treat weaker substitutes as equivalent.\n\nIf the missing source is only optional enrichment, continue with the strongest available evidence and label the gap when it materially affects the answer.\n\n## Workflow\n\n### 1. Define The Diagnostic Question\n\nFrame the diagnostic so it is clear what changed and what comparison would prove it.\n\nDefine:\n\n- what the metric means in business terms\n- the time window and comparison that make the change measurable\n- the population and grain that determine what counts\n- the source that owns the metric definition\n- the diagnostic question being answered, for example movement, concentration, or reconciliation\n\nUse $gather-business-context when business context is needed to understand what the metric means, what changed around the analysis period, or which explanations are plausible.\n\n### 2. Validate The Metric Definition And Source\n\nBefore explaining the movement, confirm that the metric is defined correctly and that the source data can measure it reliably.\n\nConfirm the metric definition, grain, aggregation logic, filters, joins, exclusions, freshness, lineage, and any disagreement between trusted surfaces. Keep this source check focused on issues that could change the answer.\n\nTreat current context, named semantic layers, and familiar table names as source candidates, not source selection. For broad metric questions, run live source discovery against available tables, dashboards, metric docs, semantic layers, or other source-of-truth surfaces before choosing the controlling source. When both are available, inspect at least one business-facing or top-line surface and one lower-level source surface, then state why the selected source owns the answer.\n\nUse $analyze-data-quality when freshness, grain, joins, missingness, schema drift, outliers, unexpected categories, or distribution shifts could affect trust.\n\nUse $jupyter-notebooks when fresh SQL, Python, statistical modeling, reusable calculations, or multi-step decomposition need an inspectable analytical record.\n\n### 3. Establish The Metric Pattern\n\nBefore looking for drivers, establish the metric pattern the diagnostic needs to explain. Quantify the metric over the relevant period and scope. If the question includes a comparison, reproduce that comparison.\n\nDo not search for causes until the size, timing, and scope of the pattern are verified or explicitly marked uncertain.\n\n### 4. Choose The Diagnostic Plan\n\nChoose the smallest set of cuts and checks likely to explain the pattern or strengthen confidence.\n\nChoose driver dimensions from the metric's operating logic, business context, and source shape. Prioritize drivers the business usually monitors or can act on, not every field available in the source. If the relevant drivers are unclear, use current context, a named semantic layer, or $gather-business-context to understand how the business explains the metric and what changed around the analysis period.\n\nWhen using a lower-level table, do not limit the driver analysis to fields surfaced by the first query. Recreate or join the business grouping needed to answer the question, such as model family, model superfamily, segment, region, cohort, product taxonomy, or customer hierarchy. If the grouping cannot be reconstructed, say so before simplifying the analysis.\n\nUse the explanation mode that fits the question. Common examples:\n\n- **Metric change**: compare the focal window with a baseline, rank segment contributions, check peer or historical context, and test mix shift versus within-segment movement.\n- **Spike, regression, or incident**: pin down onset, peak, recovery,\n  distribution shape rather than only averages, affected slices, broad versus localized degradation, and whether traffic or failure behavior changed.\n- **Largest contributors or concentration**: define \"largest\", rank entities,\n  compare total share and change, and look for major movers, entrants, and exits.\n- **Reconciliation or difference analysis**: align definitions, filters, grain,\n  numerator, denominator, and exclusions; quantify the components explaining the gap and state any residual.\n\n### 5. Decompose And Validate Drivers\n\nQuantify the main drivers and validate whether they explain the pattern.\n\nSize each major driver with the strongest readily available evidence. Show whether it explains the pattern, how large it is relative to the relevant base, trend, or gap, whether it is broad or concentrated, and whether it holds under the right comparison or scope.\n\nIterate on driver hypotheses until the explanation answers why in a way that is relevant to the business. Follow promising cross-cuts and drill-downs when they could reveal the key explanation, and stop when additional cuts are unlikely to change the conclusion or materially improve confidence.\n\nInterpret driver results in context:\n\n- Use the relevant base, comparison, or share of total to make the driver meaningful.\n- For rates, check whether the numerator, denominator, or both explain the change.\n- For additive metrics, calculate contribution share when it sharpens the story.\n- Separate composition effects from within-segment performance effects when that distinction changes the explanation.\n- Prefer mutually exclusive driver buckets when additive contributions need to be interpreted; reconcile the decomposition exactly or size and explain the residual.\n\nTreat measurement issues as possible explanations, not just cleanup details. For example, the pattern may come from logging changes, incomplete recent data, duplicated rows, or a shifted denominator rather than an underlying business change.\n\nCalibrate the explanation to the evidence, and make important uncertainty visible. Use context when it changes interpretation, such as whether the pattern is ordinary, unusual, expected, or tied to a known change.\n\nUse $visualize-data when a chart would make the diagnostic claim easier to understand or verify.\n\n### 6. State Implications And Follow-Up\n\nLead with the answer to the diagnostic question, then state the practical implications when the evidence supports them.\n\nThe answer should make clear:\n\n- the pattern being explained\n- the strongest driver explanation and supporting evidence\n- why it matters for the business\n- how much confidence to place in the explanation\n- the implication, next action, or follow-up that matters most\n\nUse $product-business-analysis when the user needs a recommendation or tradeoff decision, not just the diagnostic implication.\n\nKeep implications distinguishable from verified factual reporting so a reader can tell where evidence ends and interpretation begins. Do not claim causality from timing alone; state when an explanation is only a plausible hypothesis.\n\nUse $gather-business-context when the metric result is clear but business context is needed to interpret the `so what` or identify realistic next actions.\n\nUse $validate-data when methodology, calculations, caveats, or the evidentiary support for the diagnostic conclusion need review before sharing.\n\nDo not treat artifact or report validation as analytical validation. Before handing off, confirm the analysis has the headline metric movement, driver contribution shares or effect sizes, source/window reconciliation, exact executed SQL or query references when queries were used, and caveats that would change interpretation.\n\nPass the diagnostic substance and supporting evidence to $build-report unless the user explicitly requests an inline, chat-only, brief/no-artifact answer, asks not to create a report/file/artifact, or selects another primary artifact. This handoff is mandatory when no explicit human waiver was given; do not infer a waiver because the user asked a direct diagnostic question or did not use the word \"report\". Let $build-report own the report surface, presentation polish, reproducibility treatment, and sharing handoff.\n\n<!-- File: packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/product-business-analysis/SKILL.md (Tokens: ~1921 | Category: anthropic-skill) -->\n---\nname: product-business-analysis\ndescription: \"Analyze product or business data to support a decision or recommendation. Use when a decision depends on metric-backed evidence, such as choosing a direction, prioritizing an opportunity, evaluating a change, segmenting users, sizing tradeoffs, or deciding what to do next.\"\n---\n\n## Related Skills\n\nUse $metric-diagnostics when the recommendation depends on explaining a metric movement, anomaly, gap, or discrepancy.\n\n# Product And Business Analysis\n\nUse this skill to answer product or business questions with data-backed evidence, context, and a recommendation. Give the audience enough trustworthy evidence, interpretation, and uncertainty framing to choose a practical next action.\n\n## Skill Configuration\n\n### Source Discovery And Verification\n\nUse the relevant semantic layer as a starting map, not a boundary.\n\n1. **Explore all possible sources.** Search every connected or provided source that could contain task-relevant data or change the interpretation. Within each structured-data source, run fresh catalog or metadata discovery for relevant schemas, datasets, tables, views, models, and metrics. Known sources, tables, dashboards, and semantic mappings are starting points, not stopping points.\n2. **Compare duplicates and conflicts.** When sources overlap or disagree, compare ownership, freshness, definition, grain, coverage, and directness. Use the best authoritative source, or combine complementary sources when needed. Note material conflicts, explain why the selected source or sources control the answer, and verify selected data through live reads before concluding.\n\n### Source Access Guardrail\n\nBefore querying sources, building artifacts, or drawing conclusions, determine whether the answer requires a specific source of truth.\n\nIf a required source is unavailable, stop that path. Tell the user what source is needed, ask them to make it available or provide a reviewed fallback, and do not treat weaker substitutes as equivalent.\n\nIf the missing source is only optional enrichment, continue with the strongest available evidence and label the gap when it materially affects the answer.\n\nClarify with the user when a missing input would materially change the analytical frame or recommendation. Otherwise make a reasonable assumption, state it, and proceed.\n\n## Workflow\n\n### 1. Start From The Decision\n\nIdentify the decision, audience, and action the analysis should inform before choosing data sources or metrics.\n\nState plainly:\n\n- the question and decision the analysis should inform\n- who will use the answer and what they can act on\n- the scope and comparison that define a useful answer\n- the outcome or behavior that matters for the decision\n- any assumptions needed to proceed\n\nDo not let unclear scope turn into broad exploratory work by default.\n\n### 2. Gather Decision-Relevant Context\n\nRun $gather-business-context before deeper analysis. That skill owns source selection, retrieval, source authority, conflict handling, and compact context notes. Use this workflow to decide how the gathered context changes the analysis and recommendation.\n\nKeep the context pass proportional to the task. For self-contained prompts or cases where the user already provided enough context, the pass can be brief: confirm the decision frame, definitions, source assumptions, and any obvious gaps before moving on. Do not turn mandatory context gathering into a broad background scan.\n\nRelevant context should clarify:\n\n- intent: what the work was meant to accomplish and why\n- definitions: how the work, metric, or source is defined and measured\n- timing: what changed around the analysis period that could affect interpretation\n- constraints: decisions, caveats, or limitations that affect what action is realistic\n\n### 3. Frame The Analysis\n\nTurn the question into a focused analytical framework.\n\nDefine a framework for answering the question with data:\n\n- the specific data questions that would support or change the recommendation\n- the comparisons and dimensions to inspect\n- the unit of analysis that matches the decision\n- the metric definitions and caveats needed to interpret the result\n\nUse the framework to surface plausible hypotheses or interpretations, then turn them into focused data questions. Keep the framework specific enough to avoid broad exploration and support a recommendation.\n\nUse $design-kpis when the success metric, driver metrics, guardrails, or measurement plan need to be defined before the analysis can proceed.\n\nStart by defining what the answer needs to show in plain language. Then choose the data that matches that meaning as closely as possible, including who is counted and what comparison makes the number meaningful. If a field or event captures only part of what the decision cares about, say what it captures and what it leaves out.\n\n### 4. Run Focused Quantitative Analysis\n\nRun enough quantitative analysis to support or reject the framed hypotheses and inform the decision:\n\n- **Follow the framework.** Run the analyses that could change the recommendation first. Track additional data questions that emerge, answer the ones that matter for the decision, and leave lower-impact cuts as follow-up instead of expanding into broad exploration.\n\n- **Use the right comparison.** Interpret results against the relevant baseline, denominator, or comparison point before turning them into a recommendation. For example, do not conclude that one group is the best opportunity just because it has the most total usage. Check whether usage is high because the group is larger, whether the pattern still holds after normalizing by the active base, whether the group is growing or declining, whether the usage reflects the behavior or outcome that matters, and whether business context changes the interpretation.\n\n- **Size the opportunities.** Estimate the magnitude of impact each important opportunity could have. State what is being compared, which metric represents impact, what denominator or population it uses, and whether the data is complete enough to trust. Keep material unknown or unclassified groups visible when they could change the interpretation.\n\n- **Keep quantitative work inspectable.** Use $jupyter-notebooks to record queries and analysis. Use $analyze-data-quality when source freshness, grain, joins, missingness, schema drift, or unexpected distributions could affect trust.\n\n- **Validate before concluding.** Use $validate-data before sharing stakeholder-facing recommendations, high-impact claims, or surprising results. When dashboards and direct queries both exist, reconcile them or explain why they differ.\n\n### 5. Translate Evidence Into Decision Implications\n\nFrame the findings within the broader business context. Do not present quantitative evidence and business context as two unrelated streams.\n\nInterpret the evidence through the decision lenses that best fit the question. Choose lenses that would actually change the recommendation, and skip ones that would add noise or false precision. Common lenses include:\n\n- **Current scale:** Is the opportunity or problem large enough today to matter for the decision?\n- **Momentum:** Is the signal growing, shrinking, accelerating, or newly emerging?\n- **Breadth:** Is the pattern broad-based, or does it only appear in a narrow corner of the business?\n- **Concentration:** Does the conclusion depend on a few large entities, events, or outliers?\n- **Intensity:** Is the behavior deep enough per unit to suggest real need, value, or risk?\n- **Efficiency:** Does the option create better output, margin, conversion, productivity, or quality for the input required?\n- **Addressability:** Can the team realistically act on this option with available product, GTM, operational, policy, or technical levers?\n- **Differentiation:** Does this group or use case require a distinct motion, product experience, support model, or message?\n- **Substitution:** Is there evidence that behavior, spend, time, or workload could shift from another path?\n- **Risk or dependency:** Are there quality, trust, compliance, technical, operational, or data constraints that change the recommendation?\n- **Coverage:** Are unknown, missing, or sparsely tagged records large enough to change the answer?\n\nUse these as thinking tools, not a checklist. Explain why the chosen lenses matter for this decision, and mention omitted cuts only when they would plausibly change the interpretation or help explain the result.\n\nUse the measured opportunities to explain which differences matter for the decision and which ones call for different actions. If the business context shows that the initial sizing misses the actionable part of the opportunity, add the focused sizing cut needed to make the recommendation useful.\n\nIf evidence conflicts, say so directly and explain which interpretation is better supported. Do not smooth over disagreement between sources.\n\n### 6. Hand Off The Recommendation\n\nEnd by handing the decision-ready recommendation to $build-report unless the user explicitly requests an inline, chat-only, brief/no-artifact answer, asks not to create a report/file/artifact, or selects another primary artifact. This handoff is mandatory when no explicit human waiver was given; do not infer a waiver because the user asked a direct question or did not use the word \"report\". This workflow owns the analytical conclusion; $build-report owns the reader-facing structure, visuals, evidence placement, and delivery surface.\n\nBefore handoff, make the recommendation explicit:\n\n- what they should believe or do next\n- why the evidence supports that recommendation\n- which caveats or dependencies matter\n- what follow-up analysis would most improve confidence\n\nIf evidence is incomplete, label the recommendation as provisional and state what would change confidence. Do not overstate the conclusion just to make the answer feel decisive.\n\nUse $validate-data when methodology, calculations, caveats, or the evidentiary support for the conclusion need review before sharing.\n\nPass narrative ingredients to the report surface, not only result tables:\n\n- direct answer and recommendation\n- key evidence and how to interpret it\n- implication for the decision\n- unresolved uncertainty and caveats\n- recommended follow-up\n\n<!-- File: packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/validate-data/SKILL.md (Tokens: ~2698 | Category: anthropic-skill) -->\n---\nname: validate-data\ndescription: \"Validate whether an analysis is accurate, well-supported, and ready to share or use for a decision. Use when reviewing methodology, calculations, comparisons, visuals, caveats, or conclusions.\"\n---\n## Related Skills\n\nUse $analyze-data-quality when validation depends on whether the underlying data is trustworthy, comparable, fresh, or at the right grain.\n\nUse $product-business-analysis when the task asks for a recommendation or decision after the validation pass.\n\n# Validate Data Analysis\n\nValidate an analysis before it is shared with stakeholders. Focus on whether the question, data, methodology, calculations, visuals, claims, caveats, and recommendations are trustworthy enough for the stated audience and decision.\nThis skill is for analysis QA, not raw dataset profiling alone. When validation depends on dataset reliability checks such as freshness, grain, missingness,\nduplicates, join coverage, or source mismatches, use $analyze-data-quality as a companion.\n\n## Workflow\n\n1. Inventory the artifact and claims.\n\n   Identify the report, notebook, spreadsheet, SQL, dashboard, chart, pasted analysis, or recommendation being validated. Inspect source artifacts when a path, link, query, notebook, spreadsheet, or dashboard is referenced. Extract the main question, audience, decision, key claims, headline numbers, data sources, time windows, populations, filters, comparison baselines, and stated caveats. Verify that every metric or KPI requested by the user appears in the analysis or is explicitly marked unavailable, not applicable, or out of scope.\n\n2. Validate the question, methodology, and assumptions.\n\n   Confirm that the analysis answers the stated business or product question,\n   not a nearby easier question. Check whether the population, eligibility rules, exclusions, sampling, metric definitions, formulas, units,\n   denominators, timezones, cohorts, comparison periods, and baselines match the stakeholder decision. Flag hidden exclusions, inconsistent definitions,\n   partial-period comparisons, and causal wording that lacks experimental or otherwise credible causal evidence.\n\n3. Validate data selection and quality risks.\n\n   Confirm that the chosen tables, files, dashboards, or extracts are appropriate and current enough for the decision. Check freshness or \"as of\"\n   date, expected partitions, segment coverage, row/category completeness, null handling, deduplication, filter logic, join coverage, and source mismatches when those risks could change the conclusion. Use `~~structured_data` for source metadata, schema checks, sample rows, query history, or SQL spot checks through the relevant source connector when available. Use `~~operations_logs` for table freshness, lineage, or pipeline context.\n\n4. Verify calculations and aggregations.\n\n   Recompute the highest-impact numbers independently when possible. Check grain, subtotals, denominators, non-zero denominators, rate bases,\n   period-over-period bases, weighted averages, units, currency, timezone handling, and whether mutually exclusive categories add to totals. For SQL,\n   inspect join types, group-by grain, filters, distinct counts, and row counts before and after joins. Use $jupyter-notebooks or `~~spreadsheet_workspace`\n   when the artifact itself is a notebook or spreadsheet, or when reproducible spot checks need code or formulas.\n\n5. Test reasonableness and common analytical traps.\n\n   Compare magnitudes against known dashboards, historical reports, prior analyses, finance sources, or expected product scale when possible. Investigate trend jumps, drops, flatlines, exact round numbers, 0% or 100% rates, segment shares that should sum to about 100%, and results that perfectly confirm the hypothesis without friction. Check edge cases such as empty segments, new entities, and boundary dates.\n\n6. Review visuals and presentation integrity.\n\n   Confirm that charts use appropriate chart types, scales, axes, intervals,\n   titles, labels, units, ordering, annotations, color, and precision. Use\n   $visualize-data for non-trivial chart review. For rendered reports,\n   dashboards, slides, docs, PDFs, HTML, or other final artifacts, inspect the rendered output for broken charts, missing tables, clipped text, bad formatting, stale placeholders, and obvious layout issues. Check whether a quick reader could walk away with a misleading interpretation, especially from truncated axes, dual axes, 3D effects, inconsistent intervals, missing date ranges, or chart titles that overstate the data.\n\n7. Evaluate narrative, conclusions, and recommendations.\n\n   Confirm each conclusion is supported by visible evidence or saved artifacts.\n   Separate verified findings from interpretation, caveats, and open questions.\n   Identify alternative explanations, uncertainty, missing context,\n   recommendations that go beyond the evidence, and any causal language that is not supported by the design.\n\n8. Produce a confidence assessment and required fixes.\n\n   Prioritize issues that materially affect the stakeholder decision. Separate blockers from caveats: do not block sharing for minor polish issues, but do block when a number, denominator, join, time window, population, comparison,\n   or conclusion is materially unreliable. Record incomplete handoff blockers separately from caveats, including missing access, unavailable source artifacts, unrun checks, broken render steps, unresolved data-quality risks,\n   or absent owner confirmation. If SQL, Python, a notebook, or a spreadsheet was used for validation, include the artifact path, query permalink, notebook path, spreadsheet tab, or dashboard link so the check is reproducible.\n\n## Standards\n\n### Validation Stance\n\n- Validate the claims the analysis actually makes, not just whether the artifact looks polished.\n- Prefer concrete evidence: recompute important numbers, inspect source data,\n  check code paths, trace records, or reconcile against trusted sources when tools and access allow it.\n- Label anything that cannot be verified, and state what would be needed to verify it.\n- Treat surprising results, stakeholder-facing recommendations, causal claims,\n  high-impact decisions, and externally shared analyses as higher-risk validation targets.\n- Select checks that match the artifact and decision. Do not run every possible check mechanically.\n\n### Methodology Checks\n\n- Question framing: the analysis answers the stated business or product question.\n- Data selection: sources are appropriate and current enough for the decision.\n- Population: inclusions, exclusions, eligibility rules, and sampling are explicit.\n- Metric definitions: formulas, units, denominators, and timezones are clear and aligned with stakeholder definitions.\n- Baselines: comparison periods, cohorts, and contexts are comparable.\n- Causality: causal wording is backed by experimental or otherwise credible causal evidence.\n\n### Data Quality Checks\n\n- Freshness: the analysis states or can recover the data \"as of\" date.\n- Completeness: no unexpected missing partitions, segments, rows, or categories.\n- Null handling: key columns have expected null rates or explicit treatment.\n- Deduplication: primary entities are not double counted.\n- Filter verification: filters and WHERE clauses do not silently exclude the population of interest.\n- Join coverage: dimensions, experiments, and reference tables do not drop or multiply important rows.\n\n### Calculation Checks\n\n- Grain: the aggregation level matches the intended analysis grain.\n- Denominators: rates and percentages use the correct population and non-zero denominators.\n- Period alignment: comparisons use equal or explicitly caveated windows.\n- Weighted metrics: averages are weighted correctly when group sizes differ.\n- Subtotals: parts add to totals where categories are mutually exclusive.\n- Units: currency, token, user, request, account, day/week/month, and timezone units are consistent.\n\n### Reasonableness Checks\n\n- Magnitudes are plausible relative to known dashboards, historical reports, or expected product scale.\n- Percentages fall in expected ranges and segment shares sum to about 100% where expected.\n- Trend jumps, drops, flatlines, exact round numbers, and 0% or 100% rates have an explanation.\n- Results do not perfectly confirm the hypothesis without friction or exceptions.\n- Edge cases such as empty segments, new entities, and boundary dates behave sensibly.\n\n### Common Pitfalls\n\n- Join explosion: many-to-many joins silently multiply rows and inflate counts or sums. Compare row counts and distinct primary entities before and after the join, and check whether the right-hand table has multiple rows per join key.\n  Aggregate the right-hand table to the intended grain before joining when needed, use `COUNT(DISTINCT primary_id)` when counting entities through joins,\n  and comment intentional one-to-many joins.\n- Survivorship bias: the analysis only includes entities that exist today and misses deleted, churned, failed, or otherwise absent entities. Ask who is not in the dataset and whether the missing population changes the conclusion.\n- Incomplete period comparison: a partial period is compared with a complete period. Use complete periods, compare the same number of elapsed days, or label the partial-period caveat prominently.\n- Denominator shifting: the eligible population changes between periods or segments. Validate that conversion, churn, activation, attach, and retention rates use stable definitions across compared groups.\n- Average of averages: pre-computed averages are averaged without weighting for group size. Aggregate from raw numerators and denominators or use a weighted average.\n- Timezone mismatch: sources use different timestamp conventions or daily cutoffs. Confirm the analysis standardizes timestamps or explicitly states the timezone and cutoff.\n- Selection bias in segmentation: segments are defined by the outcome being measured. Define comparison groups by pre-treatment characteristics when making lift, causality, or behavior-difference claims.\n- Other statistical traps: Simpson's paradox where aggregate and segment-level trends conflict, correlation presented as causation, small samples,\n  outlier-dominated averages that need medians or distribution views, multiple testing, cherry-picked time ranges, and look-ahead bias.\n\n### Spot-Check Recipes\n\n- Recompute a key metric from raw numerators and denominators.\n- Trace a few individual records through joins, filters, and final output.\n- Reconcile a key total against a trusted dashboard, prior report, or finance source.\n- Reverse engineer a headline number from component metrics, such as users times per-user revenue.\n- Run a one-day, one-segment, or one-entity boundary check to make sure filters and joins behave sensibly.\n- Compare the same metric through an alternate query path when a claim is surprising or high stakes.\n\n### Visualization Checks\n\n- Bar charts should generally start at zero; waterfall, bridge, variance, and other delta-focused charts may use a non-zero or narrowed value axis when zero would materially compress the intended movement, provided exact values, units, and the focused scale are clear.\n- Comparison charts should use consistent scales unless the scale difference is explicit and justified.\n- Axes, units, legends, and date ranges should be labeled.\n- Category ordering should match the comparison the reader should make.\n- Truncated axes, dual axes, 3D effects, and inconsistent intervals require explicit justification or redesign.\n- Chart titles and annotations should match exactly what the data supports.\n- Titles should state the finding and include date range or scope when needed.\n- Caveats should be visible near the claims they qualify.\n- Number formatting should use appropriate precision and units.\n- Rendered artifacts should be checked in their final form when available, not only in source form.\n\n### Confidence Ratings\n\n- `Ready to share`: The analysis is methodologically sound, key calculations are verified or low risk, caveats are clear, and any remaining issues are minor.\n- `Share with caveats`: The analysis is directionally usable, but specific assumptions, limitations, or unverified checks must be communicated to stakeholders.\n- `Needs revision`: There are material errors, unsupported claims, missing checks, or methodological issues that should be fixed before sharing.\n\n### Output Standards\n\nUse this structure unless the user asks for a lighter review:\n\n```markdown\n## Validation Report\n\n### Overall Assessment: [Ready to share | Share with caveats | Needs revision]\n\n### Methodology Review\n[Findings about question framing, data selection, population, definitions, comparisons, and assumptions.]\n\n### Issues Found\n1. [Severity: High/Medium/Low] [Issue description, evidence, and impact]\n2. ...\n\n### Calculation Spot-Checks\n- [Metric or claim]: [Verified / Discrepancy found / Not verified] - [brief evidence]\n\n### Visualization Review\n[Chart or presentation issues, if applicable.]\n\n### Suggested Improvements\n1. [Improvement and why it matters]\n\n### Required Caveats for Stakeholders\n- [Caveat that must be communicated]\n```\n\n- Include the question being answered, data sources and \"as of\" date, metric and segment definitions, time period and timezone, methodology steps, assumptions and limitations, SQL queries, notebook paths, spreadsheet tabs, dashboard links, or caveats required before acting when those details are relevant.\n- Preserve source references from the original artifact, including links, query IDs, notebook paths, spreadsheet tabs, dashboard URLs, cited documents, and other evidence needed to trace the analysis.\n- Verify that every section requested by the user or implied by the deliverable format is present; explain omitted sections.\n- Keep issues prioritized by decision impact, not by artifact section order.\n- Make unverified claims and remaining caveats explicit.\n- List incomplete handoff blockers separately from caveats and suggested improvements.\n\n<!-- File: packages/cli/src/skill/builtin/.bundle/data-analytics/workflows/visualize-data/SKILL.md (Tokens: ~590 | Category: anthropic-skill) -->\n---\nname: visualize-data\ndescription: \"Design, create, revise, or QA quantitative charts and figures for reports, dashboards, notebooks, slides, files, or inline analytical answers.\"\n---\n\n# Visualize Data\n\nCreate quantitative visuals that are analytically sound, immediately readable, and appropriate for their destination. Treat a chart as evidence for a takeaway, not decoration.\n\n## Workflow\n\n1. State the analytical question and intended takeaway.\n2. Verify the data grain, measures, dimensions, units, missing values, filters, time window, sample size, and source.\n3. Choose the chart family from the analytical relationship:\n   - Change over ordered time: line or area chart.\n   - Category comparison: bar chart.\n   - Distribution: histogram, box plot, or density plot.\n   - Relationship between numeric measures: scatter plot.\n   - Composition: stacked bar/area; use pie only for a small set of meaningful parts.\n   - Funnel progression: funnel or ordered bars with stage conversion.\n   - Contribution to change: waterfall.\n   - Exact lookup values: table, optionally with small bars or sparklines.\n4. Define explicit encodings, sorting, aggregation, grouping, scales, labels, units, colors, annotations, and uncertainty treatment.\n5. Render with the destination's native system when one is selected. Otherwise prefer reproducible Python/Matplotlib or SVG for files and inline artifacts. Notebook-native plotting is appropriate for notebooks.\n6. Inspect the final output in context when the host provides image, browser, document, or notebook inspection.\n\nDo not install or require React, Recharts, Vite, MCP widgets, or proprietary UI renderers. For self-contained HTML, use inline SVG/canvas or a static image plus semantic fallback data. Avoid remote scripts unless the user explicitly accepts the dependency.\n\n## Visual quality\n\n- Use an answer-oriented title and a subtitle only when it adds a distinct takeaway.\n- Label axes and units; show legends or direct labels for every visible group.\n- Use consistent scales for comparisons and avoid misleading truncated axes unless clearly justified.\n- Prefer direct labeling and restrained color. Reserve semantic colors for meaning such as positive, warning, or negative states.\n- Keep annotations selective and evidence-backed.\n- Make dense charts readable through aggregation, faceting, filtering, or a table rather than shrinking text.\n- Provide accessible contrast, text alternatives, and a data table when the destination supports them.\n- Put provenance in a source note rather than cluttering the title.\n\n## QA\n\n- Recompute plotted values from the reviewed rows.\n- Confirm the visual answers the stated question and does not imply unsupported causality.\n- Check ordering, scales, labels, clipping, overlap, empty states, and small-screen behavior where relevant.\n- Confirm the exported file opens and contains the expected marks and text.\n- Preserve the code or notebook needed to reproduce the chart when the user needs an auditable artifact.\n\n<!-- File: packages/cli/src/skill/builtin/.bundle/deep-research/SKILL.md (Tokens: ~1153 | Category: anthropic-skill) -->\n---\nname: deep-research\ndescription: Deep research on any topic using parallel sub-agents and built-in tools only (WebSearch/WebFetch + free APIs, no keys). Use when the user asks for a thorough multi-source investigation with a cited report — \"深度调研X\"、\"deep research\"、\"帮我全面研究一下\"、\"多方求证\"、\"写一份调研报告\". NOT for simple lookups (single WebSearch suffices) and NOT for academic literature surveys (use auto-research skill instead).\n---\n\n# Deep Research\n\nOrchestrate parallel research sub-agents, then write one coherent cited report. Research is parallel; writing is single-point — never let multiple agents write report sections.\n\n## Step 0 — Always first\n\n1. Run `date +%Y-%m-%d` via Bash. Never assume the current year from training data.\n2. Triage:\n   - Answerable with 1-2 searches? → STOP, just use WebSearch directly. Do not use this skill.\n   - Enumeration task (N items × M fields, e.g. \"compare 20 frameworks\")? → still this skill, but use table-oriented decomposition (one sub-agent per item batch).\n   - Open-ended investigation? → continue below.\n3. Pick depth (default **standard**; user can override with words like \"quick\"/\"exhaustive\"):\n\n| Mode | Sub-agents (round 1) | Max follow-up rounds | Sources target |\n|---|---|---|---|\n| quick | 2-3 | 0 | 8+ |\n| standard | 3-5 | 1 | 15+ |\n| deep | 5-8 | 2 | 25+ |\n\nThese are hard budgets. Reflection (Phase 4) can spend them but never exceed them.\n\n## Workspace\n\nAll state lives on disk at `./research/<slug>/` — never only in context (survives compaction):\n\n```\nresearch/<slug>/\n├── brief.md         # research brief — the single contract for all phases\n├── findings/        # F1.md, F2.md ... one per sub-agent, structured evidence\n└── REPORT.md        # final deliverable\n```\n\nOn resume: re-read `brief.md` + list `findings/`, skip completed angles, continue.\n\n## Phase 1 — Scope\n\nAsk at most one round of clarifying questions (AskUserQuestion), only if genuinely ambiguous: audience, time frame, region, decision at stake. If the user said \"just run it\" or intent is clear, skip asking and write assumptions into the brief instead.\n\nThen write `brief.md`: refined question, scope boundaries (in/out), assumptions, depth mode, today's date. This brief — not the raw conversation — is what every later phase measures against.\n\n## Phase 2 — Plan\n\nDecompose the brief into 3-8 **independent** research angles. Pull from these lenses as applicable: core facts/definitions · recent developments (last 12 months) · quantitative data/benchmarks · counter-arguments & failure cases · practitioner experience (forums, issues) · academic work · key players/alternatives.\n\nList angles in `brief.md` under `## Angles`. For deep mode or contested topics, show the angle list to the user for a quick confirm before spending budget.\n\n## Phase 3 — Parallel research\n\nSpawn one sub-agent per angle **in a single message** (parallel). Build each prompt from the locked template in [reference/subagent-prompt.md](reference/subagent-prompt.md) — reproduce it verbatim, replacing only the `{variables}`. Each sub-agent:\n\n- researches ONE angle only, using WebSearch/WebFetch and the free endpoints in [reference/sources.md](reference/sources.md)\n- writes structured findings to `findings/F<n>.md` (claim / quote / URL / date / confidence per item)\n- returns only a 3-5 line summary to you — raw page content must never enter your context\n\nIf a sub-agent fails or returns thin results, note it and move on; do not block other angles.\n\n## Phase 4 — Reflect (gap check)\n\nRead all `findings/*.md`. Against `brief.md`, ask: which parts of the brief have no evidence? Which major claims rest on a single source? Where do sources conflict?\n\n- Gaps found AND follow-up budget remains → spawn targeted sub-agents with delta-queries (same template, narrower angle). Repeat once per remaining round.\n- No budget left or coverage sufficient → proceed. Record unresolved gaps; they go in the report's \"Open questions\".\n\n## Phase 5 — Write (single-point)\n\nYou alone write `REPORT.md` in one pass, following [reference/report.md](reference/report.md). Core rules:\n\n- Every non-obvious claim carries an inline citation `[n]` mapping to a Sources section; citation URLs come only from findings files — never from memory.\n- Where sources conflict, present both sides with dates; prefer newer + primary sources.\n- Mark single-source claims with `[single source]`, speculation with `[speculative]`.\n- End with: Open questions · Sources (numbered, with access date).\n\nFor deep mode, before finalizing do one critique pass: reread the report as a skeptical reviewer (unsupported claims? stale data? missing counter-view?) and fix in place.\n\nFinally, give the user a 5-10 line summary of key conclusions and the report path.\n\n<!-- File: packages/cli/src/skill/builtin/.bundle/docx-official/SKILL.md (Tokens: ~2413 | Category: anthropic-skill) -->\n---\nname: docx-official\ndescription: \"Use this skill whenever a Microsoft Word (.docx) file is being produced, opened, transformed, or read. That includes: drafting reports, letters, contracts, RFPs, technical documents, or any long-form written deliverable; extracting text or structure from an existing Word file; filling a Word template with values; converting Word to PDF or plain text; splitting or merging documents; inspecting styles, headings, sections, tables, images, comments, or tracked changes. Trigger on mentions of 'Word doc', 'DOCX', 'Office document', a filename ending in .docx, or requests like 'turn this into a Word report'.\"\nlicense: Apache-2.0 — see LICENSE for terms and third-party attributions\n---\n\n# DOCX Skill\n\nAn Apache-2.0 toolkit for producing, editing, and reading Microsoft Word (`.docx`) files. Written from scratch against the public [ECMA-376 / ISO/IEC 29500](https://www.ecma-international.org/publications-and-standards/standards/ecma-376/) specification and built on permissively-licensed tooling (`python-docx` MIT, `lxml` BSD-3-Clause, optional external binaries `pandoc` and `soffice`) so it can be reused in commercial projects without restriction.\n\n## Decision matrix\n\n| Situation | Path | Read first |\n|-----------|------|------------|\n| No source file — build a document from a prompt / data | Author from scratch with `python-docx` | [`create.md`](create.md) |\n| You have a `.docx` template to fill in or lightly modify | Placeholder replacement via `python-docx`, keeps styles | [`edit.md`](edit.md) → *Workflow A — `python-docx` in-place edit* |\n| Deep structural edits, new sections, custom XML, unusual layouts | Explode → edit XML → assemble | [`edit.md`](edit.md) → *Workflow B — Explode → edit XML → assemble* |\n| You only need the text / structure / metadata out of a `.docx` | Extraction pipeline | [`read.md`](read.md) |\n| Need a PDF preview for QA | `scripts/render_pdf.py` via LibreOffice | see *QA* below |\n\nIf the task mixes several of these, do them in this order: **read → plan → edit/create → validate**.\n\n## One-time environment setup\n\n> **Bundled runtime:** when the `MIMO_PYTHON` environment variable is set, skip `uv`/`python3` and pip installs entirely — run every command below with `uv run` replaced by `\"$MIMO_PYTHON\"` (e.g. `\"$MIMO_PYTHON\" scripts/extract_text.py input.docx`). This skill's Python dependencies are preinstalled in that interpreter; pip console scripts are unavailable, so always go through `\"$MIMO_PYTHON\" -m <module>`. A bundled LibreOffice is exposed as `MIMO_SOFFICE` and picked up automatically by the scripts here.\n\nAll scripts include [PEP 723](https://peps.python.org/pep-0723/) inline metadata, so `uv run` resolves dependencies automatically — no manual install step needed. Just run:\n\n```bash\nuv run scripts/extract_text.py input.docx\n```\n\nIf you don't use `uv`, install dependencies once:\n\n```bash\npython3 -m pip install --upgrade python-docx lxml\n# Optional but recommended:\n#   LibreOffice (for docx → pdf preview):   brew install --cask libreoffice   (macOS)\n#                                           apt-get install -y libreoffice    (Debian/Ubuntu)\n#   Poppler   (for pdf → image, QA loop):   brew install poppler\n```\n\nAlternatively, if this skill lives in a persistent workspace you can `uv init` a project, `uv add python-docx lxml`, and run scripts with `uv run scripts/...` from the project root — this gives you a lockfile and reproducible environment.\n\nAll scripts here use the standard library plus `python-docx`. No proprietary dependencies.\n\n## Common commands\n\n```bash\n# 1. Extract plain text (best for \"what does this file say?\" questions)\nuv run scripts/extract_text.py input.docx > input.txt\n\n# 2. Explode a .docx into readable XML for structural surgery\nuv run scripts/explode.py input.docx exploded/\n\n# 3. Assemble an exploded directory into a fresh .docx\nuv run scripts/assemble.py exploded/ output.docx\n\n# 4. Render a .docx as PDF (used for visual QA)\nuv run scripts/render_pdf.py output.docx           # writes output.pdf next to it\n\n# 5. Well-formedness check (ZIP integrity + parseable XML + python-docx open)\nuv run scripts/audit.py output.docx\n\n# 6. Accept every tracked change without needing Word/LibreOffice\nuv run scripts/resolve_revisions.py reviewed.docx clean.docx\n\n# 7. Add a comment to an exploded directory\nuv run scripts/annotate.py exploded/ \"Please check\" --author \"Reviewer\" --anchor \"text\"\n```\n\nEvery script is a small, self-contained Python file. Read the top of the file for full CLI options.\n\n## Authoring principles\n\nWord is a **flowing** document format, not a slide surface. Users expect it to look like something a human wrote in Word — not a design tool trying to reinvent typography. Keep that in mind:\n\n1. **Rely on named styles.** Use `Heading 1`, `Heading 2`, `Normal`, `Title`, `Quote`, `List Bullet`, `List Number`, `Caption`. They are what makes Word's ToC, navigation pane, and cross-references work.\n2. **One idea per paragraph.** Long paragraphs are fine; run-on paragraphs are not. Break at logical boundaries.\n3. **Structure first, prose second.** Draft the heading tree, then write inside it. Reviewers scan headings before words.\n4. **Tables for tabular data only.** Do not use tables to fake multi-column layouts — export to PDF and users see the borders through the layout.\n5. **Line length is set by page margins, not by hard breaks.** Never insert manual line breaks to control wrapping.\n6. **Use fields, not literal text, for things that change** — page numbers, dates, ToC, cross-references. `python-docx` supports field codes via low-level XML (see `edit.md`).\n7. **Every image needs alt text** — accessibility, and Word screams at you in review mode when it's missing.\n\n## Typography defaults (safe starting point)\n\n| Element        | Font          | Size | Weight | Notes |\n|----------------|---------------|------|--------|-------|\n| Title          | Calibri Light | 28pt | Bold   | Centered or left, one line |\n| Heading 1      | Calibri Light | 18pt | Bold   | Space before 12pt |\n| Heading 2      | Calibri Light | 14pt | Bold   | Space before 10pt |\n| Heading 3      | Calibri       | 12pt | Bold   | Space before 6pt |\n| Body           | Calibri       | 11pt | Regular| Line spacing 1.15, space after 6pt |\n| Caption        | Calibri       | 9pt  | Italic | Muted gray `#595959` |\n| Code / mono    | Consolas      | 10pt | Regular| Left-aligned, no first-line indent |\n\nChange the palette for the topic — muted navy `#1F3A5F` for legal/finance, warm charcoal `#2E2A26` for editorial. Avoid pure `#000000` for body text; `#1F1F1F` reads softer on print.\n\n## Page setup (A4 vs Letter)\n\nAsk the user which one to use. If you cannot ask, default to the region implied by the language (Chinese/European → A4, US English → Letter). Margins:\n\n| Size   | Width × Height    | Standard margins (T/B/L/R) |\n|--------|-------------------|-----------------------------|\n| A4     | 21.0 × 29.7 cm    | 2.54 / 2.54 / 3.18 / 3.18 cm |\n| Letter | 8.5 × 11.0 in     | 1.00 / 1.00 / 1.25 / 1.25 in |\n\n## QA checklist — always run before declaring done\n\n**Assume something is wrong.** Word files fail silently: a broken relationship, an unclosed `<w:p>`, a missing style — Word will still open the file but strip content or throw a \"content had problems\" warning. Verify explicitly.\n\n1. **Open cleanly** — no repair prompt.\n   ```bash\n   uv run python -c \"import docx; docx.Document('output.docx')\"   # loads without exceptions\n   ```\n2. **Text integrity** — no placeholder residue.\n   ```bash\n   uv run scripts/extract_text.py output.docx | grep -Ei \"TODO|TBD|\\{\\{|lorem|xxxx\"\n   ```\n   Grep must return nothing.\n3. **Visual sanity** — render a PDF, open the first and last pages, scan for:\n   - Widowed headings alone at the bottom of a page.\n   - Tables split awkwardly across pages.\n   - Images pushed to their own page because they exceeded content width.\n   - Missing page numbers, wrong header/footer content.\n   ```bash\n   uv run scripts/render_pdf.py output.docx\n   ```\n4. **Style hygiene** — every heading uses a real style, not just bold+large text:\n   ```bash\n   uv run python -c \"\n   import docx; d = docx.Document('output.docx')\n   for p in d.paragraphs:\n       if p.text and p.style.name == 'Normal' and p.runs and p.runs[0].bold:\n           print('possible fake heading:', p.text[:80])\"\n   ```\n\nIf any of these fail, fix and re-run — don't paper over.\n\n## What is out of scope\n\n- **`.doc` (legacy Word 97-2003)** — this skill only targets `.docx` (Office Open XML). Convert `.doc` to `.docx` with LibreOffice first: `soffice --headless --convert-to docx old.doc`.\n- **Live collaborative editing** — the Word online API is a separate concern; here we produce and modify files.\n- **Macros / VBA** — do not generate `.docm` files. If the user asks for automation, offer a Python script that regenerates the doc instead.\n\n## Where each detail lives\n\n- **Creating from scratch**: [`create.md`](create.md) — headings, paragraphs, styles, tables, images, page setup, headers/footers, tables of contents.\n- **Editing / templating**: [`edit.md`](edit.md) — placeholder replacement, section swap, raw XML surgery, tracked changes, comments.\n- **Reading / extracting**: [`read.md`](read.md) — plain-text export, structural walk, metadata, table extraction.\n- **Scripts**: [`scripts/`](scripts/) — self-contained CLI utilities used by all of the above.\n\n<!-- File: packages/cli/src/skill/builtin/.bundle/grok-build/SKILL.md (Tokens: ~1163 | Category: anthropic-skill) -->\n---\nname: grok-build\ndescription: Reference and workflow guidance for the Grok Build CLI (`grok`), including interactive and headless runs, authentication, sessions, worktrees, permissions, sandboxing, MCP servers, plugins, inspection, updates, and automation output. Invoke only when the user explicitly requests the `grok-build` skill, explicitly asks to use Grok Build CLI, or an already-selected workflow requires Grok Build; do not invoke for general coding, generic shell tasks, or other agent CLIs.\n---\n\n# Grok Build CLI\n\nOperate Grok Build from a terminal while keeping execution mode, permissions, sandboxing, session state, and output handling explicit.\n\n## Start with Local Evidence\n\n1. Confirm that the CLI is available:\n\n   ```bash\n   command -v grok\n   grok version\n   ```\n\n2. Inspect the installed command before giving version-sensitive advice:\n\n   ```bash\n   grok --help\n   grok <subcommand> --help\n   ```\n\n3. Inspect the configuration discovered for the target workspace when behavior depends on rules, skills, plugins, hooks, or MCP servers:\n\n   ```bash\n   grok --cwd /path/to/repo inspect\n   grok --cwd /path/to/repo inspect --json\n   ```\n\n4. Treat current official documentation and installed help as authoritative when they differ from this bundled reference.\n\n## Choose an Execution Mode\n\n- Run `grok` with no arguments for the interactive TUI.\n- Run `grok \"<initial prompt>\"` to open the TUI with an initial task.\n- Run `grok -p \"<prompt>\"` for one non-interactive turn that prints a result and exits.\n- Run `grok agent stdio` for an ACP client that communicates over stdin/stdout.\n- Run `grok dashboard` to open the Agent Dashboard.\n\nPrefer headless mode for scripts, CI, bots, and agent orchestration. Prefer ACP only when the caller implements the ACP JSON-RPC lifecycle and consumes `session/update` chunks.\n\n## Authenticate\n\nUse an interactive login on a developer machine:\n\n```bash\ngrok login\n```\n\nUse device-code authentication in headless or remote environments:\n\n```bash\ngrok login --device-auth\n```\n\nUse a locally cached login or provide `XAI_API_KEY` only to the process that needs it. Never print, persist, or commit credentials. Use `grok logout` to clear cached credentials.\n\n## Run Headlessly\n\nUse an explicit working directory and output format:\n\n```bash\ngrok --no-auto-update \\\n  --cwd /path/to/repo \\\n  --sandbox workspace \\\n  -p \"Inspect the repository and explain the failing test.\" \\\n  --output-format json\n```\n\nChoose output according to the consumer:\n\n- Use `plain` for humans.\n- Use `json` for one final machine-readable object.\n- Use `streaming-json` for newline-delimited incremental events.\n- Add `--json-schema '<schema>'` when the installed CLI supports constrained structured output.\n\nPass `--no-auto-update` in scripts and CI to suppress background update checks. Do not parse interactive TUI rendering in automation.\n\n## Control Permissions and Isolation\n\nTreat permissions and sandboxing as separate controls:\n\n- Use permission rules to decide whether a tool call may run.\n- Use a sandbox profile to limit what an approved call may access.\n- Prefer `--sandbox workspace` for normal repository changes.\n- Prefer `--sandbox read-only` for review and auditing.\n- Prefer `--sandbox strict` for an untrusted repository, then add narrow permission rules.\n- Use `--allow <RULE>` and `--deny <RULE>` for per-run policy; remember that deny rules win.\n- Use `--always-approve` only when the environment and command scope justify unattended execution. Pair it with a suitable sandbox and explicit deny rules.\n\nDo not describe `--always-approve` as equivalent to sandboxing. The sandbox is off by default unless configured or selected.\n\n## Manage Sessions and Worktrees\n\nContinue or resume intentionally:\n\n```bash\ngrok -c\ngrok --resume <session-id>\ngrok --resume\n```\n\nUse `--session-id <UUID>` for a new named session, not to resume an existing one. Add `--fork-session` when branching from a resumed session.\n\nUse a worktree when concurrent work could collide:\n\n```bash\ngrok --worktree --ref main \"Fix the flaky test\"\ngrok --worktree=feature-name \"Implement the feature\"\n```\n\nPreview removal with `grok worktree rm --dry-run <id>` before deleting a worktree. Do not assume deleting a session removes its worktree.\n\n## Diagnose Before Editing Configuration\n\nUse built-in inspection and diagnostics first:\n\n```bash\ngrok inspect --json\ngrok mcp list --json\ngrok mcp doctor\ngrok plugin list\ngrok models\n```\n\nPrefer `grok mcp add`, `grok mcp remove`, and plugin subcommands over manually editing configuration when the CLI supports the requested operation. Keep secrets in environment variables rather than command history or committed configuration.\n\n## Read the Bundled References\n\n- Read [references/cli-reference.md](references/cli-reference.md) for the subcommand and common flag index.\n- Read [references/workflows.md](references/workflows.md) for headless execution, sessions, worktrees, permissions, sandboxing, and MCP examples.\n\nVerify destructive commands such as session deletion, plugin removal, MCP removal, memory clearing, and worktree removal with the user or the governing workflow before running them.\n\n<!-- File: packages/cli/src/skill/builtin/.bundle/html-to-video-pipeline/SKILL.md (Tokens: ~4288 | Category: anthropic-skill) -->\n---\nname: html-to-video-pipeline\ndescription: Reliable HTML-to-MP4 rendering via headless browser recording (Playwright/Puppeteer) + ffmpeg — the ordering, gotchas, and verification steps you MUST get right or the output silently rots. Trigger whenever the user is building or debugging any pipeline that turns an HTML/CSS/JS page (single-file, multi-composition, GSAP-driven, or `@keyframes`-driven) into a video file, including headless recording, screen capture of a web page, deterministic frame-by-frame capture, multi-scene concatenation, or engine-mixed video output. Also trigger when the symptom sounds like: font swap flashing in the opening frames (FOUT), the first few seconds of the video are frozen/dead, animations play during page load and get truncated, concatenated segments produce a video whose duration is wildly wrong (e.g., 8s becomes 35s), `file://` loaded HTML fails to fetch its sub-scenes, the exported video is soft/blurry compared to the browser, or playback stutters/looks choppy despite passing a high `-r` fps to ffmpeg. Use even for one-off scripts — the failure modes here are subtle enough that starting from scratch usually reintroduces them.\n---\n\n# HTML → Video: the pipeline that actually works\n\nTurning a live HTML page into an MP4 sounds like a one-liner (\"Playwright records, ffmpeg encodes\") and the first draft always looks fine — until you play back the export and notice text flashing in a fallback font, three dead seconds at the start, or a \"10-second\" clip that clocks in at 35s. This skill captures the specific ordering, waits, and encoder flags that make the output trustworthy.\n\nThink of the pipeline as five phases with a single invariant between them:\n\n```\nlaunch  →  hold @ frame 0  →  align capture start with animation start  →  record  →  trim & encode\n```\n\nThe invariant: **no pixel of the animation should render before capture is ready, AND capture must not start before every asset that affects layout has loaded.** Every gotcha below is a violation of that invariant.\n\nQuick checklist (each item is expanded below):\n\n1. `viewport` must exactly equal `recordVideo.size` — mismatch silently rescales the output soft/blurry.\n2. Freeze CSS animations via `addInitScript` **before** `goto()`.\n3. `goto` with `domcontentloaded`, never `load`.\n4. Pre-inline `data-composition-src` sub-scenes — `file://` blocks client-side `fetch`.\n5. Font wait = stylesheet `<link>` load → `face.load()` per face → `fonts.ready` → 2 rAFs.\n6. Probe duration with infinite-iteration / `repeat: -1` guards.\n7. Unfreeze = t=0; trim `leadInMs − 120ms` with `-ss` *before* `-i`.\n8. Concat: same engine → demuxer `-c copy`; mixed engines → concat *filter* + re-encode.\n9. Verify with ffprobe duration + full decode + sampled frames. Always.\n\nThere are two capture modes, and picking the wrong one wastes a day:\n\n- **Mode A — real-time `recordVideo`** (the phases below). Simple, wall-clock = clip length. But the screencast is best-effort variable frame rate (~25fps) and competes with the animation for CPU. Good enough for previews and ≤30fps deliverables on an idle machine.\n- **Mode B — deterministic frame stepping** (pause everything, seek to `i / fps`, screenshot, encode the PNG sequence). Exact fps, every frame rendered, no lead-in trim, immune to machine load. Required when the output must be genuinely smooth ≥30fps or renders run on loaded CI. See \"Deterministic frame stepping\" below.\n\n## Prerequisites — install these first\n\nTwo hard requirements: a headless browser driver (Playwright or Puppeteer) and `ffmpeg`. Everything below assumes both are installed and on `PATH`.\n\n### 1. Headless browser driver\n\nPlaywright is the default in this skill (its `recordVideo` API is what the pipeline is written against). Puppeteer works too but you'll wire recording yourself via CDP screencast — pick Playwright unless you have a reason not to.\n\n```bash\n# Playwright (recommended) — npm / pnpm / bun all work\nnpm  install playwright\npnpm add playwright\nbun  add playwright\n\n# Then install the actual browser binaries (this is the step people forget):\nnpx playwright install chromium              # just Chromium — enough for this pipeline\nnpx playwright install --with-deps chromium  # Linux/CI: also install shared libs\n```\n\nVerify: `npx playwright --version` prints the driver version, and `node -e \"require('playwright').chromium.launch().then(b => b.close())\"` exits cleanly.\n\nPuppeteer alternative (only if you already have it in the project):\n\n```bash\nnpm install puppeteer            # bundles a matching Chromium automatically\n# or, to reuse a system Chrome:\nnpm install puppeteer-core       # no bundled browser — you supply executablePath\n```\n\n### 2. ffmpeg\n\nThe encode/trim/concat/verify steps all shell out to `ffmpeg` (and `ffprobe`, which ships in the same package). It is **not** an npm dependency — install it at the OS level.\n\n```bash\n# macOS\nbrew install ffmpeg\n\n# Debian / Ubuntu\nsudo apt-get update && sudo apt-get install -y ffmpeg\n\n# Fedora / RHEL\nsudo dnf install ffmpeg          # requires RPM Fusion enabled\n\n# Windows\nwinget install Gyan.FFmpeg       # or: choco install ffmpeg\n```\n\nVerify: `ffmpeg -version` and `ffprobe -version` both print. If a script spawns `ffmpeg` and gets `ENOENT`, the binary isn't on `PATH` — see the graceful-failure snippet in `references/ffmpeg-cheatsheet.md`.\n\nDo **not** rely on the `ffmpeg-static` / `@ffmpeg-installer/ffmpeg` npm packages for production: their bundled builds skip codecs and encoder flags you'll hit sooner or later (e.g. `libx264` presets, `tpad`). A system ffmpeg is the durable choice.\n\n### 3. Optional — ImageMagick (verification only)\n\nOnly needed if you want the \"did anything render?\" pixel-mean check from Phase 6. Skip it otherwise.\n\n```bash\nbrew install imagemagick         # macOS\nsudo apt-get install imagemagick # Debian/Ubuntu\n```\n\nVerify: `magick -version` (ImageMagick 7) or `convert -version` (ImageMagick 6).\n\n## The pipeline\n\n### Phase 1 — Launch and prepare the recorder\n\nUse `playwright.chromium.launch({ headless: true })` and a context configured with `recordVideo: { dir, size: { width, height } }`. Two sizing rules:\n\n- **`viewport` must exactly equal `recordVideo.size`.** When they differ, Playwright rescales the screencast to fit the recording size and the whole output goes soft. Derive both from the same constants.\n- `recordVideo` captures at CSS-pixel resolution; `deviceScaleFactor` does **not** raise recording resolution. For a 1080p export use a 1920×1080 viewport, not 960×540 @ 2x.\n\nRecording begins the instant the context exists — treat that timestamp as the WebM's t=0 and remember it (`tWebmStart = Date.now()`); you will need it in Phase 5 to trim the dead opening.\n\nKnow the recorder's ceiling: the screencast runs at a variable ~25fps and drops frames under CPU load. The `-r <fps>` flag in Phase 5 makes the container constant-frame-rate but only duplicates frames — it cannot add smoothness. If stutter matters, switch to frame stepping (Mode B) instead of fighting this.\n\n### Phase 2 — Freeze animations BEFORE the page parses\n\nThis is the single most-missed step. Pure-CSS `@keyframes` animations begin the moment the element is styled — there is no JS trigger to hold. If you `goto()` the HTML and then start waiting for fonts (which takes seconds), the CSS timeline has *already been running the whole time*. The recording captures the fallback font swapping to the real face mid-clip, and the opening beats of the animation are lost to the font wait.\n\nFix: inject a global freeze **via `page.addInitScript()`**, which runs before any of the document's own scripts and before CSS is applied, so the timeline is paused at frame 0 the moment it exists:\n\n```js\nawait page.addInitScript(() => {\n  const style = document.createElement('style');\n  style.id = '__freeze';\n  style.textContent =\n    '*, *::before, *::after { animation-play-state: paused !important;' +\n    ' -webkit-animation-play-state: paused !important; }';\n  const attach = () => (document.head || document.documentElement).appendChild(style);\n  if (document.head || document.documentElement) attach();\n  else document.addEventListener('DOMContentLoaded', attach, { once: true });\n  window.__unfreeze = () => document.getElementById('__freeze')?.remove();\n});\n```\n\nThis does not stop GSAP tweens driven by JS (see Phase 4 for those) — for GSAP-driven templates, register the master timeline paused and expose a `window.__playAll()` you call in Phase 4.\n\n### Phase 3 — Load with `domcontentloaded`, not `load`\n\n`waitUntil: 'load'` blocks on every external asset, including cross-origin videos with no CORS headers. Chromium will retry those for ~4s before giving up, and those 4s get burned into the recording as a frozen first scene. Use `waitUntil: 'domcontentloaded'` — the DOM + synchronous inline scripts (GSAP, your player) are ready, and you handle fonts explicitly next.\n\nIf the template is multi-composition (scenes loaded via `data-composition-src` and client-side `fetch`), you must **pre-inline** those sub-files into the entry HTML on the Node side and write it to a sibling `.tmp.html`. Chromium blocks `file://` fetch, so client-side scene loaders that work in a browser tab will silently produce an empty shell in a headless recording. See `references/multi-composition.md`.\n\n### Phase 4 — Wait for fonts properly, then release\n\n`document.fonts.ready` alone is **not enough** and this is the second most-missed step. Under `domcontentloaded`, the Google Fonts (or any external) `<link rel=\"stylesheet\">` has usually not returned yet. Until its CSS arrives, its `@font-face` rules are not in `document.fonts` at all — so `fonts.ready` sees an empty set and resolves *instantly*. Recording proceeds, the CSS lands mid-clip, faces download, and the swap happens on-camera.\n\nThe correct sequence, all inside a `page.evaluate()` with an 8s hard cap so a wedged CDN can't stall forever:\n\n1. Wait for every `<link rel=\"stylesheet\">` to `load` or `error` — that registers `@font-face` rules into `document.fonts`.\n2. For each registered face, call `face.load()` explicitly. `font-display: swap` defers the download until something paints with that face — if your first frame doesn't happen to use the face, it never fetches without this.\n3. `await fonts.ready`.\n4. Two rAFs so layout settles on the real glyph metrics before frame 0.\n\nThen, and only then:\n\n5. Drive playback: for GSAP multi-composition templates, call `window.__playAll()` to start every registered (paused) master timeline from 0. For pure-CSS templates, this is a no-op.\n6. Call `window.__unfreeze()` to remove the freeze style. **This is the true t=0 of the animation.** Record the wall-clock offset from `tWebmStart` (`leadInMs = Date.now() - tWebmStart`) — this is what you trim in Phase 5.\n\nThe full JS for Phase 4 is in `references/font-wait.md`.\n\n### Phase 5 — Probe duration, record, then trim and encode\n\n**Probe duration first** (skip this only if you know the exact intended length). The user's requested `duration` may be shorter than the animation, in which case you'd cut the animation mid-play. Take the maximum of:\n\n- The longest **non-infinite** CSS animation (`animation-duration + animation-delay` for entries where `animation-iteration-count !== 'infinite'`).\n- The longest **finite** GSAP tween. Do **not** use `gsap.globalTimeline.totalDuration()` — a `repeat: -1` tween (blinking cursor, looping background) makes it ~1e10s. Walk `globalTimeline.getChildren(true, true, true)` and skip anything with `repeat() === -1`.\n\nAdd a ~400ms settle so the last animation frame is captured, cap at 30s so a stray huge value can't run away. If your caller passed an *explicit* per-frame duration (e.g. \"each scene is exactly 4s\"), do **not** extend — treat it as a hard cap and pad the tail if the animation finished early (see below). If duration was 'auto', extend to the probed length.\n\n**Record** for `totalDuration`, then `context.close()`. Playwright drops the WebM in `recordDir`.\n\n**Encode with ffmpeg**, applying two corrections:\n\n```\nffmpeg -y \\\n  [ -ss <(leadInMs - 120) / 1000> ]  # trim dead lead-in, back off 120ms so we don't clip frame 1\n  -i input.webm \\\n  [ -vf tpad=stop_mode=clone:stop_duration=<totalDuration> ]  # pad tail only when duration is explicit\n  -t <totalDuration> \\                # trim to exact length (recordVideo sometimes overshoots)\n  -r <fps> \\\n  -c:v libx264 -pix_fmt yuv420p -preset medium -crf 20 \\\n  -movflags +faststart \\\n  out.mp4\n```\n\nThe `-ss` back-off matters: recorder start jitter and rounding can steal the first real frame if you trim to exactly `leadInMs`. A couple of extra still frames at the head are invisible; a missing opening beat is obvious.\n\n## Deterministic frame stepping (Mode B)\n\nWhen the deliverable must be genuinely smooth at an exact fps — or the render runs on a loaded CI box where real-time capture visibly stutters — don't record in real time at all. Keep Phases 1–4 (minus `recordVideo`), then: pause every timeline, seek to `i / fps`, `page.screenshot()` each frame, and encode the PNG sequence with `ffmpeg -framerate <fps>`. Duration is exact by construction, there is no lead-in to trim, and every single frame is fully rendered regardless of machine load.\n\nIt works when the page's motion is declaratively seekable — CSS `@keyframes` (via `document.getAnimations()` + `currentTime`), WAAPI, and GSAP (`gsap.globalTimeline.time(t)`). It does **not** work for `<video>` elements, `setTimeout`-choreographed scenes, or rAF-driven physics; those need real-time recording or a CDP virtual clock. Step time monotonically forward, never backwards.\n\nFull loop, the seek/suppressEvents subtleties, the \"animations created later by JS are invisible to the seek\" trap, and optional 2x supersampling are in `references/frame-stepping.md`.\n\n## Multi-segment concatenation\n\nWhen you have N per-scene MP4s and need one output, the correct ffmpeg strategy depends on whether the inputs share a codec/timebase.\n\n**Same encoder, same params (typical: all scenes rendered by the same adapter)** — use `concat` demuxer with stream copy. Fast, lossless:\n\n```\nffmpeg -y -f concat -safe 0 -i list.txt -c copy out.mp4\n```\n\nwhere `list.txt` is `file 'seg1.mp4'\\nfile 'seg2.mp4'\\n...`.\n\n**Mixed sources (e.g. scene A recorded by headless Chromium, scene B rendered by a React/Remotion pipeline)** — the concat demuxer's `-c copy` path assumes compatible timebases and PTS. When timebases differ, PTS accumulate incorrectly and an 8-second output can become 35 seconds. **Even `-vsync cfr` won't save you** — the bad PTS have already been fed in. You must re-encode via the concat **filter**, which rebuilds the timeline:\n\n```\nffmpeg -y -i seg1.mp4 -i seg2.mp4 -i seg3.mp4 \\\n  -filter_complex \"[0:v][1:v][2:v]concat=n=3:v=1:a=0[v]\" \\\n  -map \"[v]\" -c:v libx264 -pix_fmt yuv420p -r 60 \\\n  -movflags +faststart out.mp4\n```\n\nDecision rule in code: pass a `reencode: boolean` down to your concat helper. Set it to `true` whenever any segment came from a different rendering engine than the others, or when you're not sure.\n\n## Verify — always\n\nYou cannot trust \"the file was written\" as success. The failure modes above (wrong duration, FOUT, dead lead-in) all produce a playable MP4. Before declaring success:\n\n- `ffprobe -v error -show_entries format=duration -of csv=p=0 out.mp4` — actual duration matches expected within ~50ms?\n- `ffmpeg -v error -i out.mp4 -f null -` — full decode, no errors? A \"silently corrupted\" output from a bad concat will decode fine but be the wrong length; conversely, a broken concat demuxer output can throw here.\n- Sample a frame near t=0.1s and t=0.5s (`ffmpeg -ss 0.1 -i out.mp4 -frames:v 1 -y f1.png`) — text renders in the intended font? If your test rig has ImageMagick, `magick f1.png -threshold 50% -format '%[fx:100*mean]' info:` gives a rough non-background pixel percentage that catches \"recording is completely blank\" regressions.\n\nFor fonts specifically: **studio-style live iframe previews will not reproduce FOUT** because the browser tab caches faces. Only cold-headless rendering (i.e. the actual export path) reproduces it. Verify on the exported MP4, not the preview.\n\n## When to depart from this template\n\n- **Non-animated single-frame PNG export.** Skip Phases 2, 4-5-recording; goto → `fonts.ready` → `page.screenshot()` is enough. FOUT still applies for the screenshot.\n- **You own the animation timeline in JS end-to-end** (e.g. Motion Canvas / Remotion generator style). The freeze/unfreeze dance is unnecessary because *you* drive frame-by-frame rendering — use the framework's own frame API and skip Playwright recording entirely. The concat rules still apply if you're mixing engines.\n- **Interactive-page capture** (recording a real user session). Duration probing is meaningless; use manual start/stop signals and skip lead-in trim.\n\n## Reference files\n\n- `references/font-wait.md` — full JS for the Phase 4 font-wait routine, with per-link timeout and rAF-based settle.\n- `references/frame-stepping.md` — the Mode B deterministic capture loop: seek-per-frame, screenshot, PNG-sequence encode, supersampling, and its limits.\n- `references/multi-composition.md` — inlining `data-composition-src` scenes for `file://` recording, including re-executing cloned `<script>` nodes.\n- `references/duration-probe.md` — CSS + GSAP probe with the infinite-iteration guards.\n- `references/ffmpeg-cheatsheet.md` — the encode/concat/verify commands in one place.\n\n<!-- File: packages/cli/src/skill/builtin/.bundle/learn-everything/SKILL.md (Tokens: ~2379 | Category: anthropic-skill) -->\n---\nname: learn-everything\ndescription: Turn an uploaded PDF, paper, book chapter, document, URL, or user-provided topic into a structured, interactive learning course. Use when the user wants to learn, study, understand, master, review, or practice a subject chapter by chapter; asks for a tutorial or curriculum from source material; wants exercises, quizzes, answer grading, hints, spaced review, or a final assessment; or says \"teach me this\", \"learn this PDF\", \"分章节教学\", \"带我学\", or similar; or returns to continue a previous course (\"continue my course\", \"接着上次学\") or supplies a saved course-state file or state block. Adapt explanations and practice to the learner's level, preserve page or section references for documents, and teach incrementally rather than dumping all content at once.\n---\n\n# Learn Everything\n\nConvert source material or a topic into an adaptive course that alternates explanation, retrieval, application, feedback, and review.\n\n## Core behavior\n\n- Teach in the user's language unless they request another language.\n- Optimize for durable understanding, not merely summarization.\n- Work incrementally. Present a course map, then teach one chapter or lesson at a time.\n- Do not reveal exercise solutions before the learner attempts them, unless the learner explicitly asks.\n- Persist learning state. When file tools are available, maintain `learn/<slug>/course-state.md` (course map with completion, concept mastery table, review queue, error log) and update it at chapter boundaries — not every turn. Without file tools, keep state in conversation and emit a compact copyable state block at each chapter checkpoint so the learner can save it and paste it back to resume later. See `references/session-formats.md` for both formats.\n- Prefer concrete examples, analogies, diagrams described in text, counterexamples, and worked derivations over abstract exposition alone.\n- Separate source claims from added background knowledge. Never attribute added material to the source.\n- Match depth and notation to the learner. Define unfamiliar terms before relying on them.\n\n## Determine the input mode\n\n### Document mode\n\nUse document mode for PDFs, papers, books, slides, notes, or other supplied material.\n\n1. Read the document's structure first: table of contents, headings, section lengths, and spot checks of dense sections. Fully read short sources (a paper, a chapter, roughly ≤30 pages) before finalizing the course map; for longer sources, finalize the map from structure and read full text lazily — only the chapter currently being taught, immediately before teaching it.\n2. Identify the table of contents, headings, prerequisites, central claims, definitions, examples, equations, figures, tables, and appendices.\n3. Use semantic units rather than equal page ranges. Merge short dependent sections and split dense sections.\n4. Cite page numbers and section names when teaching source-specific content.\n5. Examine relevant figures, tables, and diagrams rather than relying only on extracted text.\n6. Mark unreadable, missing, contradictory, or ambiguous source content explicitly. Do not invent a reconstruction.\n7. Treat the supplied source as the primary curriculum. Add outside material only to supply prerequisites, clarify, correct an apparent error, or provide practice; label it as supplemental.\n\n### Topic mode\n\nUse topic mode when the learner supplies a subject rather than a source.\n\n1. Define a sensible scope and end capability.\n2. Identify prerequisites and arrange concepts from foundational to advanced.\n3. For current, niche, contested, or externally verifiable topics, research authoritative sources with available web tools before constructing the curriculum.\n4. Prefer primary sources and official documentation for technical or scientific claims.\n5. Distinguish stable fundamentals from current developments.\n6. State material scope and assumptions in the course map.\n\nDo not delay progress for minor ambiguity. Choose a useful default scope and make it visible.\n\n### Resume mode\n\nUse resume mode when the learner supplies a saved course-state file or state block, or asks to continue a previous course.\n\n1. Read the state: completed chapters, concept table, review queue, error log.\n2. Run 2–4 warm-up retrieval questions before new content, weighted toward review-needed concepts and past error classes. Ask fresh questions, never the originals verbatim.\n3. Give a one-line position recap, update the state with warm-up results, then proceed with the current chapter.\n4. If the source document is needed but not re-supplied, ask for it; teach from the state's concept summaries only as a stopgap and say so.\n\n## Start the course\n\nGather only information that materially changes the lesson. If the learner's level or goal is unknown, either:\n\n- ask one compact diagnostic question, or\n- offer a 3-question diagnostic quiz and let the learner skip it.\n\nDo not ask a long questionnaire. Infer preferences from the conversation whenever possible.\n\nThen provide:\n\n1. **Target capability** — what the learner should be able to explain or do.\n2. **Course map** — 3–12 chapters, each with purpose and prerequisites.\n3. **Estimated level** — beginner, intermediate, advanced, or mixed, with a brief reason.\n4. **Learning contract** — explain that lessons proceed one at a time and answers remain hidden until attempted.\n5. **Next action** — begin the first lesson or diagnostic immediately.\n\nUse the detailed formats in `references/session-formats.md` when consistency is useful.\n\n## Build the course map\n\nCreate chapters around conceptual dependencies, not source length alone. Each chapter should have:\n\n- a concise title;\n- one observable learning objective;\n- key concepts;\n- prerequisite links;\n- source pages or sections in document mode;\n- one planned practice outcome.\n\nUse these sizing rules:\n\n- Split a chapter when it contains more than one major reasoning jump.\n- Merge sections that cannot be understood independently.\n- Create a prerequisite bridge chapter when the source assumes missing knowledge.\n- Keep advanced appendices optional unless needed for the learner's goal.\n- For sources with more than ~12 natural chapters, group chapters into parts, agree on scope with the learner, and run the course part by part rather than flattening everything into one map.\n- Reorder only when pedagogically necessary; explain the reordering in document mode.\n\n## Teach each lesson\n\nFollow this lesson loop:\n\n1. **Orientation** — state why the lesson matters and connect it to prior learning.\n2. **Objectives** — give 2–4 observable goals.\n3. **Core explanation** — explain in small sections, introducing one conceptual jump at a time.\n4. **Worked example** — demonstrate the reasoning, not only the final result.\n5. **Misconception check** — identify 1–3 likely confusions or boundary cases.\n6. **Active recall** — ask a brief check before proceeding to longer practice.\n7. **Practice** — assign exercises calibrated to current mastery.\n8. **Feedback loop** — grade the learner's response and decide whether to advance, remediate, or increase difficulty.\n\nFor dense material, pause after each major concept and ask a single check question. For straightforward material, teach the full lesson before practice.\n\n## Design practice\n\nSelect exercises from multiple cognitive levels:\n\n- **Recall:** define, list, label, reproduce.\n- **Explain:** restate in the learner's own words; compare concepts; explain why.\n- **Apply:** solve a representative problem or use the method in context.\n- **Debug:** find an error in reasoning, code, derivation, or interpretation.\n- **Transfer:** apply the idea in a novel setting.\n- **Synthesize:** connect several chapters or produce an artifact.\n\nDefault to 3–5 exercises per lesson, mixing at least two levels. Prefer one exercise at a time when grading interactively. Use larger sets only when the learner requests a worksheet or exam.\n\nConsult `references/practice-and-mastery.md` for exercise-writing rules, difficulty bands, adaptation, and grading rubrics. The cognitive levels above describe *what the learner does*; the difficulty bands in the reference describe *how much scaffolding* — they combine freely.\n\n## Grade and respond to learner answers\n\nEvaluate substance before wording. Use this sequence:\n\n1. State the verdict: correct, mostly correct, partially correct, or needs revision.\n2. Identify what was done well.\n3. Point to the first important gap or error.\n4. Explain the correction with the smallest useful amount of teaching.\n5. Ask for a revision, provide a targeted follow-up, or advance.\n\nDo not merely say “correct.” Reinforce the decisive reasoning.\n\nWhen the answer is wrong:\n\n- First provide a hint that targets the misconception.\n- Give a stronger hint after another failed attempt.\n- Reveal a worked solution after repeated attempts, an explicit request, or when further guessing has low learning value.\n- Immediately follow a revealed solution with a near-transfer question.\n\nWhen the answer is correct:\n\n- Increase difficulty gradually.\n- Ask for explanation if the learner may have guessed.\n- Use a transfer question when mastery appears strong.\n\n## Track mastery and review\n\nMaintain a concept table — one row per concept — in the course state (file or state block):\n\n- status: unseen, introduced, practicing, mastered, or review-needed;\n- evidence: strongest recent answer or error;\n- confidence: low, medium, or high;\n- next review point.\n\nUpdate it at chapter boundaries and after significant errors. Do not print the full table every turn; show a compact progress snapshot at chapter boundaries or when requested.\n\nSchedule cumulative review:\n\n- after each chapter: 2–4 retrieval questions from current and earlier material;\n- after roughly one-third and two-thirds of the course: mixed checkpoint;\n- at course end: final assessment and synthesis task;\n- revisit recurring errors more often than mastered concepts.\n\nTreat mastery as demonstrated transfer, not one correct recall answer.\n\n## Handle learner commands\n\nRecognize and act on natural commands such as:\n\n- “继续 / continue” — move to the next pending step.\n- “提示 / hint” — give the next hint without the full answer.\n- “答案 / show solution” — reveal and explain the solution, then ask a near-transfer question.\n- “更简单 / simpler” — reduce abstraction, add prerequisites and examples.\n- “更深入 / deeper” — add derivation, edge cases, and harder transfer.\n- “跳过 / skip” — mark the item skipped and continue.\n- “复习 / review” — generate retrieval practice weighted toward weak concepts.\n- “考试 / test me” — run a closed-book mixed assessment.\n- “进度 / progress” — show completed chapters, mastery, weak points, and next step.\n- “重做课程 / rebuild course” — revise scope or chaptering while preserving demonstrated mastery.\n\n## Complete the course\n\nAt the end, provide:\n\n1. a mixed final assessment without solutions shown initially;\n2. a synthesis task that uses multiple chapters;\n3. grading with concept-level feedback;\n4. a concise mastery report;\n5. a personalized review plan focused on weak concepts;\n6. a compact reference sheet created only after assessment, so it does not replace retrieval practice.\n\nFor document mode, include a source navigation index linking mastered concepts back to pages or sections.\n\n## Quality checks\n\nBefore each response, verify:\n\n- Solutions are not exposed before the learner attempts the exercise.\n- The current activity matches the course state, and the state is updated at chapter boundaries.\n- The lesson does not assume an unexplained prerequisite.\n- The response gives the learner exactly one clear next action.\n\n<!-- ... +62 more modular skills available via /api/skills/XiaomiMiMo/MiMo-Code?path={path} -->\n</yakaai_skills>"}