Skill: sdk-team/alibabacloud-analyticdb-mysql-copilot (version 0.0.2)

--- name: alibabacloud-analyticdb-mysql-copilot description: | Alibaba Cloud AnalyticDB for MySQL Operations & Diagnosis Assistant. Supports cluster info queries, performance monitoring, slow query diagnosis, running SQL analysis, table-level optimization suggestions, etc. Triggers: "ADB MySQL", "AnalyticDB", "cluster list", "slow query", "BadSQL", "data skew", "idle index", "SQL Pattern", "space diagnosis", "table diagnosis", "performance monitoring". --- > **Skill Load Prompt**: When this Skill is loaded, output the following line at the beginning of the first response: `[Skill Loaded] alibabacloud-analyticdb-mysql-copilot — ADB MySQL Operations & Diagnosis Assistant` This Skill is the **Alibaba Cloud AnalyticDB for MySQL (ADB MySQL) Operations & Diagnosis Assistant**, which directly calls ADB MySQL OpenAPI via `aliyun-cli` to retrieve real-time data and provide diagnostic recommendations. Core capabilities: - **Cluster Management**: View cluster list, cluster details, storage space, accounts, network information - **Performance Monitoring**: Query CPU, QPS, RT, memory, connection count and other performance metrics - **Slow Query Diagnosis**: Detect BadSQL, analyze SQL Patterns, identify slow query root causes - **Running SQL Analysis**: View currently executing SQL, identify long-running queries - **Space Diagnosis**: Instance space inspection, covering partition rationality diagnosis, oversized non-partitioned table diagnosis, table data skew diagnosis, replicated table rationality diagnosis, primary key rationality diagnosis, idle index & hot/cold table optimization suggestions --- > **Pre-check: Aliyun CLI >= 3.3.3 required** > Run `aliyun version` to verify version >= 3.3.3. If not installed or version is too low, > run `curl -fsSL https://aliyuncli.alicdn.com/setup.sh | bash` to install/update, > or see `references/cli-installation-guide.md`. > Then [MUST] run `aliyun configure set --auto-plugin-install true` to enable automatic plugin installation. > [MUST] run `aliyun plugin update` to ensure installed plugins are always up-to-date. > **Pre-check: Alibaba Cloud Credentials Required** > > **Security Rules:** > - **NEVER** read, echo, or print AK/SK values (e.g., `echo $ALIBABA_CLOUD_ACCESS_KEY_ID` is FORBIDDEN) > - **NEVER** ask the user to input AK/SK directly in the conversation or command line > - **NEVER** use `aliyun configure set` with literal credential values > - **ONLY** use `aliyun configure list` to check credential status > > ```bash > aliyun configure list > ``` > Check whether the output contains a valid profile (AK, STS, or OAuth identity). > > **If no valid profile exists, stop here.** > 1. Obtain credentials from [Alibaba Cloud Console](https://ram.console.aliyun.com/manage/ak) > 2. Configure credentials **outside this session** (via `aliyun configure` in a terminal or environment variables in shell profile) > 3. Return and re-execute once `aliyun configure list` shows a valid profile > **[MUST] CLI User-Agent** — Every `aliyun` CLI command invocation must include: > `--user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-mysql-copilot` At the **start** of the Core Workflow (before any CLI invocation): **[MUST] Enable AI-Mode** — AI-mode is required for Agent Skill execution. Run the following commands before any CLI invocation: ```bash aliyun configure ai-mode enable aliyun configure ai-mode set-user-agent --user-agent [REDACTED_SECRET] ``` **[MUST] Disable AI-Mode at EVERY exit point** — Before delivering the final response for ANY reason, always disable AI-mode first. This applies to ALL exit paths: workflow success, workflow failure, error/exception, user cancellation, session end, or any other scenario where no further CLI commands will be executed. AI-mode is only used for Agent Skill invocation scenarios and MUST NOT remain enabled after the skill stops running. ```bash aliyun configure ai-mode disable ``` --- ## 1. Region & Cluster ID Conventions ### 1.1 Cluster Management (aliyun adb) **Convention**: For any interface that requires **`--db-cluster-id`**, the `aliyun adb` command **must also explicitly include `--biz-region-id`**. Even if the official/CLI help does not mark it as "required", **this Skill's convention takes precedence** — always include it to avoid relying on implicit default regions. **Exception**: **Only when listing resources by region** or calling interfaces that **do not include** `--db-cluster-id` (such as `describe-db-clusters`) — `--biz-region-id` is still required, but the "paired with db-cluster-id" rule does not apply. **`<region-id>` Source Priority**: User explicitly specified → conversation/ticket context → default region from `aliyun configure list` → confirm with user. ### 1.2 Intelligent Diagnosis (aliyun adbai) `aliyun adbai describe-chat-message` supports two scenarios with different workflows: #### Product Knowledge Q&A (No Region or Cluster Required) When the user asks about product concepts, syntax, feature questions, etc. (e.g., "What is BUILD", "How to create a partitioned table"), **no need** to confirm region and cluster — **execute directly** with the following command: ```bash aliyun adbai describe-chat-message --region cn-beijing --endpoint adbai.cn-beijing.aliyuncs.com --biz-region-id cn-beijing --query "<user question>" --user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-mysql-copilot ``` #### Instance-Level Diagnosis (Requires Region + Cluster) When diagnosis involves specific instance data or status (e.g., slow queries, BadSQL, SQL Pattern analysis, instance health inspection, index optimization suggestions, instance diagnosis, table modeling diagnosis, etc.), **the following steps must be completed**: 1. **Region Confirmation**: `<region-id>` source priority is: user explicitly specified → conversation/ticket context → default region from `aliyun configure list` → confirm with user. If user confirmation is needed, **must read `references/region-list.md`** and present options as option cards — **forbidden** to require manual region ID input. 2. **Cluster ID Validation**: Before calling `aliyun adbai`, **must first execute** `aliyun adb describe-db-clusters --api-version 2021-12-01 --biz-region-id <region-id> --region <region-id>`, and search for the user's cluster ID in the returned `Items.DBCluster[]`: - Match found → validation passed - Empty list or no match → **do not proceed**, display actual clusters as option cards for user to select - User did not provide cluster ID → display cluster list as option cards (≤10 options) for user to select 3. **Pre-Execution Confirmation**: After parameter validation, present the operation to be executed as option cards (e.g., "Continue" / "Cancel") for user confirmation — **forbidden** to require manual confirmation input. 4. **Mandatory Checklist** (all conditions **must be met** before execution, none can be omitted): - [ ] `biz-region-id` confirmed by user - [ ] `cluster-id` confirmed by user and exists in `describe-db-clusters` returned list - [ ] Pre-execution confirmation obtained from user 5. **Region Routing Rules (P0)**: The `aliyun adbai` service endpoint is not deployed in every region. **For all `aliyun adbai` calls, `--region` and `--endpoint` must be forcibly overridden** according to the following routing table mapping, even if the user has specified a region — do not use the user's specified values: | biz-region-id | --region | --endpoint | |-----------|----------|------------| | cn-hangzhou, cn-shanghai, cn-beijing, cn-shenzhen, cn-hongkong, cn-qingdao, cn-heyuan, cn-chengdu, cn-guangzhou, cn-zhangjiakou, cn-wulanchabu, cn-huhehaote, cn-shanghai-cloudspe, cn-hangzhou-finance, cn-beijing-finance-1, cn-shenzhen-finance-1, cn-shanghai-finance-1 | cn-beijing | adbai.cn-beijing.aliyuncs.com | | ap-southeast-1, ap-southeast-3, ap-southeast-5, ap-southeast-6, ap-southeast-7, ap-northeast-1, ap-northeast-2, eu-central-1, eu-west-1, me-east-1, me-central-1, na-south-1 | ap-southeast-1 | adbai.ap-southeast-1.aliyuncs.com | | us-east-1, us-west-1 | us-west-1 | adbai.us-west-1.aliyuncs.com | **Example**: User's cluster is in `cn-zhangjiakou` → `--biz-region-id cn-zhangjiakou --region cn-beijing --endpoint adbai.cn-beijing.aliyuncs.com` All sections below and examples in `references/*.md` that contain `--db-cluster-id` without `--biz-region-id` **are automatically supplemented per this section's convention**; this is not repeated in each reference — **this section takes precedence**. ## 2. Scenario Routing > **Product Boundary**: This Skill only applies to **AnalyticDB for MySQL (ADB MySQL)**, cluster IDs typically start with `am-xxx` or `amv-xxx`. If the user mentions other Alibaba Cloud products (e.g., Elasticsearch, RDS MySQL, PolarDB, ClickHouse, etc.), clearly inform the user that this Skill does not apply and stop execution. --- > **🚨🚨🚨 MUST | P0 | NON-NEGOTIABLE — Mandatory Enforcement Rules (Violation = Failure) 🚨🚨🚨** > > The following rules have the highest priority and **must be enforced unconditionally** — they **must not be violated** under any circumstances: > > ### Rule 1: Mandatory API Invocation > When a user request matches the following scenarios, **must immediately execute the corresponding API call** — **skipping is prohibited**: > > | User Request Keywords | MUST-Call API | Prohibited Behavior | > |---------------|---------------|----------| > | "cluster list", "instance list", "all clusters", "list clusters" | `describe-db-clusters` | ❌ Not calling API, giving advice directly | > | "data skew", "BadSQL", "slow SQL detection", "running SQL", "idle index", "SQL Pattern", "space diagnosis", "health inspection", "instance diagnosis", "slow query", "RT increase", "cluster stall" and other diagnosis keywords | `DescribeChatMessage` | ❌ Not calling API, only giving advice/explaining concepts | > > ### Rule 2: Mandatory Command String Output (First Line of Response) > **MUST**: Every ADB OpenAPI call, **must explicitly output the executed command string at the [first line] or [beginning] of the response**. > > **Mandatory Format** (must be strictly followed): > ``` > Command executed: `aliyun adb <command-name> --api-version 2021-12-01 --biz-region-id <region-id> [--db-cluster-id <cluster-id>] [other parameters]` > or > Command executed: `aliyun adbai describe-chat-message --region <mapped-region> --endpoint <mapped-endpoint> --biz-region-id <region-id> --query "<user question>"` > > [Then diagnostic results, tables, etc.] > ``` > > **Correct Examples**: > ``` > Command executed: `aliyun adb describe-db-clusters --api-version 2021-12-01 --biz-region-id cn-zhangjiakou --region cn-zhangjiakou` > > Query complete! There are 2 ADB MySQL clusters in the Zhangjiakou region... > ``` > > ``` > Command executed: `aliyun adbai describe-chat-message --region cn-beijing --endpoint adbai.cn-beijing.aliyuncs.com --biz-region-id cn-zhangjiakou --query "amv-xxx slow query diagnosis for the last 3 hours"` > > Diagnosis complete! Found the following issues... > ``` > > **Incorrect Examples** (violation = failure): > ``` > ❌ Query complete! There are 2 clusters in the Zhangjiakou region... (command string not output) > ❌ I called the API to query the cluster list... (complete command not output) > ❌ Command executed... (specific command content not output) > ❌ aliyun adb describe-db-clusters --biz-region-id cn-zhangjiakou --region cn-zhangjiakou (missing --api-version 2021-12-01) > ``` > > ### Rule 3: Prohibited Evasion Behaviors > **NON-NEGOTIABLE**: The following behaviors **are absolutely prohibited**: > - ❌ Not calling API and directly giving general advice or concept explanations > - ❌ Calling API but not outputting the complete command string at the beginning of the response > - ❌ Using vague expressions like "We suggest you...", "You can try..." instead of actual diagnosis > - ❌ Only outputting documentation content without executing actual operations > - ❌ Placing the command string in the middle or end of the response > - ❌ Calling `aliyun adb` commands without `--api-version 2021-12-01` (would default to the old version `2019-03-15`) > > **Violating the above rules = task failure, no exceptions** --- > **🔴 Cluster ID Recognition Rule (Highest Priority)**: If the user-provided cluster ID starts with `am-` or `amv-`, then the cluster **is definitely** an ADB MySQL cluster. **No need** and **must not** verify its ownership through `aliyun rds`, `aliyun polardb`, `aliyun clickhouse`, `aliyun hbase` or other product commands. Violating this rule will result in numerous invalid API calls. Based on the user's intent, read the corresponding `references/` files for detailed operation guidelines. | User Intent | Reference File | When to Use | MUST-Call API | |----------|----------|----------|----------------| | View instance list, instance details, cluster configuration, storage space | Read `references/cluster-info.md` then execute | When the user wants to know what instances exist, instance specifications, or disk usage | `describe-db-clusters` / `describe-db-cluster-attribute` | | Slow query diagnosis, BadSQL, running queries, SQL Pattern, instance diagnosis, instance write diagnosis, space diagnosis, table modeling diagnosis, data skew, idle index, product knowledge Q&A, etc. | Read `references/cluster-diagnosis.md` then execute | When the user reports performance anomalies, needs instance diagnosis, table modeling optimization, or product knowledge Q&A | `describe-chat-message` | **Routing Rules**: 1. Identify the user's intent and find the matching scenario from the table above 2. **🚨 MUST: Immediately execute the corresponding API command** (do not skip, do not only give advice): cluster management uses `aliyun adb`, intelligent diagnosis uses `aliyun adbai describe-chat-message` 3. **🚨 MUST: Output the command string in the response** (e.g., `aliyun adb describe-db-clusters --api-version 2021-12-01 --biz-region-id <region-id> --region <region-id>` or `aliyun adbai describe-chat-message --region <mapped-region> --endpoint <mapped-endpoint> --biz-region-id <region-id> --query "<question>"`) 4. Cluster management scenario: read `references/cluster-info.md`, execute per its steps; diagnosis scenario: read `references/cluster-diagnosis.md`, execute per its steps 5. If the user's intent cannot be matched to a specific scenario in the table, execute the following **default diagnosis workflow**: 1. Call `describe-db-clusters` to confirm the cluster exists and its status is normal 2. **Use option cards** to list the 2-3 most likely routing options (refer to the table above) — **forbidden** to require manual diagnosis type input 3. Based on user selection, route to the corresponding operation and continue execution 6. Multiple scenarios can be combined — e.g., first confirm the target instance via cluster info, then diagnose and locate the issue via `describe-chat-message` **Cluster ID Validation Rule**: If the user-provided cluster ID does not exist in the API response (error code `InvalidDBClusterId.NotFound`), do not abort the task. Instead, call `describe-db-clusters` to list the actual clusters in that region, guide the user to confirm the correct cluster ID, and continue execution. ## 3. Time Parameter Handling > **Note**: The `describe-chat-message` interface automatically handles time parameters — no need to manually pass time ranges. The user only needs to describe the time in natural language within `--query` (e.g., "slow queries in the last 3 hours"), and the interface will parse it automatically. > > For cluster information query interfaces like `aliyun adb` (e.g., `describe-db-clusters`), no time parameters are needed. ## 4. Command Reference ### 4.1 OpenAPI Commands (aliyun-cli) This Skill uses two CLI command formats: #### Cluster Management (aliyun adb) ```bash aliyun adb <command-name> --api-version 2021-12-01 --biz-region-id <region-id> --region <region-id> [--db-cluster-id <cluster-id>] [other parameters] --user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-mysql-copilot ``` > **🚨 API Version Mandatory Requirement (P0)**: When calling `aliyun adb`, **must always explicitly include `--api-version 2021-12-01`**. > ADB MySQL has two API versions (`2019-03-15` and `2021-12-01`), and the CLI may default to the old version `2019-03-15`, > which lacks the interfaces needed by this Skill. **Commands without `--api-version 2021-12-01` will fail, constituting task failure.** > **This Skill's Convention**: For any row in the table below that "requires `--db-cluster-id`", the actual command **must also include `--biz-region-id <region-id>`** (see Section 1.1). Only `describe-db-clusters` does not follow the "paired" rule, but still requires `--biz-region-id`. | CLI Command Name | Description | Requires `--db-cluster-id` | |----------|------|:---:| | `describe-db-clusters` | Query ADB MySQL cluster list within a region | No | | `describe-db-cluster-attribute` | Query cluster detailed attributes | Yes | | [REDACTED_SECRET] | Query storage space overview | Yes | #### Intelligent Diagnosis (aliyun adbai) ```bash aliyun adbai describe-chat-message --region <mapped-region> --endpoint <mapped-endpoint> --biz-region-id <region-id> --query "<user question>" --user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-mysql-copilot ``` `DescribeChatMessage` is the SSE streaming interface of the ADB MySQL intelligent diagnosis assistant, providing product RAG retrieval and instance analysis, kernel diagnosis capabilities. It includes the following diagnosis scenarios: - **Slow SQL Query Diagnosis**: Performance metric analysis, BadSQL detection, running SQL analysis, SQL Pattern analysis - **Instance Diagnosis**: Instance health inspection, capacity assessment, scaling recommendations - **Instance Write Diagnosis**: Write performance analysis, write bottleneck identification - **Table Modeling Diagnosis**: Oversized non-partitioned tables, partition rationality, primary key rationality, data skew, replicated table rationality, idle indexes, hot/cold table optimization | Parameter | Description | Required | |------|------|:---:| | `--biz-region-id` | User's cluster region ID (product knowledge Q&A uses default value `cn-beijing`, no user confirmation needed) | Conditionally required | | `--query` | Query content; for instance diagnosis, format is `"<cluster-id> <diagnosis question>"`; for product knowledge questions, ask directly (e.g., `"What is BUILD"`). | Yes | | `--region` | Service endpoint region (Skill auto-maps based on `--biz-region-id`, no user specification needed) | Auto | | `--endpoint` | Service endpoint address (Skill auto-maps based on `--biz-region-id`, no user specification needed) | Auto | | `--session-id` | Session ID for multi-turn conversations (not passed = new session) | No | | `--timezone` | Timezone, default `Asia/Shanghai` | No | > **Important**: Instance-level diagnosis (slow queries, table modeling, etc.) `--query` must include the cluster ID; no need to separately pass `--db-cluster-id`; product knowledge questions do not need a cluster ID. Examples: `"amv-xxx slow query diagnosis for the last 3 hours"`, `"What is BUILD"` **Examples**: ```bash # Slow query diagnosis aliyun adbai describe-chat-message --region cn-beijing --endpoint adbai.cn-beijing.aliyuncs.com --biz-region-id cn-zhangjiakou \ --query "amv-xxx slow query diagnosis for the last 3 hours" --user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-mysql-copilot # Instance health inspection aliyun adbai describe-chat-message --region cn-beijing --endpoint adbai.cn-beijing.aliyuncs.com --biz-region-id cn-zhangjiakou \ --query "amv-xxx instance health inspection analysis" --user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-mysql-copilot # Table modeling diagnosis aliyun adbai describe-chat-message --region cn-beijing --endpoint adbai.cn-beijing.aliyuncs.com --biz-region-id cn-zhangjiakou \ --query "amv-xxx instance space diagnosis and table modeling diagnosis" --user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-mysql-copilot # Data skew detection aliyun adbai describe-chat-message --region cn-beijing --endpoint adbai.cn-beijing.aliyuncs.com --biz-region-id cn-zhangjiakou \ --query "amv-xxx detect data skewed tables" --user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-mysql-copilot # Product knowledge Q&A aliyun adbai describe-chat-message --region cn-beijing --endpoint adbai.cn-beijing.aliyuncs.com --biz-region-id cn-beijing \ --query "What is BUILD" --user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-mysql-copilot ``` ### 4.2 Common Parameters **Cluster Management Parameters (aliyun adb)**: | Parameter | Description | Default Value | |------|------|--------| | `--biz-region-id` | Region ID (this Skill requires it when `--db-cluster-id` is present) | — | | `--region` | Service endpoint region (value matches `--biz-region-id`, required for `aliyun adb` commands) | — | | `--db-cluster-id` | ADB MySQL cluster ID (e.g., `amv-xxx`) | Required | | `--db-cluster-version` | Cluster version (`3.0`/`5.0`/`All`) | `All` | | `--page-number` | Page number | `1` | | `--page-size` | Items per page | `30` | **Intelligent Diagnosis Parameters (aliyun adbai)**: | Parameter | Description | Default Value | |------|------|--------| | `--biz-region-id` | User's cluster region ID (product knowledge Q&A uses default value `cn-beijing`, no user confirmation needed) | Conditionally required | | `--query` | Query content; instance diagnosis format `"<db-cluster-id> <problem description>"`, knowledge Q&A asks directly (supports natural language time descriptions). | Required | | `--region` | Service endpoint region (Skill auto-maps based on `--biz-region-id`, no user specification needed) | Auto | | `--endpoint` | Service endpoint address (Skill auto-maps based on `--biz-region-id`, no user specification needed) | Auto | | `--session-id` | Session ID (passed for multi-turn conversations) | Empty (new session) | | `--timezone` | Timezone: e.g., `Asia/Shanghai`, etc. | `Asia/Shanghai` | ### 4.3 Credential Configuration **Alibaba Cloud API credentials** are configured via `aliyun configure` **outside this session**; the CLI reads them automatically. **Credential Status Check**: ```bash aliyun configure list ``` If the AccessKeyId column in the output is empty or shows `<empty>`, credentials are not configured. Prompt the user: 1. Run `aliyun configure` in a terminal **outside this session** to configure 2. Or configure environment variables in shell profile 3. Return and continue after configuration is complete > **🔴 Important Rules**: > - **Strictly prohibited** from guiding users to input AK/SK credentials in the session > - **Strictly prohibited** from using `aliyun configure set --access-key-id` and other explicit credential parameters > - Credential check must be the first step of the task; if it fails, report and terminate directly Multiple credential types are supported: AK, StsToken, RamRoleArn, EcsRamRole, etc. See [Credential Configuration Documentation](https://help.aliyun.com/zh/cli/configure-credentials). ## 5. RAM Policy For the complete RAM permission list required by this Skill, see `references/ram-policies.md`. > **[MUST] Permission Failure Handling:** When any command or API call fails due to permission errors during execution, follow this process: > 1. Read `references/ram-policies.md` for the complete permission list required by this Skill > 2. Use `ram-permission-diagnose` skill to guide the user to apply for necessary permissions > 3. Pause and wait for user confirmation that required permissions have been granted ## 6. Parameter Confirmation > **IMPORTANT: Parameter Confirmation** — Before executing any command or API call, all user-configurable parameters (such as biz-region-id, db-cluster-id, --query, etc.) **must be confirmed with the user**. **Do not** assume or use default values without the user's explicit approval. > > **Interaction Mode Mandatory Rule**: For any step requiring user confirmation or selection (region, cluster, diagnosis scenario, execution confirmation, etc.), **must use option cards** — **forbidden** to require manual input. Specifically: > - Region confirmation → option cards (read `references/region-list.md` for options, see Section 1.2 region confirmation rules) — **Product knowledge Q&A does not require this step** > - Cluster ID selection → option cards (generated from `describe-db-clusters` results) — **Product knowledge Q&A does not require this step** > - Diagnosis scenario selection → option cards (when user intent is unclear, list available diagnosis types) > - Pre-execution confirmation → option cards (e.g., "Continue" / "Cancel") — **Product knowledge Q&A does not require this step, execute directly** ## 7. Best Practices 1. **CLI-First**: Prioritize using CLI commands for diagnosis; cluster management uses `aliyun adb`, intelligent diagnosis uses `aliyun adbai` 2. **Command Output**: Every API call must output the complete command string at the beginning of the response 3. **Error Handling**: When cluster ID does not exist, guide the user to select the correct cluster instead of failing directly 4. **Product Boundary**: Only handle ADB MySQL clusters (ID prefix `am-` or `amv-`), do not mix other product APIs 5. **Options First**: For any step requiring user confirmation or selection, always use option cards; do not require manual input ## 8. Reference Links | Reference File | Content | |----------|------| | `references/ram-policies.md` | RAM permission list | | `references/verification-method.md` | Verification methods | | `references/cli-installation-guide.md` | Aliyun CLI installation guide | | `references/region-list.md` | Alibaba Cloud region ID list | | `references/cluster-info.md` | Cluster info query detailed steps | | `references/cluster-diagnosis.md` | Cluster intelligent diagnosis detailed steps |

path: references/acceptance-criteria.md
content: # Acceptance Criteria: alibabacloud-analyticdb-mysql-copilot

**Scenario**: ADB MySQL Operations & Diagnosis
**Purpose**: Skill test acceptance criteria

---

# Correct CLI Command Patterns

## 1. Product — Verify Product Name Exists

#### ✅ CORRECT
```bash
aliyun adb describe-db-clusters --biz-region-id cn-hangzhou --region cn-hangzhou --user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-mysql-copilot
aliyun adbai describe-chat-message --region cn-beijing --endpoint adbai.cn-beijing.aliyuncs.com --biz-region-id cn-hangzhou --query "What is BUILD" --user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-mysql-copilot
```

#### ❌ INCORRECT
```bash
aliyun adbx describe-db-clusters --biz-region-id cn-hangzhou  # Product name does not exist
aliyun ADB describe-db-clusters --biz-region-id cn-hangzhou   # Product name should be lowercase
aliyun adb describe-chat-message                       # Product name mismatch, should be adbai
```

## 2. Command — Verify Action Exists

#### ✅ CORRECT
```bash
aliyun adb describe-db-clusters --biz-region-id cn-hangzhou --region cn-hangzhou --user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-mysql-copilot
aliyun adbai describe-chat-message --region cn-beijing --endpoint adbai.cn-beijing.aliyuncs.com --biz-region-id cn-hangzhou --query "What is BUILD" --user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-mysql-copilot
```

#### ❌ INCORRECT
```bash
aliyun adb GetDBClusters --biz-region-id cn-hangzhou   # Action name incorrect
aliyun adb list-clusters --biz-region-id cn-hangzhou   # Action name incorrect
aliyun adbai describe-chat --biz-region-id cn-hangzhou # Action name incomplete
```

## 3. Parameters — Verify Parameter Names Exist

#### ✅ CORRECT
```bash
# Cluster management (aliyun adb): parameters use camelCase naming
aliyun adb describe-db-clusters --biz-region-id cn-hangzhou --region cn-hangzhou --page-number 1 --page-size 100 --user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-mysql-copilot
aliyun adb describe-db-cluster-attribute --biz-region-id cn-hangzhou --region cn-hangzhou --db-cluster-id am-xxx --user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-mysql-copilot

# Intelligent diagnosis (aliyun adbai)
aliyun adbai describe-chat-message --region cn-beijing --endpoint adbai.cn-beijing.aliyuncs.com --biz-region-id cn-hangzhou --query "What is BUILD" --user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-mysql-copilot
```

#### ❌ INCORRECT
```bash
aliyun adb describe-db-clusters --RegionId cn-hangzhou          # Parameter name format incorrect (should use --biz-region-id)
aliyun adb describe-db-cluster-attribute --biz-region-id cn-hangzhou --region cn-hangzhou   # Missing --db-cluster-id
aliyun adb describe-db-cluster-attribute --db-cluster-id am-xxx     # Missing --biz-region-id, --region (this Skill mandates them)
aliyun adbai describe-chat-message --biz-region-id cn-hangzhou     # Missing --region, --endpoint
```

## 4. Parameter Value Formats — Verify Parameter Value Format

#### ✅ CORRECT (Query Format)
```bash
# Instance diagnosis: Query includes cluster ID + natural language question
aliyun adbai describe-chat-message --region cn-beijing --endpoint adbai.cn-beijing.aliyuncs.com --biz-region-id cn-hangzhou --query "am-xxx slow query diagnosis for the last 3 hours" --user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-mysql-copilot

# Product knowledge Q&A: Query asks directly
aliyun adbai describe-chat-message --region cn-beijing --endpoint adbai.cn-beijing.aliyuncs.com --biz-region-id cn-hangzhou --query "What is BUILD" --user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-mysql-copilot
```

#### ❌ INCORRECT (Query Format)
```bash
# Instance diagnosis Query missing cluster ID
aliyun adbai describe-chat-message --biz-region-id cn-hangzhou --query "slow query diagnosis for the last 3 hours"  # Missing --region, --endpoint
```

---

# Correct Response Output Patterns

## 1. Command String Must Be at the Beginning of the Response

#### ✅ CORRECT
```
Command executed: `aliyun adb describe-db-clusters --biz-region-id cn-hangzhou --region cn-hangzhou`

Query complete! There are 2 ADB MySQL clusters in the Hangzhou region...
```

#### ❌ INCORRECT
```
Query complete! There are 2 clusters in the Hangzhou region... (command string not output)

I called the API to query the cluster list... (complete command not output)

Cluster list below... Command: aliyun adb describe-db-clusters... (command at the end)
```

## 2. Must Execute API Calls

#### ✅ CORRECT
- User asks "view cluster list" → Execute `describe-db-clusters`
- User asks "data skew diagnosis", "BadSQL detection", "slow query diagnosis", "instance health inspection" and other diagnosis questions → Execute `describe-chat-message`

#### ❌ INCORRECT
- User asks "view cluster list" → Directly output documentation content, not calling API
- User asks "data skew diagnosis" → Only explain data skew concept, not calling API
- User asks "BadSQL detection" → Give general optimization suggestions, not calling API

---

# Correct Product Boundary Judgment

## 1. Cluster ID Identification

#### ✅ CORRECT
- `am-xxx` or `amv-xxx` → ADB MySQL, cluster management uses `aliyun adb`, intelligent diagnosis uses `aliyun adbai`
- No need to verify ownership through other product APIs

#### ❌ INCORRECT
- `am-xxx` → Use `aliyun rds` to verify → Failure
- `am-xxx` → Use `aliyun polardb` to verify → Failure
- `am-xxx` → Use `aliyun adb describe-chat-message` → Failure (product name mismatch, should be adbai)

## 2. Product Boundary Notification

#### ✅ CORRECT
- User mentions Elasticsearch → Inform "This Skill only applies to ADB MySQL"
- User mentions RDS MySQL → Inform "This Skill only applies to ADB MySQL"

#### ❌ INCORRECT
- User mentions Elasticsearch → Attempt to use `aliyun adb` command → Failure

path: references/cli-installation-guide.md
content: # Aliyun CLI Installation & Configuration Guide

Complete guide for installing and configuring Aliyun CLI.

> **Aliyun CLI 3.3.3+**: Supports installing and using all published Alibaba Cloud product plugins. Make sure to upgrade to 3.3.3 or later for full plugin ecosystem coverage.

## Installation

### macOS

**Using Homebrew (Recommended)**
```bash
brew install aliyun-cli
# Upgrade to latest
brew upgrade aliyun-cli

# Verify version (>= 3.3.3)
aliyun version
```

**Using Binary**
```bash
# Download
wget https://aliyuncli.alicdn.com/aliyun-cli-macosx-latest-amd64.tgz

# Extract
tar -xzf aliyun-cli-macosx-latest-amd64.tgz

# Move to PATH
sudo mv aliyun /usr/local/bin/

# Verify
aliyun version
```

### Linux

**Debian/Ubuntu**
```bash
# Download
wget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-amd64.tgz

# Extract and install
tar -xzf aliyun-cli-linux-latest-amd64.tgz
sudo mv aliyun /usr/local/bin/

# Verify
aliyun version
```

**CentOS/RHEL**
```bash
# Download
wget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-amd64.tgz

# Extract and install
tar -xzf aliyun-cli-linux-latest-amd64.tgz
sudo mv aliyun /usr/local/bin/

# Verify
aliyun version
```

**ARM64 Architecture**
```bash
# Download ARM64 version
wget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-arm64.tgz

# Extract and install
tar -xzf aliyun-cli-linux-latest-arm64.tgz
sudo mv aliyun /usr/local/bin/
```

### Windows

**Using Binary**
1. Download from: https://aliyuncli.alicdn.com/aliyun-cli-windows-latest-amd64.zip
2. Extract the ZIP file
3. Add the directory to your PATH environment variable
4. Open new Command Prompt or PowerShell
5. Verify: `aliyun version`

**Using PowerShell**
```powershell
# Download
Invoke-WebRequest -Uri "https://aliyuncli.alicdn.com/aliyun-cli-windows-latest-amd64.zip" -OutFile "aliyun-cli.zip"

# Extract
Expand-Archive -Path aliyun-cli.zip -DestinationPath C:\aliyun-cli

# Add to PATH (requires admin privileges)
$env:Path += ";C:\aliyun-cli"
[Environment]::SetEnvironmentVariable("Path", $env:Path, [System.EnvironmentVariableTarget]::Machine)

# Verify
aliyun version
```

## Configuration

### Quick Start

```bash
aliyun configure set \
  --mode AK \
  --access-key-id <your-access-key-id> \
  --access-key-secret <your-access-key-secret> \
  --region cn-hangzhou
```

All `aliyun configure` commands support non-interactive flags, which is the recommended approach —
it works in scripts, CI/CD pipelines, and agent-driven automation without hanging on stdin prompts.

**Where to Get Access Keys**

1. Log in to Aliyun Console: https://ram.console.aliyun.com/
2. Navigate to: AccessKey Management
3. Create a new AccessKey pair
4. Save the secret immediately — it's only shown once

### Configuration Modes

Aliyun CLI supports 6 authentication modes. All examples below use non-interactive flags.

#### 1. AK Mode (Access Key)

Most common mode for personal accounts and scripts.

```bash
aliyun configure set \
  --mode AK \
  --access-key-id LTAI5tXXXXXXXX \
  --access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \
  --region cn-hangzhou
```

Configuration is stored in `~/.aliyun/config.json`:

```json
{
  "current": "default",
  "profiles": [
    {
      "name": "default",
      "mode": "AK",
      "access_key_id": "LTAI5tXXXXXXXX",
      "access_key_secret": "8dXXXXXXXXXXXXXXXXXXXXXXXX",
      "region_id": "cn-hangzhou",
      "output_format": "json",
      "language": "en"
    }
  ]
}
```

#### 2. StsToken Mode (Temporary Credentials)

For short-lived access (tokens expire in 1-12 hours).

```bash
aliyun configure set \
  --mode StsToken \
  --access-key-id LTAI5tXXXXXXXX \
  --access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \
  --sts-token v1.0:XXXXXXXXXXXXXXXX \
  --region cn-hangzhou
```

Use cases: CI/CD pipelines, temporary access for external contractors, cross-account access.

#### 3. RamRoleArn Mode (Assume RAM Role)

Assume a RAM role for elevated or cross-account access.

```bash
aliyun configure set \
  --mode RamRoleArn \
  --access-key-id LTAI5tXXXXXXXX \
  --access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \
  --ram-role-arn acs:ram::123456789012:role/AdminRole \
  --role-session-name my-session \
  --region cn-hangzhou
```

Use cases: cross-account resource access, temporary elevated privileges, role-based access control.

#### 4. EcsRamRole Mode (ECS Instance RAM Role)

Use the RAM role attached to an ECS instance — no credentials needed.

```bash
aliyun configure set \
  --mode EcsRamRole \
  --ram-role-name MyEcsRole \
  --region cn-hangzhou
```

Requirements: must be running on an ECS instance with a RAM role attached.

Use cases: scripts and automation running on ECS instances.

#### 5. RsaKeyPair Mode (RSA Key Pair)

Use RSA key pair for authentication (generate key pair in Aliyun Console first).

```bash
aliyun configure set \
  --mode RsaKeyPair \
  --private-key /path/to/private-key.pem \
  --key-pair-name my-key-pair \
  --region cn-hangzhou
```

#### 6. RamRoleArnWithEcs Mode (ECS + RAM Role)

Combine ECS instance role with RAM role assumption for cross-account access from ECS.

```bash
aliyun configure set \
  --mode RamRoleArnWithEcs \
  --ram-role-name MyEcsRole \
  --ram-role-arn acs:ram::123456789012:role/TargetRole \
  --role-session-name my-session \
  --region cn-hangzhou
```

### Environment Variables

**Highest priority** - overrides config file

**Access Key Mode**
```bash
export ALIBABA_CLOUD_ACCESS_KEY_ID=your_access_key_id
export ALIBABA_CLOUD_ACCESS_KEY_SECRET=your_access_key_secret
export ALIBABA_CLOUD_REGION_ID=cn-hangzhou
```

**STS Token Mode**
```bash
export ALIBABA_CLOUD_ACCESS_KEY_ID=your_access_key_id
export ALIBABA_CLOUD_ACCESS_KEY_SECRET=your_access_key_secret
export ALIBABA_CLOUD_SECURITY_TOKEN=your_sts_token
export ALIBABA_CLOUD_REGION_ID=cn-hangzhou
```

**ECS RAM Role Mode**
```bash
export ALIBABA_CLOUD_ECS_METADATA=role_name
```

**Use Case**:
- CI/CD pipelines
- Docker containers
- Temporary credential override

### Managing Multiple Profiles

**Create Named Profiles**

```bash
aliyun configure set --profile projectA \
  --mode AK \
  --access-key-id LTAI5tAAAAAAAA \
  --access-key-secret 8dAAAAAAAAAAAAAAAAAAAAAAAA \
  --region cn-hangzhou

aliyun configure set --profile projectB \
  --mode AK \
  --access-key-id LTAI5tBBBBBBBB \
  --access-key-secret 8dBBBBBBBBBBBBBBBBBBBBBBBB \
  --region cn-shanghai
```

**Use Specific Profile**

```bash
aliyun ecs describe-instances --profile projectA

export ALIBABA_CLOUD_PROFILE=projectA
aliyun ecs describe-instances   # Uses projectA
```

**List and Switch Profiles**

```bash
aliyun configure list                      # List all profiles
aliyun configure set --current projectA    # Switch default profile
```

### Credential Priority

Credentials are loaded in this order (first found wins):

1. **Command-line flag**: `--profile <name>`
2. **Environment variable**: `ALIBABA_CLOUD_PROFILE`
3. **Environment credentials**: `ALIBABA_CLOUD_ACCESS_KEY_ID`, etc.
4. **Configuration file**: `~/.aliyun/config.json` (current profile)
5. **ECS Instance RAM Role**: If running on ECS with attached role

## Verification

### Test Authentication

```bash
# Basic test - list regions
aliyun ecs describe-regions

# Expected output: JSON array of regions
```

**If successful**, you'll see:
```json
{
  "Regions": {
    "Region": [
      {
        "RegionId": "cn-hangzhou",
        "RegionEndpoint": "ecs.cn-hangzhou.aliyuncs.com",
        "LocalName": "East China 1 (Hangzhou)"
      },
      ...
    ]
  },
  "RequestId": "..."
}
```

**If failed**, you'll see error messages:
- `InvalidAccessKeyId.NotFound` - Wrong Access Key ID
- `SignatureDoesNotMatch` - Wrong Access Key Secret
- `InvalidSecurityToken.Expired` - STS token expired (for StsToken mode)
- `Forbidden.RAM` - Insufficient permissions

### Debug Configuration

```bash
# Show current configuration
aliyun configure get

# Test with debug logging
aliyun ecs describe-regions --log-level=debug

# Check credential provider
aliyun configure get mode
```

## Security Best Practices

### 1. Use RAM Users (Not Root Account)

❌ **Don't**: Use Aliyun root account credentials
✅ **Do**: Create RAM users with specific permissions

```bash
# Create RAM user in console
# Attach only necessary policies
# Use RAM user's access keys
```

### 2. Principle of Least Privilege

Grant only the minimum permissions needed:

```bash
# Example: Read-only ECS access
# Attach policy: AliyunECSReadOnlyAccess
```

### 3. Rotate Access Keys Regularly

```bash
# Create new access key in RAM Console, then update configuration
aliyun configure set --access-key-id NEW_KEY --access-key-secret NEW_SECRET
# Delete old access key from console
```

### 4. Use STS Tokens for Temporary Access

```bash
aliyun configure set --mode StsToken \
  --access-key-id XXXX --access-key-secret XXXX \
  --sts-token XXXX --region cn-hangzhou
```

### 5. Use ECS RAM Roles When Possible

```bash
aliyun configure set --mode EcsRamRole --ram-role-name MyRole --region cn-hangzhou
```

### 6. Never Commit Credentials

```bash
# Add to .gitignore
echo "~/.aliyun/config.json" >> .gitignore

# Use environment variables in CI/CD instead
```

### 7. Secure Config File

```bash
# Restrict permissions
chmod 600 ~/.aliyun/config.json
```

## Troubleshooting

### Issue: Command Not Found

```bash
# Check installation
which aliyun

# Check PATH
echo $PATH

# Reinstall or add to PATH
```

### Issue: Authentication Failed

```bash
# Verify configuration
aliyun configure get

# Test with debug
aliyun ecs describe-regions --log-level=debug

# Check credentials in console
# Verify access key is active
```

### Issue: Permission Denied

```bash
# Error: Forbidden.RAM

# Check RAM user permissions
# Attach necessary policies in RAM console
# Example: AliyunECSFullAccess for ECS operations
```

### Issue: STS Token Expired

```bash
# Error: InvalidSecurityToken.Expired

# Reconfigure with new token
aliyun configure set --mode StsToken \
  --access-key-id XXXX --access-key-secret XXXX \
  --sts-token NEW_TOKEN --region cn-hangzhou
```

### Issue: Wrong Region

```bash
# Some resources may not exist in the specified region

# Check available regions
aliyun ecs describe-regions

# Update default region
aliyun configure set region cn-shanghai
```

## Advanced Configuration

### Custom Endpoint

```bash
# Use custom or private endpoint
export ALIBABA_CLOUD_ECS_ENDPOINT=ecs-vpc.cn-hangzhou.aliyuncs.com
```

### Proxy Settings

```bash
# HTTP proxy
export HTTP_PROXY=http://proxy.example.com:8080
export HTTPS_PROXY=http://proxy.example.com:8080

# No proxy for specific domains
export NO_PROXY=localhost,127.0.0.1,.aliyuncs.com
```

### Timeout Settings

```bash
# Connection timeout (default: 10s)
export ALIBABA_CLOUD_CONNECT_TIMEOUT=30

# Read timeout (default: 10s)
export ALIBABA_CLOUD_READ_TIMEOUT=30
```

## Next Steps

After installation and configuration:

1. **Install plugins** for services you need (v3.3.3+ supports all published product plugins):
   ```bash
   aliyun plugin install --names ecs vpc rds

   # List all available plugins
   aliyun plugin list-remote
   ```

2. **Explore commands**:
   ```bash
   aliyun ecs --help
   aliyun fc --help
   ```

3. **Read documentation**:
   - [Command Syntax Guide](./command-syntax.md)
   - [Global Flags Reference](./global-flags.md)
   - [Common Scenarios](./common-scenarios.md)

## References

- Official Documentation: https://help.aliyun.com/zh/cli/
- RAM Console: https://ram.console.aliyun.com/
- Access Key Management: https://ram.console.aliyun.com/manage/ak
- Plugin Repository: https://github.com/aliyun/aliyun-cli


path: references/cluster-diagnosis.md
content: # Cluster Intelligent Diagnosis

> **🚨🚨🚨 MUST | P0 | NON-NEGOTIABLE — Execution Checklist 🚨🚨🚨**
>
> When the user requests diagnostic analysis, **the following checks must be executed**:
>
> - [ ] **MUST**: Execute the `aliyun adbai describe-chat-message` command
> - [ ] **MUST**: Output the command string on the **first line** of the response, format: `Command executed: aliyun adbai describe-chat-message --region <mapped-region> --endpoint <mapped-endpoint> --biz-region-id <region-id> --query "<user question>"`
> - [ ] **NON-NEGOTIABLE**: Do not skip API call and directly give advice or concept explanations
>
> **Violating any checklist item = task failure**

When the user needs slow query diagnosis, table modeling optimization, instance inspection, product knowledge Q&A, etc., call the `DescribeChatMessage` intelligent diagnosis interface.

## 1. Command Format

```bash
aliyun adbai describe-chat-message --region <mapped-region> --endpoint <mapped-endpoint> --biz-region-id <region-id> --query "<user question>" --user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-mysql-copilot
```

> **🚨 Region Routing Rules (P0)**: For all `aliyun adbai` calls, **must forcibly override `--region` and `--endpoint`** according to the routing table in SKILL.md "Section 1.2 Region Routing Rules", even if the user has specified a region — do not use the user's specified values.

## 2. Query Construction Rules

`--query` is the only question input parameter, constructed in two ways depending on the scenario:

> **Interaction Mode Mandatory Rule**: When the diagnosis type cannot be automatically determined, **must use option cards** to let the user select the diagnosis scenario (refer to the "Section 3 Supported Diagnosis Scenarios" table) — **forbidden** to require manual diagnosis type or problem description input.

### Instance-Level Diagnosis (Must Include Cluster ID)

When diagnosis involves specific instance data or status, the Query format is `"<db-cluster-id> <problem description>"`:

```bash
aliyun adbai describe-chat-message --region cn-beijing --endpoint adbai.cn-beijing.aliyuncs.com --biz-region-id cn-zhangjiakou \
  --query "amv-xxx slow query diagnosis for the last 3 hours" --user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-mysql-copilot
```

### Product Knowledge Q&A (No Cluster ID Required, No Region or Cluster Confirmation Required)

When the user asks about ADB MySQL product concepts, syntax, features, etc., **no need to confirm region and cluster**, ask directly:

```bash
aliyun adbai describe-chat-message --region cn-beijing --endpoint adbai.cn-beijing.aliyuncs.com --biz-region-id cn-beijing \
  --query "What is BUILD" --user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-mysql-copilot
```

> For product knowledge Q&A, `--region`, `--endpoint`, `--biz-region-id` all use default values `cn-beijing` / `adbai.cn-beijing.aliyuncs.com`, no user confirmation needed.

**Judgment Criteria**: Does it require reading instance's real-time data or status? → Yes → Instance-level diagnosis (add cluster ID, confirm region and cluster); No → Product knowledge Q&A (no region or cluster needed, execute directly).

> If unable to determine automatically, **use option cards** to provide the following options for user selection:
> - Instance-level diagnosis (requires cluster ID)
> - Product knowledge Q&A (no cluster ID required)

## 3. Supported Diagnosis Scenarios

| Diagnosis Scenario | Query Example | Description |
|----------|-----------|------|
| Slow SQL Query Diagnosis | `"amv-xxx slow query diagnosis for the last 3 hours"` | BadSQL detection, running SQL analysis, SQL Pattern analysis |
| Instance Diagnosis | `"amv-xxx instance health inspection analysis"` | Instance health inspection, capacity assessment, scaling recommendations |
| Instance Write Diagnosis | `"amv-xxx write performance analysis"` | Write performance analysis, write bottleneck identification |
| Table Modeling Diagnosis | `"amv-xxx instance space diagnosis and table modeling diagnosis"` | Oversized non-partitioned tables, partition rationality, primary key rationality, data skew, replicated table rationality, idle indexes, hot/cold table optimization |
| Product Knowledge Q&A | `"What is BUILD"` | ADB MySQL product concepts, syntax, features, etc. |

## 4. Parameter Description

| Parameter | Description | Required |
|------|------|:---:|
| `--region` | Service endpoint region (Skill auto-maps based on `--biz-region-id`, see SKILL.md "Section 1.2", no user specification needed) | Auto |
| `--endpoint` | Service endpoint address (Skill auto-maps based on `--biz-region-id`, see SKILL.md "Section 1.2", no user specification needed) | Auto |
| `--biz-region-id` | User's cluster region ID (product knowledge Q&A uses default value `cn-beijing`, no user confirmation needed) | Conditionally required |
| `--query` | Query content | Yes |
| `--session-id` | Session ID for multi-turn conversations (not passed = new session) | No |
| `--timezone` | Timezone, default `Asia/Shanghai` | No |

**Multi-turn Conversation Example**:

```bash
# First turn: Diagnose slow queries
aliyun adbai describe-chat-message --region cn-beijing --endpoint adbai.cn-beijing.aliyuncs.com --biz-region-id cn-zhangjiakou \
  --query "amv-xxx slow query diagnosis for the last 3 hours" --user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-mysql-copilot

# Second turn: Follow-up on results (use SessionId from first turn)
aliyun adbai describe-chat-message --region cn-beijing --endpoint adbai.cn-beijing.aliyuncs.com --biz-region-id cn-zhangjiakou \
  --query "How to optimize this slow query" --session-id <session-id> --user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-mysql-copilot
```

## 5. Time Parameters

`DescribeChatMessage` automatically handles time parameters — no need to manually pass time ranges. The user only needs to describe the time in natural language in the Query:

- `"slow queries in the last 3 hours"` ✓
- `"yesterday's BadSQL detection"` ✓
- `"this week's SQL Pattern analysis"` ✓

## 6. Common Use Cases

- **User says "queries are very slow, help me troubleshoot"** → Instance-level diagnosis, Query: `"<cluster-id> recent slow query diagnosis"`
- **User says "are there any data skewed tables"** → Instance-level diagnosis, Query: `"<cluster-id> detect data skewed tables"`
- **User says "help me do an instance health inspection"** → Instance-level diagnosis, Query: `"<cluster-id> instance health inspection analysis"`
- **User says "What is BUILD"** → Product knowledge Q&A, Query: `"What is BUILD"`
- **User says "what idle indexes are there"** → Instance-level diagnosis, Query: `"<cluster-id> idle index optimization suggestions"`
- **User intent unclear** → **Use option cards** to list diagnosis scenarios (slow SQL query diagnosis, instance diagnosis, instance write diagnosis, table modeling diagnosis, product knowledge Q&A) for user selection — **forbidden** to require manual input

path: references/cluster-info.md
content: # Cluster Information Query

> **🚨🚨🚨 MUST | P0 | NON-NEGOTIABLE — Execution Checklist 🚨🚨🚨**
>
> When the user asks about cluster information, **the following checks must be executed**:
>
> - [ ] **MUST**: Execute the corresponding `aliyun adb describe-db-clusters` or `describe-db-cluster-attribute` command based on user needs
> - [ ] **MUST**: Output the command string on the **first line** of the response, format: `Command executed: aliyun adb <command-name> --biz-region-id <region-id>`
> - [ ] **NON-NEGOTIABLE**: Do not skip API call and directly give advice
>
> **Violating any checklist item = task failure**

When the user wants to know "what instances exist", "what is the instance configuration", "cluster status", etc., follow the steps below.

## 1. Query Cluster List

**Response Format Template** (must be followed):
```
Command executed: `aliyun adb describe-db-clusters --biz-region-id <region-id> --region <region-id>`

[Query results, tables, etc.]
```

List all ADB MySQL clusters under the specified region:

```bash
aliyun adb describe-db-clusters --api-version 2021-12-01 --biz-region-id <region-id> --region <region-id>
```

## 2. Query Cluster Detailed Attributes

Get complete configuration information for a single cluster (specification, VPC, storage, version, etc.):

```bash
aliyun adb describe-db-cluster-attribute --api-version 2021-12-01 --biz-region-id <region-id> --region <region-id> --db-cluster-id <cluster-id>
```

**Key Fields in Response**:

| Field | Meaning |
|------|------|
| `DBClusterId` | Cluster ID |
| `DBClusterDescription` | Cluster description / alias |
| `DBClusterStatus` | Cluster status (Running, Stopped, etc.) |
| `DBClusterType` | Cluster type |
| `CommodityCode` | Billing method |
| `ComputeResource` | Compute resource specification |
| `StorageResource` | Storage resource specification |
| `DBVersion` | Kernel version |
| `VPCId` / `VSwitchId` | Network information |
| `ConnectionString` | Connection address |
| `Port` | Port |
| `CreationTime` | Creation time |
| `ExpireTime` | Expiration time (valid for subscription billing) |

## 3. Query Storage Space Overview

Understand the cluster's disk usage:

```bash
aliyun adb describe-db-cluster-space-summary --api-version 2021-12-01 --biz-region-id <region-id> --region <region-id> --db-cluster-id <cluster-id>
```

**Key Fields in Response**:

| Field | Meaning |
|------|------|
| `TotalSize` | Total data size (unit: bytes) |
| **HotData** | **Hot data information** |
| `HotData.TotalSize` | Hot data total size (bytes) |
| `HotData.DataSize` | Table record data size (bytes) |
| `HotData.IndexSize` | Regular index data size (bytes) |
| `HotData.PrimaryKeyIndexSize` | Primary key index data size (bytes) |
| `HotData.OtherSize` | Other data size (bytes) |
| **ColdData** | **Cold data information** |
| `ColdData.TotalSize` | Cold data total size (bytes) |
| `ColdData.DataSize` | Table record data size (bytes) |
| `ColdData.IndexSize` | Regular index data size (bytes) |
| `ColdData.PrimaryKeyIndexSize` | Primary key index data size (bytes) |
| `ColdData.OtherSize` | Other data size (bytes) |
| **DataGrowth** | **Data growth information** |
| `DataGrowth.DayGrowth` | Last day data growth amount (bytes) |
| `DataGrowth.WeekGrowth` | Last 7 days average daily data growth amount (bytes) |

> **Calculation Formula**:
> - Total data size = Hot data size + Cold data size
> - Hot data size = Table record data + Regular index + Primary key index + Other data
> - Last 7 days average daily growth = (Current data size - 7 days ago data size) / 7

## 4. Common Use Cases

- **User says "help me see what ADB instances exist"** → Execute step 1
- **User says "what is the configuration of instance amv-xxx"** → Execute step 2
- **User says "is this cluster about to expire"** → Execute step 2, check `ExpireTime`
- **User says "how much disk space is left"** → Execute step 3
- **User doesn't know cluster-id** → First execute step 1 to get the list, then select the target cluster for subsequent operations

path: references/ram-policies.md
content: # RAM Policy - ADB MySQL Operations & Diagnosis Assistant

This file lists all RAM permissions required by the `alibabacloud-analyticdb-mysql-copilot` Skill.

## Permission List

### Cluster Management Permissions

| API Name | Permission Action | Description |
|----------|-------------|------|
| `DescribeDBClusters` | `adb:DescribeDBClusters` | Query ADB MySQL cluster list within a region |
| `DescribeDBClusterAttribute` | `adb:DescribeDBClusterAttribute` | Query cluster detailed attributes |
| `DescribeDBClusterSpaceSummary` | `adb:DescribeDBClusterSpaceSummary` | Query storage space overview |

### Instance Diagnosis Permissions

| API Name | Permission Action | Description |
|----------|-------------|------|
| `DescribeChatMessage` | `adbai:DescribeChatMessage` | Instance kernel diagnosis, including: slow SQL query diagnosis, instance diagnosis, instance write diagnosis, table modeling diagnosis |

## Minimum Permission Policy Template

```json
{
  "Version": "1",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "adb:DescribeDBClusters",
        "adb:DescribeDBClusterAttribute",
        "adb:DescribeDBClusterSpaceSummary",
        "adbai:DescribeChatMessage"
      ],
      "Resource": "*"
    }
  ]
}
```

## System Policy Recommendations

For quick configuration, use the following Alibaba Cloud system policies:

| Policy Name | Description |
|----------|------|
| `AliyunADBFullAccess` | ADB MySQL full access permissions (includes all read/write operations) |
| `AliyunADBReadOnlyAccess` | ADB MySQL read-only access permissions (suitable for diagnosis scenarios) |
| `AliyunADBDeveloperAccess` | ADB MySQL developer permissions (for developers, supports diagnosis scenarios) |

> **Security Recommendation**: For operations diagnosis scenarios, we recommend using the `AliyunADBReadOnlyAccess` read-only policy, which meets all diagnosis API permission requirements while avoiding the risk of accidental operations.

path: references/region-list.md
content: # Alibaba Cloud Region ID List

ADB MySQL supported region IDs and their corresponding region names, used for the `--biz-region-id` parameter (for both aliyun adb and aliyun adbai).

## China

| Region ID | English Name |
|---------|----------|
| cn-hangzhou | China (Hangzhou) |
| cn-shanghai | China (Shanghai) |
| cn-beijing | China (Beijing) |
| cn-shenzhen | China (Shenzhen) |
| cn-hongkong | China (Hong Kong) |
| cn-qingdao | China (Qingdao) |
| cn-heyuan | China (Heyuan) |
| cn-chengdu | China (Chengdu) |
| cn-guangzhou | China (Guangzhou) |
| cn-zhangjiakou | China (Zhangjiakou) |
| cn-wulanchabu | China (Ulanqab) |
| cn-huhehaote | China (Hohhot) |
| cn-hangzhou-finance | China East 1 Finance |
| cn-shenzhen-finance-1 | China South 1 Finance |
| cn-shanghai-finance-1 | China East 2 Finance |

## Asia Pacific

| Region ID | English Name |
|---------|----------|
| ap-southeast-1 | Singapore |
| ap-southeast-3 | Malaysia (Kuala Lumpur) |
| ap-southeast-5 | Indonesia (Jakarta) |
| ap-southeast-6 | Philippines (Manila) |
| ap-southeast-7 | Thailand (Bangkok) |
| ap-northeast-1 | Japan (Tokyo) |
| ap-northeast-2 | South Korea (Seoul) |

## Europe & Middle East

| Region ID | English Name |
|---------|----------|
| eu-central-1 | Germany (Frankfurt) |
| eu-west-1 | UK (London) |
| me-east-1 | UAE (Dubai) |
| me-central-1 | SAU (Riyadh) |

## Americas

| Region ID | English Name |
|---------|----------|
| us-east-1 | US (Virginia) |
| us-west-1 | US (Silicon Valley) |

path: references/verification-method.md
content: # Verification Methods

This document describes the success indicators for each API call and common error handling.

## Success Indicators

### Cluster Management
- `describe-db-clusters`: Returns `TotalCount` field, `Items` array contains cluster list
- `describe-db-cluster-attribute`: Returns `Items` array, `Items[0].DBClusterId` matches the input
- `describe-db-cluster-space-summary`: Returns `TotalSize`, `HotData`, `ColdData` and other fields

### Intelligent Diagnosis
- `describe-chat-message`: SSE streaming interface; returns HTTP 200 with valid SSE event stream indicates success

## Common Error Codes

| Error Code | Meaning | Solution |
|--------|------|----------|
| `InvalidDBClusterId.NotFound` | Cluster ID does not exist | Call `describe-db-clusters` to get the correct cluster ID |
| `InvalidParameter.Query` | Query parameter format error | Ensure Query contains a valid cluster ID and diagnosis question |
| `Forbidden.RAM` | Insufficient permissions | Use `ram-permission-diagnose` skill to guide user to apply for permissions |
| `InvalidAccessKeyId.NotFound` | AK does not exist | Run `aliyun configure list` to check credential status |
| `SignatureDoesNotMatch` | AK Secret error | Reconfigure credentials outside this session |
| `InvalidSecurityToken.Expired` | STS Token expired | Obtain new temporary credentials |

## Cluster ID Validation Rules

If the user-provided cluster ID does not exist in the API response (error code `InvalidDBClusterId.NotFound`), do not abort the task. Instead:
1. Call `describe-db-clusters` to list the actual clusters in that region
2. Guide the user to confirm the correct cluster ID and continue execution

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