Skill: sdk-team/alibabacloud-agentloop-contextstore (version 0.0.1)

--- name: alibabacloud-agentloop-contextstore description: | Operate Alibaba Cloud CloudMonitor Service (CMS) AgentLoop ContextStore by using aliyun CLI with api version 2024-03-30. Use when users mention CloudMonitor, CMS, AgentLoop, agent loop, context, memory, experience, ContextStore, context store, 上下文库, 记忆库, 经验库, or ask to create/query/update/delete stores, write/search/update/delete context records, manage store API keys, or debug aliyun cms ContextStore commands. --- # AgentLoop ContextStore Skill ## Scenario Description This skill operates ContextStore resources under Alibaba Cloud CloudMonitor Service (CMS) AgentLoop. ContextStore persists long-running agent context in two store types: - `memory`: user preferences, facts, episode summaries, and conversation-derived memories. - `experience`: troubleshooting or task execution experience summarized from agent traces. Architecture: `Aliyun CLI` + `CMS AgentLoop` + `ContextStore` + optional source `Log Service project/logstore` + store-level `API Key`. Always confirm the target store `contextType` before data operations. Memory and experience stores share the same CLI product and subcommands, but their write schemas, filter field paths, and formatted outputs are different. ## Installation **Pre-check: Aliyun CLI >= 3.3.3 required** > Run `aliyun version` to verify >= 3.3.3. If not installed or version too low, run `curl -fsSL https://aliyuncli.alicdn.com/setup.sh | bash` to install/update, or see `references/cli-installation-guide.md` for installation instructions. ```bash aliyun version ``` **Pre-check: Aliyun CLI plugin update required** > [MUST] run `aliyun configure set --auto-plugin-install true` to enable automatic plugin installation. > [MUST] run `aliyun plugin update` to ensure that any existing plugins are always up to date. ```bash aliyun configure set --auto-plugin-install true aliyun plugin update ``` **Pre-check: CMS plugin >= 0.2.4 required** > ContextStore subcommands and correct typed-value handling for `experience` / `metadata` / `config.metadataField` require the CMS plugin at version `0.2.4` or later. Earlier versions silently coerce nested numbers, booleans, arrays, and null values to strings. Verify and install if necessary: > > ```bash > aliyun plugin show --name cms > # If missing or older than 0.2.4: > aliyun plugin install --names cms --version 0.2.4 > # Or install the latest: > aliyun plugin install --names cms > ``` ## Environment Variables No ContextStore-specific environment variables are required. Aliyun CLI credentials and region may come from a configured CLI profile, Alibaba Cloud environment variables, STS, OAuth, or an ECS RAM role. Never read, echo, or print secret environment variable values. Use `aliyun configure list` only to check whether a valid profile or identity is available. ## Authentication > **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 the output for 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 of this session** (via `aliyun configure` in terminal or environment variables in shell profile) > 3. Return and re-run after `aliyun configure list` shows a valid profile ## RAM Policy ContextStore operations require CMS AgentLoop permissions for store, context, and API key APIs. See `references/ram-policies.md` for the full action list and a policy template. > **[MUST] Permission Failure Handling:** When any command or API call fails due to permission errors at any point during execution, follow this process: > 1. Read `references/ram-policies.md` to get the full list of permissions required by this SKILL. > 2. If the `ram-permission-diagnose` skill is installed in the current environment, invoke it to guide the user through requesting the necessary permissions. Otherwise, surface the missing RAM action(s) plus the policy template from `references/ram-policies.md` and ask the user to attach the policy to the current RAM identity via the [Alibaba Cloud RAM Console](https://ram.console.aliyun.com/). > 3. Pause and wait until the user confirms that the required permissions have been granted before retrying. ## Parameter Confirmation > **IMPORTANT: Parameter Confirmation** -- Before executing any command or API call, > ALL user-customizable parameters (e.g., RegionId, instance names, CIDR blocks, > passwords, domain names, resource specifications, etc.) MUST be confirmed with the > user. Do NOT assume or use default values without explicit user approval. | Parameter Name | Required/Optional | Description | Default Value | | --- | --- | --- | --- | | `--region` | Optional | Region override for the current CLI command. Confirm when the user does not want the configured default region. | CLI configured region | | `--workspace` | Required | AgentLoop workspace ID. | None | | `--context-store-name` | Required except `list-context-stores` | ContextStore name. | None | | `--context-type` | Required for create/write flows | Store type: `memory` or `experience`. | None | | `--memory-type` | Required for memory writes only | Memory write type: `short` or `long`. Never use for experience writes. | None | | `--context-id` | Required for single-record get/update/delete | Context record ID. | None | | `--items` | Required for `add-contexts` | JSON array of records to write. Schema depends on `contextType`. | None | | `--filter` | Optional | JSON filter for `search-context` or `delete-contexts`. Field paths depend on `contextType`. | None | | `--query` | Required for search | Semantic search query. | None | | `--limit` | Optional | Maximum search results. | Service default | | `--retrieval-option` | Optional | Experience search options: `reranker`, `llm_rank`, or both comma-separated. | None | | `--config` | Optional/Required by flow | Store configuration. Required for experience stores and memory stores sourced from an existing logstore. | None | | `--name` | Required for API key commands | Store-level API key name. | None | ## Core Workflow > **[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 workflow success, workflow failure, error/exception, user cancellation, session end, or any other scenario where no further CLI commands will be executed. > > ```bash > aliyun configure ai-mode disable > ``` > > If a previous run left AI-mode enabled (e.g. due to crash, session interruption, or a forgotten exit), check current state with `aliyun configure ai-mode show` and run `aliyun configure ai-mode disable` once before the new workflow starts. 1. Classify the intent: store management, memory data, experience data, API key management, filter construction, or verification. 2. Confirm all user-customizable parameters from the table above. 3. Run the CLI and credential pre-checks. Stop if CLI version or credentials are not valid. 4. If the store type is unknown, query it before choosing a data schema: ```bash aliyun cms --api-version 2024-03-30 get-context-store \ --workspace <workspace> \ --context-store-name <context_store_name> ``` 5. For uncertain JSON, run a dry run before the real request: ```bash aliyun cms --api-version 2024-03-30 <subcommand> \ --workspace <workspace> \ --context-store-name <context_store_name> \ --cli-dry-run ``` 6. Execute the matching operation: - Store and API key operations: see `references/store-management.md`. - Memory and experience data operations: see `references/context-data-operations.md`. - Filter syntax: see `references/filter-syntax.md`. 7. Verify success with the command-specific checks in `references/verification-method.md`. 8. Disable AI-mode before returning the final response. ## Success Verification Method Use `references/verification-method.md` for command validation, non-destructive store checks, data write/search checks, API key checks, and cleanup verification. ## Cleanup Confirm destructive cleanup parameters before execution. Prefer narrow deletes (single record) over batch deletes; use store deletion only when the user explicitly confirms the entire store should be removed. Single record: ```bash aliyun cms --api-version 2024-03-30 delete-context \ --workspace <workspace> \ --context-store-name <context_store_name> \ --context-id <context_id> ``` Batch (mutually exclusive flags `--context-ids` or `--filter`; never both, never a request body): ```bash aliyun cms --api-version 2024-03-30 delete-contexts \ --workspace <workspace> \ --context-store-name <context_store_name> \ --context-ids "<context_id_1>,<context_id_2>" aliyun cms --api-version 2024-03-30 delete-contexts \ --workspace <workspace> \ --context-store-name <context_store_name> \ --filter '<filter_json>' ``` Records with `immutable: true` (memory) or `metadata.immutable: true` (experience) are skipped server-side and not counted in `deletedCount`. Whole store (irreversible; system-managed datasets and internal logstores are removed; user-provided source logstores are NOT removed): ```bash aliyun cms --api-version 2024-03-30 delete-context-store \ --workspace <workspace> \ --context-store-name <context_store_name> ``` API key: ```bash aliyun cms --api-version 2024-03-30 delete-context-store-api-key \ --workspace <workspace> \ --context-store-name <context_store_name> \ --name <api_key_name> ``` ## Command Tables All supported ContextStore commands, parameter rules, and validation helpers are listed in `references/related-commands.md`. ## Best Practices 1. Always include `--api-version 2024-03-30`; otherwise ContextStore subcommands may not be available. 2. Confirm `contextType` before writing, filtering, updating, or interpreting formatted output. 3. Use `--memory-type short` or `--memory-type long` only for memory writes; never pass it for experience writes. 4. Keep memory `categories`, `immutable`, and `expirationDate` at the item top level; keep experience `categories` and `immutable` inside `metadata`. 5. Quote complex JSON arguments with single quotes in shell, and use double quotes inside JSON. 6. Treat API key creation output as secret material. The plaintext secret is returned only once by `create-context-store-api-key`; never paste it into conversation history, and ask the user to store it securely outside the session. 7. Use `--cli-dry-run` before destructive operations or complex JSON requests. 8. Immutable records cannot be updated or deleted; bulk delete skips them and they do not appear in `deletedCount`. 9. Use `delete-contexts` only with `--context-ids` or `--filter`; it does not accept a request body, and the two flags are mutually exclusive. 10. `contextType`, `contextStoreName`, and `config.source` are immutable after store creation. To change the source logstore or store type, create a new store and migrate data. 11. **CMS plugin >= 0.2.4 prerequisite**: earlier plugin versions silently stringify typed values inside `experience` / `metadata` / `config.metadataField`. Verify with `aliyun plugin show --name cms` before any write operation; upgrade with `aliyun plugin install --names cms --version 0.2.4` (or omit `--version` for latest). 12. Do not write the legacy `triggerCondition` field for new experience records; the v1 schema uses `experience` (object) plus `metadata` (object). ## Common Mistakes to Avoid | Wrong | Right | Why | | --- | --- | --- | | `aliyun cms add-contexts ...` (no `--api-version`) | `aliyun cms --api-version 2024-03-30 add-contexts ...` | Subcommand only exists in this API version | | Memory write without `--memory-type` | `--memory-type short` or `--memory-type long` | Required for memory writes | | Experience write with `--memory-type long` | Omit `--memory-type` for experience | Forbidden for experience writes | | Experience with `categories` / `immutable` at item top level | Put them inside `metadata` | Memory uses top-level; experience uses metadata | | Experience filter `{"serviceName":"x"}` | `{"metadata.serviceName":"x"}` | Experience metadata fields use `metadata.` prefix | | `delete-contexts --body '{...}'` | `delete-contexts --context-ids "id1,id2"` or `--filter '{...}'` | `delete-contexts` does not accept a body | | `metadata.traceStartNs: 1775799927869697848` (number) | `"traceStartNs": "1775799927869697848"` (string) | Bare numbers above 2^53 lose precision via Go float64 parsing | | `echo $ALIBABA_CLOUD_ACCESS_KEY_SECRET` | `aliyun configure list` | Never read or print AK/SK secrets | ## Reference Links | Reference | Contents | | --- | --- | | `references/store-management.md` | Create, get, list, update, delete stores and manage store API keys. | | `references/context-data-operations.md` | Memory and experience write/search/update/delete schemas and examples. | | `references/filter-syntax.md` | Shared filter operators and memory versus experience field paths. | | `references/related-commands.md` | Supported CLI command table and help validation commands. | | `references/verification-method.md` | Success checks, dry-run checks, and command validation workflow. | | `references/ram-policies.md` | Required RAM actions and policy template. | | `references/cli-installation-guide.md` | Aliyun CLI installation and configuration guide. |

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": "华东 1（杭州）"
      },
      ...
    ]
  },
  "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/context-data-operations.md
content: # Context Data Operations

Memory and experience stores share ContextStore data subcommands, but their item schemas and filter fields are different. Query `get-context-store` first when the store type is unknown.

## Prerequisites

- Aliyun CLI >= 3.3.3 with the CMS plugin >= 0.2.4 installed (see SKILL.md "Installation").
- Always `--cli-dry-run` before a real write to confirm the serialized HTTP body matches your intent.

## Legacy Field Note

The CLI `--items` structure still exposes `triggerCondition`, which belonged to a previous experience schema. The current v1 experience schema uses `experience` (object) plus `metadata` (object). Do not write or update `triggerCondition` for new experience records.

## Memory Writes

Memory writes require `--context-type memory` and `--memory-type`.

`--memory-type short` writes short-term message events. At least one of `userId`, `agentId`, `appId`, or `runId` is required. `infer: true` lets the service asynchronously extract long-term memory. Short-term memory defaults to a 30-day TTL.

```bash
aliyun cms --api-version 2024-03-30 add-contexts \
  --workspace <workspace> \
  --context-store-name <memory_store_name> \
  --context-type memory \
  --memory-type short \
  --items '[{
    "messages": [{"role":"user","content":"<message_content>"}],
    "userId": "<user_id>",
    "agentId": "<agent_id>",
    "metadata": {"source":"dialog"},
    "infer": true,
    "customInstructions": "<memory_extraction_instruction>"
  }]'
```

`--memory-type long` writes long-term memory directly.

```bash
aliyun cms --api-version 2024-03-30 add-contexts \
  --workspace <workspace> \
  --context-store-name <memory_store_name> \
  --context-type memory \
  --memory-type long \
  --items '[{
    "content": "<long_term_memory_text>",
    "userId": "<user_id>",
    "agentId": "<agent_id>",
    "metadata": {"source":"user_confirmed","topic":"debugging_preference"},
    "categories": ["preference"],
    "immutable": false,
    "expirationDate": "<yyyy-mm-dd>"
  }]'
```

Memory field placement:

- `categories`, `immutable`, and `expirationDate` are item top-level fields.
- User metadata keys can be filtered directly, such as `topic` or `source`.
- When user metadata conflicts with system fields (`userId` / `agentId` / `appId` / `runId` / `categories` / `immutable` / `hash` / `createdAt` / `updatedAt` / `expirationDate`), the user-provided value takes precedence.

## Memory Get, Search, Update, Delete

```bash
aliyun cms --api-version 2024-03-30 get-context \
  --workspace <workspace> \
  --context-store-name <memory_store_name> \
  --context-id <context_id>
```

`formatted=true` is the default and returns assembled text plus metadata for agent prompts. Use `--formatted=false` to inspect raw content and payload.

```bash
aliyun cms --api-version 2024-03-30 search-context \
  --workspace <workspace> \
  --context-store-name <memory_store_name> \
  --query "<search_query>" \
  --limit <limit> \
  --filter '{
    "userId": "<user_id>",
    "categories": {"contains": "preference"},
    "createdAt": {"gte": "<start_time_utc>"}
  }'
```

```bash
aliyun cms --api-version 2024-03-30 update-context \
  --workspace <workspace> \
  --context-store-name <memory_store_name> \
  --context-id <context_id> \
  --content "<updated_memory_text>" \
  --payload '{"topic":"debugging_preference","categories":["preference"]}'
```

`--payload` uses JSON merge-patch semantics. Omitted fields remain unchanged.

```bash
aliyun cms --api-version 2024-03-30 delete-context \
  --workspace <workspace> \
  --context-store-name <memory_store_name> \
  --context-id <context_id>
```

```bash
aliyun cms --api-version 2024-03-30 delete-contexts \
  --workspace <workspace> \
  --context-store-name <memory_store_name> \
  --context-ids "<context_id_1>,<context_id_2>"
```

```bash
aliyun cms --api-version 2024-03-30 delete-contexts \
  --workspace <workspace> \
  --context-store-name <memory_store_name> \
  --filter '{"userId":"<user_id>"}'
```

## Experience Writes

Experience writes use `--context-type experience` and must not include `--memory-type`.

```bash
aliyun cms --api-version 2024-03-30 add-contexts \
  --workspace <workspace> \
  --context-store-name <experience_store_name> \
  --context-type experience \
  --items '[{
    "experience": {
      "userQuestion": "<user_question>",
      "taskDescription": "<task_description>",
      "taskType": "troubleshooting",
      "complexity": "medium",
      "confidence": 0.95,
      "experience": "<experience_summary>",
      "taskPlanning": "<task_plan>"
    },
    "metadata": {
      "traceId": "<trace_id>",
      "version": "v1",
      "serviceName": "<service_name>",
      "sessionId": "<session_id>",
      "traceStartNs": "1775799927869697848",
      "traceEndNs": "1775799959938866990",
      "categories": ["debugging"],
      "immutable": false,
      "qualityScore": null,
      "humanLabel": null
    }
  }]'
```

Experience field placement:

- `categories`, `immutable`, and other semantic fields belong inside `metadata`.
- `experience.experience` is the main experience body.
- `experience.userQuestion` and `experience.taskDescription` participate in semantic recall.
- `metadata.version` identifies the schema version, currently `v1`.
- Do not pass `triggerCondition` for new experience records; it is a legacy field.
- `metadata.traceStartNs` / `metadata.traceEndNs` are nanosecond timestamps that exceed Go float64 safe range — **pass them as JSON strings** (as shown above). The CLI parses the string as int64 and serializes it as a precise number in the HTTP body. Plain numeric input would lose the last few digits. Other numeric fields (`confidence`, `qualityScore`, etc.) stay below 2^53 and are safe as plain numbers.

## Experience Get, Search, Update, Delete

```bash
aliyun cms --api-version 2024-03-30 get-context \
  --workspace <workspace> \
  --context-store-name <experience_store_name> \
  --context-id <context_id>
```

`formatted=true` is the default and returns an XML string in `context`, while retaining the full metadata object for display and debugging. Use `--formatted=false` to get the raw `experience` and `metadata` objects.

```bash
aliyun cms --api-version 2024-03-30 search-context \
  --workspace <workspace> \
  --context-store-name <experience_store_name> \
  --query "<search_query>" \
  --limit <limit> \
  --retrieval-option "reranker,llm_rank" \
  --filter '{
    "metadata.serviceName": "<service_name>",
    "metadata.taskType": {"in":["troubleshooting","knowledge_retrieval"]},
    "metadata.confidence": {"gte": 0.8}
  }'
```

`--retrieval-option` accepts `reranker`, `llm_rank`, or both comma-separated. When both are used, execution order is `reranker` then `llm_rank`.

```bash
aliyun cms --api-version 2024-03-30 update-context \
  --workspace <workspace> \
  --context-store-name <experience_store_name> \
  --context-id <context_id> \
  --experience '{"confidence": 0.98}' \
  --metadata '{"qualityScore": 4.5, "humanLabel": "verified"}'
```

`--experience` and `--metadata` are merged independently. Updating recall text such as `userQuestion` or `taskDescription` causes the service to regenerate embedding.

```bash
aliyun cms --api-version 2024-03-30 delete-context \
  --workspace <workspace> \
  --context-store-name <experience_store_name> \
  --context-id <context_id>
```

```bash
aliyun cms --api-version 2024-03-30 delete-contexts \
  --workspace <workspace> \
  --context-store-name <experience_store_name> \
  --filter '{"metadata.serviceName":"<service_name>","metadata.confidence":{"lt":0.5}}'
```

Records with `immutable: true` or `metadata.immutable: true` cannot be updated or deleted. Bulk delete skips immutable records and does not count them in `deletedCount`.


path: references/filter-syntax.md
content: # ContextStore Filter Syntax

`search-context` and `delete-contexts` share the same filter syntax.

## Operators

| Operation | Example |
| --- | --- |
| Exact match | `{"userId": "<user_id>"}` |
| Field exists | `{"agentId": "*"}` |
| Equal / not equal | `{"metadata.severity": {"eq": "high"}}`, `{"metadata.severity": {"ne": "low"}}` |
| Range | `{"createdAt": {"gte": "2026-04-01T00:00:00Z"}}` |
| Contains / case-insensitive contains | `{"metadata.topic": {"contains": "debug"}}`, `{"metadata.topic": {"icontains": "debug"}}` |
| In list | `{"metadata.taskType": {"in":["troubleshooting","knowledge_retrieval"]}}` |

## Logic

Top-level multiple keys are combined as `AND`. Explicit `AND`, `OR`, and `NOT` are supported. Maximum nesting depth is 4.

```json
{
  "AND": [
    {"userId": "<user_id>"},
    {"OR": [
      {"metadata.scene": "debugging"},
      {"metadata.scene": "monitoring"}
    ]},
    {"NOT": {"agentId": "deprecated-agent"}}
  ]
}
```

`NOT` takes one condition object, not an array.

## Memory Filter Fields

Use direct field names for system fields and user metadata:

- `userId`
- `agentId`
- `appId`
- `runId`
- `categories`
- `immutable`
- `createdAt`
- User metadata keys such as `topic` or `source`

Example:

```json
{
  "userId": "<user_id>",
  "categories": {"contains": "preference"},
  "createdAt": {"gte": "2026-04-01T00:00:00Z"}
}
```

## Experience Filter Fields

Use `metadata.<field>` for experience metadata fields:

- `metadata.serviceName`
- `metadata.taskType`
- `metadata.complexity`
- `metadata.confidence`
- `metadata.traceId`
- `metadata.version`
- `metadata.sessionId`
- `metadata.categories`
- `metadata.immutable`
- `createdAt`
- `updatedAt`

Example:

```json
{
  "metadata.serviceName": "sls-sop-daily",
  "metadata.taskType": {"in":["troubleshooting","knowledge_retrieval"]},
  "metadata.confidence": {"gte": 0.8}
}
```


path: references/ram-policies.md
content: # RAM Policies

The exact authorization model can change with the CMS API release. Use this file as the required permission inventory for this skill, and verify action names against the current Alibaba Cloud RAM console or API metadata when creating production policies.

## Required CMS Actions

| API | RAM Action |
| --- | --- |
| CreateContextStore | `cms:CreateContextStore` |
| GetContextStore | `cms:GetContextStore` |
| ListContextStores | `cms:ListContextStores` |
| UpdateContextStore | `cms:UpdateContextStore` |
| DeleteContextStore | `cms:DeleteContextStore` |
| AddContexts | `cms:AddContexts` |
| GetContext | `cms:GetContext` |
| SearchContext | `cms:SearchContext` |
| UpdateContext | `cms:UpdateContext` |
| DeleteContext | `cms:DeleteContext` |
| DeleteContexts | `cms:DeleteContexts` |
| CreateContextStoreApiKey | `cms:CreateContextStoreApiKey` |
| ListContextStoreApiKeys | `cms:ListContextStoreApiKeys` |
| DeleteContextStoreApiKey | `cms:DeleteContextStoreApiKey` |

## Policy Template

Scope resources more narrowly when resource-level authorization is documented for the account and region. Use `Resource: "*"` only when the service does not support narrower resource ARNs for these actions.

```json
{
  "Version": "1",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "cms:CreateContextStore",
        "cms:GetContextStore",
        "cms:ListContextStores",
        "cms:UpdateContextStore",
        "cms:DeleteContextStore",
        "cms:AddContexts",
        "cms:GetContext",
        "cms:SearchContext",
        "cms:UpdateContext",
        "cms:DeleteContext",
        "cms:DeleteContexts",
        "cms:CreateContextStoreApiKey",
        "cms:ListContextStoreApiKeys",
        "cms:DeleteContextStoreApiKey"
      ],
      "Resource": "*"
    }
  ]
}
```

## Optional Source Logstore Access

When creating a memory store from an existing logstore or an experience store from a trace logstore, the caller or service-linked role may also need read access to the source Log Service project/logstore. Confirm the current SLS permission requirements before issuing a policy. Typical read permissions include project/logstore describe and log read actions.

## Permission Failure Handling

When a command fails with authorization errors:

1. Capture the API name, request ID, and denied action from the CLI error.
2. Compare the denied action with the tables above to identify the missing permission.
3. If the `ram-permission-diagnose` skill is installed in the current environment, invoke it to guide the user through requesting the missing permissions. Otherwise, present the missing RAM action(s) to the user along with the policy template above and instruct them to attach the policy to the current RAM identity in the [Alibaba Cloud RAM Console](https://ram.console.aliyun.com/).
4. Pause until the user confirms that permissions have been granted before retrying the failed command.


path: references/related-commands.md
content: # Related CLI Commands

All commands use plugin mode and must include `--api-version 2024-03-30`.

| Area | Command | Purpose | Help Validation |
| --- | --- | --- | --- |
| Store | `aliyun cms --api-version 2024-03-30 create-context-store` | Create memory or experience stores. | `aliyun cms --api-version 2024-03-30 create-context-store help` |
| Store | `aliyun cms --api-version 2024-03-30 get-context-store` | Get one store and inspect `contextType`. | `aliyun cms --api-version 2024-03-30 get-context-store help` |
| Store | `aliyun cms --api-version 2024-03-30 list-context-stores` | List stores, optionally filtered by type. | `aliyun cms --api-version 2024-03-30 list-context-stores help` |
| Store | `aliyun cms --api-version 2024-03-30 update-context-store` | Update mutable store configuration and description. | `aliyun cms --api-version 2024-03-30 update-context-store help` |
| Store | `aliyun cms --api-version 2024-03-30 delete-context-store` | Delete a ContextStore. | `aliyun cms --api-version 2024-03-30 delete-context-store help` |
| Context | `aliyun cms --api-version 2024-03-30 add-contexts` | Batch write memory or experience records. | `aliyun cms --api-version 2024-03-30 add-contexts help` |
| Context | `aliyun cms --api-version 2024-03-30 get-context` | Get one context record. | `aliyun cms --api-version 2024-03-30 get-context help` |
| Context | `aliyun cms --api-version 2024-03-30 search-context` | Semantic search over records. | `aliyun cms --api-version 2024-03-30 search-context help` |
| Context | `aliyun cms --api-version 2024-03-30 update-context` | Merge-update one context record. | `aliyun cms --api-version 2024-03-30 update-context help` |
| Context | `aliyun cms --api-version 2024-03-30 delete-context` | Delete one context record. | `aliyun cms --api-version 2024-03-30 delete-context help` |
| Context | `aliyun cms --api-version 2024-03-30 delete-contexts` | Batch delete by IDs or filter. | `aliyun cms --api-version 2024-03-30 delete-contexts help` |
| API Key | `aliyun cms --api-version 2024-03-30 create-context-store-api-key` | Create a store-scoped API key. | `aliyun cms --api-version 2024-03-30 create-context-store-api-key help` |
| API Key | `aliyun cms --api-version 2024-03-30 list-context-store-api-keys` | List API keys for one store. | `aliyun cms --api-version 2024-03-30 list-context-store-api-keys help` |
| API Key | `aliyun cms --api-version 2024-03-30 delete-context-store-api-key` | Delete a store-scoped API key by name. | `aliyun cms --api-version 2024-03-30 delete-context-store-api-key help` |

## Required Common Parameters

| Parameter | Commands | Notes |
| --- | --- | --- |
| `--workspace` | All ContextStore commands | Required workspace ID. |
| `--context-store-name` | All except `list-context-stores` | Required store name. |
| `--context-type` | `create-context-store`, `add-contexts` | `memory` or `experience`. |
| `--memory-type` | `add-contexts` for memory only | `short` or `long`; forbidden for experience. |
| `--items` | `add-contexts` | JSON array. |
| `--context-id` | `get-context`, `update-context`, `delete-context` | Single context ID. |
| `--context-ids` | `delete-contexts` | Comma-separated IDs. Mutually exclusive with `--filter`. |
| `--filter` | `search-context`, `delete-contexts` | JSON filter string. |
| `--query` | `search-context` | Semantic query text. |
| `--name` | API key create/delete | API key name. |


path: references/store-management.md
content: # ContextStore Store Management

All ContextStore commands use the CMS product and API version `2024-03-30`:

```bash
aliyun cms --api-version 2024-03-30 <subcommand> [flags]
```

Required parameters:

- `--workspace` for all commands.
- `--context-store-name` for all commands except `list-context-stores`.

Use `--cli-dry-run` to inspect method, URL, and request body before sending a request.

## Create Stores

### Memory Store

```bash
aliyun cms --api-version 2024-03-30 create-context-store \
  --workspace <workspace> \
  --context-store-name <memory_store_name> \
  --context-type memory \
  --description "<description>"
```

### Memory Store From an Existing Logstore

```bash
aliyun cms --api-version 2024-03-30 create-context-store \
  --workspace <workspace> \
  --context-store-name <memory_store_name> \
  --context-type memory \
  --config '{"source":{"project":"<source_project>","logstore":"<source_logstore>"}}'
```

### Experience Store

Experience stores require a source trace logstore. `startTime` format is `yyyy-MM-dd'T'HH:mm:ss'Z'`.

```bash
aliyun cms --api-version 2024-03-30 create-context-store \
  --workspace <workspace> \
  --context-store-name <experience_store_name> \
  --context-type experience \
  --description "<description>" \
  --config '{
    "source": {
      "project": "<source_project>",
      "logstore": "<source_logstore>",
      "startTime": "<start_time_utc>"
    },
    "metadataField": {
      "project": "attributes.project",
      "agentId": "attributes.agent_id",
      "errorType": "analysis.error_type"
    }
  }'
```

Constraints:

- `config.source.project` and `config.source.logstore` must be in the same region as the workspace.
- `metadataField` is supported only for experience stores.
- `contextType`, `contextStoreName`, and `config.source` are not mutable after creation.

## Query, List, Update, Delete Stores

```bash
aliyun cms --api-version 2024-03-30 get-context-store \
  --workspace <workspace> \
  --context-store-name <context_store_name>
```

```bash
aliyun cms --api-version 2024-03-30 list-context-stores \
  --workspace <workspace> \
  --context-type <memory_or_experience> \
  --max-results <max_results>
```

```bash
aliyun cms --api-version 2024-03-30 update-context-store \
  --workspace <workspace> \
  --context-store-name <context_store_name> \
  --description "<new_description>" \
  --config '{"metadataField":{"project":"attributes.project","errorType":"analysis.error_type"}}'
```

```bash
aliyun cms --api-version 2024-03-30 delete-context-store \
  --workspace <workspace> \
  --context-store-name <context_store_name>
```

Deletion removes system-managed datasets and internal logstores created for the store. User-provided source logstores are not deleted.

## Store-Level API Keys

API keys are scoped to one ContextStore and cannot be reused across stores. The `create-context-store-api-key` response returns the secret value only once.

```bash
aliyun cms --api-version 2024-03-30 create-context-store-api-key \
  --workspace <workspace> \
  --context-store-name <context_store_name> \
  --name <api_key_name>
```

```bash
aliyun cms --api-version 2024-03-30 list-context-store-api-keys \
  --workspace <workspace> \
  --context-store-name <context_store_name>
```

```bash
aliyun cms --api-version 2024-03-30 delete-context-store-api-key \
  --workspace <workspace> \
  --context-store-name <context_store_name> \
  --name <api_key_name>
```


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

Use this workflow to validate the generated ContextStore commands before running user-impacting operations.

## 1. Local CLI Checks

```bash
aliyun version
aliyun plugin show --name cms
aliyun configure list
```

Expected:

- `aliyun version` is `3.3.3` or later.
- `aliyun plugin show --name cms` reports `Version: 0.2.4` or later. If older, upgrade with `aliyun plugin install --names cms` (or pin with `--version 0.2.4`). Earlier versions stringify typed values inside `experience` / `metadata` / `config.metadataField` and will silently corrupt writes.
- `aliyun configure list` shows a valid profile or identity without revealing secrets.

## 2. Command Surface Validation

Validate the subcommand and parameter surface before using a command in a workflow:

```bash
aliyun cms --api-version 2024-03-30 <subcommand> help
```

Subcommands to validate:

- `create-context-store`
- `get-context-store`
- `list-context-stores`
- `update-context-store`
- `delete-context-store`
- `add-contexts`
- `get-context`
- `search-context`
- `update-context`
- `delete-context`
- `delete-contexts`
- `create-context-store-api-key`
- `list-context-store-api-keys`
- `delete-context-store-api-key`

Check that each parameter used by the workflow appears in the help output, including `--workspace`, `--context-store-name`, `--context-type`, `--memory-type`, `--items`, `--filter`, `--query`, `--context-id`, `--context-ids`, `--retrieval-option`, `--experience`, and `--metadata`.

## 3. Dry-Run Validation

For complex JSON or destructive commands, append `--cli-dry-run` and inspect method, URL, query parameters, and body.

```bash
aliyun cms --api-version 2024-03-30 add-contexts \
  --workspace <workspace> \
  --context-store-name <context_store_name> \
  --context-type memory \
  --memory-type long \
  --items '[{"content":"<content>","userId":"<user_id>"}]' \
  --cli-dry-run
```

Expected:

- JSON stays intact after shell parsing.
- `--api-version 2024-03-30` is present.
- Memory write includes `--memory-type`; experience write omits it.
- Typed values inside `experience` / `metadata` (numbers, booleans, arrays, null, nested objects) appear with their original types in the dry-run `Body:` output. If they appear stringified, the CMS plugin is older than `0.2.4`; upgrade with `aliyun plugin install --names cms`.
- `metadata.traceStartNs` / `metadata.traceEndNs` were passed as JSON strings (the only fields large enough to require it).

## 4. Store Verification

After creating or updating a store:

```bash
aliyun cms --api-version 2024-03-30 get-context-store \
  --workspace <workspace> \
  --context-store-name <context_store_name>
```

Expected:

- The response includes the requested store name.
- `contextType` matches the intended type.
- Mutable fields such as `description` or `metadataField` reflect updates.

## 5. Data Verification

After `add-contexts`, capture the returned context IDs, then verify one record:

```bash
aliyun cms --api-version 2024-03-30 get-context \
  --workspace <workspace> \
  --context-store-name <context_store_name> \
  --context-id <context_id> \
  --formatted=false
```

Then verify retrieval:

```bash
aliyun cms --api-version 2024-03-30 search-context \
  --workspace <workspace> \
  --context-store-name <context_store_name> \
  --query "<search_query>" \
  --limit 5
```

Expected:

- `get-context` returns the written content or raw `experience` and `metadata`.
- `search-context` returns relevant records for the semantic query.

## 6. API Key Verification

After creating an API key, do not expose the returned secret in chat. Verify key metadata by listing keys:

```bash
aliyun cms --api-version 2024-03-30 list-context-store-api-keys \
  --workspace <workspace> \
  --context-store-name <context_store_name>
```

Expected:

- The key name appears in the list.
- Secret material is not required for verification.

## 7. Cleanup Verification

After deleting a context or store, run the corresponding get/list command and confirm the deleted object no longer appears. Do not run cleanup against production resources unless the user explicitly confirms the exact IDs or store name.


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