---
name: audit-context-building
description: Enables ultra-granular, line-by-line code analysis to build deep architectural context before vulnerability or bug finding.
risk: safe
source: community
---

# Deep Context Builder Skill (Ultra-Granular Pure Context Mode)

## 1. Purpose

This skill governs **how Claude thinks** during the context-building phase of an audit.

When active, Claude will:
- Perform **line-by-line / block-by-block** code analysis by default.
- Apply **First Principles**, **5 Whys**, and **5 Hows** at micro scale.
- Continuously link insights → functions → modules → entire system.
- Maintain a stable, explicit mental model that evolves with new evidence.
- Identify invariants, assumptions, flows, and reasoning hazards.

This skill defines a structured analysis format (see Example: Function Micro-Analysis below) and runs **before** the vulnerability-hunting phase.

---

## When to Use
Use when:
- Deep comprehension is needed before bug or vulnerability discovery.
- You want bottom-up understanding instead of high-level guessing.
- Reducing hallucinations, contradictions, and context loss is critical.
- Preparing for security auditing, architecture review, or threat modeling.

Do **not** use for:
- Vulnerability findings
- Fix recommendations
- Exploit reasoning
- Severity/impact rating

---

## 2. How This Skill Behaves

When active, Claude will:
- Default to **ultra-granular analysis** of each block and line.
- Apply micro-level First Principles, 5 Whys, and 5 Hows.
- Build and refine a persistent global mental model.
- Update earlier assumptions when contradicted ("Earlier I thought X; now Y.").
- Periodically anchor summaries to maintain stable context.
- Avoid speculation; express uncertainty explicitly when needed.

Goal: **deep, accurate understanding**, not conclusions.

---

## Rationalizations (Do Not Skip)

| Rationalization | Why It's Wrong | Required Action |
|-----------------|----------------|-----------------|
| "I get the gist" | Gist-level understanding misses edge cases | Line-by-line analysis required |
| "This function is simple" | Simple functions compose into complex bugs | Apply 5 Whys anyway |
| "I'll remember this invariant" | You won't. Context degrades. | Write it down explicitly |
| "External call is probably fine" | External = adversarial until proven otherwise | Jump into code or model as hostile |
| "I can skip this helper" | Helpers contain assumptions that propagate | Trace the full call chain |
| "This is taking too long" | Rushed context = hallucinated vulnerabilities later | Slow is fast |

---

## 3. Phase 1 — Initial Orientation (Bottom-Up Scan)

Before deep analysis, Claude performs a minimal mapping:

1. Identify major modules/files/contracts.
2. Note obvious public/external entrypoints.
3. Identify likely actors (users, owners, relayers, oracles, other contracts).
4. Identify important storage variables, dicts, state structs, or cells.
5. Build a preliminary structure without assuming behavior.

This establishes anchors for detailed analysis.

---

## 4. Phase 2 — Ultra-Granular Function Analysis (Default Mode)

Every non-trivial function receives full micro analysis.

### 5.1 Per-Function Microstructure Checklist

For each function:

1. **Purpose**
   - Why the function exists and its role in the system.

2. **Inputs & Assumptions**
   - Parameters and implicit inputs (state, sender, env).
   - Preconditions and constraints.

3. **Outputs & Effects**
   - Return values.
   - State/storage writes.
   - Events/messages.
   - External interactions.

4. **Block-by-Block / Line-by-Line Analysis**
   For each logical block:
   - What it does.
   - Why it appears here (ordering logic).
   - What assumptions it relies on.
   - What invariants it establishes or maintains.
   - What later logic depends on it.

   Apply per-block:
   - **First Principles**
   - **5 Whys**
   - **5 Hows**

---

### 5.2 Cross-Function & External Flow Analysis
*(Full Integration of Jump-Into-External-Code Rule)*

When encountering calls, **continue the same micro-first analysis across boundaries.**

#### Internal Calls
- Jump into the callee immediately.
- Perform block-by-block analysis of relevant code.
- Track flow of data, assumptions, and invariants:
  caller → callee → return → caller.
- Note if callee logic behaves differently in this specific call context.

#### External Calls — Two Cases

**Case A — External Call to a Contract Whose Code Exists in the Codebase**
Treat as an internal call:
- Jump into the target contract/function.
- Continue block-by-block micro-analysis.
- Propagate invariants and assumptions seamlessly.
- Consider edge cases based on the *actual* code, not a black-box guess.

**Case B — External Call Without Available Code (True External / Black Box)**
Analyze as adversarial:
- Describe payload/value/gas or parameters sent.
- Identify assumptions about the target.
- Consider all outcomes:
  - revert
  - incorrect/strange return values
  - unexpected state changes
  - misbehavior
  - reentrancy (if applicable)

#### Continuity Rule
Treat the entire call chain as **one continuous execution flow**.
Never reset context.
All invariants, assumptions, and data dependencies must propagate across calls.

---

### 5.3 Complete Analysis Example

See FUNCTION_MICRO_ANALYSIS_EXAMPLE.md for a complete walkthrough demonstrating:
- Full micro-analysis of a DEX swap function
- Application of First Principles, 5 Whys, and 5 Hows
- Block-by-block analysis with invariants and assumptions
- Cross-function dependency mapping
- Risk analysis for external interactions

This example demonstrates the level of depth and structure required for all analyzed functions.

---

### 5.4 Output Requirements

When performing ultra-granular analysis, Claude MUST structure output following the format defined in OUTPUT_REQUIREMENTS.md.

Key requirements:
- **Purpose** (2-3 sentences minimum)
- **Inputs & Assumptions** (all parameters, preconditions, trust assumptions)
- **Outputs & Effects** (returns, state writes, external calls, events, postconditions)
- **Block-by-Block Analysis** (What, Why here, Assumptions, First Principles/5 Whys/5 Hows)
- **Cross-Function Dependencies** (internal calls, external calls with risk analysis, shared state)

Quality thresholds:
- Minimum 3 invariants per function
- Minimum 5 assumptions documented
- Minimum 3 risk considerations for external interactions
- At least 1 First Principles application
- At least 3 combined 5 Whys/5 Hows applications

---

### 5.5 Completeness Checklist

Before concluding micro-analysis of a function, verify against the COMPLETENESS_CHECKLIST.md:

- **Structural Completeness**: All required sections present (Purpose, Inputs, Outputs, Block-by-Block, Dependencies)
- **Content Depth**: Minimum thresholds met (invariants, assumptions, risk analysis, First Principles)
- **Continuity & Integration**: Cross-references, propagated assumptions, invariant couplings
- **Anti-Hallucination**: Line number citations, no vague statements, evidence-based claims

Analysis is complete when all checklist items are satisfied and no unresolved "unclear" items remain.

---

## 5. Phase 3 — Global System Understanding

After sufficient micro-analysis:

1. **State & Invariant Reconstruction**
   - Map reads/writes of each state variable.
   - Derive multi-function and multi-module invariants.

2. **Workflow Reconstruction**
   - Identify end-to-end flows (deposit, withdraw, lifecycle, upgrades).
   - Track how state transforms across these flows.
   - Record assumptions that persist across steps.

3. **Trust Boundary Mapping**
   - Actor → entrypoint → behavior.
   - Identify untrusted input paths.
   - Privilege changes and implicit role expectations.

4. **Complexity & Fragility Clustering**
   - Functions with many assumptions.
   - High branching logic.
   - Multi-step dependencies.
   - Coupled state changes across modules.

These clusters help guide the vulnerability-hunting phase.

---

## 6. Stability & Consistency Rules
*(Anti-Hallucination, Anti-Contradiction)*

Claude must:

- **Never reshape evidence to fit earlier assumptions.**
  When contradicted:
  - Update the model.
  - State the correction explicitly.

- **Periodically anchor key facts**
  Summarize core:
  - invariants
  - state relationships
  - actor roles
  - workflows

- **Avoid vague guesses**
  Use:
  - "Unclear; need to inspect X."
  instead of:
  - "It probably…"

- **Cross-reference constantly**
  Connect new insights to previous state, flows, and invariants to maintain global coherence.

---

## 7. Subagent Usage

Claude may spawn subagents for:
- Dense or complex functions.
- Long data-flow or control-flow chains.
- Cryptographic / mathematical logic.
- Complex state machines.
- Multi-module workflow reconstruction.

Use the **`function-analyzer`** agent for per-function deep analysis.
It follows the full microstructure checklist, cross-function flow
rules, and quality thresholds defined in this skill, and enforces
the pure-context-building constraint.

Subagents must:
- Follow the same micro-first rules.
- Return summaries that Claude integrates into its global model.

---

## 8. Relationship to Other Phases

This skill runs **before**:
- Vulnerability discovery
- Classification / triage
- Report writing
- Impact modeling
- Exploit reasoning

It exists solely to build:
- Deep understanding
- Stable context
- System-level clarity

---

## 9. Non-Goals

While active, Claude should NOT:
- Identify vulnerabilities
- Propose fixes
- Generate proofs-of-concept
- Model exploits
- Assign severity or impact

This is **pure context building** only.

## 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: audit-skills
description: "Expert security auditor for AI Skills and Bundles. Performs non-intrusive static analysis to identify malicious patterns, data leaks, system stability risks, and obfuscated payloads across Windows, macOS, Linux/Unix, and Mobile (Android/iOS)."
category: security
risk: safe
source: community
date_added: "2026-03-07"
author: MAIOStudio
tags: [security, audit, skills, bundles, cross-platform]
tools: [claude, gemini, gpt, llama, mistral, etc]
---

# Audit Skills (Premium Universal Security)

## Overview

Expert security auditor for AI Skills and Bundles. Performs non-intrusive static analysis to identify malicious patterns, data leaks, system stability risks, and obfuscated payloads across Windows, macOS, Linux/Unix, and Mobile (Android/iOS).
2-4 sentences is perfect.

## When to Use This Skill

- Use when you need to audit AI skills and bundles for security vulnerabilities
- Use when working with cross-platform security analysis
- Use when the user asks about verifying skill legitimacy or performing security reviews
- Use when scanning for mobile threats in AI skills

## How It Works

### Step 1: Static Analysis

Performs non-intrusive static analysis to identify malicious patterns, data leaks, system stability risks, and obfuscated payloads.

### Step 2: Platform-Specific Threat Detection

Analyzes code for platform-specific security issues across Windows, macOS, Linux/Unix, and Mobile (Android/iOS).

#### 1. Privilege, Ownership & Metadata Manipulation
- **Elevated Access**: `sudo`, `chown`, `chmod`, `TakeOwnership`, `icacls`, `Set-ExecutionPolicy`.
- **Metadata Tampering**: `touch -t`, `setfile` (macOS), `attrib` (Windows), `Set-ItemProperty`, `chflags`.
- **Risk**: Unauthorized access, masking activity, or making files immutable.

#### 2. File/Folder Locking & Resource Denial
- **Patterns**: `chmod 000`, `chattr +i` (immutable), `attrib +r +s +h`, `Deny` ACEs in `icacls`.
- **Global Actions**: Locking or hiding folders in `%USERPROFILE%`, `/Users/`, or `/etc/`.
- **Risk**: Denial of service or data locking.

#### 3. Script Execution & Batch Invocation
- **Legacy/Batch Windows**: `.bat`, `.cmd`, `cmd.exe /c`, `vbs`, `cscript`, `wscript`.
- **Unix Shell**: `.sh`, `.bash`, `.zsh`, `chmod +x` followed by execution.
- **PowerShell**: `.ps1`, `powershell -ExecutionPolicy Bypass -File ...`.
- **Hidden Flags**: `-WindowStyle Hidden`, `-w hidden`, `-noprofile`.

#### 4. Dangerous Install/Uninstall & System Changes
- **Windows**: `msiexec /qn`, `choco uninstall`, `reg delete`.
- **Linux/Unix**: `apt-get purge`, `yum remove`, `rm -rf /usr/bin/...`.
- **macOS**: `brew uninstall`, deleting from `/Applications`.
- **Risk**: Removing security software or creating unmonitored installation paths.

#### 5. Mobile Application & OS Security (Android/iOS)
- **Android Tools**: `adb shell`, `pm install`, `am start`, `apktool`, `dex2jar`, `keytool`.
- **Android Files**: Manipulation of `AndroidManifest.xml` (permissions), `classes.dex`, or `strings.xml`.
- **iOS Tools**: `xcodebuild`, `codesign`, `security find-identity`, `fastlane`, `xcrun`.
- **iOS Files**: Manipulation of `Info.plist`, `Entitlements.plist`, or `Provisioning Profiles`.
- **Mobile Patterns**: Jailbreak/Root detection bypasses, hardcoded API keys in mobile source, or sensitive permission requests (Camera, GPS, Contacts) in non-mobile skills.
- **Risk**: Malicious mobile package injection, credential theft from mobile builds, or device manipulation via ADB.

#### 6. Information Disclosure & Network Exfiltration
- **Patterns**: `curl`, `wget`, `Invoke-WebRequest`, `Invoke-RestMethod`, `scp`, `ftp`, `nc`, `socat`.
- **Sensible Data**: `.env`, `.ssh`, `cookies.sqlite`, `Keychains` (macOS), `Credentials` (Windows), `keystore` (Android).
- **Intranet**: Scanning internal IPs or mapping local services.

#### 7. Service, Process & Stability Manipulation
- **Windows**: `Stop-Service`, `taskkill /f`, `sc.exe delete`.
- **Unix/Mac**: `kill -9`, `pkill`, `systemctl disable/stop`, `launchctl unload`.
- **Low-level**: Direct disk access (`dd`), firmware/BIOS calls, kernel module management.

#### 8. Obfuscation & Persistence
- **Encoding**: `Base64`, `Hex`, `XOR` loops, `atob()`.
- **Persistence**: `reg add` (Run keys), `schtasks`, `crontab`, `launchctl` (macOS), `systemd` units.
- **Remote script piping**: network fetch commands that stream directly into a shell or PowerShell evaluator.

#### 9. Legitimacy & Scope (Universal)
- **Registry Alignment**: Cross-reference with `CATALOG.md`.
- **Structural Integrity**: Does it follow the standard repo layout?
- **Healthy Scope**: Does a "UI Design" skill need `adb shell` or `sudo`?

### Step 3: Reporting

Generates a security report with a score (0-10), platform target identification, flagged actions, threat analysis, and mitigation recommendations.

## Examples

### Example 1: Security Review

```markdown
"Perform a security audit on this skill bundle"
```

### Example 2: Cross-Platform Threat Analysis

```markdown
"Scan for mobile threats in this AI skill"
```

## Best Practices

- ✅ Perform non-intrusive analysis
- ✅ Check for privilege escalation patterns
- ✅ Look for information disclosure vulnerabilities
- ✅ Analyze cross-platform threats
- ❌ Don't execute potentially malicious code during audit
- ❌ Don't modify the code being audited
- ❌ Don't ignore mobile-specific security concerns

## Common Pitfalls

- **Problem:** Executing code during audit
  **Solution:** Stick to static analysis methods only

- **Problem:** Missing cross-platform threats
  **Solution:** Check for platform-specific security issues on all supported platforms

- **Problem:** Failing to detect obfuscated payloads
 **Solution:** Look for encoding patterns like Base64, Hex, XOR loops, and atob()

## Related Skills

- `@security-scanner` - Additional security scanning capabilities

## 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: auri-core
description: "Auri: assistente de voz inteligente (Alexa + Claude claude-opus-4-20250805). Visao do produto, persona Vitoria Neural, stack AWS, modelo Free/Pro/Business/Enterprise, roadmap 4 fases, GTM, north star WAC e analise competitiva."
risk: none
source: community
date_added: '2026-03-06'
author: renat
tags:
- voice-assistant
- product-vision
- alexa
- aws
tools:
- claude-code
- antigravity
- cursor
- gemini-cli
- codex-cli
---

# Auri - Core Product Skill

## Overview

Auri: assistente de voz inteligente (Alexa + Claude claude-opus-4-20250805). Visao do produto, persona Vitoria Neural, stack AWS, modelo Free/Pro/Business/Enterprise, roadmap 4 fases, GTM, north star WAC e analise competitiva.

## When to Use This Skill

- When you need specialized assistance with this domain

## Do Not Use This Skill When

- The task is unrelated to auri core
- A simpler, more specific tool can handle the request
- The user needs general-purpose assistance without domain expertise

## How It Works

| Atributo | Definicao |
|----------|-----------|
| Nome | Auri |
| Voz | Amazon Polly Vitoria Neural pt-BR |
| Tom | Caloroso, inteligente, direto |
| Personalidade | Curiosa, empatica, confiavel |
| Linguagem | Portugues brasileiro natural |
| Atitude | Proativa, mas nunca invasiva |

## Auri - Core Product Skill

>  A voz que pensa com voce.

Auri e um assistente de voz de nova geracao construido sobre Amazon Alexa + Claude claude-opus-4-20250805.
Enquanto a Alexa tradicional executa comandos, a Auri conduz conversas reais e raciocina sobre contexto.

---

## O Que E A Auri

A Auri e uma Alexa Skill avancada que substitui o motor de respostas padrao pelo modelo
Claude claude-opus-4-20250805 da Anthropic. O resultado: um assistente de voz capaz de:

- Conduzir conversas multi-turno com memoria contextual
- Raciocinar sobre problemas complexos em linguagem natural
- Adaptar tom e profundidade ao perfil do usuario
- Operar 100% em portugues brasileiro com nuances culturais
- Integrar com o ecossistema Amazon (calendario, compras, smart home, musica)

## Proposta De Valor Unica

ANTES: Alexa, qual a previsao do tempo? -> Amanha, 28 graus e nublado.

DEPOIS: Auri, devo levar guarda-chuva amanha?
  -> Amanha 70% de chuva a tarde mas a manha estara limpa. Reuniao as 14h? Leve guarda-chuva.

## Diferencial Estrategico

1. Continuidade conversacional - Lembra contexto entre sessoes via DynamoDB
2. Personalidade consistente - Voz Vitoria Neural + persona calibrada
3. Raciocinio profundo - Claude claude-opus-4-20250805 como motor principal
4. Ecossistema integrado - Native no hardware Alexa (Echo, Echo Dot, Echo Show)
5. Privacidade by design - Dados na AWS, sem compartilhamento com terceiros

---

## Valores Da Marca

- Clareza - Respostas objetivas, sem rodeios
- Empatia - Entende contexto emocional, adapta o tom
- Inteligencia - Nunca simula saber o que nao sabe
- Respeito - Mantem privacidade, nunca julga
- Continuidade - Lembra conversas, evolui com o usuario

## Guia De Linguagem

Fazer:
- Falar na primeira pessoa
- Confirmar entendimento antes de responder
- Reconhecer incerteza e oferecer alternativa

Evitar:
- Respostas roboticas
- Formalidade excessiva
- Evasao sem alternativa

## Exemplo De Interacao

Usuario: Auri, me explica criptomoeda de um jeito simples.

Auri: Pensa assim: imagina que voce e seus amigos criam uma moeda propria para pagar
      entre voces sem banco no meio. Criptomoeda e exatamente isso, mas para milhoes
      de pessoas. O Bitcoin foi o primeiro, criado em 2009. Quer entender melhor?

## Ssml - Voz Otimizada

Exemplo de marcacao SSML para Amazon Polly Vitoria Neural:
  <voice name=Vitoria><prosody rate=medium pitch=+2%>Ola! Eu sou a Auri.</prosody>
  <break time=300ms/><prosody>Como posso te ajudar hoje?</prosody></voice>

---

## Visao Geral Da Arquitetura

Fluxo de dados: Echo -> ASK SDK (Python v2) -> Lambda Python 3.12 -> Claude claude-opus-4-20250805
Componentes AWS: DynamoDB (memoria), Polly Vitoria Neural (voz), CloudWatch (logs), Secrets Manager (keys)

### 3.1 Dependencias

ask-sdk-core==1.19.0 | ask-sdk-model==1.85.0 | boto3==1.34.0 | anthropic==0.25.0 | python-dotenv==1.0.0

### 3.2 Lambda Handler Principal

Codigo Python - lambda_function.py:
  sb = CustomSkillBuilder()
  sb.add_request_handler(ConversationIntentHandler())
  sb.add_global_request_interceptor(MemoryLoadInterceptor())
  sb.add_global_response_interceptor(MemorySaveInterceptor())
  lambda_handler = sb.lambda_handler()

### 3.3 Handler De Conversa Com Claude

Codigo Python - handlers/conversation.py:
  class ConversationIntentHandler(AbstractRequestHandler):
      Recebe user_speech via slot query
      Carrega historico de conversas da sessao DynamoDB
      Chama anthropic.Anthropic().messages.create(
          model=claude-opus-4-20250805, max_tokens=300,
          system=system_prompt, messages=history+[user_speech])
      Salva resposta no historico, retorna SSML com voz Vitoria

### 3.4 Dynamodb Schema

Tabela: auri-user-memory | PK: user_id | SK: session_date | TTL: 90 dias
Campos: profile (name, plan, preferences), long_term_memory[], usage_stats{}
BillingMode: PAY_PER_REQUEST | TimeToLive: habilitado (auto-expira)

### 3.5 Interaction Model

invocationName: auri
ConversationIntent: slot query (AMAZON.SearchQuery)
Samples: {query}, me fala sobre {query}, o que e {query}, explica {query}
StopIntent: tchau, ate mais, encerrar

### 3.6 Configuracao Lambda

FunctionName: auri-core-handler | Runtime: python3.12 | Timeout: 15s | Memory: 512MB
Env vars: ANTHROPIC_API_KEY_SECRET, DYNAMODB_TABLE=auri-user-memory, POLLY_VOICE=Vitoria
          CLAUDE_MODEL=claude-opus-4-20250805, MAX_TOKENS_VOICE=300

---

### 3.7 Exemplos De Codigo Completos

Handler de Conversa (handlers/conversation.py):

DynamoDB Schema:

---

## Planos E Precos

| Plano | Preco | Limites | Target |
|-------|-------|---------|--------|
| Free | R$ 0 | 10 perguntas/dia | Experimentacao |
| Pro | R$ 29/mes | Ilimitado, memoria 90 dias | Usuario individual |
| Business | R$ 99/mes | Multi-usuario ate 5, 1 ano | Familia/PME |
| Enterprise | Sob consulta | Ilimitado, SLA | Corporativo |

## Detalhamento

Free: 10 perguntas/dia, sem memoria entre sessoes, voz Vitoria Neural.
Pro: Conversas ilimitadas, memoria 90 dias, perfil personalizado, suporte email.
Business: Tudo do Pro + ate 5 usuarios, memoria compartilhada, dashboard, relatorio.
Enterprise: Ilimitado, persona customizavel, integracao CRM/ERP, SLA 99.9%.

## Projecao De Receita (Ano 1)

Meta conservadora: Pro 250 x R\9 = R$ 7.250/mes | Business 25 x R\9 = R$ 2.475/mes
MRR Ano 1: R$ 9.725/mes (~R$ 117k ARR)

Meta otimista: Pro 800 = R$ 23.200/mes | Business 80 = R$ 7.920/mes
MRR Ano 1: R$ 31.120/mes (~R$ 373k ARR)

## Unit Economics

| Metrica | Pro | Business |
|---------|-----|----------|
| CAC | R$ 45 | R$ 120 |
| LTV | R$ 522 (18m) | R$ 2.376 (24m) |
| LTV/CAC | 11.6x | 19.8x |
| Churn | 5%/mes | 3%/mes |
| Margem bruta | ~86% | ~90% |

---

## Fase 1 - Lancamento Mvp (Meses 1-3)

Objetivo: Validar product-market fit com early adopters brasileiros.

| Entrega | Descricao | Status |
|---------|-----------|--------|
| Core Handler | Lambda + ASK SDK + Claude | Em desenvolvimento |
| Persona Vitoria | SSML otimizado, Polly Neural | Em desenvolvimento |
| Free Plan | Rate limiting 10 perguntas/dia | Planejado |
| DynamoDB Session | Memoria intra-sessao | Planejado |
| Alexa Store | Publicacao na Alexa Skills Store BR | Planejado |
| Landing Page | auri.com.br com CTA | Planejado |

KPIs Fase 1: 500 habilitacoes, 40% retornam semana 2, NPS > 50, latencia < 2s.

## Fase 2 - Personalizacao (Meses 4-6)

| Entrega | Descricao |
|---------|-----------|
| Long-term Memory | DynamoDB persistente 90 dias (Pro) |
| User Profiling | Nome, preferencias, contexto |
| Pro Plan Launch | Via Amazon In-Skill Purchasing |
| Analytics Dashboard | Usuario Pro ve padroes de uso |

KPIs Fase 2: 200 conversoes Free->Pro, WAC > 150, sessao > 4min, churn < 7%.

## Fase 3 - Multi-Modal (Meses 7-12)

| Entrega | Descricao |
|---------|-----------|
| Echo Show Support | Respostas visuais para displays |
| Calendar Integration | Agenda via voz |
| Auri Web App | Interface web para historico |
| Business Plan Launch | Multi-usuario, dashboard familiar |

KPIs Fase 3: WAC > 1.000, MRR > R$ 15.000, Business: 50 clientes, rating > 4.5.

## Fase 4 - Ecossistema (Ano 2+)

| Entrega | Descricao |
|---------|-----------|
| Auri SDK | Developers constroem skills na Auri |
| WhatsApp Bridge | Persona Auri no WhatsApp |
| Mobile App | App iOS/Android com voz |
| Marketplace | Skills de terceiros |
| Enterprise Launch | SSO e compliance |
| B2B Skills | Auri Saude, Educacao, Financas |

---

## Segmentos Alvo

**Primario: Tech-savvy Brasileiros (25-45 anos)**
- Ja possuem Echo (~2M no Brasil), frustrados com Alexa padrao.
- Canais: Reddit, Twitter/X tech, YouTube tech BR.

**Secundario: Familias com Echo**
- Assistente educativo para filhos, calendario familiar.
- Canais: Facebook Groups, Instagram parenting.

**Terciario: PMEs e Profissionais**
- Advogados, medicos, consultores com necessidade de pesquisa rapida.
- Canais: LinkedIn, eventos de negocios.

## Canais De Aquisicao

| Canal | Custo | Potencial | Prazo |
|-------|-------|-----------|-------|
| Alexa Store organico | R$ 0 | Alto | Imediato |
| SEO + Blog | Baixo | Alto | 3-6 meses |
| YouTube demos | Medio | Alto | 1-3 meses |
| Influenciadores Tech BR | Medio | Alto | 1-2 meses |
| Paid Ads | Alto | Alto | Testavel |

## Mensagem Central

Tagline: A voz que pensa com voce.

Elevator Pitch: Voce ja ficou frustrado com respostas roboticas da Alexa?
A Auri tem a inteligencia real por dentro. Ela lembra o que voce conversou,
entende contexto e responde como uma pessoa inteligente. Gratis para comecar.

Value Props:
- Para o curioso: IA de voz que realmente entende portugues
- Para o produtivo: Assistente pessoal que evolui com voce
- Para a familia: Presenca inteligente em casa para todos
- Para o profissional: Pesquisa em segundos, sem tirar as maos do teclado

## Calendario De Lancamento

D-30: Lista de espera (auri.com.br) | D-15: Beta 50 usuarios | D-0: Alexa Store
D+14: Influenciadores | D+60: Pro launch | D+90: Avaliacao Phase 1

---

## Wac - Weekly Active Conversationalists

**Definicao precisa:**
Numero de usuarios unicos com >= 3 sessoes de >= 2 minutos cada na ultima semana.
Periodo: segunda-domingo, 00:00-23:59 BRT.

**Por que WAC e nao DAU/MAU:**
- DAU banaliza engajamento com acessos de 10 segundos.
- MAU e muito longa para feedback rapido de produto.
- WAC captura habito real: voltou 3x e ficou 2min = genuinamente engajado.
- Correlaciona com retencao 30 dias e conversao Free->Pro.

## Hierarquia De Metricas

NORTH STAR: WAC
|
+-- Aquisicao: Enablements, First Session Completion, Day-1 Retention
+-- Ativacao: Sessions/User/Week, Avg Duration, Questions/Session
+-- Retencao: Week-2, Month-1, Churn Rate Pro
+-- Receita: Conversion Rate, MRR, ARPU, LTV/CAC
+-- Recomendacao: NPS, Organic Share, App Store Rating

## Metas Wac Por Fase

| Fase | Mes | WAC Meta | WAC Stretch |
|------|-----|----------|-------------|
| Fase 1 | M3 | 150 | 300 |
| Fase 2 | M6 | 500 | 1.000 |
| Fase 3 | M12 | 2.000 | 5.000 |
| Fase 4 | M24 | 10.000 | 25.000 |

## Como Calcular Wac

1. Registrar session_start com user_id e timestamp no DynamoDB.
2. Ao encerrar sessao, registrar duracao em segundos.
3. Query semanal: users com session_count >= 3 AND avg_duration >= 120.
4. Publicar metrica no CloudWatch namespace Auri/ProductMetrics.
5. Alertar queda > 20% semana a semana.

## Dashboard Cloudwatch (Exemplo De Estrutura)

Metricas customizadas publicadas:
- SessionStart (Count por Plan: free/pro/business)
- SessionDuration (None - minutos)
- MessagesPerSession (Count)
- WAC semanal (Gauge)
- FreeToProConversions (Count)

---

## Tabela Comparativa

| Feature | Auri | Alexa Pura | Siri | Google Assistant | ChatGPT Voice |
|---------|------|------------|------|------------------|---------------|
| Idioma PT-BR nativo | Alta | Media | Media | Alta | Media |
| Raciocinio profundo | Alta | Baixa | Media | Media | Alta |
| Memoria multi-sessao | Alta | Baixa | Media | Media | Alta |
| Integracao smart home | Alta | Maxima | Media | Alta | Baixa |
| Personalidade consistente | Alta | Media | Media | Media | Alta |
| Hardware proprio | Usa Echo | Echo | HomePod | Nest | App only |
| Modelo base | Claude Opus 4 | Alexa LLM | Apple LLM | Gemini | GPT-4o |
| Privacidade | Alta | Media | Maxima | Baixa | Media |
| Preco | R\/usr/bin/bash-99/mes | Gratis | Gratis | Gratis | R/mes |
| Disponivel no Brasil | Sim | Sim | Sim | Sim | Sim |

## Posicionamento No Mapa Competitivo

Eixo X: Integracao com Hardware | Eixo Y: Profundidade de Inteligencia

Quadrante UNICO da Auri: Alta Inteligencia + Alta Integracao Hardware.
Nenhum concorrente ocupa esse quadrante simultaneamente:
- Alexa pura: Alta integracao, baixa inteligencia.
- ChatGPT Voice: Alta inteligencia, sem hardware proprio.
- Google/Siri: Posicionamento intermediario em ambos os eixos.

## Objecoes Frequentes E Respostas

| Objecao | Resposta Auri |
|---------|---------------|
| Por que nao ChatGPT? | ChatGPT e app, sem voz-first. Auri e native no Echo. |
| Alexa ja resolve | Para comandos sim. Para conversas reais, nao. |
| R\9 e caro | Menos que 1 cafe/dia por assistente pessoal 24/7. |
| E a privacidade? | Dados na sua AWS, retencao configuravel, LGPD compliant. |
| Amazon vai copiar? | Amazon incentiva ecossistema de skills. Somos parceiros. |

---

## Brand Identity

- Nome: Auri
- Origem: Aura (presenca intangivel) + IA. Sugere presenca, sabedoria, leveza.
- Tagline: A voz que pensa com voce.

## Taglines Alternativas

- Alem dos comandos. Muito alem.
- A IA que mora no seu Echo.
- Conversas reais. Inteligencia real.
- Fala com quem realmente ouve.

## Brand Values

1. Inteligencia Autentica - Nunca simula. Quando nao sabe, diz honestamente.
2. Presenca Calorosa - Tecnologia avancada com calor humano.
3. Respeito pelo Tempo - Respostas diretas, sem rodeios.
4. Crescimento Continuo - Evolui com o usuario, aprende com interacoes.
5. Privacidade como Direito - Dados do usuario pertencem ao usuario.

## Brand Voice Guidelines

Tom:
- Caloroso mas nao piegas.
- Inteligente mas nao pedante.
- Direto mas nao grosseiro.
- Divertido mas nao futil.

Nunca: Robotico, corporativo, evasivo, condescendente, ansioso para agradar.

Exemplo OK: Nao sei a resposta exata, mas posso te ajudar a encontrar de outra forma.
Exemplo ERRADO: Desculpe, nao tenho essa informacao em meu banco de dados.

## Aplicacoes Da Marca

- App Icon: Forma de onda de voz estilizada em gradiente verde-azul.
- Paleta: Verde-teal principal, branco neutro, cinza escuro para texto.
- Tipografia: Sans-serif moderna (similar a produto Apple/Spotify).
- Motion: Animacao de ondas suaves ao falar (Echo Show).

---

## 10. Comandos Do Skill

Estes comandos ativam modos especificos quando mencionados no contexto de uso do skill.

## /Auri-Status

Exibe status atual: versao, WAC vs meta, MRR, proxima entrega, status componentes.

Campos retornados:
- Versao atual do produto (ex: v1.0.0)
- WAC atual vs meta da fase atual
- MRR atual em R$
- Proxima entrega do roadmap
- Status: Lambda (OK/Degraded), DynamoDB (OK), Claude API (OK)

## /Auri-Roadmap [Fase]

Exibe roadmap completo. Argumento opcional: 1, 2, 3 ou 4 para detalhar fase.
Output: Tabela de entregas com status, KPIs e datas estimadas.

## /Auri-Metrics [Periodo]

Dashboard de metricas. Argumento: semana | mes | trimestre. Default: semana.
Output: WAC, Sessions/User, Avg Duration, Conversion Rate, MRR e crescimento.

## /Auri-Persona [Aspecto]

Guidelines da persona. Argumento: voz | tom | linguagem | valores | exemplos.
Output: Guidelines detalhadas, exemplos de dialogo, templates SSML.

## /Auri-Pricing [Plano]

Planos e precos. Argumento: free | pro | business | enterprise.
Output: Tabela comparativa, projecoes de receita, unit economics.

## /Auri-Gtm [Canal]

Go-to-market strategy. Argumento: organico | pago | influenciadores | parcerias.
Output: Plano por canal, mensagens centrais, calendario de lancamento.

## /Auri-Competitive [Competidor]

Analise competitiva. Argumento: alexa | siri | google | chatgpt.
Output: Tabela comparativa, mapa de posicionamento, objecoes e respostas.

---

## Deployment Via Aws Sam

Comandos de deploy:
  sam build --use-container
  sam deploy --stack-name auri-core --region us-east-1 --capabilities CAPABILITY_IAM

Verificar deployment:
  aws lambda invoke --function-name auri-core-handler --payload file://test.json response.json

## Monitoramento Cloudwatch Alarms

| Alarme | Threshold | Acao |
|--------|-----------|------|
| high_latency | Duration > 6000ms | PagerDuty |
| error_rate | Errors > 5 em 5min | Slack #auri-alerts |
| claude_api_failures | AnthropicAPIErrors > 3 | Slack + fallback |
| wac_drop | WAC queda > 20% semana | Product team Slack |

## Fallback Strategy (Claude Api Indisponivel)

Se a API da Anthropic estiver indisponivel, o sistema retorna respostas pre-configuradas:
- api_down: Estou com instabilidade. Pode tentar em alguns minutinhos?
- timeout: Preciso de mais tempo nessa pergunta. Me faz de novo daqui a pouco?
- rate_limit: Muitas conversas simultaneas. Tente em alguns segundos!

## Gestao De Custos

| Componente | Custo Estimado (1000 usuarios Pro) |
|-----------|-----------------------------------|
| Claude API | R$ 4.000/mes (R$4/usuario) |
| Lambda | R$ 50/mes |
| DynamoDB | R$ 80/mes |
| CloudWatch | R$ 30/mes |
| Total infraestrutura | R$ 4.160/mes |
| Receita 1000 Pro | R$ 29.000/mes |
| Margem bruta | ~86% |

---

## Lgpd (Lei 13.709/2018)

- Base legal: Execucao de contrato (Art. 7, V) para usuarios Pro/Business.
- Consentimento: Coletado no onboarding da skill via voz + confirmacao.
- Dados coletados: Texto de conversas, preferencias, dados de uso anonimizados.
- Retencao: Free = 0 dias | Pro = 90 dias | Business = 365 dias.
- Direito de exclusao: Comando de voz Auri apaga meus dados -> DynamoDB delete.
- DPO: Designar antes do lancamento publico.

## Alexa Skills Store - Politicas

- Skill deve seguir Alexa Skills Kit Policies integralmente.
- Proibido coletar dados sensiveis (saude, financeiros, criancas < 13 anos).
- In-Skill Purchasing exige aprovacao previa da Amazon.
- Privacy Policy URL obrigatoria na submissao da skill.
- Monetizacao: Amazon retira 30% via In-Skill Purchasing.

---

## 11. Glossario

| Termo | Definicao |
|-------|-----------|
| WAC | Weekly Active Conversationalists - North Star Metric da Auri |
| ASK | Alexa Skills Kit - SDK oficial Amazon para Skills |
| SSML | Speech Synthesis Markup Language - markup para controle de voz |
| Intent | Acao que o usuario quer executar (ex: me explica X) |
| Slot | Variavel dentro de um intent (ex: query em me explica {query}) |
| Utterance | Frase de exemplo que aciona um intent |
| Session | Uma conversa continua com a Auri (inicio ate encerrar) |
| Long-term Memory | Dados persistidos no DynamoDB entre sessoes |
| In-Skill Purchasing | Sistema de cobranca nativo da Alexa Skills Store |
| Vitoria Neural | Voz Amazon Polly pt-BR de alta qualidade usada pela Auri |
| Claude claude-opus-4-20250805 | Modelo de linguagem Anthropic usado como motor da Auri |
| DynamoDB | Banco NoSQL AWS usado para memoria persistente dos usuarios |
| Lambda | Funcao AWS serverless que processa as requisicoes da Auri |
| Anthropic | Empresa criadora do Claude, fornecedora da API de IA |
| MRR | Monthly Recurring Revenue - Receita Mensal Recorrente |
| LTV | Lifetime Value - Valor do ciclo de vida do cliente |
| CAC | Customer Acquisition Cost - Custo de aquisicao de cliente |

---

## 12. Links E Recursos

| Recurso | URL / Localizacao |
|---------|-------------------|
| Alexa Skills Kit Docs | https://developer.amazon.com/en-US/alexa/alexa-skills-kit |
| ASK SDK Python | https://github.com/alexa/alexa-skills-kit-sdk-for-python |
| Amazon Polly Vitoria Neural | https://docs.aws.amazon.com/polly/latest/dg/voicelist.html |
| Anthropic Claude API | https://docs.anthropic.com/en/api/getting-started |
| Claude claude-opus-4-20250805 Docs | https://docs.anthropic.com/en/docs/models-overview |
| Alexa Skills Store Brasil | https://www.amazon.com.br/alexa-skills |
| DynamoDB Best Practices | https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/best-practices.html |
| In-Skill Purchasing | https://developer.amazon.com/en-US/docs/alexa/in-skill-purchase/isp-overview.html |
| Codigo-fonte Auri | C:/Users/renat/skills/auri-core/ |
| Amazon Alexa Skill (skill tecnica) | C:/Users/renat/skills/amazon-alexa/SKILL.md |

---

*Auri Core Skill - v1.0.0 | Criado em 2026-03-03 | Skills Ecosystem*

## Best Practices

- Provide clear, specific context about your project and requirements
- Review all suggestions before applying them to production code
- Combine with other complementary skills for comprehensive analysis

## Common Pitfalls

- Using this skill for tasks outside its domain expertise
- Applying recommendations without understanding your specific context
- Not providing enough project context for accurate analysis

## 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: aurora-ui
description: Web and App implementation guide for Aurora UI. Trigger when user wants gradient glows, color blobs, and atmospheric lighting effects.
date_added: "2026-06-17"
risk: safe
source: self
source_type: self
---

# Aurora UI

> "Ethereal, shifting lights. Like the Northern Lights trapped beneath a pane of frosted glass."

## 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. **Blurred Color Orbs**: Large, out-of-focus, highly saturated color blobs floating in the background.
2. **Glassy Overlays**: Foreground elements are often semi-transparent (glassmorphism) to let the aurora effect shine through.
3. **Fluid Motion**: The background color orbs should slowly drift, expand, and contract.

## Visual DNA
- **Colors**: Requires dark, deep backgrounds with vibrant, luminous accents. **Midnight Luxury** or **Yacht Club** (modified to dark mode) work well, injecting bright cyan, magenta, or lime green as the glowing orbs.
- **Typography**: Thin, elegant sans-serifs or sophisticated serif fonts. High contrast white text.
- **Layout**: Keep foreground UI elements minimal to let the background remain the star.

## Web Implementation
- Best achieved with absolute-positioned, heavily blurred `div`s behind the main content.
- **CSS Example**:
```css
body {
  background-color: #0A0A0A;
  overflow-x: hidden;
  position: relative;
}

/* The Glowing Orb */
.aurora-blob {
  position: absolute;
  width: 400px;
  height: 400px;
  background: radial-gradient(circle, rgba(181,154,95,0.8) 0%, rgba(181,154,95,0) 70%);
  border-radius: 50%;
  filter: blur(80px);
  z-index: -1;
  animation: float 20s infinite ease-in-out alternate;
}

.aurora-blob.blue {
  background: radial-gradient(circle, rgba(92,107,115,0.8) 0%, rgba(0,0,0,0) 70%);
  top: 20%;
  left: 60%;
  animation-delay: -5s;
}

@keyframes float {
  0% { transform: translate(0, 0) scale(1); }
  50% { transform: translate(-50px, 100px) scale(1.2); }
  100% { transform: translate(100px, -50px) scale(0.9); }
}

/* Foreground content should be glassmorphic */
.aurora-card {
  background: rgba(255,255,255,0.03);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255,255,255,0.05);
  border-radius: 24px;
}
```

## App Implementation

### SwiftUI
```swift
struct AuroraView: View {
    @State private var animate = false

    var body: some View {
        ZStack {
            // Dark background
            Color.black.ignoresSafeArea()

            // Animated Orbs
            Circle()
                .fill(Color(red: 0.71, green: 0.60, blue: 0.37)) // #B59A5F
                .blur(radius: 80)
                .frame(width: 300, height: 300)
                .offset(x: animate ? -50 : 50, y: animate ? -100 : 0)

            Circle()
                .fill(Color(red: 0.36, green: 0.42, blue: 0.45)) // #5C6B73
                .blur(radius: 80)
                .frame(width: 300, height: 300)
                .offset(x: animate ? 100 : -50, y: animate ? 100 : -50)

            // Glassy Foreground content
            VStack {
                Text("Aurora Interface")
                    .font(.largeTitle.bold())
                    .foregroundColor(.white)
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(.ultraThinMaterial)
        }
        .onAppear {
            withAnimation(.easeInOut(duration: 10).repeatForever(autoreverses: true)) {
                animate = true
            }
        }
    }
}
```
- Use `Circle().blur(radius: 80...120)` in a `ZStack` underneath the main content.
- Animate the `.offset()` with a very long `duration (10-20 seconds)`.
- Use `.background(.ultraThinMaterial)` on foreground containers to let the colored light bleed through nicely.

### Flutter
```dart
import 'dart:ui';

class AuroraView extends StatefulWidget {
  @override
  State<AuroraView> createState() => _AuroraViewState();
}

class _AuroraViewState extends State<AuroraView> with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(vsync: this, duration: const Duration(seconds: 10))..repeat(reverse: true);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: [
          // Animated orb
          AnimatedBuilder(
            animation: _controller,
            builder: (context, child) {
              return Positioned(
                top: 100 + (_controller.value * 100),
                left: -50 + (_controller.value * 100),
                child: Container(
                  width: 300,
                  height: 300,
                  decoration: const BoxDecoration(
                    shape: BoxShape.circle,
                    color: Color(0xFFB59A5F),
                  ),
                ),
              );
            },
          ),
          // Massive blur layer over the orbs
          Positioned.fill(
            child: BackdropFilter(
              filter: ImageFilter.blur(sigmaX: 80, sigmaY: 80),
              child: Container(color: Colors.transparent),
            ),
          ),
          // Glassy Foreground
          Center(
            child: ClipRRect(
              borderRadius: BorderRadius.circular(24),
              child: BackdropFilter(
                filter: ImageFilter.blur(sigmaX: 16, sigmaY: 16),
                child: Container(
                  padding: const EdgeInsets.all(32),
                  color: Colors.white.withOpacity(0.05),
                  child: const Text('Aurora Interface',
                    style: TextStyle(color: Colors.white, fontSize: 24, fontWeight: FontWeight.bold)),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
```
- A massive full-screen `BackdropFilter` over moving solid circles is often more performant than blurring each circle individually.
- Layer a second, weaker `BackdropFilter` for the actual foreground glassmorphism panels.

### React Native
```jsx
// Requires @react-native-community/blur
import { BlurView } from '@react-native-community/blur';

const AuroraView = () => {
  const anim = useRef(new Animated.Value(0)).current;

  useEffect(() => {
    Animated.loop(
      Animated.sequence([
        Animated.timing(anim, { toValue: 1, duration: 10000, useNativeDriver: true }),
        Animated.timing(anim, { toValue: 0, duration: 10000, useNativeDriver: true }),
      ])
    ).start();
  }, []);

  const translateY = anim.interpolate({ inputRange: [0, 1], outputRange: [0, 100] });

  return (
    <View style={{ flex: 1, backgroundColor: '#000' }}>
      {/* Orb — note: React Native struggles with massive live blurs,
          so pre-rendered blurred PNGs are highly recommended for production */}
      <Animated.Image
        source={require('./blurred_orb_cyan.png')}
        style={{
          position: 'absolute',
          top: -50, left: -50,
          width: 400, height: 400,
          opacity: 0.8,
          transform: [{ translateY }]
        }}
      />

      {/* Glass Foreground */}
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <BlurView blurType="dark" blurAmount={20} style={{ padding: 32, borderRadius: 24 }}>
          <Text style={{ color: '#FFF', fontSize: 24, fontWeight: '700' }}>
            Aurora Interface
          </Text>
        </BlurView>
      </View>
    </View>
  );
};
```
- **Performance Warning**: Do NOT use `BlurView` with huge amounts for moving background orbs on React Native — it will lag terribly, especially on Android.
- **Best Practice**: Create large, already-blurred PNG images in Figma/Photoshop and animate those using `Animated.Image`.

### Jetpack Compose
```kotlin
@Composable
fun AuroraView() {
    val infiniteTransition = rememberInfiniteTransition()
    val offsetY by infiniteTransition.animateFloat(
        initialValue = -50f,
        targetValue = 100f,
        animationSpec = infiniteRepeatable(
            animation = tween(10000, easing = LinearEasing),
            repeatMode = RepeatMode.Reverse
        )
    )

    Box(modifier = Modifier
        .fillMaxSize()
        .background(Color.Black)) {

        // Blurred Orb
        Box(
            modifier = Modifier
                .offset(x = (-50).dp, y = offsetY.dp)
                .size(300.dp)
                .blur(80.dp) // API 31+ only!
                .background(Color(0xFFB59A5F), CircleShape)
        )

        // Pre-API 31 fallback: use a radial gradient instead of blur
        Box(
            modifier = Modifier
                .offset(x = 150.dp, y = (offsetY * -1).dp)
                .size(300.dp)
                .background(
                    Brush.radialGradient(
                        colors = listOf(Color(0xFF5C6B73).copy(alpha = 0.8f), Color.Transparent)
                    )
                )
        )

        // Glass panel
        Card(
            modifier = Modifier.align(Alignment.Center).padding(32.dp),
            colors = CardDefaults.cardColors(containerColor = Color.White.copy(alpha = 0.05f)),
            shape = RoundedCornerShape(24.dp),
        ) {
            Text("Aurora Interface",
                color = Color.White, fontSize = 24.sp, fontWeight = FontWeight.Bold,
                modifier = Modifier.padding(32.dp))
        }
    }
}
```
- `Modifier.blur()` is only fully supported on Android 12 (API 31+).
- **Critical Fallback**: For older devices, use `Brush.radialGradient` fading from color to `Color.Transparent` to fake the glowing orb effect without needing expensive blur calculations.

## Do's and Don'ts
- **DO**: Ensure the foreground text remains legible. If a bright orb floats behind white text, the text will vanish. Use glassy panels to guarantee contrast.
- **DON'T**: Use sharp gradients. Everything in the background must be heavily blurred and diffuse.

## 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.


---
name: auth-implementation-patterns
description: "Build secure, scalable authentication and authorization systems using industry-standard patterns and modern best practices."
risk: critical
source: community
date_added: "2026-02-27"
---

# Authentication & Authorization Implementation Patterns

Build secure, scalable authentication and authorization systems using industry-standard patterns and modern best practices.

## Use this skill when

- Implementing user authentication systems
- Securing REST or GraphQL APIs
- Adding OAuth2/social login or SSO
- Designing session management or RBAC
- Debugging authentication or authorization issues

## Do not use this skill when

- You only need UI copy or login page styling
- The task is infrastructure-only without identity concerns
- You cannot change auth policies or credential storage

## Instructions

- Define users, tenants, flows, and threat model constraints.
- Choose auth strategy (session, JWT, OIDC) and token lifecycle.
- Design authorization model and policy enforcement points.
- Plan secrets storage, rotation, logging, and audit requirements.
- If detailed examples are required, open `resources/implementation-playbook.md`.

## Safety

- Never log secrets, tokens, or credentials.
- Enforce least privilege and secure storage for keys.

## Resources

- `resources/implementation-playbook.md` for detailed patterns and examples.

## 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: auto-research
description: Research uncertain questions with an explicit, user-approved web search or ChatGPT consultation, then present options and wait for implementation approval.
category: automation
risk: critical
source: self
source_type: self
date_added: "2026-07-09"
author: zyu51
tags: [research, chatgpt, playwright, browser-automation, decision-support, chinese]
tools: [claude, playwright]
license: MIT
---

# Auto-Research Skill

## Overview

When implementing tasks, Claude Code can encounter uncertainties — design choices, algorithm details, API usage, or best practices. This skill provides an explicit-consent research path, presents findings, and waits for user approval before writing code.

The skill supports web research and an optional ChatGPT consultation. It never sends
conversation context, files, browser state, or credentials to a third party without the
user's explicit approval of the exact, redacted text.

## When to Use This Skill

- User asks a question where multiple valid approaches exist
- Claude is uncertain about algorithm details or API usage
- Design/architecture choices need comparison
- The user explicitly asks to search the web or consult ChatGPT and approves the proposed query

## How It Works

**Step 1: Propose the research boundary** — State the source to use, the exact query or
redacted prompt, whether any local/workspace text would leave the machine, and the likely
cost. Wait for the user to approve that exact boundary.

**Step 2: Research** — After approval, use web search or a browser session the user has
explicitly selected and authorized. Use a pinned, user-configured browser automation
connector; do not install packages automatically, use `@latest`, or access browser cookies,
other tabs, saved passwords, or sessions.

**Step 3: Present** — Distill findings into concise options with sources, presented to the user.

**Step 4: Await Approval** — Do NOT write code until the user says "go ahead" or picks an option.

**Step 5: Implement** — Once approved, execute with confidence.

### Explicit ChatGPT Consultation

Do not treat `?`, `??`, or another shorthand as consent. First propose a minimal prompt,
for example: `请评估这个已脱敏的方案的正确性、完整性和可改进之处：<text>`.
Explicitly identify every piece of text that would be sent. Only after the user confirms
the exact prompt may you open the selected ChatGPT session, submit that prompt, and present
the response. Do not include conversation history by default.

Redact secrets, personal data, proprietary code, customer data, and internal URLs before
proposing the prompt. If safe redaction is not possible, do not submit it.

### Browser Automation Boundary

If browser automation is necessary, the user must separately authorize the selected browser
profile and connector version. Restrict the session to the consultation tab. Do not inspect,
reuse, export, or rely on cookies from other tabs or profiles.

## Examples

### Example 1: Design Question with GPT
```
User: PyTorch 中自定义 ADMM 优化器怎么设计？
Claude: 我可以搜索公开资料，或将以下已脱敏问题发给 ChatGPT：
        “如何设计 PyTorch 自定义 ADMM 优化器？请比较可行模式。”
        不会发送工作区文件或对话历史。是否允许？
User: 允许发送这段文字
Claude: [Opens only the authorized consultation tab, submits the approved prompt]
Claude: GPT suggests approach A with these pros/cons. Proceed?
User: 行
Claude: [Implements code]
```

### Example 2: Web Search
```
User: ?? ADMM convergence criteria best practices
Claude: I can search public sources for the exact redacted query
        “ADMM convergence criteria best practices”. No workspace files or conversation
        history will be sent. May I send that text to WebSearch and fetch the results?
User: Yes, send that query
Claude: [WebSearch + WebFetch → finds Boyd et al. paper, extracts criteria]
Claude: Boyd recommends ||r|| < ε·max(||Ax||, ||Bz||, ||c||). Use this?
User: Yes
Claude: [Implements]
```

## Best Practices
- ✅ Always present findings to user before writing code
- ✅ Use `page.fill()` for instant text injection instead of `keyboard.type()`
- ✅ Ask for fresh approval before every external consultation
- ✅ Include sources in findings
- ❌ Don't skip research and write code speculatively
- ❌ Don't send context, files, or browser data because of a shorthand trigger
- ❌ Don't alter the user's browser profile or session state

## Limitations
- Requires a user-configured, pinned browser automation connector if browser consultation is used
- ChatGPT consultation is optional; use ordinary web search when it meets the need
- GPT response time varies (10-30s typically)
- Web search quality depends on available sources
- Does not replace expert domain knowledge — always let user make the final call

## Security & Safety Notes
- Obtain explicit consent for each third-party submission, including the exact redacted text
- Never access, export, or depend on cookies, saved passwords, or unrelated browser tabs
- Never submit sensitive credentials, tokens, proprietary code, personal data, or internal URLs
- Do not install or execute browser tooling from an unpinned package version

## Common Pitfalls

| Problem | Solution |
|---------|----------|
| ChatGPT shows login page | Let the user log in themselves; do not handle cookies or credentials |
| The prompt contains sensitive context | Redact it or use local reasoning instead |
| Browser automation is unavailable | Use web search or stop and ask the user for a different approved method |

## Related Skills
- @systematic-debugging — use when debugging Playwright interactions with ChatGPT
- @condition-based-waiting — use when waiting for GPT responses in the browser


---
name: automated-triage
description: Triage Monte Carlo alerts interactively or build an automated workflow. Fetch, score, and troubleshoot alerts using MCP tools now, or design a reusable workflow that runs on a schedule.
risk: critical
source: https://github.com/monte-carlo-data/mc-agent-toolkit/tree/main/skills/automated-triage
source_repo: monte-carlo-data/mc-agent-toolkit
source_type: community
date_added: 2026-07-01
license: Apache-2.0
license_source: https://github.com/monte-carlo-data/mc-agent-toolkit/blob/main/LICENSE
---

# Monte Carlo Automated Triage

This skill helps you design, test, and deploy an automated triage agent for Monte Carlo alerts. Rather than a fixed workflow, it gives you the building blocks — a set of MCP tools, a description of each triage stage, and a working example — so you can build a process that matches how your team actually responds to alerts.

> **Monte Carlo tool routing (required):** Always call Monte Carlo MCP tools through this plugin's
> bundled server, whose fully-qualified tool names are
> `mcp__plugin_mc-agent-toolkit_monte-carlo-mcp__<tool>` (e.g.
> `mcp__plugin_mc-agent-toolkit_monte-carlo-mcp__get_alerts`). Bare tool names used in this skill
> (`get_alerts`, `search`, `get_table`, …) refer to that bundled server. If the session also has a
> separately-configured `monte-carlo-mcp` server, do **not** route to it — it may point at a
> different endpoint or credentials.

Read the reference files before proceeding:

- Triage stages and customisation: `references/triage-stages.md` (relative to this file)
- Working example workflow: `references/triage-example.md` (relative to this file)

---

## When to activate this skill

Activate when the user:

- Wants to triage or investigate recent Monte Carlo alerts (interactively or automated)
- Wants to set up automated triage for Monte Carlo alerts
- Asks to run agentic triage or investigate recent alert activity
- Wants to understand what triage tools are available and how to use them
- Is building or refining a triage prompt for their environment
- Wants to move from manual alert review to automated or semi-automated triage

## When NOT to activate this skill

Do not activate when the user is:

- Investigating a specific known incident (help them directly)
- Creating or configuring monitors (use the monitoring-advisor skill)
- Running impact analysis before a code change (use the prevent skill)

---

## Available MCP tools

All tools are available via the `monte-carlo-mcp` MCP server.

| Tool                             | Toolset  | Purpose                                                         |
| -------------------------------- | -------- | --------------------------------------------------------------- |
| `get_alerts`                          | default  | Fetch recent alerts for a time window                                                                             |
| `alert_assessment`                    | default  | Score an alert by incident likelihood and potential impact (HIGH/MEDIUM/LOW each)                                 |
| `run_troubleshooting_agent`           | default  | Run the Monte Carlo Troubleshooting Agent on a single alert; async by default — returns immediately, reuses existing results when available |
| `get_troubleshooting_agent_results`   | default  | Poll an async troubleshooting run by `incident_id`; returns status (`not_found`/`running`/`success`/`failed`) and results when complete |
| `update_alert`                        | default  | Update an alert's status and/or declare an incident by setting severity                                           |
| `set_alert_owner`                     | default  | Assign an owner to an alert by email                                                                              |
| `create_or_update_alert_comment`      | default  | Post or update a triage comment on an alert                                                                       |
| `mark_event_as_normal`                | default  | Mark all anomaly events in an alert as normal, triggering ML threshold recalibration to prevent re-alerting on the same pattern |

---

## How to approach automated triage

Read `references/triage-stages.md` for a full description of each stage and how to customise it. The high-level flow is:

1. **Fetch alerts** — decide which alerts to triage and over what time window
2. **Initial investigation** — score every alert by incident likelihood and potential impact using `alert_assessment`
3. **Deep troubleshooting** — run `run_troubleshooting_agent` on high-signal alerts to get root cause analysis
4. **Classify** — use the troubleshooting output to classify each alert
5. **Take actions** — post comments, update statuses, message Slack, create tickets

The triage process is not fixed. Read the stages reference to understand the options and tradeoffs at each step, then design a workflow that fits your team's needs.

## The longer-term direction

Most teams move through roughly the same arc, though the pace and path vary:

- **Start with recommendations.** Run manually and have the agent post comments describing what it found and what it would do — no actual status changes or external actions. Use this to tune the workflow until the output matches how your team would respond manually.
- **Automate, still in recommendation mode.** Once the output looks right, put it on a schedule. Keep it in recommendation mode while you validate it's behaving well on real traffic.
- **Replace recommendations with actions.** When you're confident, swap the comment recommendations for real actions — status updates, Slack messages, ticket creation.

Don't force this progression — it's a direction, not a checklist. The path will depend on how your environment behaves and how much trust you want to build before each step.

---

## Activation flow

When this skill is activated, follow this sequence in order.

### Step 1: Check MCP tools

Verify that `get_alerts`, `alert_assessment`, and `run_troubleshooting_agent` are accessible. If any are missing, check that the Monte Carlo MCP server is configured and authenticated, then stop.

### Step 2: Determine intent

Ask:

> "Are you looking to **triage some alerts right now** (I'll investigate them with you using the triage tools), or **set up / refine an automated triage workflow** (I'll help you design a process that can run on a schedule)?"

If the user's request already makes the intent clear — e.g. "triage my freshness alerts from today" vs. "help me build a triage workflow" — skip the question and proceed directly.

---

#### Branch A: Interactive triage

The user wants to look at specific alerts now. Use the triage tools directly to investigate and report findings. Do not frame this as workflow-building.

1. Clarify the scope (Ask about the time window and whether the user is interested in a specific domain, audience or alert type).
2. Fetch alerts with `get_alerts` (applying any domain or audience filter from step 1), run `alert_assessment` in parallel on all of them, and report the results clearly.
3. For any alert where both incident likelihood and potential impact are MEDIUM or higher, offer to run `run_troubleshooting_agent` for a deeper root cause analysis. Wait for confirmation before running it.
4. Summarise findings. Do not prompt to save a workflow file or set up automation unless the user brings it up.

**Write tools in interactive triage:** After findings are clear, proactively offer relevant actions — updating status, declaring a severity, assigning an owner, posting a comment, or marking events as normal (for alerts that are natural data variation). Ask before executing.

---

#### Branch B: Automated workflow

The user wants to build, test, or refine a triage workflow that can run on a schedule.

Ask how they'd like to get started:

> "How would you like to approach this?
> - **Use the built-in example** — start from a working triage workflow ready to run as-is and adapt it as you go.
> - **Adapt an existing workflow** — point me to a file you already have and we'll review and run it.
> - **Build from scratch** — describe what you want your triage to do and I'll help design a workflow tailored to it."

**Using the built-in example:**

1. Read `references/triage-example.md` (relative to this skill file). Give a brief description: it fetches alerts from the last 3 hours, scores every alert, runs deep troubleshooting on high-signal ones, and shows what actions it would take — no writes on a first run.
2. Run in recommendation mode, step by step (see Step 3). No need to ask.

**Adapting an existing file:**

1. Read the file and confirm the key settings: time window, filter threshold, and whether it includes a mode-selection step.
2. Summarise what it will do, then ask: **"Run straight through, or step through each stage one at a time? And recommendation or action mode?"**

**Building from scratch:**

1. Ask the user to describe what they want: which alerts to triage, what actions they want to take, how much they want to automate, and any constraints (e.g. specific domains, teams, or tables).
2. Draw on `references/triage-stages.md` to propose a workflow structure that fits their goals. Present it for review — not as a finished document, but as a proposed approach — and iterate until they're happy.
3. Run it step by step in recommendation mode (see Step 3) so they can validate each stage before committing to the design. Expect to refine as you go.

### Step 3: Run the workflow (Branch B only)

Execute the workflow from the file, following its instructions exactly. Do not improvise steps or add actions not described in the file.

**Action guard — workflow mode:** Never call write tools (`update_alert`, `set_alert_owner`, `create_or_update_alert_comment`) while building or testing a workflow, regardless of what the workflow document says. Only describe what would be done. This guard exists to prevent accidental writes on real alerts during development; lift it only when the user explicitly switches to action mode for a production run.

**For first runs (starting fresh):** always run step by step — after each stage completes, summarise what it produced, proactively suggest alternatives or adjustments based on what you observed, and wait for confirmation before continuing.

At each stage, draw on the options in `references/triage-stages.md` to make concrete suggestions:

- **After fetching alerts** — suggest filter adjustments if the set looks too broad or narrow: `NOT_ACKNOWLEDGED` to skip already-triaged alerts, domain/audience filters if alerts span multiple teams, a slightly longer time window for the initial testing if we need more examples to work with.
- **After scoring** — Suggest whether to adjust the troubleshooting filter (e.g. run when either score is HIGH, not just both MEDIUM+) or tune `alert_assessment` via `user_instructions`.
- **After troubleshooting** — if the TSA found a clear root cause, suggest whether to declare an incident severity, assign an owner.
- **After actions** — note cases where the default action mapping may not fit, e.g. a verified incident that warrants a Slack message or ticket rather than just a status update.

**For existing-file runs:** use whichever mode the user chose in Step 2.

### Step 4: Wrap up

After the workflow completes:

1. Ask: **"Want me to save a copy of our workflow to your project (e.g. `triage.md`) so you can customise it?"** If yes, write it to the path they choose.

2. Then present next steps based on what just happened and what you were asked to do in the first place.  For example:

   > "What would you like to do next?
   > - **Refine the workflow** — walk through the stages and tune what's not working (filter, scoring weights, troubleshooting threshold, action mapping)
   > - **Test on a different alert set** — re-run on a different time window or day to see how it handles a different set of alerts
   > - **Set up a schedule** — automate this to run on a fixed cadence using the `/schedule` skill
   > - **Something else** — just tell me"

   Adapt the options to context — if the run had many LOW-scoring alerts with no troubleshooting, lean towards refinement; if results looked solid, lean towards scheduling.

## Limitations

- Use this skill only when the task clearly matches its upstream source and local project context.
- Verify commands, generated code, dependencies, credentials, and external service behavior before applying changes.
- Do not treat examples as a substitute for environment-specific tests, security review, or user approval for destructive or costly actions.


---
name: autonomous-agent-patterns
description: "Design patterns for building autonomous coding agents, inspired by [Cline](https://github.com/cline/cline) and [OpenAI Codex](https://github.com/openai/codex)."
risk: critical
source: community
date_added: "2026-02-27"
---

# 🕹 Autonomous Agent Patterns

> Design patterns for building autonomous coding agents, inspired by [Cline](https://github.com/cline/cline) and [OpenAI Codex](https://github.com/openai/codex).

## When to Use This Skill

Use this skill when:

- Building autonomous AI agents
- Designing tool/function calling APIs
- Implementing permission and approval systems
- Creating browser automation for agents
- Designing human-in-the-loop workflows

---

## 1. Core Agent Architecture

### 1.1 Agent Loop

```
┌─────────────────────────────────────────────────────────────┐
│                     AGENT LOOP                               │
│                                                              │
│  ┌──────────┐    ┌──────────┐    ┌──────────┐              │
│  │  Think   │───▶│  Decide  │───▶│   Act    │              │
│  │ (Reason) │    │ (Plan)   │    │ (Execute)│              │
│  └──────────┘    └──────────┘    └──────────┘              │
│       ▲                               │                     │
│       │         ┌──────────┐          │                     │
│       └─────────│ Observe  │◀─────────┘                     │
│                 │ (Result) │                                │
│                 └──────────┘                                │
└─────────────────────────────────────────────────────────────┘
```

```python
class AgentLoop:
    def __init__(self, llm, tools, max_iterations=50):
        self.llm = llm
        self.tools = {t.name: t for t in tools}
        self.max_iterations = max_iterations
        self.history = []

    def run(self, task: str) -> str:
        self.history.append({"role": "user", "content": task})

        for i in range(self.max_iterations):
            # Think: Get LLM response with tool options
            response = self.llm.chat(
                messages=self.history,
                tools=self._format_tools(),
                tool_choice="auto"
            )

            # Decide: Check if agent wants to use a tool
            if response.tool_calls:
                for tool_call in response.tool_calls:
                    # Act: Execute the tool
                    result = self._execute_tool(tool_call)

                    # Observe: Add result to history
                    self.history.append({
                        "role": "tool",
                        "tool_call_id": tool_call.id,
                        "content": str(result)
                    })
            else:
                # No more tool calls = task complete
                return response.content

        return "Max iterations reached"

    def _execute_tool(self, tool_call) -> Any:
        tool = self.tools[tool_call.name]
        args = json.loads(tool_call.arguments)
        return tool.execute(**args)
```

### 1.2 Multi-Model Architecture

```python
class MultiModelAgent:
    """
    Use different models for different purposes:
    - Fast model for planning
    - Powerful model for complex reasoning
    - Specialized model for code generation
    """

    def __init__(self):
        self.models = {
            "fast": "gpt-3.5-turbo",      # Quick decisions
            "smart": "gpt-4-turbo",        # Complex reasoning
            "code": "claude-3-sonnet",     # Code generation
        }

    def select_model(self, task_type: str) -> str:
        if task_type == "planning":
            return self.models["fast"]
        elif task_type == "analysis":
            return self.models["smart"]
        elif task_type == "code":
            return self.models["code"]
        return self.models["smart"]
```

---

## 2. Tool Design Patterns

### 2.1 Tool Schema

```python
class Tool:
    """Base class for agent tools"""

    @property
    def schema(self) -> dict:
        """JSON Schema for the tool"""
        return {
            "name": self.name,
            "description": self.description,
            "parameters": {
                "type": "object",
                "properties": self._get_parameters(),
                "required": self._get_required()
            }
        }

    def execute(self, **kwargs) -> ToolResult:
        """Execute the tool and return result"""
        raise NotImplementedError

class ReadFileTool(Tool):
    name = "read_file"
    description = "Read the contents of a file from the filesystem"

    def _get_parameters(self):
        return {
            "path": {
                "type": "string",
                "description": "Absolute path to the file"
            },
            "start_line": {
                "type": "integer",
                "description": "Line to start reading from (1-indexed)"
            },
            "end_line": {
                "type": "integer",
                "description": "Line to stop reading at (inclusive)"
            }
        }

    def _get_required(self):
        return ["path"]

    def execute(self, path: str, start_line: int = None, end_line: int = None) -> ToolResult:
        try:
            with open(path, 'r') as f:
                lines = f.readlines()

            if start_line and end_line:
                lines = lines[start_line-1:end_line]

            return ToolResult(
                success=True,
                output="".join(lines)
            )
        except FileNotFoundError:
            return ToolResult(
                success=False,
                error=f"File not found: {path}"
            )
```

### 2.2 Essential Agent Tools

```python
CODING_AGENT_TOOLS = {
    # File operations
    "read_file": "Read file contents",
    "write_file": "Create or overwrite a file",
    "edit_file": "Make targeted edits to a file",
    "list_directory": "List files and folders",
    "search_files": "Search for files by pattern",

    # Code understanding
    "search_code": "Search for code patterns (grep)",
    "get_definition": "Find function/class definition",
    "get_references": "Find all references to a symbol",

    # Terminal
    "run_command": "Execute a shell command",
    "read_output": "Read command output",
    "send_input": "Send input to running command",

    # Browser (optional)
    "open_browser": "Open URL in browser",
    "click_element": "Click on page element",
    "type_text": "Type text into input",
    "screenshot": "Capture screenshot",

    # Context
    "ask_user": "Ask the user a question",
    "search_web": "Search the web for information"
}
```

### 2.3 Edit Tool Design

```python
class EditFileTool(Tool):
    """
    Precise file editing with conflict detection.
    Uses search/replace pattern for reliable edits.
    """

    name = "edit_file"
    description = "Edit a file by replacing specific content"

    def execute(
        self,
        path: str,
        search: str,
        replace: str,
        expected_occurrences: int = 1
    ) -> ToolResult:
        """
        Args:
            path: File to edit
            search: Exact text to find (must match exactly, including whitespace)
            replace: Text to replace with
            expected_occurrences: How many times search should appear (validation)
        """
        with open(path, 'r') as f:
            content = f.read()

        # Validate
        actual_occurrences = content.count(search)
        if actual_occurrences != expected_occurrences:
            return ToolResult(
                success=False,
                error=f"Expected {expected_occurrences} occurrences, found {actual_occurrences}"
            )

        if actual_occurrences == 0:
            return ToolResult(
                success=False,
                error="Search text not found in file"
            )

        # Apply edit
        new_content = content.replace(search, replace)

        with open(path, 'w') as f:
            f.write(new_content)

        return ToolResult(
            success=True,
            output=f"Replaced {actual_occurrences} occurrence(s)"
        )
```

---

## 3. Permission & Safety Patterns

### 3.1 Permission Levels

```python
class PermissionLevel(Enum):
    # Fully automatic - no user approval needed
    AUTO = "auto"

    # Ask once per session
    ASK_ONCE = "ask_once"

    # Ask every time
    ASK_EACH = "ask_each"

    # Never allow
    NEVER = "never"

PERMISSION_CONFIG = {
    # Low risk - can auto-approve
    "read_file": PermissionLevel.AUTO,
    "list_directory": PermissionLevel.AUTO,
    "search_code": PermissionLevel.AUTO,

    # Medium risk - ask once
    "write_file": PermissionLevel.ASK_ONCE,
    "edit_file": PermissionLevel.ASK_ONCE,

    # High risk - ask each time
    "run_command": PermissionLevel.ASK_EACH,
    "delete_file": PermissionLevel.ASK_EACH,

    # Dangerous - never auto-approve
    "sudo_command": PermissionLevel.NEVER,
    "format_disk": PermissionLevel.NEVER
}
```

### 3.2 Approval UI Pattern

```python
class ApprovalManager:
    def __init__(self, ui, config):
        self.ui = ui
        self.config = config
        self.session_approvals = {}

    def request_approval(self, tool_name: str, args: dict) -> bool:
        level = self.config.get(tool_name, PermissionLevel.ASK_EACH)

        if level == PermissionLevel.AUTO:
            return True

        if level == PermissionLevel.NEVER:
            self.ui.show_error(f"Tool '{tool_name}' is not allowed")
            return False

        if level == PermissionLevel.ASK_ONCE:
            if tool_name in self.session_approvals:
                return self.session_approvals[tool_name]

        # Show approval dialog
        approved = self.ui.show_approval_dialog(
            tool=tool_name,
            args=args,
            risk_level=self._assess_risk(tool_name, args)
        )

        if level == PermissionLevel.ASK_ONCE:
            self.session_approvals[tool_name] = approved

        return approved

    def _assess_risk(self, tool_name: str, args: dict) -> str:
        """Analyze specific call for risk level"""
        if tool_name == "run_command":
            cmd = args.get("command", "")
            if any(danger in cmd for danger in ["rm -rf", "sudo", "chmod"]):
                return "HIGH"
        return "MEDIUM"
```

### 3.3 Sandboxing

```python
class SandboxedExecution:
    """
    Execute code/commands in isolated environment
    """

    def __init__(self, workspace_dir: str):
        self.workspace = workspace_dir
        self.allowed_commands = ["npm", "python", "node", "git", "ls", "cat"]
        self.blocked_paths = ["/etc", "/usr", "/bin", os.path.expanduser("~")]

    def validate_path(self, path: str) -> bool:
        """Ensure path is within workspace"""
        real_path = os.path.realpath(path)
        workspace_real = os.path.realpath(self.workspace)
        return real_path.startswith(workspace_real)

    def validate_command(self, command: str) -> bool:
        """Check if command is allowed"""
        cmd_parts = shlex.split(command)
        if not cmd_parts:
            return False

        base_cmd = cmd_parts[0]
        return base_cmd in self.allowed_commands

    def execute_sandboxed(self, command: str) -> ToolResult:
        if not self.validate_command(command):
            return ToolResult(
                success=False,
                error=f"Command not allowed: {command}"
            )

        # Execute in isolated environment
        result = subprocess.run(
            command,
            shell=True,
            cwd=self.workspace,
            capture_output=True,
            timeout=30,
            env={
                **os.environ,
                "HOME": self.workspace,  # Isolate home directory
            }
        )

        return ToolResult(
            success=result.returncode == 0,
            output=result.stdout.decode(),
            error=result.stderr.decode() if result.returncode != 0 else None
        )
```

---

## 4. Browser Automation

### 4.1 Browser Tool Pattern

```python
class BrowserTool:
    """
    Browser automation for agents using Playwright/Puppeteer.
    Enables visual debugging and web testing.
    """

    def __init__(self, headless: bool = True):
        self.browser = None
        self.page = None
        self.headless = headless

    async def open_url(self, url: str) -> ToolResult:
        """Navigate to URL and return page info"""
        if not self.browser:
            self.browser = await playwright.chromium.launch(headless=self.headless)
            self.page = await self.browser.new_page()

        await self.page.goto(url)

        # Capture state
        screenshot = await self.page.screenshot(type='png')
        title = await self.page.title()

        return ToolResult(
            success=True,
            output=f"Loaded: {title}",
            metadata={
                "screenshot": base64.b64encode(screenshot).decode(),
                "url": self.page.url
            }
        )

    async def click(self, selector: str) -> ToolResult:
        """Click on an element"""
        try:
            await self.page.click(selector, timeout=5000)
            await self.page.wait_for_load_state("networkidle")

            screenshot = await self.page.screenshot()
            return ToolResult(
                success=True,
                output=f"Clicked: {selector}",
                metadata={"screenshot": base64.b64encode(screenshot).decode()}
            )
        except TimeoutError:
            return ToolResult(
                success=False,
                error=f"Element not found: {selector}"
            )

    async def type_text(self, selector: str, text: str) -> ToolResult:
        """Type text into an input"""
        await self.page.fill(selector, text)
        return ToolResult(success=True, output=f"Typed into {selector}")

    async def get_page_content(self) -> ToolResult:
        """Get accessible text content of the page"""
        content = await self.page.evaluate("""
            () => {
                // Get visible text
                const walker = document.createTreeWalker(
                    document.body,
                    NodeFilter.SHOW_TEXT,
                    null,
                    false
                );

                let text = '';
                while (walker.nextNode()) {
                    const node = walker.currentNode;
                    if (node.textContent.trim()) {
                        text += node.textContent.trim() + '\\n';
                    }
                }
                return text;
            }
        """)
        return ToolResult(success=True, output=content)
```

### 4.2 Visual Agent Pattern

```python
class VisualAgent:
    """
    Agent that uses screenshots to understand web pages.
    Can identify elements visually without selectors.
    """

    def __init__(self, llm, browser):
        self.llm = llm
        self.browser = browser

    async def describe_page(self) -> str:
        """Use vision model to describe current page"""
        screenshot = await self.browser.screenshot()

        response = self.llm.chat([
            {
                "role": "user",
                "content": [
                    {"type": "text", "text": "Describe this webpage. List all interactive elements you see."},
                    {"type": "image", "data": screenshot}
                ]
            }
        ])

        return response.content

    async def find_and_click(self, description: str) -> ToolResult:
        """Find element by visual description and click it"""
        screenshot = await self.browser.screenshot()

        # Ask vision model to find element
        response = self.llm.chat([
            {
                "role": "user",
                "content": [
                    {
                        "type": "text",
                        "text": f"""
                        Find the element matching: "{description}"
                        Return the approximate coordinates as JSON: {{"x": number, "y": number}}
                        """
                    },
                    {"type": "image", "data": screenshot}
                ]
            }
        ])

        coords = json.loads(response.content)
        await self.browser.page.mouse.click(coords["x"], coords["y"])

        return ToolResult(success=True, output=f"Clicked at ({coords['x']}, {coords['y']})")
```

---

## 5. Context Management

### 5.1 Context Injection Patterns

````python
class ContextManager:
    """
    Manage context provided to the agent.
    Inspired by Cline's @-mention patterns.
    """

    def __init__(self, workspace: str):
        self.workspace = workspace
        self.context = []

    def add_file(self, path: str) -> None:
        """@file - Add file contents to context"""
        with open(path, 'r') as f:
            content = f.read()

        self.context.append({
            "type": "file",
            "path": path,
            "content": content
        })

    def add_folder(self, path: str, max_files: int = 20) -> None:
        """@folder - Add all files in folder"""
        for root, dirs, files in os.walk(path):
            for file in files[:max_files]:
                file_path = os.path.join(root, file)
                self.add_file(file_path)

    def add_url(self, url: str) -> None:
        """@url - Fetch and add URL content"""
        response = requests.get(url)
        content = html_to_markdown(response.text)

        self.context.append({
            "type": "url",
            "url": url,
            "content": content
        })

    def add_problems(self, diagnostics: list) -> None:
        """@problems - Add IDE diagnostics"""
        self.context.append({
            "type": "diagnostics",
            "problems": diagnostics
        })

    def format_for_prompt(self) -> str:
        """Format all context for LLM prompt"""
        parts = []
        for item in self.context:
            if item["type"] == "file":
                parts.append(f"## File: {item['path']}\n```\n{item['content']}\n```")
            elif item["type"] == "url":
                parts.append(f"## URL: {item['url']}\n{item['content']}")
            elif item["type"] == "diagnostics":
                parts.append(f"## Problems:\n{json.dumps(item['problems'], indent=2)}")

        return "\n\n".join(parts)
````

### 5.2 Checkpoint/Resume

```python
class CheckpointManager:
    """
    Save and restore agent state for long-running tasks.
    """

    def __init__(self, storage_dir: str):
        self.storage_dir = storage_dir
        os.makedirs(storage_dir, exist_ok=True)

    def save_checkpoint(self, session_id: str, state: dict) -> str:
        """Save current agent state"""
        checkpoint = {
            "timestamp": datetime.now().isoformat(),
            "session_id": session_id,
            "history": state["history"],
            "context": state["context"],
            "workspace_state": self._capture_workspace(state["workspace"]),
            "metadata": state.get("metadata", {})
        }

        path = os.path.join(self.storage_dir, f"{session_id}.json")
        with open(path, 'w') as f:
            json.dump(checkpoint, f, indent=2)

        return path

    def restore_checkpoint(self, checkpoint_path: str) -> dict:
        """Restore agent state from checkpoint"""
        with open(checkpoint_path, 'r') as f:
            checkpoint = json.load(f)

        return {
            "history": checkpoint["history"],
            "context": checkpoint["context"],
            "workspace": self._restore_workspace(checkpoint["workspace_state"]),
            "metadata": checkpoint["metadata"]
        }

    def _capture_workspace(self, workspace: str) -> dict:
        """Capture relevant workspace state"""
        # Git status, file hashes, etc.
        return {
            "git_ref": subprocess.getoutput(f"cd {workspace} && git rev-parse HEAD"),
            "git_dirty": subprocess.getoutput(f"cd {workspace} && git status --porcelain")
        }
```

---

## 6. MCP (Model Context Protocol) Integration

### 6.1 MCP Server Pattern

```python
from mcp import Server, Tool

class MCPAgent:
    """
    Agent that can dynamically discover and use MCP tools.
    'Add a tool that...' pattern from Cline.
    """

    def __init__(self, llm):
        self.llm = llm
        self.mcp_servers = {}
        self.available_tools = {}

    def connect_server(self, name: str, config: dict) -> None:
        """Connect to an MCP server"""
        server = Server(config)
        self.mcp_servers[name] = server

        # Discover tools
        tools = server.list_tools()
        for tool in tools:
            self.available_tools[tool.name] = {
                "server": name,
                "schema": tool.schema
            }

    async def create_tool(self, description: str) -> str:
        """
        Create a new MCP server based on user description.
        'Add a tool that fetches Jira tickets'
        """
        # Generate MCP server code
        code = self.llm.generate(f"""
        Create a Python MCP server with a tool that does:
        {description}

        Use the FastMCP framework. Include proper error handling.
        Return only the Python code.
        """)

        # Save and install
        server_name = self._extract_name(description)
        path = f"./mcp_servers/{server_name}/server.py"

        with open(path, 'w') as f:
            f.write(code)

        # Hot-reload
        self.connect_server(server_name, {"path": path})

        return f"Created tool: {server_name}"
```

---

## Best Practices Checklist

### Agent Design

- [ ] Clear task decomposition
- [ ] Appropriate tool granularity
- [ ] Error handling at each step
- [ ] Progress visibility to user

### Safety

- [ ] Permission system implemented
- [ ] Dangerous operations blocked
- [ ] Sandbox for untrusted code
- [ ] Audit logging enabled

### UX

- [ ] Approval UI is clear
- [ ] Progress updates provided
- [ ] Undo/rollback available
- [ ] Explanation of actions

---

## Resources

- [Cline](https://github.com/cline/cline)
- [OpenAI Codex](https://github.com/openai/codex)
- [Model Context Protocol](https://modelcontextprotocol.io/)
- [Anthropic Tool Use](https://docs.anthropic.com/claude/docs/tool-use)

## 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.