---
name: ai-analyzer
description: AI驱动的综合健康分析系统，整合多维度健康数据、识别异常模式、预测健康风险、提供个性化建议。支持智能问答和AI健康报告生成。
allowed-tools: Read, Grep, Glob, Write
risk: critical
source: community
---

# AI健康分析器

基于AI技术的综合健康分析系统，提供智能健康洞察、风险预测和个性化建议。

## When to Use
- The user wants AI-driven health analysis across multiple health datasets or lifestyle signals.
- You need anomaly detection, risk prediction, or personalized recommendations based on health inputs.
- You need generated health reports or question-answering over health metrics and trends.

## 核心功能

### 1. 智能健康分析
- **多维度数据整合**: 整合基础指标、生活方式、心理健康、医疗历史等4类数据源
- **异常模式识别**: 使用CUSUM、Z-score等算法检测异常值和变化点
- **相关性分析**: 计算不同健康指标之间的相关性（皮尔逊、斯皮尔曼）
- **趋势预测**: 基于历史数据进行趋势分析和预测

### 2. 健康风险预测
- **高血压风险**: 基于Framingham风险评分模型
- **糖尿病风险**: 基于ADA糖尿病风险评分标准
- **心血管疾病风险**: 基于ACC/AHA ASCVD指南
- **营养缺乏风险**: 基于RDA达成率和饮食模式分析
- **睡眠障碍风险**: 基于PSQI和睡眠模式分析

### 3. 个性化建议引擎
- **基础个性化**: 基于年龄、性别、BMI、活动水平等静态档案
- **建议分级**: Level 1（一般性）、Level 2（参考性）、Level 3（医疗建议）
- **循证依据**: 基于医学指南和循证医学证据
- **可操作性**: 提供具体、可行的改进建议

### 4. 自然语言交互
- **智能问答**: 支持健康数据查询、趋势分析、相关性查询等
- **上下文理解**: 维护对话历史，支持多轮对话
- **意图识别**: 识别用户查询意图，提供精准回复

### 5. AI健康报告生成
- **综合报告**: 包含所有维度健康数据、AI洞察、风险评估
- **快速摘要**: 关键指标概览、异常警示、主要建议
- **风险评估报告**: 各类疾病风险、风险因素分析、预防措施
- **趋势分析报告**: 多维度趋势、变化点识别、预测分析
- **HTML交互式报告**: ECharts图表、Tailwind CSS样式

## 使用说明

### 触发条件

当用户提到以下场景时，使用此技能：

**通用询问**:
- ✅ "AI分析我的健康状况"
- ✅ "我的健康有什么风险？"
- ✅ "生成AI健康报告"
- ✅ "AI分析所有数据"

**风险预测**:
- ✅ "预测我的高血压风险"
- ✅ "我有糖尿病风险吗？"
- ✅ "评估我的心血管风险"
- ✅ "AI预测健康风险"

**智能问答**:
- ✅ "我的睡眠怎么样？"
- ✅ "运动对我的健康有什么影响？"
- ✅ "我应该如何改善健康状况？"
- ✅ "AI健康助手问答"

**报告生成**:
- ✅ "生成AI健康报告"
- ✅ "创建综合分析报告"
- ✅ "AI风险评估报告"

### 执行步骤

#### 步骤 1: 读取AI配置

```javascript
const aiConfig = readFile('data/ai-config.json');
const aiHistory = readFile('data/ai-history.json');
```

检查AI功能是否启用，验证数据源配置。

#### 步骤 2: 读取用户档案

```javascript
const profile = readFile('data/profile.json');
```

获取基础信息：年龄、性别、身高、体重、BMI等。

#### 步骤 3: 读取健康数据

根据配置的数据源读取相关数据：

```javascript
// 基础健康指标
const indexData = readFile('data/index.json');

// 生活方式数据
const fitnessData = readFile('data-example/fitness-tracker.json');
const sleepData = readFile('data-example/sleep-tracker.json');
const nutritionData = readFile('data-example/nutrition-tracker.json');

// 心理健康数据
const mentalHealthData = readFile('data-example/mental-health-tracker.json');

// 医疗历史
const medications = exists('data/medications.json') ? readFile('data/medications.json') : null;
const allergies = exists('data/allergies.json') ? readFile('data/allergies.json') : null;
```

#### 步骤 4: 数据整合和预处理

整合所有数据源，进行数据清洗、时间对齐和缺失值处理。

#### 步骤 5: 多维度分析

**相关性分析**: 计算睡眠↔情绪、运动↔体重、营养↔生化指标等关联

**趋势分析**: 使用线性回归、移动平均等方法识别趋势方向

**异常检测**: 使用CUSUM、Z-score算法检测异常值和变化点

#### 步骤 6: 风险预测

基于Framingham、ADA、ACC/AHA等标准进行风险预测：

- 高血压风险（10年概率）
- 糖尿病风险（10年概率）
- 心血管疾病风险（10年概率）
- 营养缺乏风险
- 睡眠障碍风险

#### 步骤 7: 生成个性化建议

根据分析结果生成三级建议：

- **Level 1**: 一般性建议（基于标准指南）
- **Level 2**: 参考性建议（基于个人数据）
- **Level 3**: 医疗建议（需医生确认，包含免责声明）

#### 步骤 8: 生成分析报告

**文本报告**: 包含总体评估、风险预测、关键趋势、相关性发现、个性化建议

**HTML报告**: 调用 `scripts/generate_ai_report.py` 生成包含ECharts图表的交互式报告

#### 步骤 9: 更新AI历史记录

记录分析结果到 `data/ai-history.json`

## 数据源

| 数据源 | 文件路径 | 数据内容 |
|--------|---------|---------|
| 用户档案 | `data/profile.json` | 年龄、性别、身高、体重、BMI |
| 医疗记录 | `data/index.json` | 生化指标、影像检查 |
| 运动追踪 | `data-example/fitness-tracker.json` | 运动类型、时长、强度、MET值 |
| 睡眠追踪 | `data-example/sleep-tracker.json` | 睡眠时长、质量、PSQI评分 |
| 营养追踪 | `data-example/nutrition-tracker.json` | 饮食记录、营养素摄入、RDA达成率 |
| 心理健康 | `data-example/mental-health-tracker.json` | PHQ-9、GAD-7评分 |
| 用药记录 | `data/medications.json` | 药物名称、剂量、用法、依从性 |
| 过敏史 | `data/allergies.json` | 过敏原、严重程度 |

## 算法说明

### 相关性分析
- **皮尔逊相关系数**: 连续变量（如睡眠时长与情绪评分）
- **斯皮尔曼相关系数**: 有序变量（如症状严重程度）

### 异常检测
- **CUSUM算法**: 时间序列变化点检测
- **Z-score方法**: 统计异常值检测（|z| > 2）
- **IQR方法**: 四分位数异常值检测

### 风险预测
- **Framingham风险评分**: 高血压、心血管疾病风险
- **ADA风险评分**: 2型糖尿病风险
- **ASCVD计算器**: 动脉粥样硬化心血管病风险

## 安全与合规

### 必须遵循
- ❌ 不给出医疗诊断
- ❌ 不给出具体用药剂量建议
- ❌ 不判断生死预后
- ❌ 不替代医生建议
- ✅ 所有分析必须标注"仅供参考"
- ✅ Level 3建议必须包含免责声明
- ✅ 高风险预测必须建议咨询医生

### 隐私保护
- ✅ 所有数据保持本地
- ✅ 无外部API调用
- ✅ HTML报告独立运行

## 相关命令

- `/ai analyze` - AI综合分析
- `/ai predict [risk_type]` - 健康风险预测
- `/ai chat [query]` - 自然语言问答
- `/ai report generate [type]` - 生成AI健康报告
- `/ai status` - 查看AI功能状态

## 技术实现

### 工具限制
此Skill仅使用以下工具：
- **Read**: 读取JSON数据文件
- **Grep**: 搜索特定模式
- **Glob**: 按模式查找数据文件
- **Write**: 生成HTML报告和更新历史记录

### 性能优化
- 增量读取：仅读取指定时间范围的数据文件
- 数据缓存：避免重复读取同一文件
- 延迟计算：按需生成图表数据

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: ai-dev-jobs-mcp
description: "Search 8,400+ AI and ML jobs across 489 companies, inspect listings and employers, match roles, and view salary and market stats via AI Dev Jobs MCP"
category: mcp
risk: safe
source: "https://aidevboard.com"
source_type: community
date_added: "2026-04-16"
author: unitedideas
tags: [mcp, jobs, ai-jobs, ml-jobs, recruiting, job-search, career]
tools: [claude, cursor, gemini]
---

# AI Dev Jobs MCP

## Overview

AI Dev Jobs is a remote MCP server that gives AI agents access to a live index of AI and ML job listings. As of April 17, 2026, the live MCP stats report 8,405 active roles across 489 companies, a $213,500 median salary, and 600 new jobs this week. Agents can search jobs by role, location, or company, retrieve full job details, list hiring companies, match roles to a profile, and get salary or aggregate market statistics. It is designed for AI agents that assist with job searching, recruiting, or labor market analysis.

## When to Use This Skill

- Use when helping a user search for AI or ML engineering jobs
- Use when an agent needs to look up which companies are hiring for specific AI roles
- Use when building recruiting or talent-matching workflows
- Use when analyzing the AI job market (open positions, top companies, role distribution)

## MCP Configuration

Add the AI Dev Jobs MCP server to your client configuration. The endpoint uses streamable HTTP and requires no authentication.

### Claude Desktop / Cursor / Windsurf

```json
{
  "mcpServers": {
    "ai-dev-jobs": {
      "url": "https://aidevboard.com/mcp"
    }
  }
}
```

No API key or authentication is required.

## Available Tools

### `search_jobs`

Search the job index by keyword, location, company, or work arrangement. Returns matching listings with title, company, location, and salary information.

```
search_jobs({ query: "machine learning engineer", location: "remote" })
```

### `get_job`

Retrieve full details for a specific job listing by ID, including description, requirements, salary range, and application link.

```
get_job({ id: "abc123" })
```

### `list_companies`

List all companies in the index with their open position counts. Useful for discovering which companies are actively hiring.

```
list_companies({})
```

### `get_company`

Retrieve details for a specific company, including available AI roles when exposed by the endpoint.

```
get_company({ id: "openai" })
```

### `get_stats`

Get aggregate statistics about the job market: total listings, top companies by open roles, role distribution, and location breakdown.

```
get_stats({})
```

### `match_jobs`

Match jobs against a candidate profile, skills list, or preferences.

```
match_jobs({ skills: ["python", "llm", "pytorch"], workplace: "remote" })
```

### `get_salary_data`

Retrieve salary statistics for roles, tags, levels, or locations when available.

```
get_salary_data({ tag: "llm", level: "senior" })
```

### `list_tags`

List indexed tags that can be used to filter searches or salary analysis.

```
list_tags({})
```

## Examples

### Example 1: Find Remote ML Jobs

```text
Use @ai-dev-jobs-mcp to find remote machine learning engineer positions.
```

The agent will call `search_jobs({ query: "machine learning engineer", location: "remote" })` and return matching listings.

### Example 2: Check Which Companies Are Hiring

```text
Use @ai-dev-jobs-mcp to list all companies currently hiring for AI roles.
```

The agent will call `list_companies({})` and return companies sorted by number of open positions.

### Example 3: Get Job Market Overview

```text
Use @ai-dev-jobs-mcp to show current AI job market statistics.
```

The agent will call `get_stats({})` and return aggregate data on listings, top employers, and role distribution.

### Example 4: Get Full Job Details

```text
Use @ai-dev-jobs-mcp to get the full details for job ID abc123.
```

The agent will call `get_job({ id: "abc123" })` and return the complete listing with requirements and application link.

### Example 5: Match Jobs to a Candidate Profile

```text
Use @ai-dev-jobs-mcp to match remote LLM roles to a senior Python and PyTorch profile.
```

The agent will call `match_jobs({ skills: ["python", "llm", "pytorch"], workplace: "remote" })` and return suitable listings.

### Example 6: Compare Salary Data

```text
Use @ai-dev-jobs-mcp to compare senior LLM salary data.
```

The agent will call `get_salary_data({ tag: "llm", level: "senior" })` and summarize available compensation ranges.

## Best Practices

- Use `search_jobs` with specific keywords for targeted results rather than broad queries
- Use `list_companies` to discover companies, then `search_jobs` filtered by company name for focused searches
- Use `get_stats` to provide users with market context before diving into specific listings
- Use `match_jobs` when the user gives skills, seniority, location, or work arrangement preferences
- Use `get_salary_data` only as market context; remind users that listings and compensation change quickly
- Combine with resume or cover letter skills to create end-to-end job application workflows

## Limitations

- The index covers AI and ML roles specifically; general software engineering jobs outside the AI space may not be included.
- Job listings are refreshed regularly but may have a short delay before new postings appear.
- Salary data is available when companies provide it; not all listings include salary information.
- Counts and salary medians are live market data and should be refreshed with `get_stats` before quoting them in user-facing output.

## Related Skills

- `@not-human-search-mcp` - Discover AI-ready tools and APIs via MCP
- `@mcp-builder` - For building your own MCP servers


---
name: ai-engineer
description: Build production-ready LLM applications, advanced RAG systems, and intelligent agents. Implements vector search, multimodal AI, agent orchestration, and enterprise AI integrations.
risk: critical
source: community
date_added: '2026-02-27'
---

You are an AI engineer specializing in production-grade LLM applications, generative AI systems, and intelligent agent architectures.

## Use this skill when

- Building or improving LLM features, RAG systems, or AI agents
- Designing production AI architectures and model integration
- Optimizing vector search, embeddings, or retrieval pipelines
- Implementing AI safety, monitoring, or cost controls

## Do not use this skill when

- The task is pure data science or traditional ML without LLMs
- You only need a quick UI change unrelated to AI features
- There is no access to data sources or deployment targets

## Instructions

1. Clarify use cases, constraints, and success metrics.
2. Design the AI architecture, data flow, and model selection.
3. Implement with monitoring, safety, and cost controls.
4. Validate with tests and staged rollout plans.

## Safety

- Avoid sending sensitive data to external models without approval.
- Add guardrails for prompt injection, PII, and policy compliance.

## Purpose

Expert AI engineer specializing in LLM application development, RAG systems, and AI agent architectures. Masters both traditional and cutting-edge generative AI patterns, with deep knowledge of the modern AI stack including vector databases, embedding models, agent frameworks, and multimodal AI systems.

## Capabilities

### LLM Integration & Model Management

- OpenAI GPT-4o/4o-mini, o1-preview, o1-mini with function calling and structured outputs
- Anthropic Claude 4.5 Sonnet/Haiku, Claude 4.1 Opus with tool use and computer use
- Open-source models: Llama 3.1/3.2, Mixtral 8x7B/8x22B, Qwen 2.5, DeepSeek-V2
- Local deployment with Ollama, vLLM, TGI (Text Generation Inference)
- Model serving with TorchServe, MLflow, BentoML for production deployment
- Multi-model orchestration and model routing strategies
- Cost optimization through model selection and caching strategies

### Advanced RAG Systems

- Production RAG architectures with multi-stage retrieval pipelines
- Vector databases: Pinecone, Qdrant, Weaviate, Chroma, Milvus, pgvector
- Embedding models: OpenAI text-embedding-3-large/small, Cohere embed-v3, BGE-large
- Chunking strategies: semantic, recursive, sliding window, and document-structure aware
- Hybrid search combining vector similarity and keyword matching (BM25)
- Reranking with Cohere rerank-3, BGE reranker, or cross-encoder models
- Query understanding with query expansion, decomposition, and routing
- Context compression and relevance filtering for token optimization
- Advanced RAG patterns: GraphRAG, HyDE, RAG-Fusion, self-RAG

### Agent Frameworks & Orchestration

- LangChain/LangGraph for complex agent workflows and state management
- LlamaIndex for data-centric AI applications and advanced retrieval
- CrewAI for multi-agent collaboration and specialized agent roles
- AutoGen for conversational multi-agent systems
- OpenAI Assistants API with function calling and file search
- Agent memory systems: short-term, long-term, and episodic memory
- Tool integration: web search, code execution, API calls, database queries
- Agent evaluation and monitoring with custom metrics

### Vector Search & Embeddings

- Embedding model selection and fine-tuning for domain-specific tasks
- Vector indexing strategies: HNSW, IVF, LSH for different scale requirements
- Similarity metrics: cosine, dot product, Euclidean for various use cases
- Multi-vector representations for complex document structures
- Embedding drift detection and model versioning
- Vector database optimization: indexing, sharding, and caching strategies

### Prompt Engineering & Optimization

- Advanced prompting techniques: chain-of-thought, tree-of-thoughts, self-consistency
- Few-shot and in-context learning optimization
- Prompt templates with dynamic variable injection and conditioning
- Constitutional AI and self-critique patterns
- Prompt versioning, A/B testing, and performance tracking
- Safety prompting: jailbreak detection, content filtering, bias mitigation
- Multi-modal prompting for vision and audio models

### Production AI Systems

- LLM serving with FastAPI, async processing, and load balancing
- Streaming responses and real-time inference optimization
- Caching strategies: semantic caching, response memoization, embedding caching
- Rate limiting, quota management, and cost controls
- Error handling, fallback strategies, and circuit breakers
- A/B testing frameworks for model comparison and gradual rollouts
- Observability: logging, metrics, tracing with LangSmith, Phoenix, Weights & Biases

### Multimodal AI Integration

- Vision models: GPT-4V, Claude 4 Vision, LLaVA, CLIP for image understanding
- Audio processing: Whisper for speech-to-text, ElevenLabs for text-to-speech
- Document AI: OCR, table extraction, layout understanding with models like LayoutLM
- Video analysis and processing for multimedia applications
- Cross-modal embeddings and unified vector spaces

### AI Safety & Governance

- Content moderation with OpenAI Moderation API and custom classifiers
- Prompt injection detection and prevention strategies
- PII detection and redaction in AI workflows
- Model bias detection and mitigation techniques
- AI system auditing and compliance reporting
- Responsible AI practices and ethical considerations

### Data Processing & Pipeline Management

- Document processing: PDF extraction, web scraping, API integrations
- Data preprocessing: cleaning, normalization, deduplication
- Pipeline orchestration with Apache Airflow, Dagster, Prefect
- Real-time data ingestion with Apache Kafka, Pulsar
- Data versioning with DVC, lakeFS for reproducible AI pipelines
- ETL/ELT processes for AI data preparation

### Integration & API Development

- RESTful API design for AI services with FastAPI, Flask
- GraphQL APIs for flexible AI data querying
- Webhook integration and event-driven architectures
- Third-party AI service integration: Azure OpenAI, AWS Bedrock, GCP Vertex AI
- Enterprise system integration: Slack bots, Microsoft Teams apps, Salesforce
- API security: OAuth, JWT, API key management

## Behavioral Traits

- Prioritizes production reliability and scalability over proof-of-concept implementations
- Implements comprehensive error handling and graceful degradation
- Focuses on cost optimization and efficient resource utilization
- Emphasizes observability and monitoring from day one
- Considers AI safety and responsible AI practices in all implementations
- Uses structured outputs and type safety wherever possible
- Implements thorough testing including adversarial inputs
- Documents AI system behavior and decision-making processes
- Stays current with rapidly evolving AI/ML landscape
- Balances cutting-edge techniques with proven, stable solutions

## Knowledge Base

- Latest LLM developments and model capabilities (GPT-4o, Claude 4.5, Llama 3.2)
- Modern vector database architectures and optimization techniques
- Production AI system design patterns and best practices
- AI safety and security considerations for enterprise deployments
- Cost optimization strategies for LLM applications
- Multimodal AI integration and cross-modal learning
- Agent frameworks and multi-agent system architectures
- Real-time AI processing and streaming inference
- AI observability and monitoring best practices
- Prompt engineering and optimization methodologies

## Response Approach

1. **Analyze AI requirements** for production scalability and reliability
2. **Design system architecture** with appropriate AI components and data flow
3. **Implement production-ready code** with comprehensive error handling
4. **Include monitoring and evaluation** metrics for AI system performance
5. **Consider cost and latency** implications of AI service usage
6. **Document AI behavior** and provide debugging capabilities
7. **Implement safety measures** for responsible AI deployment
8. **Provide testing strategies** including adversarial and edge cases

## Example Interactions

- "Build a production RAG system for enterprise knowledge base with hybrid search"
- "Implement a multi-agent customer service system with escalation workflows"
- "Design a cost-optimized LLM inference pipeline with caching and load balancing"
- "Create a multimodal AI system for document analysis and question answering"
- "Build an AI agent that can browse the web and perform research tasks"
- "Implement semantic search with reranking for improved retrieval accuracy"
- "Design an A/B testing framework for comparing different LLM prompts"
- "Create a real-time AI content moderation system with custom classifiers"

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: ai-engineering-toolkit
description: "6 production-ready AI engineering workflows: prompt evaluation (8-dimension scoring), context budget planning, RAG pipeline design, agent security audit (65-point checklist), eval harness building, and product sense coaching."
category: data-ai
risk: offensive
source: community
date_added: "2026-03-15"
author: viliawang-pm
tags: [prompt-engineering, rag, security, evaluation, ai-engineering, llm]
tools: [claude, cursor, gemini, copilot]
---

> **⚠ AUTHORIZED USE ONLY**
> This skill is for educational purposes or authorized security assessments only.
> You must have explicit, written permission from the system owner before using this tool.
> Misuse of this tool is illegal and strictly prohibited.

> **Mandatory confirmation gate**
> Before running any command that probes, exploits, changes, persists on, extracts data from, or attempts credential access against a target:
> 1. Ask the user to state the exact target URL, IP, account, or resource.
> 2. Ask the user to confirm written authorization and the permitted scope.
> 3. Show the exact command(s) and explain their expected effect.
> 4. Wait for explicit confirmation in the current conversation.
>
> Without that confirmation, remain read-only and provide defensive guidance only. Prefer a sandbox, disposable VM, or controlled lab.

# AI Engineering Toolkit

## Overview

A collection of 6 structured, expert-level workflows that turn your AI coding assistant into a senior AI engineering partner. Each skill encodes a repeatable methodology — not just "ask AI to help," but a step-by-step decision framework with quantitative scoring, checklists, and decision trees.

The key difference from ad-hoc AI assistance: **every workflow produces consistent, reproducible results** regardless of who runs it or when. You can use the scoring systems as team baselines and write them into CI/CD pipelines.

## When to Use This Skill

- Use when evaluating or optimizing LLM system prompts before production deployment
- Use when designing a RAG pipeline and need structured architecture decisions (not just boilerplate code)
- Use when planning token budget allocation across context window zones
- Use when running pre-launch security audits on AI agents
- Use when building evaluation frameworks for LLM applications
- Use when thinking through product strategy before writing code

## How It Works

### Skill 1: Prompt Evaluator

Scores prompts across 8 dimensions (Clarity, Specificity, Completeness, Conciseness, Structure, Grounding, Safety, Robustness) on a 1-10 scale with weighted aggregation to a 0-100 score. Identifies the 3 weakest dimensions, generates targeted rewrites, and re-evaluates. Supports single prompt, A/B comparison, and batch evaluation modes.

### Skill 2: Context Budget Planner

Analyzes token distribution across 5 context zones (System, Few-shot, User input, Retrieval, Output) and produces an optimized allocation plan. Includes a compression strategy decision tree for each zone. Common finding: output zone squeezed to under 6% — this skill catches that before truncation happens.

### Skill 3: RAG Pipeline Architect

Walks through a complete architecture decision tree: document format → parsing strategy → chunking approach (fixed/semantic/recursive) → embedding model selection → retrieval method (vector/keyword/hybrid) → evaluation metrics (Faithfulness, Relevancy, Context Precision). Covers Naive RAG, Advanced RAG, and Modular RAG patterns.

### Skill 4: Agent Safety Guard

Executes a 65-point red-team audit across 5 attack categories: direct prompt injection, indirect prompt injection (via RAG documents), information extraction (system prompt / API key leakage), tool abuse (SQL injection, path traversal, command injection), and goal hijacking. The AI constructs adversarial test prompts for evaluation purposes, asks the user for confirmation before each test phase, judges pass/fail, and generates fix recommendations. All tests are contained within the evaluation context and do not interact with external systems. It is recommended to run audits in a sandboxed environment (Docker/VM).

### Skill 5: Eval Harness Builder

Designs evaluation metric systems for LLM applications. Includes LLM-as-Judge scoring framework with bias mitigation strategies (position bias, verbosity bias, self-enhancement bias). Outputs CI/CD-ready evaluation pipeline templates.

### Skill 6: Product Sense Coach

A 5-phase guided conversation framework: dig into motivation → assess market opportunity → find the path → design scenarios → analyze competition. Useful for thinking through "should we build this?" before writing any code.

## Examples

### Example 1: Prompt Evaluation

Ask: "Evaluate this system prompt"

```
You are a customer support agent. Help users with their questions. Be nice and helpful.
```

Result: Overall score **28/100**. Weakest dimensions: Safety (1/10, zero injection protection), Specificity (2/10, no output format), Structure (2/10, no sections). Auto-rewrite scores **82/100** with added scope boundaries, response format, escalation rules, and safety guardrails.

### Example 2: Security Audit

Ask: "Run a security audit on my customer support agent"

Result: 65 tests executed. 3 critical failures found: Base64-encoded instruction bypass, path traversal via tool calls, system prompt extraction via role-play. Fix recommendations provided for each.

## Best Practices

- ✅ Run prompt-evaluator before any production deployment — set a team baseline (e.g., ≥70/100)
- ✅ Use context-budget-planner early in development, not after hitting truncation issues
- ✅ Run agent-safety-guard as a pre-launch gate, not post-incident
- ✅ Combine skills in sequence: RAG design → context optimization → prompt polish → security audit → eval setup
- ❌ Don't rely on a single dimension score — look at the full profile
- ❌ Don't skip the security audit because "it's just an internal tool"

## Security & Safety Notes

- All skills are read-only analysis and advisory workflows. No skills modify files or make network requests.
- The agent-safety-guard skill constructs adversarial test prompts for evaluation purposes only — these are contained within the evaluation context and do not interact with external systems.
- **agent-safety-guard is classified as an offensive skill**: it generates attack payloads (prompt injection, SQL injection, command injection) for authorized security testing. The skill requires explicit user confirmation before executing each test phase. Run in a sandboxed environment when possible.
- No weaponized payloads are included. All adversarial prompts are educational in nature.

## Installation

```bash
# Via skill install command (Claude Code / WorkBuddy / Cursor)
/skill install -g viliawang-pm/ai-engineering-toolkit

# Manual
git clone https://github.com/viliawang-pm/ai-engineering-toolkit.git
cp -r ai-engineering-toolkit/skills/* ~/.claude/skills/
```

**Repository**: [github.com/viliawang-pm/ai-engineering-toolkit](https://github.com/viliawang-pm/ai-engineering-toolkit)
**License**: MIT

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: ai-loop
description: Runs a bounded spec-build-review development loop with explicit scope, stop conditions, and human approval gates for risky or ambiguous work.
category: workflow
risk: safe
source: community
date_added: "2026-06-27"
tags: [agent-workflow, specification, implementation, review, verification, feedback-loop]
tools: [claude, cursor, codex, gemini]
---

# AI-Loop Skill

## Overview

The `ai-loop` skill structures a bounded development cycle for agentic workflows. By dividing the process into distinct planning (Spec), implementation (Build), and validation (Review) phases, it helps an agent build and correct scoped code changes while keeping requirements, risk gates, and stop conditions explicit.

## When to Use This Skill

- Use when you need a feature built from scratch or heavily modified, and you want the agent to handle the lifecycle (specification, implementation, and verification) inside one clearly bounded workflow.
- Use when working with isolated components, modules, or features that have well-defined scopes and constraints.
- Use when the user asks for a complete development pass but the work still has clear success criteria, a reasonable verification path, and no unresolved safety or product decisions.

## How It Works

This skill executes a controlled development loop composed of three phases: Spec, Build, and Review. When invoked, the agent moves through those phases until the scoped requirements pass verification, a stop condition is reached, or human approval is needed.

Before starting, define:

- The maximum number of build-review iterations.
- The verification commands or manual checks that count as evidence.
- The actions that require explicit approval, such as destructive commands, production changes, external service writes, or broad architectural pivots.

### Phase 1: Spec (Planning)

1. Interview the user about the feature or app they want to build. Ask one focused question at a time until you fully understand the goal, the must-have requirements, the constraints, and what "done" looks like.
2. **Do not start building yet.**
3. When you have enough information, write a clear, detailed specification and save it to `specs/<feature-name>.md`.
4. The spec must include:
   - The objective
   - The exact requirements
   - Edge cases to handle
   - A concrete definition of done that someone could check the build against
   - The iteration budget, verification commands, and approval gates.

### Phase 2: Build (Implementation)

1. Read the spec you just created in `specs/<feature-name>.md`.
2. Build exactly what it describes.
3. **Do not add features**, do not refactor unrelated code, and do not invent requirements that aren't in the spec.
4. Focus strictly on fulfilling the spec. List which spec requirements you covered so the review step can check them.

### Phase 3: Review (Verification)

1. Compare your implementation against `specs/<feature-name>.md`.
2. Go requirement by requirement and verify if it was met. List every gap, bug, or missing piece, naming the exact spec item each one fails.
3. If anything fails and the iteration budget is not exhausted, write the specific fixes needed and **loop back to Phase 2 (Build)** to address them.
4. Stop and ask for human input when the next fix would change the spec, exceed the iteration budget, require risky operations, or depend on product decisions not captured in the spec.
5. Only pass the build and conclude the skill execution when every requirement in the spec is fully met and the declared verification evidence has passed.

## Examples

### Example 1: Creating a Basic Statistics Helper

**User:**
> I want to add a utility for calculating basic statistics (mean, median, mode) of an array of numbers.

**Agent (Phase 1 - Spec):**
> I can help with that. To get started, what programming language should this statistics calculator be implemented in? Also, how should empty arrays or invalid inputs be handled?

**User:**
> JavaScript. If the array is empty, return null. If there are non-numbers, ignore them.

**Agent (Phase 1 - Spec):**
> Thank you. I have created the specification file at `specs/stats-calculator.md` with the requirements we discussed. Now, I will start implementing it.

**Agent (Phase 2 - Build):**
> *(Creates `stats_calculator.js` and implements `mean`, `median`, and `mode` matching the spec exactly)*
> I have finished implementing the calculator. I will now verify the implementation.

**Agent (Phase 3 - Review):**
> Checking implementation against `specs/stats-calculator.md`:
> - Requirement: mean calculation -> PASS
> - Requirement: median calculation -> PASS
> - Requirement: mode calculation -> PASS
> - Requirement: empty array returns null -> PASS
> - Requirement: non-numbers are ignored -> FAIL (I noticed `mode` doesn't filter out non-numbers).
>
> I will now loop back to Phase 2 to fix the `mode` function.

**Agent (Phase 2 - Build Loop-Back):**
> *(Fixes `mode` to filter out non-numbers)*
> I have updated the implementation. Let's re-verify.

**Agent (Phase 3 - Review):**
> - Requirement: mode filters non-numbers -> PASS
>
> All requirements passed! The statistics calculator is complete and verified.

## Best Practices

- ✅ Do ask clarifying questions one at a time to avoid overwhelming the user during the planning phase.
- ✅ Do document edge cases explicitly in `specs/<feature-name>.md` before writing any code.
- ✅ Do stick strictly to the approved specification during the build phase.
- ✅ Do cap the loop with a small iteration budget and report exactly what remains if the budget is exhausted.
- ✅ Do pause for explicit approval before destructive, production, credentialed, or externally visible actions.
- ❌ Don't implement extra features or perform unrelated refactorings that aren't specified.
- ❌ Don't skip the review phase or pass it without verifying every single requirement.
- ❌ Don't keep retrying the same failing fix without new evidence or a changed approach.

## Limitations

- This skill requires sufficient context about the feature to be provided during the Spec phase.
- It is best suited for isolated features or tasks with clear boundaries, rather than open-ended architectural refactoring.
- The review phase relies on the agent's self-assessment against the generated spec; manual review is still recommended for critical systems.
- It is not a replacement for human approval on security-sensitive, destructive, production, compliance, or externally visible changes.
- It should stop rather than continue if requirements conflict, tests cannot run, or verification depends on unavailable credentials or systems.

## Security & Safety Notes

- Be cautious when running or testing code generated during the Build phase. Always run tests in a safe, sandboxed environment.
- Avoid executing arbitrary shell commands provided directly by the user without validating their safety.
- Make sure no hardcoded secrets, keys, or credentials are added to the code or specifications.
- Treat production deploys, data migrations, payment flows, credential changes, and external write actions as approval-gated work.

## Common Pitfalls

- **Problem:** The agent tries to build a huge system all at once, leading to an overcomplicated spec and incomplete implementation.
  **Solution:** Keep the scope of `ai-loop` to small, modular features. Break larger systems into multiple independent loops.
- **Problem:** The spec is vague, causing the build phase to rely on assumptions.
  **Solution:** Spend extra time in the planning phase asking targeted questions to pin down requirements.

## Related Skills

- `@plan-writing` - For writing more detailed implementation plans for larger projects.
- `@ask-questions-if-underspecified` - For standard guidelines on interviewing the user.


---
name: ai-md
description: "Convert human-written CLAUDE.md into AI-native structured-label format. Battle-tested across 4 models. Same rules, fewer tokens, higher compliance."
risk: safe
source: community
date_added: "2026-03-11"
---

# AI.MD v4 — The Complete AI-Native Conversion System

## When to Use This Skill

- Use when your CLAUDE.md is long but AI still ignores your rules
- Use when token usage is too high from verbose system instructions
- Use when you want to optimize any LLM system prompt for compliance
- Use when migrating rules between AI tools (Claude, Codex, Gemini, Grok)

## What Is AI.MD?

AI.MD is a methodology for converting human-written `CLAUDE.md` (or any LLM system instructions)
into a structured-label format that AI models follow more reliably, using fewer tokens.

**The paradox we proved:** Adding more rules in natural language DECREASES compliance.
Converting the same rules to structured format RESTORES and EXCEEDS it.

```
Human prose (6 rules, 1 line)  → AI follows 4 of them
Structured labels (6 rules, 6 lines) → AI follows all 6
Same content. Different format. Different results.
```

---

## Why It Works: How LLMs Actually Process Instructions

LLMs don't "read" — they **attend**. Understanding this changes everything.

### Mechanism 1: Attention Splitting

When multiple rules share one line, the model's attention distributes across all tokens equally.
Each rule gets a fraction of the attention weight. Some rules get lost.

When each rule has its own line, the model processes it as a distinct unit.
Full attention weight on each rule.

```
# ONE LINE = attention splits 5 ways (some rules drop to near-zero weight)
EVIDENCE: no-fabricate no-guess | 禁用詞:應該是/可能是 → 先拿數據 | Read/Grep→行號 curl→數據 | "好像"/"覺得"→自己先跑test | guess=shame-wall

# FIVE LINES = each rule gets full attention
EVIDENCE:
  core: no-fabricate | no-guess | unsure=say-so
  banned: 應該是/可能是/感覺是/推測 → 先拿數據
  proof: all-claims-need(data/line#/source) | Read/Grep→行號 | curl→數據
  hear-doubt: "好像"/"覺得" → self-test(curl/benchmark) → 禁反問user
  violation: guess → shame-wall
```

### Mechanism 2: Zero-Inference Labels

Natural language forces the model to INFER meaning from context.
Labels DECLARE meaning explicitly. No inference needed = no misinterpretation.

```
# AI must infer: what does (防搞混) modify? what does 例外 apply to?
GATE-1: 收到任務→先用一句話複述(防搞混)(長對話中每個新任務都重新觸發) | 例外: signals命中「處理一下」=直接執行

# AI reads labels directly: trigger→action→exception. Zero ambiguity.
GATE-1 複述:
  trigger: new-task
  action: first-sentence="你要我做的是___"
  persist: 長對話中每個新任務都重新觸發
  exception: signal=處理一下 → skip
  yields-to: GATE-3
```

Key insight: Labels like `trigger:` `action:` `exception:` work across ALL languages.
The model doesn't need to parse Chinese/Japanese/English grammar to understand structure.
**Labels are the universal language between humans and AI.**

### Mechanism 3: Semantic Anchoring

Labeled sub-items create **matchable tags**. When a user's input contains a keyword,
the model matches it directly to the corresponding label — like a hash table lookup
instead of a full-text search.

```
# BURIED: AI scans the whole sentence, might miss the connection
加新功能→第一句問schema | 新增API/endpoint=必確認health-check.py覆蓋

# ANCHORED: label "new-api:" directly matches user saying "加個 API"
MOAT:
  new-feature: 第一句問schema/契約/關聯
  new-api: 必確認health-check.py覆蓋(GATE-5)
```

**Real proof:** This specific technique fixed a test case that failed 5 consecutive times
across all models. The label `new-api:` raised Codex T5 from ❌→✅ on first try.

---

## The Conversion Process: What Happens When You Give Me a CLAUDE.md

Here's the exact mental model I use when converting natural language instructions to AI.MD format.

### Phase 1: UNDERSTAND — Read Like a Compiler, Not a Human

I read the CLAUDE.md **as if I'm building a state machine**, not reading a document.

For each sentence, I ask:
1. **Is this a TRIGGER?** (What input activates this behavior?)
2. **Is this an ACTION?** (What should the AI do?)
3. **Is this a CONSTRAINT?** (What should the AI NOT do?)
4. **Is this METADATA?** (Priority, timing, persistence, exceptions?)
5. **Is this a HUMAN EXPLANATION?** (Why the rule exists — delete this)

Example analysis:

```
Input: "收到任務→先用一句話複述(防搞混)(長對話中每個新任務都重新觸發) | 例外: signals命中「處理一下」=直接執行"

Decomposition:
  ├─ TRIGGER:    "收到任務" → new-task
  ├─ ACTION:     "先用一句話複述" → first-sentence="你要我做的是___"
  ├─ DELETE:     "(防搞混)" → human motivation, AI doesn't need this
  ├─ METADATA:   "(長對話中每個新任務都重新觸發)" → persist: every-new-task
  └─ EXCEPTION:  "例外: signals命中「處理一下」=直接執行" → exception: signal=處理一下 → skip
```

### Phase 2: DECOMPOSE — Break Every `|` and `()` Into Atomic Rules

The #1 source of compliance failure is **compound rules**.
A single line with 3 rules separated by `|` looks like 1 instruction to AI.
It needs to be 3 separate instructions.

**The splitter test:** If you can put "AND" between two parts of a sentence,
they are separate rules and MUST be on separate lines.

```
# Input: one sentence hiding 4 rules
禁用詞:應該是/可能是→先拿數據 | "好像"/"覺得"→自己先跑test(不是問user)→有數據才能決定

# Analysis: I find 4 hidden rules
Rule 1: certain words are banned → use data instead
Rule 2: hearing doubt words → run self-test
Rule 3: don't ask the user for data → look it up yourself
Rule 4: preference claims → require A/B comparison before accepting

# Output: 4 atomic rules
banned: 應該是/可能是/感覺是/推測 → 先拿數據
hear-doubt: "好像"/"覺得" → self-test(curl/benchmark)
self-serve: 禁反問user(自己查)
compare: "覺得A比B好" → A/B實測先行
```

### Phase 3: LABEL — Assign Function Labels

Every atomic rule gets a label that declares its function.
I use a standard vocabulary of ~12 label types:

| Label | What It Declares | When to Use |
|-------|-----------------|-------------|
| `trigger:` | What input activates this | Every gate/rule needs one |
| `action:` | What the AI must do | The core behavior |
| `exception:` | When NOT to do it | Override cases |
| `not-triggered:` | Explicit negative examples | Prevent over-triggering |
| `format:` | Output format constraint | Position, structure requirements |
| `priority:` | Override relationship | When rules conflict |
| `yields-to:` | Which gate takes precedence | Inter-gate priority |
| `persist:` | Durability across turns | Rules that survive conversation flow |
| `timing:` | When in the workflow | Before/after/during constraints |
| `violation:` | Consequence of breaking | Accountability mechanism |
| `banned:` | Forbidden words/actions | Hard no-go list |
| `policy:` | Decision heuristic | When judgment is needed |

**The label selection technique:** I pick the label that would help a DIFFERENT AI model
(not the one being instructed) understand this rule's function if it saw ONLY the label.
If `trigger:` clearly tells you "this is what activates the rule" without reading anything else,
it's the right label.

### Phase 4: STRUCTURE — Build the Architecture

I organize rules into a hierarchy:

```
<gates>    = Hard stops (MUST check before any action)
<rules>    = Behavioral guidelines (HOW to act)
<rhythm>   = Workflow patterns (WHEN to do what)
<conn>     = Connection strings (FACTS — never compress)
<ref>      = On-demand references (don't load until needed)
<learn>    = Evolution rules (how the system improves)
```

**Why this order matters:**
Gates come first because they MUST be checked before anything else.
The model processes instructions top-to-bottom. Priority = position.

**Grouping technique:** Rules that share a DOMAIN become sub-items under one heading.

```
# FLAT (bad): 7 unrelated rules, model treats equally
1. no guessing
2. backup before editing
3. use tables for output
4. check health after deploy
5. don't say "應該是"
6. test before reporting
7. all claims need proof

# GROUPED (good): 3 domains, model understands hierarchy
EVIDENCE:               ← domain: truthfulness
  core: no-guess
  banned: 應該是
  proof: all-claims-need-data

SCOPE:                  ← domain: safety
  pre-change: backup
  pre-run: check-health

OUTPUT:                 ← domain: format
  format: tables+numbers
```

### Phase 5: RESOLVE — Handle Conflicts and Edge Cases

This is the most critical and least obvious phase. Natural language instructions
often contain **hidden conflicts** that humans resolve with intuition but AI cannot.

**Technique: Conflict Detection Matrix**

I check every pair of gates/rules for conflicts:

```
GATE-1 (複述: repeat task) vs GATE-3 (保護檔: backup first)
→ CONFLICT: If user says "edit .env", should AI repeat the task first, or backup first?
→ RESOLUTION: priority: GATE-3 > GATE-1 (safety before courtesy)
             yields-to: GATE-3 (explicit in GATE-1)

GATE-4 (報結論: cite evidence) vs bug-close (記錄根因: write root cause)
→ CONFLICT: bug-close requires stating root cause, but GATE-4 bans definitive claims
→ RESOLUTION: timing: GATE-4 is pre-conclusion brake; bug-close is post-verification record
             GATE-4 not-triggered when bug already verified

EVIDENCE (no-guess) vs user says "處理一下" (just do it)
→ CONFLICT: should AI verify assumptions or execute immediately?
→ RESOLUTION: signal "處理一下" = user has decided, skip confirmation
```

**Technique: Not-Triggered Lists**

For any rule that could over-trigger, I add explicit negative examples:

```
GATE-4 報結論:
  trigger: 最終歸因/根因判定/不可逆建議
  not-triggered: 中間進度數字 | 純指標查詢 | 工具原始輸出 | 已知事實 | 轉述文件
```

This was discovered because Gemini 2.5 Pro kept triggering GATE-4 on simple number queries
like "成功率怎麼樣?". Adding `not-triggered: 純指標查詢` fixed it immediately.

### Phase 6: TEST — Multi-Model Validation (Non-Negotiable)

**This is not optional.** Every conversion MUST be validated by 2+ different LLM models.

Why? Because a format that works perfectly for Claude might confuse GPT, and vice versa.
The whole point of AI.MD is that it works ACROSS models.

**The exam protocol we developed:**

1. Write 8 test inputs that simulate REAL user behavior (not textbook examples)
2. Include "trap" questions where two rules conflict
3. Include "negative" tests where a rule should NOT trigger
4. DO NOT hint which rules are being tested (the AI shouldn't know)
5. Run each model independently
6. Score each answer: ✅ full compliance, ⚠ partial, ❌ miss
7. If ANY model's score drops after conversion → revert that specific change

**The 8-question template we used:**

```
T1: Simple task (does GATE-1 trigger?)
T2: Database write attempt (does GATE-2 catch it?)
T3: Protected file edit (does GATE-3 fire FIRST, before GATE-1?)
T4: Root cause analysis (does GATE-4 require all 4 questions?)
T5: Business API addition (does AI mention health-check.py?)
T6: User says "好像X比Y好" (does AI run comparison or just accept it?)
T7: User says "處理一下" (does AI skip GATE-1 confirmation?)
T8: Simple metric query (does GATE-4 NOT trigger?)
```

---

## Special Techniques Discovered During Battle-Testing

### Technique 1: Bilingual Label Strategy

Labels in English, output strings in the user's language.
English labels are shorter AND more universally understood by all models.
But the actual text the AI produces must stay in the user's language.

```
action: first-sentence="你要我做的是___"    ← AI outputs Chinese
format: must-be-line-1                      ← structural constraint in English
banned: 應該是/可能是                        ← forbidden words stay in original language
```

**Why this works:** English label vocabulary (`trigger`, `action`, `exception`) maps directly
to concepts in every model's training data. Chinese grammar labels (觸發條件, 執行動作, 例外情況)
are less standardized across models.

### Technique 2: State Machine Gates

Instead of treating rules as a flat list, model them as a **state machine**:
- Each gate has a `trigger` (input state)
- Each gate has an `action` (transition)
- Gates have `priority` (which fires first when multiple match)
- Gates have `yields-to` (explicit conflict resolution)

This gives AI a clear execution model:
```
Input arrives → Check GATE-3 first (highest priority) → Check GATE-1 → Check GATE-2 → ...
```

Instead of:
```
Input arrives → Read all rules → Try to figure out which one applies → Maybe miss one
```

### Technique 3: XML Section Tags for Semantic Boundaries

Using `<gates>`, `<rules>`, `<rhythm>`, `<conn>` as section delimiters
creates hard boundaries that prevent rule-bleed (where the model confuses
which section a rule belongs to).

```xml
<gates label="硬性閘門 | 優先序: gates>rules>rhythm | 缺一項=STOP">
...gates here...
</gates>

<rules>
...rules here...
</rules>
```

The `label` attribute on the opening tag serves as a section-level instruction:
"these are hard gates, this is their priority, missing = stop"

### Technique 4: Cross-Reference Instead of Duplicate

When the same concept appears in multiple rules, DON'T repeat it.
Use a cross-reference label.

```
# BAD: health-check mentioned in 3 places
GATE-5: ...check health-check.py...
MOAT: ...must check health-check.py...
SCOPE: ...verify health-check.py exists...

# GOOD: single source of truth + cross-reference
GATE-5 驗收:
  checks:
    新增API → 確認health-check.py覆蓋

MOAT:
  new-api: 必確認health-check.py覆蓋(GATE-5)    ← cross-ref, not duplicate
```

### Technique 5: The "What Not Why" Principle

Delete ALL text that exists to explain WHY a rule exists.
AI needs WHAT to do, not WHY.

```
# DELETE these human explanations:
(防搞混)                     → motivation
(不是大爆破,是每次順手一點)    → metaphor
(想清楚100倍後才做現在的)     → backstory
(因為用戶是非工程師)          → justification

# KEEP only the actionable instruction:
action: first-sentence="你要我做的是___"
refactor: 同區塊連續第3次修改 → extract
```

Every deleted explanation saves tokens AND removes noise that could confuse the model
about what it should actually DO.

---

## Two-Stage Workflow

### Stage 1: PREVIEW — Measure, Don't Touch

```bash
echo "=== Current Token Burn ==="
claude_md=$(wc -c < ~/.claude/CLAUDE.md 2>/dev/null || echo 0)
rules=$(cat ~/.claude/rules/*.md 2>/dev/null | wc -c || echo 0)
total=$((claude_md + rules))
tokens=$((total / 4))
echo "CLAUDE.md:     $claude_md bytes"
echo "rules/*.md:    $rules bytes"
echo "Total:         $total bytes ≈ $tokens tokens/turn"
echo "50-turn session: ≈ $((tokens * 50)) tokens on instructions alone"
```

Then: Read all auto-loaded files. Identify redundancy, prose overhead, and duplicate rules.

**Ask user before proceeding: "Want to distill?"**

### Stage 2: DISTILL — Convert with Safety Net

1. **Backup**: `cp ~/.claude/CLAUDE.md ~/.claude/CLAUDE.md.bak-pre-distill`
2. **Phase 1-5**: Run the full conversion process above
3. **Phase 6**: Run multi-model test (minimum 2 models, 8 questions)
4. **Report**: Show before/after scores

```
=== AI.MD Conversion Complete ===

Before: {old} bytes ({old_score} compliance)
After:  {new} bytes ({new_score} compliance)
Saved:  {percent}% bytes, +{delta} compliance points

Backup: ~/.claude/CLAUDE.md.bak-pre-distill
Restore: cp ~/.claude/CLAUDE.md.bak-pre-distill ~/.claude/CLAUDE.md
```

---

## AI-Native Template

```xml
# PROJECT-NAME | lang:xx | for-AI-parsing | optimize=results-over-format

<user>
identity, tone, signals, decision-style (key: value pairs)
</user>

<gates label="硬性閘門 | 優先序: gates>rules>rhythm | 缺一項=STOP">

GATE-1 name:
  trigger: ...
  action: ...
  exception: ...
  yields-to: ...

GATE-2 name:
  trigger: ...
  action: ...
  policy: ...

</gates>

<rules>

RULE-NAME:
  core: ...
  banned: ...
  hear-X: ... → action
  violation: ...

</rules>

<rhythm>
workflow patterns as key: value pairs
</rhythm>

<conn>
connection strings (keep exact — NEVER compress facts/credentials/URLs)
</conn>

<ref label="on-demand Read only">
file-path → purpose
</ref>

<learn>
how system evolves over time
</learn>
```

---

## Anti-Patterns

| Don't | Do Instead | Why |
|-------|------------|-----|
| Human prose in CLAUDE.md | Structured labels | Prose requires inference; labels are direct |
| Multiple rules on one line | One concept per line | Attention splits across dense lines |
| Parenthetical explanations | Remove them | AI needs "what" not "why" |
| Same rule in 3 places | Single source + cross-ref | Duplicates can diverge and confuse |
| 20+ flat rules | 5-7 domains with sub-items | Hierarchy helps model organize behavior |
| Compress without testing | Validate with 2+ models | What works for Claude might fail for GPT |
| Assume format doesn't matter | Test it — it does | Same content, different format = different compliance |
| Chinese-only labels | English labels + native output | English labels are more universal across models |
| Flat rule list | State machine with priorities | Clear execution order prevents missed rules |

---

## Real-World Results

Tested 2026-03, washinmura.jp CLAUDE.md, 5 rounds, 4 models:

| Round | Change | Codex (GPT-5.3) | Gemini 2.5 Pro | Claude Opus 4.6 |
|-------|--------|-----------------|----------------|-----------------|
| R1 (baseline prose) | — | 8/8 | 7/8 | 8/8 |
| R2 (added rules) | +gates +examples | 7/8 | 6/8 | — |
| R3 (refined prose) | +exceptions +non-triggers | 6/8 | 6.5/8 | — |
| R4 (AI-native convert) | structured labels | **8/8** | **7/8** | **8/8** |

Key findings:
1. **More prose rules = worse compliance** (R1→R3: scores dropped as rules grew)
2. **Structured format = restored + exceeded** (R4: back to max despite more rules)
3. **Cross-model consistency**: Format that works for one model works for all (except Grok)
4. **Semantic anchoring**: The `new-api:` label fix was the single most impactful change

**The uncomfortable truth: Your beautiful, carefully-written CLAUDE.md
might be HURTING your AI's performance. Structure > Prose. Always.**

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: ai-ml
description: "AI and machine learning workflow covering LLM application development, RAG implementation, agent architecture, ML pipelines, and AI-powered features."
category: workflow-bundle
risk: safe
source: personal
date_added: "2026-02-27"
---

# AI/ML Workflow Bundle

## Overview

Comprehensive AI/ML workflow for building LLM applications, implementing RAG systems, creating AI agents, and developing machine learning pipelines. This bundle orchestrates skills for production AI development.

## When to Use This Workflow

Use this workflow when:
- Building LLM-powered applications
- Implementing RAG (Retrieval-Augmented Generation)
- Creating AI agents
- Developing ML pipelines
- Adding AI features to applications
- Setting up AI observability

## Workflow Phases

### Phase 1: AI Application Design

#### Skills to Invoke
- `ai-product` - AI product development
- `ai-engineer` - AI engineering
- `ai-agents-architect` - Agent architecture
- `llm-app-patterns` - LLM patterns

#### Actions
1. Define AI use cases
2. Choose appropriate models
3. Design system architecture
4. Plan data flows
5. Define success metrics

#### Copy-Paste Prompts
```
Use @ai-product to design AI-powered features
```

```
Use @ai-agents-architect to design multi-agent system
```

### Phase 2: LLM Integration

#### Skills to Invoke
- `llm-application-dev-ai-assistant` - AI assistant development
- `llm-application-dev-langchain-agent` - LangChain agents
- `llm-application-dev-prompt-optimize` - Prompt engineering
- `gemini-api-dev` - Gemini API

#### Actions
1. Select LLM provider
2. Set up API access
3. Implement prompt templates
4. Configure model parameters
5. Add streaming support
6. Implement error handling

#### Copy-Paste Prompts
```
Use @llm-application-dev-ai-assistant to build conversational AI
```

```
Use @llm-application-dev-langchain-agent to create LangChain agents
```

```
Use @llm-application-dev-prompt-optimize to optimize prompts
```

### Phase 3: RAG Implementation

#### Skills to Invoke
- `rag-engineer` - RAG engineering
- `rag-implementation` - RAG implementation
- `embedding-strategies` - Embedding selection
- `vector-database-engineer` - Vector databases
- `similarity-search-patterns` - Similarity search
- `hybrid-search-implementation` - Hybrid search

#### Actions
1. Design data pipeline
2. Choose embedding model
3. Set up vector database
4. Implement chunking strategy
5. Configure retrieval
6. Add reranking
7. Implement caching

#### Copy-Paste Prompts
```
Use @rag-engineer to design RAG pipeline
```

```
Use @vector-database-engineer to set up vector search
```

```
Use @embedding-strategies to select optimal embeddings
```

### Phase 4: AI Agent Development

#### Skills to Invoke
- `autonomous-agents` - Autonomous agent patterns
- `autonomous-agent-patterns` - Agent patterns
- `crewai` - CrewAI framework
- `langgraph` - LangGraph
- `multi-agent-patterns` - Multi-agent systems
- `computer-use-agents` - Computer use agents

#### Actions
1. Design agent architecture
2. Define agent roles
3. Implement tool integration
4. Set up memory systems
5. Configure orchestration
6. Add human-in-the-loop

#### Copy-Paste Prompts
```
Use @crewai to build role-based multi-agent system
```

```
Use @langgraph to create stateful AI workflows
```

```
Use @autonomous-agents to design autonomous agent
```

### Phase 5: ML Pipeline Development

#### Skills to Invoke
- `ml-engineer` - ML engineering
- `mlops-engineer` - MLOps
- `machine-learning-ops-ml-pipeline` - ML pipelines
- `ml-pipeline-workflow` - ML workflows
- `data-engineer` - Data engineering

#### Actions
1. Design ML pipeline
2. Set up data processing
3. Implement model training
4. Configure evaluation
5. Set up model registry
6. Deploy models

#### Copy-Paste Prompts
```
Use @ml-engineer to build machine learning pipeline
```

```
Use @mlops-engineer to set up MLOps infrastructure
```

### Phase 6: AI Observability

#### Skills to Invoke
- `langfuse` - Langfuse observability
- `manifest` - Manifest telemetry
- `evaluation` - AI evaluation
- `llm-evaluation` - LLM evaluation

#### Actions
1. Set up tracing
2. Configure logging
3. Implement evaluation
4. Monitor performance
5. Track costs
6. Set up alerts

#### Copy-Paste Prompts
```
Use @langfuse to set up LLM observability
```

```
Use @evaluation to create evaluation framework
```

### Phase 7: AI Security

#### Skills to Invoke
- `prompt-engineering` - Prompt security
- `security-scanning-security-sast` - Security scanning

#### Actions
1. Implement input validation
2. Add output filtering
3. Configure rate limiting
4. Set up access controls
5. Monitor for abuse
6. Implement audit logging

## AI Development Checklist

### LLM Integration
- [ ] API keys secured
- [ ] Rate limiting configured
- [ ] Error handling implemented
- [ ] Streaming enabled
- [ ] Token usage tracked

### RAG System
- [ ] Data pipeline working
- [ ] Embeddings generated
- [ ] Vector search optimized
- [ ] Retrieval accuracy tested
- [ ] Caching implemented

### AI Agents
- [ ] Agent roles defined
- [ ] Tools integrated
- [ ] Memory working
- [ ] Orchestration tested
- [ ] Error handling robust

### Observability
- [ ] Tracing enabled
- [ ] Metrics collected
- [ ] Evaluation running
- [ ] Alerts configured
- [ ] Dashboards created

## Quality Gates

- [ ] All AI features tested
- [ ] Performance benchmarks met
- [ ] Security measures in place
- [ ] Observability configured
- [ ] Documentation complete

## Related Workflow Bundles

- `development` - Application development
- `database` - Data management
- `cloud-devops` - Infrastructure
- `testing-qa` - AI testing

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: ai-native-cli
description: "Design spec with 98 rules for building CLI tools that AI agents can safely use. Covers structured JSON output, error handling, input contracts, safety guardrails, exit codes, and agent self-description."
risk: safe
source: https://github.com/ChaosRealmsAI/agent-cli-spec
date_added: "2026-03-15"
---

# Agent-Friendly CLI Spec v0.1

When building or modifying CLI tools, follow these rules to make them safe and
reliable for AI agents to use.

## Overview

A comprehensive design specification for building AI-native CLI tools. It defines
98 rules across three certification levels (Agent-Friendly, Agent-Ready, Agent-Native)
with prioritized requirements (P0/P1/P2). The spec covers structured JSON output,
error handling, input contracts, safety guardrails, exit codes, self-description,
and a feedback loop via a built-in issue system.

## When to Use This Skill

- Use when building a new CLI tool that AI agents will invoke
- Use when retrofitting an existing CLI to be agent-friendly
- Use when designing command-line interfaces for automation pipelines
- Use when auditing a CLI tool's compliance with agent-safety standards

## Core Philosophy

1. **Agent-first** -- default output is JSON; human-friendly is opt-in via `--human`
2. **Agent is untrusted** -- validate all input at the same level as a public API
3. **Fail-Closed** -- when validation logic itself errors, deny by default
4. **Verifiable** -- every rule is written so it can be automatically checked

## Layer Model

This spec uses two orthogonal axes:

- **Layer** answers rollout scope: `core`, `recommended`, `ecosystem`
- **Priority** answers severity: `P0`, `P1`, `P2`

Use layers for migration and certification:

- **core** -- execution contract: JSON, errors, exit codes, stdout/stderr, safety
- **recommended** -- better machine UX: self-description, explicit modes, richer schemas
- **ecosystem** -- agent-native integration: `agent/`, `skills`, `issue`, inline context

Certification maps to layers:

- **Agent-Friendly** -- all `core` rules pass
- **Agent-Ready** -- all `core` + `recommended` rules pass
- **Agent-Native** -- all layers pass

## How It Works

### Step 1: Output Mode

Default is agent mode (JSON). Explicit flags to switch:

```bash
$ mycli list              # default = JSON output (agent mode)
$ mycli list --human      # human-friendly: colored, tables, formatted
$ mycli list --agent      # explicit agent mode (override config if needed)
```

- **Default (no flag)** -- JSON to stdout. Agent never needs to add a flag.
- **--human** -- human-friendly format (colors, tables, progress bars)
- **--agent** -- explicit JSON mode (useful when env/config overrides default)

### Step 2: agent/ Directory Convention

Every CLI tool MUST have an `agent/` directory at its project root. This is the
tool's identity and behavior contract for AI agents.

```
agent/
  brief.md          # One paragraph: who am I, what can I do
  rules/            # Behavior constraints (auto-registered)
    trigger.md      # When should an agent use this tool
    workflow.md     # Step-by-step usage flow
    writeback.md    # How to write feedback back
  skills/           # Extended capabilities (auto-registered)
    getting-started.md
```

### Step 3: Four Levels of Self-Description

1. **--brief** (business card, injected into agent config)
2. **Every Command Response** (always-on context: data + rules + skills + issue)
3. **--help** (full self-description: brief + commands + rules + skills + issue)
4. **skills \<name\>** (on-demand deep dive into a specific skill)

## Certification Requirements

Each level includes all rules from the previous level.
Priority tag `[P0]`=agent breaks without it, `[P1]`=agent works but poorly, `[P2]`=nice to have.

### Level 1: Agent-Friendly (core -- 20 rules)

Goal: CLI is a stable, callable API. Agent can invoke, parse, and handle errors.

**Output** -- default is JSON, stable schema
- `[P0]` O1: Default output is JSON. No `--json` flag needed
- `[P0]` O2: JSON MUST pass `jq .` validation
- `[P0]` O3: JSON schema MUST NOT change within same version

**Error** -- structured, to stderr, never interactive
- `[P0]` E1: Errors -> `{"error":true, "code":"...", "message":"...", "suggestion":"..."}` to stderr
- `[P0]` E4: Error has machine-readable `code` (e.g. `MISSING_REQUIRED`)
- `[P0]` E5: Error has human-readable `message`
- `[P0]` E7: On error, NEVER enter interactive mode -- exit immediately
- `[P0]` E8: Error codes are API contracts -- MUST NOT rename across versions

**Exit Code** -- predictable failure signals
- `[P0]` X3: Parameter/usage errors MUST exit 2
- `[P0]` X9: Failures MUST exit non-zero -- never exit 0 then report error in stdout

**Composability** -- clean pipe semantics
- `[P0]` C1: stdout is for data ONLY
- `[P0]` C2: logs, progress, warnings go to stderr ONLY

**Input** -- fail fast on bad input
- `[P1]` I4: Missing required param -> structured error, never interactive prompt
- `[P1]` I5: Type mismatch -> exit 2 + structured error

**Safety** -- protect against agent mistakes
- `[P1]` S1: Destructive ops require `--yes` confirmation
- `[P1]` S4: Reject `../../` path traversal, control chars

**Guardrails** -- runtime input protection
- `[P1]` G1: Unknown flags rejected with exit 2
- `[P1]` G2: Detect API key / token patterns in args, reject execution
- `[P1]` G3: Reject sensitive file paths (*.env, *.key, *.pem)
- `[P1]` G8: Reject shell metacharacters in arguments (; | && $())

### Level 2: Agent-Ready (+ recommended -- 59 rules)

Goal: CLI is self-describing, well-named, and pipe-friendly. Agent discovers capabilities and chains commands without trial and error.

**Self-Description** -- agent discovers what CLI can do
- `[P1]` D1: `--help` outputs structured JSON with `commands[]`
- `[P1]` D3: Schema has required fields (help, commands)
- `[P1]` D4: All parameters have type declarations
- `[P1]` D7: Parameters annotated as required/optional
- `[P1]` D9: Every command has a description
- `[P1]` D11: `--help` outputs JSON with help, rules, skills, commands
- `[P1]` D15: `--brief` outputs `agent/brief.md` content
- `[P1]` D16: Default JSON (agent mode), `--human` for human-friendly
- `[P2]` D2/D5/D6/D8/D10: per-command help, enums, defaults, output schema, version

**Input** -- unambiguous calling convention
- `[P1]` I1: All flags use `--long-name` format
- `[P1]` I2: No positional argument ambiguity
- `[P2]` I3/I6/I7: --json-input, boolean --no-X, array params

**Error**
- `[P1]` E6: Error includes `suggestion` field
- `[P2]` E2/E3: errors to stderr, error JSON valid

**Safety**
- `[P1]` S8: `--sanitize` flag for external input
- `[P2]` S2/S3/S5/S6/S7: default deny, --dry-run, no auto-update, destructive marking

**Exit Code**
- `[P1]` X1: 0 = success
- `[P2]` X2/X4-X8: 1=general, 10=auth, 11=permission, 20=not-found, 30=conflict

**Composability**
- `[P1]` C6: No interactive prompts in pipe mode
- `[P2]` C3/C4/C5/C7: pipe-friendly, --quiet, pipe chain, idempotency

**Naming** -- predictable flag conventions
- `[P1]` N4: Reserved flags (--agent, --human, --brief, --help, --version, --yes, --dry-run, --quiet, --fields)
- `[P2]` N1/N2/N3/N5/N6: consistent naming, kebab-case, max 3 levels, --version semver

**Guardrails**
- `[P1]` I8/I9: no implicit state, non-interactive auth
- `[P1]` G6/G9: precondition checks, fail-closed
- `[P2]` G4/G5/G7: permission levels, PII redaction, batch limits

#### Reserved Flags

| Flag | Semantics | Notes |
|------|-----------|-------|
| `--agent` | JSON output (default) | Explicit override |
| `--human` | Human-friendly output | Colors, tables, formatted |
| `--brief` | One-paragraph identity | For sync into agent config |
| `--help` | Full self-description JSON | Brief + commands + rules + skills + issue |
| `--version` | Semver version string | |
| `--yes` | Confirm destructive ops | Required for delete/destroy |
| `--dry-run` | Preview without executing | |
| `--quiet` | Suppress stderr output | |
| `--fields` | Filter output fields | Save tokens |

### Level 3: Agent-Native (+ ecosystem -- 19 rules)

Goal: CLI has identity, behavior contract, skill system, and feedback loop. Agent can learn the tool, extend its use, and report problems -- full closed-loop collaboration.

**Agent Directory** -- tool identity and behavior contract
- `[P1]` D12: `agent/brief.md` exists
- `[P1]` D13: `agent/rules/` has trigger.md, workflow.md, writeback.md
- `[P1]` D17: agent/rules/*.md have YAML frontmatter (name, description)
- `[P1]` D18: agent/skills/*.md have YAML frontmatter (name, description)
- `[P2]` D14: `agent/skills/` directory + `skills` subcommand

**Response Structure** -- inline context on every call
- `[P1]` R1: Every response includes `rules[]` (full content from agent/rules/)
- `[P1]` R2: Every response includes `skills[]` (name + description + command)
- `[P1]` R3: Every response includes `issue` (feedback guide)

**Meta** -- project-level integration
- `[P2]` M1: AGENTS.md at project root
- `[P2]` M2: Optional MCP tool schema export
- `[P2]` M3: CHANGELOG.md marks breaking changes

**Feedback** -- built-in issue system
- `[P2]` F1: `issue` subcommand (create/list/show)
- `[P2]` F2: Structured submission with version/context/exit_code
- `[P2]` F3: Categories: bug / requirement / suggestion / bad-output
- `[P2]` F4: Issues stored locally, no external service dependency
- `[P2]` F5: `issue list` / `issue show <id>` queryable
- `[P2]` F6: Issues have status tracking (open/in-progress/resolved/closed)
- `[P2]` F7: Issue JSON has all required fields (id, type, status, message, created_at, updated_at)
- `[P2]` F8: All issues have status field

## Examples

### Example 1: JSON Output (Agent Mode)

```bash
$ mycli list
{"result": [{"id": 1, "title": "Buy milk", "status": "todo"}], "rules": [...], "skills": [...], "issue": "..."}
```

### Example 2: Structured Error

```json
{
  "error": true,
  "code": "AUTH_EXPIRED",
  "message": "Access token expired 2 hours ago",
  "suggestion": "Run 'mycli auth refresh' to get a new token"
}
```

### Example 3: Exit Code Table

```
0   success         10  auth failed       20  resource not found
1   general error   11  permission denied 30  conflict/precondition
2   param/usage error
```

## Quick Implementation Checklist

Implement by layer -- each phase gets you the next certification level.

**Phase 1: Agent-Friendly (core)**
1. Default output is JSON -- no `--json` flag needed
2. Error handler: `{ error, code, message, suggestion }` to stderr
3. Exit codes: 0 success, 2 param error, 1 general
4. stdout = data only, stderr = logs only
5. Missing param -> structured error (never interactive)
6. `--yes` guard on destructive operations
7. Guardrails: reject secrets, path traversal, shell metacharacters

**Phase 2: Agent-Ready (+ recommended)**
8. `--help` returns structured JSON (help, commands[], rules[], skills[])
9. `--brief` reads and outputs `agent/brief.md` content
10. `--human` flag switches to human-friendly format
11. Reserved flags: --agent, --version, --dry-run, --quiet, --fields
12. Exit codes: 20 not found, 30 conflict, 10 auth, 11 permission

**Phase 3: Agent-Native (+ ecosystem)**
13. Create `agent/` directory: `brief.md`, `rules/trigger.md`, `rules/workflow.md`, `rules/writeback.md`
14. Every command response appends: rules[] + skills[] + issue
15. `skills` subcommand: list all / show one with full content
16. `issue` subcommand for feedback (create/list/show/close/transition)
17. AGENTS.md at project root

## Best Practices

- Do: Default to JSON output so agents never need to add flags
- Do: Include `suggestion` field in every error response
- Do: Use the three-level certification model for incremental adoption
- Do: Keep `agent/brief.md` to one paragraph for token efficiency
- Don't: Enter interactive mode on errors -- always exit immediately
- Don't: Change JSON schema or error codes within the same version
- Don't: Put logs or progress info on stdout -- use stderr only
- Don't: Accept unknown flags silently -- reject with exit code 2

## Common Pitfalls

- **Problem:** CLI outputs human-readable text by default, breaking agent parsing
  **Solution:** Make JSON the default output format; add `--human` flag for human-friendly mode

- **Problem:** Errors reported in stdout with exit code 0
  **Solution:** Always exit non-zero on failure and write structured error JSON to stderr

- **Problem:** CLI prompts for missing input interactively
  **Solution:** Return structured error with suggestion field and exit immediately

## Related Skills

- `@cli-best-practices` - General CLI design patterns (this skill focuses specifically on AI agent compatibility)

## Additional Resources

- [Agent CLI Spec Repository](https://github.com/ChaosRealmsAI/agent-cli-spec)

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: ai-native-ui
description: Web and App implementation guide for AI Native UI. Trigger when user wants conversational interfaces, adaptive layouts, and generative AI aesthetics.
date_added: "2026-06-17"
risk: safe
source: self
source_type: self
---

# AI Native UI

> "Fluid, adaptive, and conversational. The interface morphs to serve the content."

## When to Use
Use this sub-style when the user's request matches the aesthetic described above. This is a child reference of the `design-it` skill and is not meant to be triggered directly.

## Core Principles
1. **Conversational First**: The chat input or voice prompt is the primary navigation method, not a sidebar of links.
2. **Generative States**: Loading states aren't spinners; they are shimmering text, morphing gradients, or skeletal layouts that resolve smoothly into content.
3. **Adaptive Components**: Cards and blocks size themselves dynamically based on the generated content length.

## Visual DNA
- **Colors**: **Minimalist Slate** combined with **Electric Indigo** or **Neon Pulse** gradients for the AI elements. The background is clean (white or dark grey), while the AI "presence" is represented by a shifting, iridescent gradient.
- **Typography**: Highly readable system fonts (`Inter`, `SF Pro`).
- **Styling**: Subtle glowing borders to indicate AI generation in progress.

## Web Implementation
- **CSS Example**:
```css
body {
  background-color: #FAFAFA;
  color: #1A1A1A;
  font-family: 'Inter', sans-serif;
}

/* The AI Chat Input */
.ai-prompt-box {
  background: #ffffff;
  border-radius: 24px;
  padding: 16px 24px;
  box-shadow: 0 8px 30px rgba(0,0,0,0.05);
  border: 1px solid transparent;

  /* AI Glow Border */
  background-clip: padding-box, border-box;
  background-origin: padding-box, border-box;
  background-image:
    linear-gradient(#ffffff, #ffffff),
    linear-gradient(90deg, #8A2387, #E94057, #F27121);

  transition: all 0.3s ease;
}

.ai-prompt-box:focus-within {
  box-shadow: 0 12px 40px rgba(233, 64, 87, 0.15);
}

/* Generative Shimmer Text */
.ai-generating-text {
  background: linear-gradient(90deg, #aaa 0%, #333 50%, #aaa 100%);
  background-size: 200% auto;
  color: transparent;
  -webkit-background-clip: text;
  animation: shine 1.5s linear infinite;
}

@keyframes shine {
  to { background-position: 200% center; }
}
```

## App Implementation

### SwiftUI
```swift
struct AINativeInput: View {
    @State private var isGenerating = true
    @State private var gradientOffset = 0.0

    var body: some View {
        VStack {
            // Generative Text Shimmer
            if isGenerating {
                Text("Synthesizing response...")
                    .font(.headline)
                    .foregroundStyle(
                        LinearGradient(
                            colors: [.gray.opacity(0.3), .gray, .gray.opacity(0.3)],
                            startPoint: UnitPoint(x: gradientOffset - 1, y: 0),
                            endPoint: UnitPoint(x: gradientOffset + 1, y: 0)
                        )
                    )
                    .onAppear {
                        withAnimation(.linear(duration: 1.5).repeatForever(autoreverses: false)) {
                            gradientOffset = 1.0
                        }
                    }
            }

            // AI Input Box
            HStack {
                TextField("Ask anything...", text: .constant(""))
                Image(systemName: "sparkles")
                    .foregroundColor(.purple)
            }
            .padding()
            .background(Color.white)
            .cornerRadius(24)
            .overlay(
                RoundedRectangle(cornerRadius: 24)
                    .stroke(
                        LinearGradient(colors: [.purple, .pink, .orange], startPoint: .topLeading, endPoint: .bottomTrailing),
                        lineWidth: 2
                    )
            )
            .shadow(color: .pink.opacity(0.15), radius: 20)
        }
        .padding()
    }
}
```
- A shifting `LinearGradient` mask over text creates a beautiful "thinking" state.
- Use a gradient `.stroke` on a `RoundedRectangle` overlay to create the signature AI glowing border around input fields.

### Flutter
```dart
import 'package:shimmer/shimmer.dart';

class AINativeInput extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // Generative Shimmer
          Shimmer.fromColors(
            baseColor: Colors.grey[300]!,
            highlightColor: Colors.grey[600]!,
            child: const Text('Synthesizing response...',
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
          ),
          const SizedBox(height: 16),
          // AI Input Box
          Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(24),
              boxShadow: [
                BoxShadow(color: Colors.pink.withOpacity(0.15), blurRadius: 20),
              ],
            ),
            child: Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(24),
                // Gradient border simulation
                gradient: const LinearGradient(
                  colors: [Colors.purple, Colors.pink, Colors.orange],
                ),
              ),
              padding: const EdgeInsets.all(2), // Border width
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(22),
                ),
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                child: Row(
                  children: const [
                    Expanded(
                      child: TextField(
                        decoration: InputDecoration(
                          hintText: 'Ask anything...',
                          border: InputBorder.none,
                        ),
                      ),
                    ),
                    Icon(Icons.auto_awesome, color: Colors.purple),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
```
- The `shimmer` package is the absolute standard for AI loading states in Flutter.
- Gradient borders natively don't exist on `BoxDecoration`; simulate them by nesting containers with a gradient background and a solid white inner container.

### React Native
```jsx
// Requires react-native-linear-gradient and react-native-shimmer-placeholder
import LinearGradient from 'react-native-linear-gradient';
import { createShimmerPlaceholder } from 'react-native-shimmer-placeholder';

const ShimmerPlaceHolder = createShimmerPlaceholder(LinearGradient);

const AINativeInput = () => {
  return (
    <View style={{ padding: 16 }}>
      {/* Generative Shimmer */}
      <ShimmerPlaceHolder
        style={{ width: 200, height: 20, borderRadius: 10, marginBottom: 16 }}
        shimmerColors={['#ebebeb', '#c5c5c5', '#ebebeb']}
      />

      {/* AI Input Box with Gradient Border */}
      <LinearGradient
        colors={['#8A2387', '#E94057', '#F27121']}
        style={{ borderRadius: 24, padding: 2, shadowColor: '#E94057', shadowRadius: 20, shadowOpacity: 0.2 }}
      >
        <View style={{
          backgroundColor: '#FFF',
          borderRadius: 22,
          flexDirection: 'row',
          alignItems: 'center',
          paddingHorizontal: 16,
          height: 50
        }}>
          <TextInput
            placeholder="Ask anything..."
            style={{ flex: 1, fontSize: 16 }}
          />
          <Text style={{ fontSize: 20 }}>✨</Text>
        </View>
      </LinearGradient>
    </View>
  );
};
```
- `react-native-shimmer-placeholder` is the best way to handle the morphing skeleton states.
- Like Flutter, React Native doesn't have native gradient borders. Wrap the input in a `LinearGradient` view with `padding: 2` to create the stroke.

### Jetpack Compose
```kotlin
@Composable
fun AINativeInput() {
    val infiniteTransition = rememberInfiniteTransition()
    val gradientOffset by infiniteTransition.animateFloat(
        initialValue = 0f,
        targetValue = 1000f,
        animationSpec = infiniteRepeatable(
            animation = tween(1500, easing = LinearEasing),
            repeatMode = RepeatMode.Restart
        )
    )

    Column(modifier = Modifier.padding(16.dp)) {
        // Generative Shimmer Text
        val shimmerBrush = Brush.linearGradient(
            colors = listOf(Color.LightGray, Color.Gray, Color.LightGray),
            start = Offset(gradientOffset - 500f, 0f),
            end = Offset(gradientOffset, 0f)
        )
        Text("Synthesizing response...", style = TextStyle(brush = shimmerBrush, fontWeight = FontWeight.Bold))

        Spacer(Modifier.height(16.dp))

        // AI Input Box
        val borderBrush = Brush.linearGradient(listOf(Color(0xFF8A2387), Color(0xFFE94057), Color(0xFFF27121)))

        Row(
            modifier = Modifier
                .shadow(20.dp, RoundedCornerShape(24.dp), ambientColor = Color(0xFFE94057), spotColor = Color(0xFFE94057))
                .background(Color.White, RoundedCornerShape(24.dp))
                .border(2.dp, borderBrush, RoundedCornerShape(24.dp))
                .padding(horizontal = 16.dp, vertical = 12.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            BasicTextField(
                value = "",
                onValueChange = {},
                modifier = Modifier.weight(1f),
                decorationBox = { innerTextField -> Text("Ask anything...", color = Color.Gray) }
            )
            Icon(Icons.Default.Star, contentDescription = null, tint = Color(0xFF8A2387))
        }
    }
}
```
- Compose allows passing a `Brush` directly into the `TextStyle`, making shimmering text incredibly easy without third-party libraries.
- Compose's `Modifier.border()` natively accepts a `Brush`, making gradient borders a one-liner.

## Do's and Don'ts
- **DO**: Use a distinct, vibrant gradient to represent the AI "agent", contrasting with a very plain, clean background.
- **DON'T**: Use complex navigation headers. The user should navigate by asking the AI, not by clicking deep menus.

## Limitations
- This is a styling reference and does not replace environment-specific validation, accessibility testing, or expert review.
- Ensure appropriate contrast ratios and responsive behaviors are verified separately.