# Technical Documentation: midudev/autoskills

> ℹ️ **Provenance:** Multi-Tier Ingestion · [CodeWiki Reference](https://codewiki.google/github.com/midudev/autoskills)

### Overview (`README.md`)

<div align="center">

<a href="https://autoskills.sh">
<img src="https://autoskills.sh/og.jpg" alt="autoskills" />
</a>

# autoskills

**One command. Your entire AI skill stack. Installed.**

[autoskills.sh](https://autoskills.sh)

</div>

Scans your project, detects your tech stack, and installs curated AI agent skills automatically.

```bash
npx autoskills
```

## How it works

1. Run `npx autoskills` in your project root
2. Your `package.json`, Gradle files, and config files are scanned to detect technologies
3. The best matching AI agent skills are selected from the audited autoskills registry
4. Only the selected skill files are downloaded from the registry and verified before writing them locally

That's it. No config needed.

## Security model

`autoskills` does not install directly from random upstream repositories at runtime.

Skills are synced by maintainers into the repository-local autoskills registry, reviewed by AI for prompt-injection and supply-chain attacks (a fast model triages every change and a stronger one decides on anything suspicious), and recorded with SHA-256 hashes in a manifest. Skills that are safe but worth a heads-up are shown with a security warning before you install them. When you run `autoskills`, the CLI downloads only the skills your project needs from that curated registry, verifies every file against the manifest, and writes a `skills-lock.json` entry with the installed source and bundle hash.

This keeps the package small while avoiding live downloads from third-party skill sources during installation.

## Options

```
-y, --yes       Skip confirmation prompt
--dry-run       Show what would be installed without installing
--clear-cache   Clear the downloaded skills cache
-a, --agent     Install for specific IDEs only (e.g. cursor claude-code)
-v, --verbose   Show install trace and error details
-h, --help      Show help message
```

Run `npx autoskills ui` to browse the skills installed in your project in a local web desk.

## Supported Technologies

Built to work across modern frontend, backend, mobile, cloud, and media stacks.

- **Frameworks & UI:** React, Next.js, Vue, Nuxt, Svelte, Angular, Astro, Tailwind CSS, shadcn/ui, GSAP, Three.js
- **Languages & Runtimes:** TypeScript, Node.js, Go, Bun, Dart
- **Backend & APIs:** Express, Hono, NestJS, Spring Boot
- **Mobile & Desktop:** Expo, React Native, Flutter, SwiftUI, Android, Kotlin Multiplatform, Tauri, Electron
- **Data & Storage:** Supabase, Neon, Prisma, Drizzle ORM, Zod, React Hook Form
- **Auth & Billing:** Better Auth, Clerk, Stripe
- **Testing:** Vitest, Playwright
- **Cloud & Infrastructure:** Vercel, Vercel AI SDK, Cloudflare, Durable Objects, Cloudflare Agents, Cloudflare AI, AWS, Azure, Terraform
- **Tooling:** Turborepo, Vite, oxlint
- **Media & AI:** Remotion, ElevenLabs

## Requirements

Node.js >= 22.6

## License

[CC BY-NC 4.0](./LICENSE) — [midudev](https://midu.dev)

---

### Overview (`packages/autoskills/README.md`)

# autoskills

Auto-detect and install the best AI agent skills for your project. One command, zero config.

```bash
npx autoskills
```

`autoskills` scans your project, detects the technologies you use, and installs curated [AI agent skills](https://skills.sh) that make Cursor, Claude Code, and other AI coding assistants actually understand your stack.

## Quick Start

Run it in your project root:

```bash
npx autoskills
```

That's it. It will:

1. **Scan** your `package.json`, config files, and project structure
2. **Detect** every technology in your stack
3. **Show** an interactive selector with the best skills for your project
4. **Install** them in parallel with live progress
5. **Generate `CLAUDE.md` automatically** when Claude Code is one of the target agents

### Skip the prompt

```bash
npx autoskills -y
```

### Preview without installing

```bash
npx autoskills --dry-run
```

### Browse installed skills

```bash
npx autoskills ui
```

Opens a local desk (bound to `127.0.0.1`) to browse the skills installed in the current project.

### Claude Code summary

If `claude-code` is auto-detected or passed with `-a`, `autoskills` writes a `CLAUDE.md` file in your project root summarizing the markdown files installed under `.claude/skills`.

## Options

| Flag              | Description                                                |
| ----------------- | ---------------------------------------------------------- |
| `-y`, `--yes`     | Skip confirmation prompt, install all detected skills      |
| `--dry-run`       | Show detected skills without installing anything           |
| `--clear-cache`   | Clear the downloaded skills cache                          |
| `-a`, `--agent`   | Install for specific IDEs only (e.g. `cursor claude-code`) |
| `-v`, `--verbose` | Show install trace and error details                       |
| `-h`, `--help`    | Show help message                                          |

`autoskills ui` also accepts `--port <number>` and `--no-open`.

## Supported Technologies

`autoskills` detects **50+ technologies** from your `package.json`, lockfiles, Gradle files, and config files:

### Frameworks & Libraries

| Technology           | Detected from                                                                                                                                     |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| React                | `react`, `react-dom` packages                                                                                                                     |
| Next.js              | `next` package or `next.config.*`                                                                                                                 |
| Vue                  | `vue` package                                                                                                                                     |
| Nuxt                 | `nuxt` package or `nuxt.config.*`                                                                                                                 |
| Svelte               | `svelte`, `@sveltejs/kit` or `svelte.config.js`                                                                                                   |
| Angular              | `@angular/core` or `angular.json`                                                                                                                 |
| Astro                | `astro` package or `astro.config.*`                                                                                                               |
| Expo                 | `expo` package                                                                                                                                    |
| React Native         | `react-native` package                                                                                                                            |
| Flutter              | `pubspec.yaml` file with `flutter:` key                                                                                                           |
| Kotlin Multiplatform | Gradle with KMP plugin: `kotlin("multiplatform")`, `org.jetbrains.kotlin.multiplatform`, or `kotlin-multiplatform` in `gradle/libs.versions.toml` |
| Android              | Gradle with `com.android.application`, `com.android.library`, or `com.android.kotlin.multiplatform.library`                                       |
| Remotion             | `remotion`, `@remotion/cli`                                                                                                                       |
| GSAP                 | `gsap` package                                                                                                                                    |
| Three.js             | `three`, `@react-three/fiber`, `@react-three/drei`                                                                                                |
| Express              | `express` package                                                                                                                                 |
| Hono                 | `hono` package                                                                                                                                    |
| NestJS               | `@nestjs/core` package                                                                                                                            |
| Spring Boot          | Gradle with `spring-boot-starter` or `org.springframework.boot`                                                                                   |
| ASP.NET Core         | `.csproj` file with `Microsoft.NET.Sdk.Web`                                                                                                       |
| Blazor               | `.csproj` with `Microsoft.NET.Sdk.BlazorWebAssembly` or `Microsoft.AspNetCore.Components`                                                         |
| ASP.NET Minimal API  | `.csproj` with `Microsoft.AspNetCore.OpenApi` or `Swashbuckle.AspNetCore`                                                                         |

### Styling & UI

| Technology   | Detected from                                             |
| ------------ | --------------------------------------------------------- |
| Tailwind CSS | `tailwindcss`, `@tailwindcss/vite` or `tailwind.config.*` |
| shadcn/ui    | `components.json`                                         |

### Runtimes & Tooling

| Technology | Detected from                                                |
| ---------- | ------------------------------------------------------------ |
| TypeScript | `typescript` package or `tsconfig.json`                      |
| Node.js    | `package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`, `.nvmrc` |
| Bun        | `bun.lockb`, `bun.lock`, `bunfig.toml`                       |
| Dart       | `pubspec.yaml`                                               |
| Go         | `go.mod`, `go.work`                                          |
| Vite       | `vite` package or `vite.config.*`                            |
| Turborepo  | `turbo` package or `turbo.json`                              |
| Vitest     | `vitest` package or `vitest.config.*`                        |
| oxlint     | `oxlint` package or `.oxlintrc.json`                         |
| .NET       | `global.json`, `NuGet.Config`, `*.csproj`, `*.sln`           |
| C#         | `*.csproj`, `*.sln`                                          |

### Backend & Data

| Technology      | Detected from                                            |
| --------------- | -------------------------------------------------------- |
| Supabase        | `@supabase/supabase-js`, `@supabase/ssr`                 |
| Zod             | `zod` package                                            |
| React Hook Form | `react-hook-form` package                                |
| Neon Postgres   | `@neondatabase/serverless`                               |
| Prisma          | `prisma`, `@prisma/client`                               |
| Drizzle ORM     | `drizzle-orm`, `drizzle-kit`                             |
| Stripe          | `stripe`, `@stripe/stripe-js`, `@stripe/react-stripe-js` |
| Better Auth     | `better-auth` package                                    |

### Authentication

| Technology | Detected from                                                                                                         |
| ---------- | --------------------------------------------------------------------------------------------------------------------- |
| Clerk      | `@clerk/nextjs`, `@clerk/react`, `@clerk/expo`, `@clerk/astro`, `@clerk/remix`, `@clerk/vue`, or any `@clerk/*` scope |

### Cloud & Deploy

| Technology        | Detected from                                        |
| ----------------- | ---------------------------------------------------- |
| Vercel            | `vercel.json`, `.vercel/`, `@astrojs/vercel`         |
| Cloudflare        | `wrangler`, `wrangler.toml`, `@astrojs/cloudflare`   |
| Cloudflare Agents | `agents` package                                     |
| Cloudflare AI     | `@cloudflare/ai` or AI binding in `wrangler.json`    |
| Durable Objects   | `durable_objects` in `wrangler.json`/`wrangler.toml` |
| Azure             | `@azure/*` packages                                  |
| AWS               | `@aws-sdk/*`, `aws-cdk*` packages                    |

### AI

| Technology    | Detected from                                                 |
| ------------- | ------------------------------------------------------------- |
| Vercel AI SDK | `ai`, `@ai-sdk/openai`, `@ai-sdk/anthropic`, `@ai-sdk/google` |
| ElevenLabs    | `elevenlabs` package                                          |

### Other

| Technology | Detected from                                                                               |
| ---------- | ------------------------------------------------------------------------------------------- |
| Playwright | `@playwright/test`, `playwright` or `playwright.config.*`                                   |
| SwiftUI    | `Package.swift`                                                                             |
| WordPress  | `wp-config.php`, `@wordpress/*`, `composer.json` with wpackagist, theme `style.css`         |
| Tauri      | `@tauri-apps/api`, `@tauri-apps/cli` or `src-tauri/tauri.conf.json`                         |
| Electron   | `electron` package, `electron-builder.yml`, `forge.config.js`, or `electron-vite.config.ts` |

### Web Frontend Detection

Even without a framework, `autoskills` scans your file tree for web frontend signals (`.html`, `.css`, `.scss`, `.vue`, `.svelte`, `.jsx`, `.tsx`, `.twig`, `.blade.php`, etc.) and installs skills for frontend design, accessibility, and SEO.

## Combo Detection

When multiple technologies are used together, `autoskills` detects **technology combos** and adds specialized skills for the combination:

- **Next.js + Supabase** — Supabase Postgres best practices for Next.js
- **Next.js + Vercel AI SDK** — AI SDK patterns with Next.js
- **Next.js + Playwright** — E2E testing best practices for Next.js
- **React + shadcn/ui** — shadcn component patterns with React
- **Tailwind CSS + shadcn/ui** — Tailwind v4 + shadcn integration
- **React Native + Expo** — Native UI patterns
- **React Hook Form + Zod** — Form validation patterns with Zod schemas
- **GSAP + React** — GSAP animation patterns in React
- **Cloudflare + Vite** — Vinext migration guide
- **Node.js + Express** — Express server patterns

## How It Works

Skills are markdown files that teach AI assistants how to work with specific technologies, following best practices and patterns from the official maintainers. `autoskills` installs them from its own curated registry: maintainers sync them from their upstream repositories (the ones listed on [skills.sh](https://skills.sh)), an AI security review blocks anything that attacks the user or plants a serious vulnerability, and every file is recorded with a SHA-256 hash that the CLI verifies before writing it.

The detection runs entirely locally with zero network requests until installation begins.

## Requirements

- Node.js >= 22.6.0

## License

CC-BY-NC-4.0 — Created by [@midudev](https://github.com/midudev)

---

### Overview (`packages/autoskills/skills-registry/composition-patterns/README.md`)

# React Composition Patterns

A structured repository for React composition patterns that scale. These
patterns help avoid boolean prop proliferation by using compound components,
lifting state, and composing internals.

## Structure

- `rules/` - Individual rule files (one per rule)
  - `_sections.md` - Section metadata (titles, impacts, descriptions)
  - `_template.md` - Template for creating new rules
  - `area-description.md` - Individual rule files
- `metadata.json` - Document metadata (version, organization, abstract)
- **`AGENTS.md`** - Compiled output (generated)

## Rules

### Component Architecture (CRITICAL)

- `architecture-avoid-boolean-props.md` - Don't add boolean props to customize
  behavior
- `architecture-compound-components.md` - Structure as compound components with
  shared context

### State Management (HIGH)

- `state-lift-state.md` - Lift state into provider components
- `state-context-interface.md` - Define clear context interfaces
  (state/actions/meta)
- `state-decouple-implementation.md` - Decouple state management from UI

### Implementation Patterns (MEDIUM)

- `patterns-children-over-render-props.md` - Prefer children over renderX props
- `patterns-explicit-variants.md` - Create explicit component variants

## Core Principles

1. **Composition over configuration** — Instead of adding props, let consumers
   compose
2. **Lift your state** — State in providers, not trapped in components
3. **Compose your internals** — Subcomponents access context, not props
4. **Explicit variants** — Create ThreadComposer, EditComposer, not Composer
   with isThread

## Creating a New Rule

1. Copy `rules/_template.md` to `rules/area-description.md`
2. Choose the appropriate area prefix:
   - `architecture-` for Component Architecture
   - `state-` for State Management
   - `patterns-` for Implementation Patterns
3. Fill in the frontmatter and content
4. Ensure you have clear examples with explanations

## Impact Levels

- `CRITICAL` - Foundational patterns, prevents unmaintainable code
- `HIGH` - Significant maintainability improvements
- `MEDIUM` - Good practices for cleaner code

---

### Overview (`packages/autoskills/skills-registry/react-best-practices/README.md`)

# React Best Practices

A structured repository for creating and maintaining React Best Practices optimized for agents and LLMs.

## Structure

- `rules/` - Individual rule files (one per rule)
  - `_sections.md` - Section metadata (titles, impacts, descriptions)
  - `_template.md` - Template for creating new rules
  - `area-description.md` - Individual rule files
- `src/` - Build scripts and utilities
- `metadata.json` - Document metadata (version, organization, abstract)
- __`AGENTS.md`__ - Compiled output (generated)
- __`test-cases.json`__ - Test cases for LLM evaluation (generated)

## Getting Started

1. Install dependencies:
   ```bash
   pnpm install
   ```

2. Build AGENTS.md from rules:
   ```bash
   pnpm build
   ```

3. Validate rule files:
   ```bash
   pnpm validate
   ```

4. Extract test cases:
   ```bash
   pnpm extract-tests
   ```

## Creating a New Rule

1. Copy `rules/_template.md` to `rules/area-description.md`
2. Choose the appropriate area prefix:
   - `async-` for Eliminating Waterfalls (Section 1)
   - `bundle-` for Bundle Size Optimization (Section 2)
   - `server-` for Server-Side Performance (Section 3)
   - `client-` for Client-Side Data Fetching (Section 4)
   - `rerender-` for Re-render Optimization (Section 5)
   - `rendering-` for Rendering Performance (Section 6)
   - `js-` for JavaScript Performance (Section 7)
   - `advanced-` for Advanced Patterns (Section 8)
3. Fill in the frontmatter and content
4. Ensure you have clear examples with explanations
5. Run `pnpm build` to regenerate AGENTS.md and test-cases.json

## Rule File Structure

Each rule file should follow this structure:

```markdown
---
title: Rule Title Here
impact: MEDIUM
impactDescription: Optional description
tags: tag1, tag2, tag3
---

## Rule Title Here

Brief explanation of the rule and why it matters.

**Incorrect (description of what's wrong):**

```typescript
// Bad code example
```

**Correct (description of what's right):**

```typescript
// Good code example
```

Optional explanatory text after examples.

Reference: [Link](https://example.com)

## File Naming Convention

- Files starting with `_` are special (excluded from build)
- Rule files: `area-description.md` (e.g., `async-parallel.md`)
- Section is automatically inferred from filename prefix
- Rules are sorted alphabetically by title within each section
- IDs (e.g., 1.1, 1.2) are auto-generated during build

## Impact Levels

- `CRITICAL` - Highest priority, major performance gains
- `HIGH` - Significant performance improvements
- `MEDIUM-HIGH` - Moderate-high gains
- `MEDIUM` - Moderate performance improvements
- `LOW-MEDIUM` - Low-medium gains
- `LOW` - Incremental improvements

## Scripts

- `pnpm build` - Compile rules into AGENTS.md
- `pnpm validate` - Validate all rule files
- `pnpm extract-tests` - Extract test cases for LLM evaluation
- `pnpm dev` - Build and validate

## Contributing

When adding or modifying rules:

1. Use the correct filename prefix for your section
2. Follow the `_template.md` structure
3. Include clear bad/good examples with explanations
4. Add appropriate tags
5. Run `pnpm build` to regenerate AGENTS.md and test-cases.json
6. Rules are automatically sorted by title - no need to manage numbers!

## Acknowledgments

Originally created by [@shuding](https://x.com/shuding) at [Vercel](https://vercel.com).

---

### Overview (`packages/autoskills/skills-registry/react-hook-form/README.md`)

# React Hook Form Best Practices Skill

Corrective guidance for React Hook Form — the decisions that go wrong by default.

## Overview

This skill provides 35 rules across 7 categories. Every rule names a decision that a capable model gets wrong by default; rules that merely restated correct library behaviour were removed in 2.0.0. Verified against **react-hook-form 7.82.0** (July 2026), with every code block type-checked under `tsc --strict` against the real package types.

### Directory Structure

```
react-hook-form/
├── SKILL.md                    # Entry point with quick reference
├── AGENTS.md                   # Compiled comprehensive guide (TOC over references/)
├── metadata.json               # Version, org, references
├── README.md                   # This file
├── assets/
│   └── templates/
│       └── _template.md        # Rule template
└── references/
    ├── _sections.md            # Category definitions and impact ordering
    ├── formcfg-*.md            # Form configuration rules (9)
    ├── sub-*.md                # Field subscription rules (7)
    ├── ctrl-*.md               # Controlled component rules (2)
    ├── valid-*.md              # Validation pattern rules (4)
    ├── formstate-*.md          # State management rules (6)
    ├── array-*.md              # Field array rules (4)
    └── integ-*.md              # Integration pattern rules (3)
```

## Validating

This skill is validated by the repo-level tooling, not by per-skill scripts:

```bash
npm run validate                                     # structural validation of every skill
node /path/to/dev-skill/scripts/validate-skill.js .  # discipline-aware validation of this skill
```

## Creating a New Rule

1. Choose the appropriate category prefix:

| Category | Prefix | Impact |
|----------|--------|--------|
| Form Configuration | `formcfg-` | CRITICAL |
| Field Subscription | `sub-` | CRITICAL |
| Controlled Components | `ctrl-` | HIGH |
| Validation Patterns | `valid-` | HIGH |
| State Management | `formstate-` | MEDIUM-HIGH |
| Field Arrays | `array-` | MEDIUM-HIGH |
| Integration Patterns | `integ-` | MEDIUM |

2. Create a new file: `references/{prefix}-{slug}.md`

3. Use the rule template from `assets/templates/_template.md`

4. Add the rule to the SKILL.md quick reference and to the AGENTS.md table of contents (entries are ordered alphabetically by title within each section).

## Rule File Structure

```markdown
---
title: Rule Title Here
impact: CRITICAL|HIGH|MEDIUM-HIGH|MEDIUM|LOW-MEDIUM|LOW
impactDescription: What the rule prevents or enables
tags: prefix, keyword1, keyword2
---

## Rule Title Here

Brief explanation of WHY this matters (1-3 sentences).

**Incorrect (description of problem):**

\`\`\`typescript
// Bad code with comment on key line
\`\`\`

**Correct (description of solution):**

\`\`\`typescript
// Good code with minimal diff from incorrect
\`\`\`

Reference: [Documentation Link](https://example.com)
```

## File Naming Convention

Rules follow the pattern: `{prefix}-{slug}.md`

- **prefix**: Category identifier from `_sections.md` (lowercase letters only)
- **slug**: Kebab-case description of the rule

Examples:
- `formcfg-validation-mode.md`
- `sub-usewatch-over-watch.md`
- `ctrl-usecontroller-isolation.md`

## Impact Levels

| Level | Description |
|-------|-------------|
| CRITICAL | Cascade effect on entire form performance |
| HIGH | Significant impact on specific operations |
| MEDIUM-HIGH | Notable improvement for common patterns |
| MEDIUM | Measurable improvement in specific scenarios |
| LOW-MEDIUM | Minor optimization for edge cases |
| LOW | Best practice with minimal performance impact |

## Companion Skill

`react-hook-form-audit` is a static-analysis skill that detects violations of these rules in a Next.js App Router codebase and links each finding back to the corresponding file in `references/`.

## Contributing

1. Read existing rules in the same category for style consistency
2. Ensure incorrect/correct examples have minimal diff
3. Typecheck every example against the pinned react-hook-form version before committing
4. Include authoritative reference links
5. Run validation before submitting

## Acknowledgments

Based on official React Hook Form documentation, the library's shipped type definitions, and community best practices.

---

### Overview (`packages/autoskills/skills-registry/tauri-v2/README.md`)

# Tauri v2+ Development Skill

> Build cross-platform desktop and mobile apps with web frontends and Rust backends.

| | |
|---|---|
| **Status** | Active |
| **Version** | 1.0.1 |
| **Last Updated** | 2026-04-02 |
| **Confidence** | 4/5 |
| **Production Tested** | https://v2.tauri.app/ |

## What This Skill Does

Provides expert assistance for Tauri v2 application development, covering the full development lifecycle from project setup to cross-platform deployment. Specializes in Rust backend commands, IPC patterns, security configuration, and frontend-backend communication.

### Core Capabilities

- Implement Rust commands with `#[tauri::command]` and proper error handling
- Configure IPC patterns (invoke, events, channels) for frontend-backend communication
- Set up security capabilities and permissions for plugins and APIs
- Access exhaustive reference docs for plugins (fs, dialog, shell, store, etc.), updater/distribution signing, and advanced runtime (tray, sidecars, deep links)
- Build and deploy for desktop (macOS, Windows, Linux) and mobile (iOS, Android)
- Integrate Vite + TanStack Router frontends with Tauri backends
- Configure tauri.conf.json and Cargo.toml for cross-platform builds

## Auto-Trigger Keywords

### Primary Keywords
Exact terms that strongly trigger this skill:
- tauri
- tauri v2
- tauri.conf.json
- src-tauri
- #[tauri::command]
- tauri::invoke
- capabilities.json

### Secondary Keywords
Related terms that may trigger in combination:
- rust backend
- desktop app
- cross-platform app
- webview
- invoke command
- emit event
- app permissions
- bundle desktop

### Error-Based Keywords
Common error messages that should trigger this skill:
- "Command not found"
- "Permission denied" (in Tauri context)
- "Failed to invoke command"
- "Missing capability"
- "Cannot read property of undefined" (invoke result)
- "tauri build failed"
- "Missing Rust target"

## Known Issues Prevention

| Issue | Root Cause | Solution |
|-------|-----------|----------|
| Command not found | Missing from `generate_handler![]` | Register all commands in the macro |
| Permission denied | Missing capability configuration | Add required permissions to capabilities file |
| State access panic | Type mismatch in `State<T>` | Use exact type matching `.manage()` call |
| White screen | Frontend not building | Verify `beforeDevCommand` and `devUrl` |
| Mobile build fails | Missing Rust targets | Run `rustup target add <platform-targets>` |
| IPC timeout | Blocking in async command | Use non-blocking async or spawn threads |

## When to Use

### Use This Skill For
- Creating new Tauri v2 projects or commands
- Configuring permissions and capabilities
- Setting up IPC (invoke, events, channels)
- Debugging command invocation issues
- Cross-platform build configuration
- Plugin integration and configuration
- Mobile (iOS/Android) deployment setup

### Don't Use This Skill For
- Tauri v1 development (use migration guide then this skill)
- Pure frontend development without Tauri integration
- Native mobile development (Swift/Kotlin directly)
- Backend API development without Tauri

## Version Policy

> [!NOTE]
> This skill targets **Tauri v2+**. Feature availability may vary across minor versions. When exact version timing matters, check the [official Tauri changelog](https://github.com/tauri-apps/tauri/blob/dev/crates/tauri/CHANGELOG.md) and release notes for `tauri`, `@tauri-apps/api`, `@tauri-apps/cli`, and relevant plugins.

## Quick Usage

```bash
# Create new Tauri project
npm create tauri-app@latest

# Add Tauri to existing project
npm install -D @tauri-apps/cli@latest
npx tauri init

# Development
npm run tauri dev

# Production build
npm run tauri build

# Add a plugin (e.g., fs, dialog, store)
cargo tauri add fs          # Adds tauri-plugin-fs to Cargo.toml + JS package
cargo tauri add dialog
cargo tauri add store

# Mobile development
cargo tauri android init    # One-time setup
cargo tauri android dev     # Run on Android
cargo tauri android build   # Release build

cargo tauri ios init        # One-time setup (macOS only)
cargo tauri ios dev         # Run on iOS simulator
cargo tauri ios build       # Release build
```

## Token Efficiency

| Approach | Estimated Tokens | Time |
|----------|-----------------|------|
| Manual Implementation | ~15,000 | 2+ hours |
| With This Skill | ~6,000 | 30 min |
| **Savings** | **60%** | **~1.5 hours** |

## Reference Documentation

For deep-dive guidance on specific topics, see the following reference files:

| Topic | Reference File | Purpose |
|-------|----------------|---------|
| **Security & Permissions** | [`capabilities-reference.md`](references/capabilities-reference.md) | V2 security model, capability files, permissions, and scopes |
| **IPC Patterns** | [`ipc-patterns.md`](references/ipc-patterns.md) | Decision framework for Commands, Events, and Channels |
| **Official Plugins** | [`plugin-reference.md`](references/plugin-reference.md) | Install, registration, and permissions for all official plugins |
| **Updater & Distribution** | [`updater-distribution-reference.md`](references/updater-distribution-reference.md) | Signing, updater setup, and platform-specific distribution |
| **Advanced Runtime** | [`advanced-runtime-reference.md`](references/advanced-runtime-reference.md) | Tray icons, sidecars, deep links, and custom protocols |

See the [References Index](references/README.md) for a complete navigation guide.

## File Structure

```
tauri-v2/
├── SKILL.md        # Quick-start patterns, core rules, critical guidance
├── README.md       # This file - discovery and quick reference
└── references/     # Deep-dive reference documentation
    ├── README.md                          # Index and navigation
    ├── capabilities-reference.md          # Security model, permissions, scopes
    ├── ipc-patterns.md                    # Commands, events, channels decision framework
    ├── plugin-reference.md                # Exhaustive plugin install/register/permissions
    ├── updater-distribution-reference.md  # Signing, HTTPS, platform distribution
    └── advanced-runtime-reference.md      # Tray, sidecars, deep links, protocols
```

## Dependencies

| Package | Version | Verified |
|---------|---------|----------|
| `@tauri-apps/cli` | ^2 (v2+) | 2026-04-02* |
| `@tauri-apps/api` | ^2 (v2+) | 2026-04-02* |
| `tauri` (Rust) | ^2 (v2+) | 2026-04-02* |
| `tauri-build` (Rust) | ^2 (v2+) | 2026-04-02* |

*\*Last verified: 2026-04-02. Always check [official changelog](https://github.com/tauri-apps/tauri/blob/dev/crates/tauri/CHANGELOG.md) for feature timing.*

## Official Documentation

- [Tauri v2+ Documentation](https://v2.tauri.app/)
- [Commands Reference](https://v2.tauri.app/develop/calling-rust/)
- [IPC Concepts](https://v2.tauri.app/concept/inter-process-communication/)
- [Capabilities & Permissions](https://v2.tauri.app/security/capabilities/)
- [Configuration Reference](https://v2.tauri.app/reference/config/)
- [Plugin Directory](https://v2.tauri.app/plugin/)

## Related Skills

- `tanstack-start-expert` - TanStack Router patterns for type-safe frontend routing
- `react-component-architect` - React component patterns for Tauri frontends
- `go-google-style-expert` - Alternative backend patterns (if using Go instead)

## Companion Agent (Deprecated)

The `tauri-v2-expert` agent at `.claude/agents/specialized/tauri/tauri-v2-expert.md` is **deprecated/legacy**. This skill is the preferred and actively maintained interface. Use this skill over the agent for all new Tauri v2 work.

---

**License:** MIT

---

### Overview (`packages/autoskills/skills-registry/zod/README.md`)

# Zod Best Practices Skill

A comprehensive guide for using Zod effectively in TypeScript applications. This skill provides 42 rules across 8 categories, organized by impact to help AI agents and developers write better validation code.

## Overview

Zod is a TypeScript-first schema declaration and validation library. This skill covers best practices for:

- **Schema Definition**: Choosing correct types, avoiding `z.any()`, proper string validations
- **Parsing & Validation**: Using `safeParse()`, async validation, error handling
- **Type Inference**: Leveraging `z.infer`, distinguishing input/output types
- **Error Handling**: Custom messages, internationalization, form error display
- **Object Schemas**: strict/strip modes, partial updates, discriminated unions
- **Schema Composition**: Reusable schemas, intersections, recursive types
- **Refinements & Transforms**: Custom validation, data transformation
- **Performance**: Caching, Zod Mini, lazy loading, batch validation

## Usage

### For Claude Code / AI Agents

The skill is automatically loaded when working with Zod code. Reference specific rules:

```
See rules/parse-use-safeparse.md for safeParse best practices
```

### For Developers

Read `SKILL.md` for a quick reference, or `AGENTS.md` for the full compiled guide.

## File Structure

```
zod/
├── SKILL.md          # Quick reference with rule index
├── AGENTS.md         # Full compiled guide (all rules)
├── metadata.json     # Version, categories, references
├── README.md         # This file
└── rules/
    ├── _sections.md  # Category definitions
    ├── _template.md  # Rule template
    ├── schema-*.md   # Schema definition rules
    ├── parse-*.md    # Parsing rules
    ├── type-*.md     # Type inference rules
    ├── error-*.md    # Error handling rules
    ├── object-*.md   # Object schema rules
    ├── compose-*.md  # Composition rules
    ├── refine-*.md   # Refinement rules
    └── perf-*.md     # Performance rules
```

## Rule Categories

| Priority | Category | Rules | Impact |
|----------|----------|-------|--------|
| 1 | Schema Definition | 6 | CRITICAL |
| 2 | Parsing & Validation | 6 | CRITICAL |
| 3 | Type Inference | 5 | HIGH |
| 4 | Error Handling | 5 | HIGH |
| 5 | Object Schemas | 6 | MEDIUM-HIGH |
| 6 | Schema Composition | 5 | MEDIUM |
| 7 | Refinements & Transforms | 5 | MEDIUM |
| 8 | Performance & Bundle | 5 | LOW-MEDIUM |

## Key Principles

1. **Type Safety First**: Always use `z.infer`, never duplicate types manually
2. **Validate at Boundaries**: Parse external data immediately at entry points
3. **User-Friendly Errors**: Provide custom messages, collect all issues
4. **Single Source of Truth**: Schema defines validation AND TypeScript types
5. **Composition Over Duplication**: Use extend, pick, omit, partial

## References

- [Zod Official Documentation](https://zod.dev/)
- [Zod v4 Release Notes](https://zod.dev/v4)
- [Zod GitHub](https://github.com/colinhacks/zod)
- [Zod Mini](https://zod.dev/packages/mini)

---

### Overview (`packages/autoskills/skills-registry/django-expert/references/README.md`)

# Django Expert - Reference Documentation

This directory contains comprehensive Django best practices documentation that
will be loaded into the active AI coding agent's context when needed.

## Purpose

Reference files provide detailed guidelines, patterns, and examples that would
make SKILL.md too long (>5k words). The agent will read these files as needed
based on the specific Django task at hand.

## Recommended Reference Files

Create the following markdown files in this directory to provide comprehensive Django guidance:

### 1. `models-and-orm.md` - Model Design & ORM Best Practices

**Topics to cover:**
- Model field types and when to use each
- Database relationships (ForeignKey, ManyToMany, OneToOne)
- Model Meta options (ordering, indexes, constraints)
- Custom model methods and properties
- Model managers and custom querysets
- Database query optimization (select_related, prefetch_related, only, defer)
- Common ORM patterns and anti-patterns
- Migration best practices
- Database indexing strategies

**Example structure:**
```markdown
# Django Models and ORM Best Practices

## Model Design Patterns

### Field Choices
- Use TextChoices or IntegerChoices for Django 3.0+
- Keep choices close to the model definition
[detailed examples...]

## Query Optimization

### N+1 Query Problem
[explanation and solutions...]

### Using select_related vs prefetch_related
[detailed guidance with examples...]
```

### 2. `views-and-urls.md` - Views, URLs, and Request Handling

**Topics to cover:**
- Function-based views vs class-based views
- When to use generic CBVs (ListView, DetailView, CreateView, etc.)
- Custom mixins and view composition
- URL patterns and routing best practices
- Request/response handling
- Middleware usage
- Context processors
- Form handling in views
- Error handling and custom error pages

### 3. `drf-guidelines.md` - Django REST Framework Best Practices

**Topics to cover:**
- Serializer patterns (ModelSerializer, nested serializers, write-only fields)
- ViewSets vs APIView vs function-based views
- Permissions and authentication
- Filtering, searching, and pagination
- Versioning strategies
- Custom actions and decorators
- Response formatting
- Error handling in APIs
- Testing DRF endpoints

### 4. `testing-strategies.md` - Testing Django Applications

**Topics to cover:**
- Test organization and structure
- TestCase vs TransactionTestCase
- Factory patterns and fixtures
- Mocking external services
- Testing models, views, and APIs
- Testing permissions and authentication
- Database testing best practices
- Coverage and test performance
- Integration vs unit testing

### 5. `security-checklist.md` - Django Security Best Practices

**Topics to cover:**
- CSRF protection
- XSS prevention
- SQL injection prevention
- Authentication and authorization
- Password handling and storage
- Secure settings for production
- HTTPS and SSL/TLS configuration
- Content Security Policy
- Rate limiting and throttling
- Security headers
- Common vulnerabilities and mitigations

### 6. `performance-optimization.md` - Performance and Scaling

**Topics to cover:**
- Database query optimization
- Caching strategies (per-view cache, template fragment cache, low-level cache)
- Redis/Memcached integration
- Database connection pooling
- Async views and background tasks (Celery)
- Static file optimization
- Database indexing and query profiling
- Monitoring and profiling tools
- Pagination strategies for large datasets

## How to Populate These Files

1. **Research**: Gather Django best practices from official docs, style guides, and community resources
2. **Structure**: Use clear headings, code examples, and explanations
3. **Examples**: Include both good and bad examples with explanations
4. **Keep Updated**: Maintain version-specific guidance (note Django version compatibility)
5. **Be Specific**: Provide concrete examples rather than general statements

## Example Reference File

Here's an example of what a well-structured reference file looks like:

```markdown
# Django REST Framework Guidelines

## Serializer Best Practices

### 1. Use ModelSerializer for Standard CRUD

For basic model serialization, always start with ModelSerializer:

```python
# Good
from rest_framework import serializers

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = ['id', 'name', 'price', 'category']
        read_only_fields = ['id', 'created_at']
```

### 2. Nested Serializers for Relationships

For related objects, use nested serializers or use depth:

```python
# Option 1: Nested serializer (more control)
class OrderSerializer(serializers.ModelSerializer):
    items = OrderItemSerializer(many=True, read_only=True)

    class Meta:
        model = Order
        fields = ['id', 'items', 'total']

# Option 2: Auto-nesting with depth (simpler but less control)
class OrderSerializer(serializers.ModelSerializer):
    class Meta:
        model = Order
        fields = '__all__'
        depth = 1  # Be careful with performance
```

# [Continue with more patterns...]
```

## Usage

Compatible agents automatically read these files when working on Django tasks.
You don't need to manually reference them—the active agent will determine which
references are needed based on the task.

## Notes

- Keep files focused on specific topics (don't create one giant file)
- Use code examples liberally
- Include both do's and don'ts
- Reference Django and DRF version numbers when relevant
- Link to official documentation for deep dives

---

### Overview (`packages/autoskills/skills-registry/tauri-v2/references/README.md`)

# Tauri v2 References

Deep-dive reference documentation for Tauri v2 development. Use these when the main [`SKILL.md`](../SKILL.md) quick-start isn't enough.

## Reference Files

| File | Description | Key Topics |
|------|-------------|------------|
| [`capabilities-reference.md`](capabilities-reference.md) | **Security & Permissions** | Capability files, permissions, scopes, v1 vs v2 model |
| [`ipc-patterns.md`](ipc-patterns.md) | **IPC Decision Framework** | Commands vs Events vs Channels, typed `Channel<T>` |
| [`plugin-reference.md`](plugin-reference.md) | **Official Plugins** | Registration, JS package, and required capability permissions |
| [`updater-distribution-reference.md`](updater-distribution-reference.md) | **Updater & Distribution** | Signing, HTTPS endpoints, macOS/Windows/Linux packaging |
| [`advanced-runtime-reference.md`](advanced-runtime-reference.md) | **Advanced Runtime** | `TrayIconBuilder`, sidecars, deep links, custom protocols |

## Navigation Guide

- **New to Tauri v2 security?** → Start with [`capabilities-reference.md`](capabilities-reference.md) to understand the mandatory capability model.
- **Choosing an IPC method?** → See [`ipc-patterns.md`](ipc-patterns.md) for the "Commands vs Events vs Channels" decision matrix.
- **Adding a plugin?** → Check [`plugin-reference.md`](plugin-reference.md) for the specific permission strings you MUST add to your capabilities.
- **Shipping to production?** → See [`updater-distribution-reference.md`](updater-distribution-reference.md) for mandatory signing and update server requirements.
- **Tray icons, sidecars, or deep links?** → See [`advanced-runtime-reference.md`](advanced-runtime-reference.md) for v2-specific implementations.

*Last verified: 2026-04-02. Check [official Tauri changelog](https://github.com/tauri-apps/tauri/blob/dev/crates/tauri/CHANGELOG.md) for updates.*

---

### Overview (`packages/autoskills/skills-registry/azure-deploy/references/recipes/README.md`)

# Recipes

Deployment recipes for different infrastructure approaches.

| Recipe | When to Use |
|--------|-------------|
| [AZD](azd/README.md) | Projects using Azure Developer CLI |
| [AZCLI](azcli/README.md) | Projects using Azure CLI scripts |
| [Bicep](bicep/README.md) | Projects using Bicep templates |
| [Terraform](terraform/README.md) | Projects using Terraform |
| [CI/CD](cicd/README.md) | Pipeline-based deployments |

---

### Overview (`packages/autoskills/skills-registry/azure-diagnostics/references/app-service/README.md`)

# App Service Troubleshooting

> **Request to "collect"/"gather" diagnostics?** Once the app name and resource
> group are known from the request or existing context, run the
> [`appservice-diagnostics`](../../scripts/appservice-diagnostics.sh) script
> ([PowerShell](../../scripts/appservice-diagnostics.ps1)) directly as your first action —
> don't verify the app/resource group exists with separate calls first, and don't substitute
> the individual commands below for it. It's read-only and reports clearly if the
> resource can't be found. Ask only for identifiers that remain missing. See "Combined
> Diagnostic Script" below for usage.

## Common Issues Matrix

| Symptom | Likely Cause | Action |
|---------|--------------|-----------|
| High CPU / memory | Runaway process, inefficient code | Use Process Explorer via Kudu, scale up |
| Deployment failure | Build error, locked files, quota | Check Kudu logs at `https://APP.scm.azurewebsites.net/api/deployments` to look for details on build errors, locked files or lack of storage quota |
| App crash / restart | Unhandled exception, OOM kill | Review Event Log and STDERR in Diagnose & Solve |
| Slow responses | Downstream dependency, no caching | Enable request tracing, check dependency calls |
| 502 / 503 errors | App not starting, port conflict | Check STDERR logs, verify startup command |
| TLS / domain errors | Certificate expired, DNS mismatch | `az webapp config ssl list`, verify CNAME |
| Health check failure | Endpoint not returning 200 | Verify health check path responds within 2 min |

---

## High CPU / Memory Diagnosis

**Diagnose:**
```bash
# Check app metrics
az monitor metrics list --resource APP_RESOURCE_ID \
  --metric "CpuPercentage,MemoryPercentage" --interval PT1M --output table

# View running processes via ARM Processes API (Entra ID auth)
az rest --method get \
  --uri "/subscriptions/<subscription-id>/resourceGroups/<resource-group>/providers/Microsoft.Web/sites/<app-name>/processes?api-version=2024-04-01"
```

**Fix:** Scale up (`az appservice plan update -n <app-service-plan-name> -g <resource-group> --sku P1V3`) or profile the app via Kudu Process Explorer at `https://APP.scm.azurewebsites.net/ProcessExplorer/` to identify hot paths.

---

## Deployment Failure Analysis

**Diagnose:**
```bash
# List deployment history
az webapp deployment list -n APP -g RG --output table

# View deployment log for a specific deployment
az webapp log deployment show -n APP -g RG --deployment-id DEPLOY_ID

# Stream build logs from Kudu
az webapp log tail -n APP -g RG
```

**KQL — Failed deployments:**
```kql
// Replace <app-service-resource-id> with the full resource ID, for example:
// /subscriptions/<subscription-id>/resourceGroups/<resource-group>/providers/Microsoft.Web/sites/<app-name>
AppServicePlatformLogs
| where TimeGenerated > ago(24h)
| where Level == "Error" and _ResourceId == "<app-service-resource-id>"
| project TimeGenerated, Level, Message
| order by TimeGenerated desc
```

**Common deployment failures:**

| Error Message | Cause | Fix |
|---------------|-------|-----|
| `WEBSITE_RUN_FROM_PACKAGE=1` but no package | Missing zip deploy artifact | Redeploy with `az webapp deploy --src-path app.zip` |
| `Error building on server` | Oryx build failure | Check build logs, pin runtime version |
| `Locked file` during deploy | Files in use | Set an environment variable named `MSDEPLOY_RENAME_LOCKED_FILES=1` on the App Service resource to enable MSDeploy to rename locked files. |

---

## Application Crash / Restart Diagnosis

**Diagnose:**
```bash
# Check recent restarts via activity log
az monitor activity-log list -g RG --resource-id APP_RESOURCE_ID \
  --max-events 10 --query "[?operationName.value=='Microsoft.Web/sites/restart/action']"

# View STDERR/STDOUT (Linux)
az webapp log download -n APP -g RG --log-file logs.zip
```

**KQL — App crashes and errors:**
```kql
AppServiceConsoleLogs
| where TimeGenerated > ago(1h)
| where ResultDescription contains "error" or ResultDescription contains "fatal"
| project TimeGenerated, ResultDescription
| order by TimeGenerated desc
| take 50
```

**Health check failures:**
```bash
# Show health check config
az webapp show -n APP -g RG --query "siteConfig.healthCheckPath"

# Test the endpoint directly
curl -s -o /dev/null -w "%{http_code}" https://APP.azurewebsites.net/health
```

> ⚠️ **Warning:** If the health check fails on >50% of instances for 1 hour, the instance is replaced.

---

## Slow Response Time Investigation

**Diagnose:**
```bash
# Check average response time
az monitor metrics list --resource APP_RESOURCE_ID \
  --metric "HttpResponseTime" --interval PT5M --aggregation Average --output table

# Enable failed request tracing
az webapp log config -n APP -g RG --failed-request-tracing true
```

**KQL — Slow requests with dependency analysis:**
```kql
AppServiceHTTPLogs
| where TimeGenerated > ago(1h)
| where TimeTaken > 5000
| project TimeGenerated, CsUriStem, ScStatus, TimeTaken, CsHost
| order by TimeTaken desc
| take 20
```

**Auto-Heal — Automatic mitigation:**
```bash
# Configure auto-heal to recycle on slow requests
az webapp config set -n APP -g RG \
  --auto-heal-enabled true \
  --generic-configurations '{"autoHealRules":{"triggers":{"slowRequests":{"timeTaken":"00:00:30","count":10,"timeInterval":"00:02:00"}},"actions":{"actionType":"Recycle"}}}'
```

---

## Custom Domain / TLS Certificate Issues

**Diagnose:**
```bash
# List custom domains
az webapp config hostname list -g RG --webapp-name APP --output table

# List TLS certificates
az webapp config ssl list -g RG --output table

# Check SSL binding
az webapp config ssl show --certificate-name CERT -g RG
```

| Symptom | Cause | Fix |
|---------|-------|-----|
| `ERR_CERT_DATE_INVALID` | Certificate expired | If certificate came from an external certificate authority, renew with `az webapp config ssl upload` and upload a new certificate or enable managed certificates to allow Azure to provide a free TLS/SSL certificate |
| `DNS_PROBE_FINISHED_NXDOMAIN` | CNAME not configured | Add CNAME record pointing to `APP.azurewebsites.net` |
| `SSL binding not found` | Missing SNI binding | Add the missing SNI binding using `az webapp config ssl bind --certificate-thumbprint THUMB --ssl-type SNI -n APP -g RG` |
| Managed cert pending | DNS validation incomplete | Verify TXT record `asuid.DOMAIN` matches custom domain verification ID |

---

## AZ CLI or MCP Tools for App Service Diagnostics

| Tool | Command | Use When |
|----------|---------|----------|
| `Azure CLI` | `az webapp list` | List all web apps in subscription |
| `Azure CLI` | `az webapp show -n APP -g RG` | Get app config, stack, status |
| `Azure CLI` | `az webapp config appsettings list -n APP -g RG` | Check env vars and connection strings |
| `Azure CLI` | `az webapp deployment slot list -n APP -g RG` | Compare slot configurations |
| `mcp_azure_mcp_appservice` | `appservice_webapp_diagnostic_diagnose` | AI-powered root cause analysis |
| `mcp_azure_mcp_monitor` | `monitor_resource_log_query` | Run KQL against Log Analytics |
| `mcp_azure_mcp_resourcehealth` | `get` | Check platform-level health status |

> 💡 **Tip:** Start with `mcp_azure_mcp_appservice` (`diagnose`) — it automatically runs relevant detectors and surfaces the most likely root cause before you dig into logs manually.

---

## Combined Diagnostic Script

Use the [`appservice-diagnostics`](../../scripts/appservice-diagnostics.sh) script
([PowerShell](../../scripts/appservice-diagnostics.ps1)) to collect everything in one call.
It prints clearly labeled sections — app config, recent deployments, app settings, and
custom domains — and a summary line describing what it collected. Interpreting the output
remains your job.

```powershell
..\..\scripts\appservice-diagnostics.ps1 -Name <app> -ResourceGroup <rg>
```
```bash
../../scripts/appservice-diagnostics.sh --name <app> --resource-group <rg>
```

---

### Overview (`packages/autoskills/skills-registry/azure-diagnostics/references/container-apps/README.md`)

# Container Apps Troubleshooting

> **Request to "collect"/"gather" diagnostics?** Once the app name and resource
> group are known from the request or existing context, run the
> [`containerapp-diagnostics`](../../scripts/containerapp-diagnostics.sh) script
> ([PowerShell](../../scripts/containerapp-diagnostics.ps1)) directly as your first action —
> don't verify the app/resource group exists with separate calls first, and don't substitute
> the individual commands below for it. It's read-only and reports clearly if the
> resource can't be found. Ask only for identifiers that remain missing. See "Get All
> Diagnostic Info" below for usage.

### Common Issues Matrix

| Symptom | Likely Cause | Quick Fix |
|---------|--------------|-----------|
| Image pull failure | ACR credentials missing | `az containerapp registry set --identity system` |
| ACR build fails | ACR Tasks disabled (free sub) | Build locally with Docker |
| Cold start timeout | min-replicas=0 | `az containerapp update --min-replicas 1` |
| Port mismatch | Wrong target port | Check Dockerfile EXPOSE matches ingress |
| App keeps restarting | Health probe failing | Verify `/health` endpoint |

### Image Pull Failures

**Diagnose:**
```bash
# Check registry configuration
az containerapp show --name APP -g RG --query "properties.configuration.registries"

# Check revision status
az containerapp revision list --name APP -g RG --output table
```

**Fix:**
```bash
az containerapp registry set \
  --name APP -g RG \
  --server ACR.azurecr.io \
  --identity system
```

### ACR Tasks Disabled (Free Subscriptions)

**Symptom:** `az acr build` fails with "ACR Tasks is not supported"

**Fix: Build locally instead:**
```bash
docker build -t ACR.azurecr.io/myapp:v1 .
az acr login --name ACR
docker push ACR.azurecr.io/myapp:v1
```

### Cold Start Issues

**Symptom:** First request very slow or times out

**Fix:**
```bash
az containerapp update --name APP -g RG --min-replicas 1
```

### Health Probe Failures

**Symptom:** Container keeps restarting

**Check:**
```bash
# View health probe config
az containerapp show --name APP -g RG --query "properties.configuration.ingress"

# Check if /health endpoint responds
curl https://APP.REGION.azurecontainerapps.io/health
```

**Fix:** Ensure app has health endpoint returning 200:
```javascript
app.get('/health', (req, res) => res.sendStatus(200));
```

### Port Mismatch

**Symptom:** App starts but returns 502/503

**Check:**
```bash
az containerapp show --name APP -g RG --query "properties.configuration.ingress.targetPort"
```

**Verify:** App must listen on this exact port. Check:
- Dockerfile `EXPOSE` statement
- `process.env.PORT` or hardcoded port in app

### View Logs

```bash
# Stream logs (wait for replicas if scale-to-zero)
az containerapp logs show --name APP -g RG --follow

# Recent logs
az containerapp logs show --name APP -g RG --tail 100

# System logs (startup issues)
az containerapp logs show --name APP -g RG --type system
```

### Get All Diagnostic Info

Use the [`containerapp-diagnostics`](../../scripts/containerapp-diagnostics.sh) script
([PowerShell](../../scripts/containerapp-diagnostics.ps1)) to collect everything in one
call. It prints clearly labeled sections — revisions, registry config, ingress config, and
recent logs — and a summary line describing what it collected. Interpreting the output
remains your job.

```powershell
..\..\scripts\containerapp-diagnostics.ps1 -Name <app> -ResourceGroup <rg>
```
```bash
../../scripts/containerapp-diagnostics.sh --name <app> --resource-group <rg>
```

---

### Overview (`packages/autoskills/skills-registry/azure-diagnostics/references/functions/README.md`)

# Function Apps Troubleshooting

## Find Linked App Insights / Log Analytics

### Preferred: Use Azure Resource Graph

A single ARG query returns the App Insights name, instrumentation key, connection string, and Log Analytics workspace for a given function app:

```bash
az graph query -q "
resources | where type =~ 'microsoft.web/sites' and name == '<func-app-name>'
| project funcName=name, rg=resourceGroup
| join kind=inner (resources | where type =~ 'microsoft.insights/components' | project appiName=name, rg=resourceGroup, instrumentationKey=properties.InstrumentationKey, connectionString=properties.ConnectionString, workspaceId=properties.WorkspaceResourceId) on rg
| project funcName, appiName, instrumentationKey, connectionString, workspaceId
" -o json
```

> 💡 **Tip:** This join matches by resource group. If App Insights is in a different resource group, use the CLI fallback below.

### Fallback: CLI Commands

#### Step 1: Get the App Insights connection string from app settings

```bash
az functionapp config appsettings list \
  --name <func-app-name> -g <rg-name> \
  --query "[?name=='APPLICATIONINSIGHTS_CONNECTION_STRING' || name=='APPINSIGHTS_INSTRUMENTATIONKEY']"
```

#### Step 2: Find the App Insights resource by instrumentation key

```bash
az monitor app-insights component show \
  --query "[?instrumentationKey=='<key>'] | [0].{name:name, rg:resourceGroup, workspaceId:workspaceResourceId}"
```

#### Step 3: Find the Log Analytics workspace

```bash
az monitor app-insights component show --app <appinsights-name> -g <rg-name> \
  --query "workspaceResourceId" -o tsv
```

### Confirm logs are flowing

Query App Insights `traces` table to verify the function app is sending telemetry:

```bash
az monitor app-insights query --apps <appinsights-name> -g <rg-name> \
  --analytics-query "traces | where operation_Name != '' | take 1 | project timestamp, operation_Name, message"
```

For `FunctionAppLogs` (available in Log Analytics only, not App Insights), query the workspace directly:

```bash
az monitor log-analytics query -w <workspace-guid> \
  --analytics-query "FunctionAppLogs | where _ResourceId contains '<func-app-name>' | take 5 | project TimeGenerated, FunctionName, Message, Level"
```

> ⚠️ **Classic App Insights:** Some function apps use classic App Insights without a linked Log Analytics workspace (`workspaceId` is null). In this case, `FunctionAppLogs` is **not available** — use the `traces`, `requests`, and `exceptions` tables via `az monitor app-insights query` instead. As a last resort, `az webapp log tail --name <func-app-name> -g <rg-name>` can stream live logs directly.

If results are returned, logs are flowing. If empty, verify the `APPLICATIONINSIGHTS_CONNECTION_STRING` app setting matches this App Insights instance.

> ⚠️ **Always prefer querying App Insights or Log Analytics** for function app logs. `az webapp log tail` can stream live logs directly but App Insights provides richer data, historical queries, and correlation across requests.

> 💡 **Tip:** App Insights logs can be delayed by a few minutes. If you don't see recent data, wait 3-5 minutes and query again.

---

## Check Recent Deployments

Correlate issues with recent deployments by listing deployment history:

```bash
az rest --method get \
  --uri "/subscriptions/<subscription-id>/resourceGroups/<rg-name>/providers/Microsoft.Web/sites/<func-app-name>/deployments?api-version=2023-12-01"
```

Compare deployment timestamps against when errors started appearing in App Insights to identify if a deployment caused the issue.

---

## Trigger & Durable Function Troubleshooting

- [Trigger & Binding Troubleshooting](triggers.md) - HTTP, Timer, Queue, Blob, Service Bus, and Cosmos DB trigger diagnostics, plus Flex Consumption specifics and SDK conflicts.
- [Durable Functions Troubleshooting](durable.md) - stuck orchestrations, non-determinism violations, timeout/cancellation patterns, and task hub conflicts.

---

### Overview (`packages/autoskills/skills-registry/azure-diagnostics/troubleshooting/messaging/README.md`)

# Azure Messaging Troubleshooting

Diagnose and resolve issues with Azure Event Hubs and Service Bus SDKs.

## Routing

| Symptom | Guide |
|---------|-------|
| Connection failures, firewall, IP/VNet, WebSocket | [service-troubleshooting.md](service-troubleshooting.md) |
| SDK-specific errors (see language below) | Language guide |

## SDK Troubleshooting by Language

- **Event Hubs**: [Python](azure-eventhubs-py.md) | [Java](azure-eventhubs-java.md) | [JS](azure-eventhubs-js.md) | [.NET](azure-eventhubs-dotnet.md)
- **Service Bus**: [Python](azure-servicebus-py.md) | [Java](azure-servicebus-java.md) | [JS](azure-servicebus-js.md) | [.NET](azure-servicebus-dotnet.md)

## Common Issues

| Issue | Category |
|-------|----------|
| AMQP link detach, idle timeout, connection inactive | [service-troubleshooting.md](service-troubleshooting.md) |
| Message lock lost/expired, lock renewal failures | Language-specific SDK guide |
| Session lock errors, session receiver detach | Language-specific SDK guide |
| Duplicate events, checkpoint/offset reset | Language-specific SDK guide |
| Batch >1 MB rejected, partition key conflicts | [service-troubleshooting.md](service-troubleshooting.md) |

## MCP Tools

| Tool | Use |
|------|-----|
| `mcp_azure_mcp_eventhubs` | List namespaces, hubs, consumer groups |
| `mcp_azure_mcp_servicebus` | List namespaces, queues, topics, subscriptions |
| `mcp_azure_mcp_monitor` | Query diagnostic logs with KQL |
| `mcp_azure_mcp_resourcehealth` | Check service health status |
| `mcp_azure_mcp_documentation` | Search Microsoft Learn for troubleshooting docs |

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/agents-sdk/README.md`)

# Cloudflare Agents SDK

Cloudflare Agents SDK enables building AI-powered agents on Durable Objects with state, WebSockets, SQL, scheduling, and AI integration.

## Core Value
Build stateful, globally distributed AI agents with persistent memory, real-time connections, scheduled tasks, and async workflows.

## When to Use
- Persistent state + memory required
- Real-time WebSocket connections
- Long-running workflows (minutes/hours)
- Chat interfaces with AI models
- Scheduled/recurring tasks with state
- DB queries with agent state

## What Type of Agent?

| Use Case | Class | Key Features |
|----------|-------|--------------|
| AI chat interface | `AIChatAgent` | Auto-streaming, tools, message history, resumable |
| MCP tool provider | `Agent` + MCP | Expose tools to AI systems |
| Custom logic/routing | `Agent` | Full control, WebSockets, email, SQL |
| Real-time collaboration | `Agent` | WebSocket state, broadcasts |
| Email processing | `Agent` | `onEmail()` handler |

## Quick Start

**AI Chat Agent:**
```typescript
import { AIChatAgent } from "agents";
import { openai } from "@ai-sdk/openai";

export class ChatAgent extends AIChatAgent<Env> {
  async onChatMessage(onFinish) {
    return this.streamText({
      model: openai("gpt-4"),
      messages: this.messages,
      onFinish,
    });
  }
}
```

**Base Agent:**
```typescript
import { Agent } from "agents";

export class MyAgent extends Agent<Env> {
  onStart() {
    this.sql`CREATE TABLE IF NOT EXISTS users (id TEXT PRIMARY KEY)`;
  }
  
  async onRequest(request: Request) {
    return Response.json({ state: this.state });
  }
}
```

## Reading Order

| Task | Files to Read |
|------|---------------|
| Quick start | README only |
| Build chat agent | README → api.md (AIChatAgent) → patterns.md |
| Setup project | README → configuration.md |
| Add React frontend | README → api.md (Client Hooks) → patterns.md |
| Build MCP server | api.md (MCP) → patterns.md |
| Background tasks | api.md (Scheduling, Task Queue) → patterns.md |
| Debug issues | gotchas.md |

## Package Entry Points

| Import | Purpose |
|--------|---------|
| `agents` | Server-side Agent classes, lifecycle |
| `agents/react` | `useAgent()` hook for WebSocket connections |
| `agents/ai-react` | `useAgentChat()` hook for AI chat UIs |

## In This Reference
- [configuration.md](./configuration.md) - SDK setup, wrangler config, routing
- [api.md](./api.md) - Agent classes, lifecycle, client hooks
- [patterns.md](./patterns.md) - Common workflows, best practices
- [gotchas.md](./gotchas.md) - Common issues, limits

## See Also
- durable-objects - Agent infrastructure
- d1 - External database integration
- workers-ai - AI model integration
- vectorize - Vector search for RAG patterns

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/ai-gateway/README.md`)

# Cloudflare AI Gateway

Expert guidance for implementing Cloudflare AI Gateway - a universal gateway for AI model providers with analytics, caching, rate limiting, and routing capabilities.

## When to Use This Reference

- Setting up AI Gateway for any AI provider (OpenAI, Anthropic, Workers AI, etc.)
- Implementing caching, rate limiting, or request retry/fallback
- Configuring dynamic routing with A/B testing or model fallbacks
- Managing provider API keys securely with BYOK
- Adding security features (guardrails, DLP)
- Setting up observability with logging and custom metadata
- Debugging AI Gateway requests or optimizing configurations

## Quick Start

**What's your setup?**

- **Using Vercel AI SDK** → Pattern 1 (recommended) - see [sdk-integration.md](./sdk-integration.md)
- **Using OpenAI SDK** → Pattern 2 - see [sdk-integration.md](./sdk-integration.md)
- **Cloudflare Worker + Workers AI** → Pattern 3 - see [sdk-integration.md](./sdk-integration.md)
- **Direct HTTP (any language)** → Pattern 4 - see [configuration.md](./configuration.md)
- **Framework (LangChain, etc.)** → See [sdk-integration.md](./sdk-integration.md)

## Pattern 1: Vercel AI SDK (Recommended)

Most modern pattern using official `ai-gateway-provider` package with automatic fallbacks.

```typescript
import { createAiGateway } from 'ai-gateway-provider';
import { createOpenAI } from '@ai-sdk/openai';
import { generateText } from 'ai';

const gateway = createAiGateway({
  accountId: process.env.CF_ACCOUNT_ID,
  gateway: process.env.CF_GATEWAY_ID,
});

const openai = createOpenAI({ 
  apiKey: process.env.OPENAI_API_KEY 
});

// Single model
const { text } = await generateText({
  model: gateway(openai('gpt-4o')),
  prompt: 'Hello'
});

// Automatic fallback array
const { text } = await generateText({
  model: gateway([
    openai('gpt-4o'),              // Try first
    anthropic('claude-sonnet-4-5'), // Fallback
  ]),
  prompt: 'Hello'
});
```

**Install:** `npm install ai-gateway-provider ai @ai-sdk/openai @ai-sdk/anthropic`

## Pattern 2: OpenAI SDK

Drop-in replacement for OpenAI API with multi-provider support.

```typescript
import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
  baseURL: `https://gateway.ai.cloudflare.com/v1/${accountId}/${gatewayId}/compat`,
  defaultHeaders: {
    'cf-aig-authorization': `Bearer ${cfToken}` // For authenticated gateways
  }
});

// Switch providers by changing model format: {provider}/{model}
const response = await client.chat.completions.create({
  model: 'openai/gpt-4o', // or 'anthropic/claude-sonnet-4-5'
  messages: [{ role: 'user', content: 'Hello!' }]
});
```

## Pattern 3: Workers AI Binding

For Cloudflare Workers using Workers AI.

```typescript
export default {
  async fetch(request, env, ctx) {
    const response = await env.AI.run(
      '@cf/meta/llama-3-8b-instruct',
      { messages: [{ role: 'user', content: 'Hello!' }] },
      { 
        gateway: { 
          id: 'my-gateway',
          metadata: { userId: '123', team: 'engineering' }
        } 
      }
    );
    
    return Response.json(response);
  }
};
```

## Headers Quick Reference

| Header | Purpose | Example | Notes |
|--------|---------|---------|-------|
| `cf-aig-authorization` | Gateway auth | `Bearer {token}` | Required for authenticated gateways |
| `cf-aig-metadata` | Tracking | `{"userId":"x"}` | Max 5 entries, flat structure |
| `cf-aig-cache-ttl` | Cache duration | `3600` | Seconds, min 60, max 2592000 (30 days) |
| `cf-aig-skip-cache` | Bypass cache | `true` | - |
| `cf-aig-cache-key` | Custom cache key | `my-key` | Must be unique per response |
| `cf-aig-collect-log` | Skip logging | `false` | Default: true |
| `cf-aig-cache-status` | Cache hit/miss | Response only | `HIT` or `MISS` |

## In This Reference

| File | Purpose |
|------|---------|
| [sdk-integration.md](./sdk-integration.md) | Vercel AI SDK, OpenAI SDK, Workers binding patterns |
| [configuration.md](./configuration.md) | Dashboard setup, wrangler, API tokens |
| [features.md](./features.md) | Caching, rate limits, guardrails, DLP, BYOK, unified billing |
| [dynamic-routing.md](./dynamic-routing.md) | Fallbacks, A/B testing, conditional routing |
| [troubleshooting.md](./troubleshooting.md) | Debugging, errors, observability, gotchas |

## Reading Order

| Task | Files |
|------|-------|
| First-time setup | README + [configuration.md](./configuration.md) |
| SDK integration | README + [sdk-integration.md](./sdk-integration.md) |
| Enable caching | README + [features.md](./features.md) |
| Setup fallbacks | README + [dynamic-routing.md](./dynamic-routing.md) |
| Debug errors | README + [troubleshooting.md](./troubleshooting.md) |

## Architecture

AI Gateway acts as a proxy between your application and AI providers:

```
Your App → AI Gateway → AI Provider (OpenAI, Anthropic, etc.)
         ↓
    Analytics, Caching, Rate Limiting, Logging
```

**Key URL patterns:**
- Unified API (OpenAI-compatible): `https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/compat/chat/completions`
- Provider-specific: `https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/{provider}/{endpoint}`
- Dynamic routes: Use route name instead of model: `dynamic/{route-name}`

## Gateway Types

1. **Unauthenticated Gateway**: Open access (not recommended for production)
2. **Authenticated Gateway**: Requires `cf-aig-authorization` header with Cloudflare API token (recommended)

## Provider Authentication Options

1. **Unified Billing**: Use AI Gateway billing to pay for inference (keyless mode - no provider API key needed)
2. **BYOK (Store Keys)**: Store provider API keys in Cloudflare dashboard
3. **Request Headers**: Include provider API key in each request

## Related Skills

- [Workers AI](../workers-ai/README.md) - For `env.AI.run()` details
- [Agents SDK](../agents-sdk/README.md) - For stateful AI patterns
- [Vectorize](../vectorize/README.md) - For RAG patterns with embeddings

## Resources

- [Official Docs](https://developers.cloudflare.com/ai-gateway/)
- [API Reference](https://developers.cloudflare.com/api/resources/ai_gateway/)
- [Provider Guides](https://developers.cloudflare.com/ai-gateway/usage/providers/)
- [Discord Community](https://discord.cloudflare.com)

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/ai-search/README.md`)

# Cloudflare AI Search Reference

Expert guidance for implementing Cloudflare AI Search (formerly AutoRAG), Cloudflare's managed semantic search and RAG service.

## Overview

**AI Search** is a managed RAG (Retrieval-Augmented Generation) pipeline that combines:
- Automatic semantic indexing of your content
- Vector similarity search
- Built-in LLM generation

**Key value propositions:**
- **Zero vector management** - No manual embedding, indexing, or storage
- **Auto-indexing** - Content automatically re-indexed every 6 hours
- **Built-in generation** - Optional AI response generation from retrieved context
- **Multi-source** - Index from R2 buckets or website crawls

**Data source options:**
- **R2 bucket** - Index files from Cloudflare R2 (supports MD, TXT, HTML, PDF, DOC, CSV, JSON)
- **Website** - Crawl and index website content (requires Cloudflare-hosted domain)

**Indexing lifecycle:**
- Automatic 6-hour refresh cycle
- Manual "Force Sync" available (30s rate limit)
- Not designed for real-time updates

## Quick Start

**1. Create AI Search instance in dashboard:**
- Go to Cloudflare Dashboard → AI Search → Create
- Choose data source (R2 or website)
- Configure instance name and settings

**2. Configure Worker:**

```jsonc
// wrangler.jsonc
{
  "ai": {
    "binding": "AI"
  }
}
```

**3. Use in Worker:**

```typescript
export default {
  async fetch(request, env) {
    const answer = await env.AI.autorag("my-search-instance").aiSearch({
      query: "How do I configure caching?",
      model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast"
    });
    
    return Response.json({ answer: answer.response });
  }
};
```

## When to Use AI Search

### AI Search vs Vectorize

| Factor | AI Search | Vectorize |
|--------|-----------|-----------|
| **Management** | Fully managed | Manual embedding + indexing |
| **Use when** | Want zero-ops RAG pipeline | Need custom embeddings/control |
| **Indexing** | Automatic (6hr cycle) | Manual via API |
| **Generation** | Built-in optional | Bring your own LLM |
| **Data sources** | R2 or website | Manual insert |
| **Best for** | Docs, support, enterprise search | Custom ML pipelines, real-time |

### AI Search vs Direct Workers AI

| Factor | AI Search | Workers AI (direct) |
|--------|-----------|---------------------|
| **Context** | Automatic retrieval | Manual context building |
| **Use when** | Need RAG (search + generate) | Simple generation tasks |
| **Indexing** | Built-in | Not applicable |
| **Best for** | Knowledge bases, docs | Simple chat, transformations |

### search() vs aiSearch()

| Method | Returns | Use When |
|--------|---------|----------|
| `search()` | Search results only | Building custom UI, need raw chunks |
| `aiSearch()` | AI response + results | Need ready-to-use answer (chatbot, Q&A) |

### Real-time Updates Consideration

**AI Search is NOT ideal if:**
- Need real-time content updates (<6 hours)
- Content changes multiple times per hour
- Strict freshness requirements

**AI Search IS ideal if:**
- Content relatively stable (docs, policies, knowledge bases)
- 6-hour refresh acceptable
- Prefer zero-ops over real-time

## Platform Limits

| Limit | Value |
|-------|-------|
| Max instances per account | 10 |
| Max files per instance | 100,000 |
| Max file size | 4 MB |
| Index frequency | Every 6 hours |
| Force Sync rate limit | Once per 30 seconds |
| Filter nesting depth | 2 levels |
| Filters per compound | 10 |
| Score threshold range | 0.0 - 1.0 |

## Reading Order

Navigate these references based on your task:

| Task | Read | Est. Time |
|------|------|-----------|
| **Understand AI Search** | README only | 5 min |
| **Implement basic search** | README → api.md | 10 min |
| **Configure data source** | README → configuration.md | 10 min |
| **Production patterns** | patterns.md | 15 min |
| **Debug issues** | gotchas.md | 10 min |
| **Full implementation** | README → api.md → patterns.md | 30 min |

## In This Reference

- **[api.md](api.md)** - API endpoints, methods, TypeScript interfaces
- **[configuration.md](configuration.md)** - Setup, data sources, wrangler config
- **[patterns.md](patterns.md)** - Common patterns, decision guidance, code examples
- **[gotchas.md](gotchas.md)** - Troubleshooting, code-level gotchas, limits

## See Also

- [Cloudflare AI Search Docs](https://developers.cloudflare.com/ai-search/)
- [Workers AI Docs](https://developers.cloudflare.com/workers-ai/)
- [Vectorize Docs](https://developers.cloudflare.com/vectorize/)

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/analytics-engine/README.md`)

# Cloudflare Workers Analytics Engine Reference

Expert guidance for implementing unlimited-cardinality analytics at scale using Cloudflare Workers Analytics Engine.

## What is Analytics Engine?

Time-series analytics database designed for high-cardinality data (millions of unique dimensions). Write data points from Workers, query via SQL API. Use for:
- Custom user-facing analytics dashboards
- Usage-based billing & metering
- Per-customer/per-feature monitoring
- High-frequency instrumentation without performance impact

**Key Capability:** Track metrics with unlimited unique values (e.g., millions of user IDs, API keys) without performance degradation.

## Core Concepts

| Concept | Description | Example |
|---------|-------------|---------|
| **Dataset** | Logical table for related metrics | `api_requests`, `user_events` |
| **Data Point** | Single measurement with timestamp | One API request's metrics |
| **Blobs** | String dimensions (max 20) | endpoint, method, status, user_id |
| **Doubles** | Numeric values (max 20) | latency_ms, request_count, bytes |
| **Indexes** | Filtered blobs for efficient queries | customer_id, api_key |

## Reading Order

| Task | Start Here | Then Read |
|------|------------|-----------|
| **First-time setup** | [configuration.md](configuration.md) → [api.md](api.md) → [patterns.md](patterns.md) | |
| **Writing data** | [api.md](api.md) → [gotchas.md](gotchas.md) (sampling) | |
| **Querying data** | [api.md](api.md) (SQL API) → [patterns.md](patterns.md) (examples) | |
| **Debugging** | [gotchas.md](gotchas.md) → [api.md](api.md) (limits) | |
| **Optimization** | [patterns.md](patterns.md) (anti-patterns) → [gotchas.md](gotchas.md) | |

## When to Use Analytics Engine

```
Need to track metrics? → Yes
  ↓
Millions of unique dimension values? → Yes
    ↓
  Need real-time queries? → Yes
      ↓
    Use Analytics Engine ✓

Alternative scenarios:
- Low cardinality (<10k unique values) → Workers Analytics (free tier)
- Complex joins/relations → D1 Database
- Logs/debugging → Tail Workers (logpush)
- External tools → Send to external analytics (Datadog, etc.)
```

## Quick Start

1. Add binding to `wrangler.jsonc`:
```jsonc
{
  "analytics_engine_datasets": [
    { "binding": "ANALYTICS", "dataset": "my_events" }
  ]
}
```

2. Write data points (fire-and-forget, no await):
```typescript
env.ANALYTICS.writeDataPoint({
  blobs: ["/api/users", "GET", "200"],
  doubles: [145.2, 1],  // latency_ms, count
  indexes: [customerId]
});
```

3. Query via SQL API (HTTP):
```sql
SELECT blob1, SUM(double2) AS total_requests
FROM my_events
WHERE index1 = 'customer_123'
  AND timestamp >= NOW() - INTERVAL '7' DAY
GROUP BY blob1
ORDER BY total_requests DESC
```

## In This Reference

- **[configuration.md](configuration.md)** - Setup, bindings, TypeScript types, limits
- **[api.md](api.md)** - `writeDataPoint()`, SQL API, query syntax
- **[patterns.md](patterns.md)** - Use cases, examples, anti-patterns
- **[gotchas.md](gotchas.md)** - Sampling, index selection, troubleshooting

## See Also

- [Cloudflare Analytics Engine Docs](https://developers.cloudflare.com/analytics/analytics-engine/)

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/api-shield/README.md`)

# Cloudflare API Shield Reference

Expert guidance for API Shield - comprehensive API security suite for discovery, protection, and monitoring.

## Reading Order

| Task | Files to Read |
|------|---------------|
| Initial setup | README → configuration.md |
| Implement JWT validation | configuration.md → api.md |
| Add schema validation | configuration.md → patterns.md |
| Detect API attacks | patterns.md → api.md |
| Debug issues | gotchas.md |

## Feature Selection

What protection do you need?

```
├─ Validate request/response structure → Schema Validation 2.0 (configuration.md)
├─ Verify auth tokens → JWT Validation (configuration.md)
├─ Client certificates → mTLS (configuration.md)
├─ Detect BOLA attacks → BOLA Detection (patterns.md)
├─ Track auth coverage → Auth Posture (patterns.md)
├─ Stop volumetric abuse → Abuse Detection (patterns.md)
└─ Discover shadow APIs → API Discovery (api.md)
```

## In This Reference

- **[configuration.md](configuration.md)** - Setup, session identifiers, rules, token/mTLS configs
- **[api.md](api.md)** - Endpoint management, discovery, validation APIs, GraphQL operations
- **[patterns.md](patterns.md)** - Common patterns, progressive rollout, OWASP mappings, workflows
- **[gotchas.md](gotchas.md)** - Troubleshooting, false positives, performance, best practices

## Quick Start

API Shield: Enterprise-grade API security (Discovery, Schema Validation 2.0, JWT, mTLS, BOLA Detection, Auth Posture). Available as Enterprise add-on with preview access.

## See Also

- [API Shield Docs](https://developers.cloudflare.com/api-shield/)
- [API Reference](https://developers.cloudflare.com/api/resources/api_gateway/)
- [OWASP API Security Top 10](https://owasp.org/www-project-api-security/)

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/api/README.md`)

# Cloudflare API Integration

Guide for working with Cloudflare's REST API - authentication, SDK usage, common patterns, and troubleshooting.

## Quick Decision Tree

```
How are you calling the Cloudflare API?
├─ From Workers runtime → Use bindings, not REST API (see ../bindings/)
├─ Server-side (Node/Python/Go) → Official SDK (see api.md)
├─ CLI/scripts → Wrangler or curl (see configuration.md)
├─ Infrastructure-as-code → See ../pulumi/ or ../terraform/
└─ One-off requests → curl examples (see api.md)
```

## SDK Selection

| Language | Package | Best For | Default Retries |
|----------|---------|----------|-----------------|
| TypeScript | `cloudflare` | Node.js, Bun, Next.js, Workers | 2 |
| Python | `cloudflare` | FastAPI, Django, scripts | 2 |
| Go | `cloudflare-go/v4` | CLI tools, microservices | 10 |

All SDKs are Stainless-generated from OpenAPI spec (consistent APIs).

## Authentication Methods

| Method | Security | Use Case | Scope |
|--------|----------|----------|-------|
| **API Token** ✓ | Scoped, rotatable | Production | Per-zone or account |
| API Key + Email | Full account access | Legacy only | Everything |
| User Service Key | Limited | Origin CA certs only | Origin CA |

**Always use API tokens** for new projects.

## Rate Limits

| Limit | Value |
|-------|-------|
| Per user/token | 1200 requests / 5 minutes |
| Per IP | 200 requests / second |
| GraphQL | 320 / 5 minutes (cost-based) |

## Reading Order

| Task | Files to Read |
|------|---------------|
| Initialize SDK client | api.md |
| Configure auth/timeout/retry | configuration.md |
| Find usage patterns | patterns.md |
| Debug errors/rate limits | gotchas.md |
| Product-specific APIs | ../workers/, ../r2/, ../kv/, etc. |

## In This Reference

- **[api.md](api.md)** - SDK client initialization, pagination, error handling, examples
- **[configuration.md](configuration.md)** - Environment variables, SDK config, Wrangler setup
- **[patterns.md](patterns.md)** - Real-world patterns, batch operations, workflows
- **[gotchas.md](gotchas.md)** - Rate limits, SDK-specific issues, troubleshooting

## See Also

- [Cloudflare API Docs](https://developers.cloudflare.com/api/)
- [Bindings Reference](../bindings/) - Workers runtime bindings (preferred over REST API)
- [Wrangler Reference](../wrangler/) - CLI tool for Cloudflare development

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/argo-smart-routing/README.md`)

# Cloudflare Argo Smart Routing Skill Reference

## Overview

Cloudflare Argo Smart Routing is a performance optimization service that detects real-time network issues and routes web traffic across the most efficient network path. It continuously monitors network conditions and intelligently routes traffic through the fastest, most reliable routes in Cloudflare's network.

**Note on Smart Shield:** Argo Smart Routing is being integrated into Cloudflare's Smart Shield product for enhanced DDoS protection and performance. Existing Argo customers maintain full functionality with gradual migration to Smart Shield features.

## Quick Start

### Enable via cURL
```bash
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/{zone_id}/argo/smart_routing" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"value": "on"}'
```

### Enable via TypeScript SDK
```typescript
import Cloudflare from 'cloudflare';

const client = new Cloudflare({ apiToken: process.env.CLOUDFLARE_API_TOKEN });

const result = await client.argo.smartRouting.edit({
  zone_id: 'your-zone-id',
  value: 'on',
});

console.log(`Argo enabled: ${result.value}`);
```

## Core Concepts

### What It Does
- **Intelligent routing**: Detects congestion, outages, packet loss in real-time
- **Global optimization**: Routes across 300+ Cloudflare data centers
- **Automatic failover**: Switches paths when issues detected (typically <1s)
- **Works with existing setup**: No origin changes required

### Billing Model
- Usage-based: Charged per GB of traffic (excluding DDoS/WAF mitigated traffic)
- Requires billing configuration before enabling
- Available on Enterprise+ plans (check zone eligibility)

### When to Use
- **High-traffic production sites** with global user base
- **Latency-sensitive applications** (APIs, real-time services)
- **Sites behind Cloudflare proxy** (orange-clouded DNS records)
- **Combined with Tiered Cache** for maximum performance gains

### When NOT to Use
- Development/staging environments (cost control)
- Low-traffic sites (<1TB/month) where cost may exceed benefit
- Sites with primarily single-region traffic

## Should I Enable Argo?

| Your Situation | Recommendation |
|----------------|----------------|
| Global production app, >1TB/month traffic | ✅ Enable - likely ROI positive |
| Enterprise plan, latency-critical APIs | ✅ Enable - performance matters |
| Regional site, <100GB/month traffic | ⚠️ Evaluate - cost may not justify |
| Development/staging environment | ❌ Disable - use in production only |
| Not yet configured billing | ❌ Configure billing first |

## Reading Order by Task

| Your Goal | Start With | Then Read |
|-----------|------------|-----------|
| Enable Argo for first time | Quick Start above → [configuration.md](configuration.md) | [gotchas.md](gotchas.md) |
| Use TypeScript/Python SDK | [api.md](api.md) | [patterns.md](patterns.md) |
| Terraform/IaC setup | [configuration.md](configuration.md) | - |
| Enable for Spectrum TCP app | [patterns.md](patterns.md) → Spectrum section | [api.md](api.md) |
| Troubleshoot enablement issue | [gotchas.md](gotchas.md) | [api.md](api.md) |
| Manage billing/usage | [patterns.md](patterns.md) → Billing section | [gotchas.md](gotchas.md) |

## In This Reference

- **[api.md](api.md)** - API endpoints, SDK methods, error handling, Python/TypeScript examples
- **[configuration.md](configuration.md)** - Terraform setup, environment config, billing configuration
- **[patterns.md](patterns.md)** - Tiered Cache integration, Spectrum TCP apps, billing management, validation patterns
- **[gotchas.md](gotchas.md)** - Common errors, permission issues, limits, best practices

## See Also

- [Cloudflare Argo Smart Routing Docs](https://developers.cloudflare.com/argo-smart-routing/)
- [Cloudflare Smart Shield](https://developers.cloudflare.com/smart-shield/)
- [Spectrum Documentation](https://developers.cloudflare.com/spectrum/)
- [Tiered Cache](https://developers.cloudflare.com/cache/how-to/tiered-cache/)

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/bindings/README.md`)

# Cloudflare Bindings Skill Reference

Expert guidance on Cloudflare Workers Bindings - the runtime APIs that connect Workers to Cloudflare platform resources.

## What Are Bindings?

Bindings are how Workers access Cloudflare resources (storage, compute, services) via the `env` object. They're configured in `wrangler.jsonc`, type-safe via TypeScript, and zero-overhead at runtime.

## Reading Order

1. **This file** - Binding catalog and selection guide
2. **[api.md](api.md)** - TypeScript types and env access patterns
3. **[configuration.md](configuration.md)** - Complete wrangler.jsonc examples
4. **[patterns.md](patterns.md)** - Best practices and common patterns
5. **[gotchas.md](gotchas.md)** - Critical pitfalls and troubleshooting

## Binding Catalog

### Storage Bindings

| Binding | Use Case | Access Pattern |
|---------|----------|----------------|
| **KV** | Key-value cache, CDN-backed reads | `env.MY_KV.get(key)` |
| **R2** | Object storage (S3-compatible) | `env.MY_BUCKET.get(key)` |
| **D1** | SQL database (SQLite) | `env.DB.prepare(sql).all()` |
| **Durable Objects** | Coordination, real-time state | `env.MY_DO.get(id)` |
| **Vectorize** | Vector embeddings search | `env.VECTORIZE.query(vector)` |
| **Queues** | Async message processing | `env.MY_QUEUE.send(msg)` |

### Compute Bindings

| Binding | Use Case | Access Pattern |
|---------|----------|----------------|
| **Service** | Worker-to-Worker RPC | `env.MY_SERVICE.fetch(req)` |
| **Workers AI** | LLM inference | `env.AI.run(model, input)` |
| **Browser Rendering** | Headless Chrome | `env.BROWSER.fetch(url)` |

### Platform Bindings

| Binding | Use Case | Access Pattern |
|---------|----------|----------------|
| **Analytics Engine** | Custom metrics | `env.ANALYTICS.writeDataPoint(data)` |
| **mTLS** | Client certificates | `env.MY_CERT` (string) |
| **Hyperdrive** | Database pooling | `env.HYPERDRIVE.connectionString` |
| **Rate Limiting** | Request throttling | `env.RATE_LIMITER.limit(id)` |
| **Workflows** | Long-running workflows | `env.MY_WORKFLOW.create()` |

### Configuration Bindings

| Binding | Use Case | Access Pattern |
|---------|----------|----------------|
| **Environment Variables** | Non-sensitive config | `env.API_URL` (string) |
| **Secrets** | Sensitive values | `env.API_KEY` (string) |
| **Text/Data Blobs** | Static files | `env.MY_BLOB` (string) |
| **WASM** | WebAssembly modules | `env.MY_WASM` (WebAssembly.Module) |

## Quick Selection Guide

**Need persistent storage?**
- Key-value < 25MB → **KV**
- Files/objects → **R2**
- Relational data → **D1**
- Real-time coordination → **Durable Objects**

**Need AI/compute?**
- LLM inference → **Workers AI**
- Scraping/PDFs → **Browser Rendering**
- Call another Worker → **Service binding**

**Need async processing?**
- Background jobs → **Queues**

**Need config?**
- Public values → **Environment Variables**
- Secrets → **Secrets** (never commit)

## Quick Start

1. **Add binding to wrangler.jsonc:**
```jsonc
{
  "kv_namespaces": [
    { "binding": "MY_KV", "id": "your-kv-id" }
  ]
}
```

2. **Generate types:**
```bash
npx wrangler types
```

3. **Access in Worker:**
```typescript
export default {
  async fetch(request, env, ctx) {
    await env.MY_KV.put('key', 'value');
    return new Response('OK');
  }
}
```

## Type Safety

Bindings are fully typed via `wrangler types`. See [api.md](api.md) for details.

## Limits

- 64 bindings max per Worker (all types combined)
- See [gotchas.md](gotchas.md) for per-binding limits

## Key Concepts

**Zero-overhead access:** Bindings compiled into Worker, no network calls to access
**Type-safe:** Full TypeScript support via `wrangler types`
**Per-environment:** Different IDs for dev/staging/production
**Secrets vs Vars:** Secrets encrypted at rest, never in config files

## See Also

- [Cloudflare Docs: Bindings](https://developers.cloudflare.com/workers/runtime-apis/bindings/)
- [Wrangler Configuration](https://developers.cloudflare.com/workers/wrangler/configuration/)

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/bot-management/README.md`)

# Cloudflare Bot Management

Enterprise-grade bot detection, protection, and mitigation using ML/heuristics, bot scores, JavaScript detections, and verified bot handling.

## Overview

Bot Management provides multi-tier protection:
- **Free (Bot Fight Mode)**: Auto-blocks definite bots, no config
- **Pro/Business (Super Bot Fight Mode)**: Configurable actions, static resource protection, analytics groupings
- **Enterprise (Bot Management)**: Granular 1-99 scores, WAF integration, JA3/JA4 fingerprinting, Workers API, Advanced Analytics

## Quick Start

```txt
# Dashboard: Security > Bots
# Enterprise: Deploy rule template
(cf.bot_management.score eq 1 and not cf.bot_management.verified_bot) → Block
(cf.bot_management.score le 29 and not cf.bot_management.verified_bot) → Managed Challenge
```

## What Do You Need?

```txt
├─ Initial setup → configuration.md
│   ├─ Free tier → "Bot Fight Mode"
│   ├─ Pro/Business → "Super Bot Fight Mode"
│   └─ Enterprise → "Bot Management for Enterprise"
├─ Workers API integration → api.md
├─ WAF rules → patterns.md
├─ Debugging → gotchas.md
└─ Analytics → api.md#bot-analytics
```

## Reading Order

| Task | Files to Read |
|------|---------------|
| Enable bot protection | README → configuration.md |
| Workers bot detection | README → api.md |
| WAF rule templates | README → patterns.md |
| Debug bot issues | gotchas.md |
| Advanced analytics | api.md#bot-analytics |

## Core Concepts

**Bot Scores**: 1-99 (1 = definitely automated, 99 = definitely human). Threshold: <30 indicates bot traffic. Enterprise gets granular 1-99; Pro/Business get groupings only.

**Detection Engines**: Heuristics (known fingerprints, assigns score=1), ML (majority of detections, supervised learning on billions of requests), Anomaly Detection (optional, baseline traffic analysis), JavaScript Detections (headless browser detection).

**Verified Bots**: Allowlisted good bots (search engines, AI crawlers) verified via reverse DNS or Web Bot Auth. Access via `cf.bot_management.verified_bot` or `cf.verified_bot_category`.

## Platform Limits

| Plan | Bot Scores | JA3/JA4 | Custom Rules | Analytics Retention |
|------|------------|---------|--------------|---------------------|
| Free | No (auto-block only) | No | 5 | N/A (no analytics) |
| Pro/Business | Groupings only | No | 20/100 | 30 days (72h at a time) |
| Enterprise | 1-99 granular | Yes | 1,000+ | 30 days (1 week at a time) |

## Basic Patterns

```typescript
// Workers: Check bot score
export default {
  async fetch(request: Request): Promise<Response> {
    const botScore = request.cf?.botManagement?.score;
    if (botScore && botScore < 30 && !request.cf?.botManagement?.verifiedBot) {
      return new Response('Bot detected', { status: 403 });
    }
    return fetch(request);
  }
};
```

```txt
# WAF: Block definite bots
(cf.bot_management.score eq 1 and not cf.bot_management.verified_bot)

# WAF: Protect sensitive endpoints
(cf.bot_management.score lt 50 and http.request.uri.path in {"/login" "/checkout"} and not cf.bot_management.verified_bot)
```

## In This Reference

- [configuration.md](./configuration.md) - Product tiers, WAF rule setup, JavaScript Detections, ML auto-updates
- [api.md](./api.md) - Workers BotManagement interface, WAF fields, JA4 Signals
- [patterns.md](./patterns.md) - E-commerce, API protection, mobile app allowlisting, SEO-friendly handling
- [gotchas.md](./gotchas.md) - False positives/negatives, score=0 issues, JSD limitations, CSP requirements

## See Also

- [waf](../waf/) - WAF custom rules for bot enforcement
- [workers](../workers/) - Workers request.cf.botManagement API
- [api-shield](../api-shield/) - API-specific bot protection

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/browser-rendering/README.md`)

# Cloudflare Browser Rendering Skill Reference

**Description**: Expert knowledge for Cloudflare Browser Rendering - control headless Chrome on Cloudflare's global network for browser automation, screenshots, PDFs, web scraping, testing, and content generation.

**When to use**: Any task involving Cloudflare Browser Rendering including: taking screenshots, generating PDFs, web scraping, browser automation, testing web applications, extracting structured data, capturing page metrics, or automating browser interactions.

## Decision Tree

### REST API vs Workers Bindings

**Use REST API when:**
- One-off, stateless tasks (screenshot, PDF, content fetch)
- No Workers infrastructure yet
- Simple integrations from external services
- Need quick prototyping without deployment

**Use Workers Bindings when:**
- Complex browser automation workflows
- Need session reuse for performance
- Multiple page interactions per request
- Custom scripting and logic required
- Building production applications

### Puppeteer vs Playwright

| Feature | Puppeteer | Playwright |
|---------|-----------|------------|
| API Style | Chrome DevTools Protocol | High-level abstractions |
| Selectors | CSS, XPath | CSS, text, role, test-id |
| Best for | Advanced control, CDP access | Quick automation, testing |
| Learning curve | Steeper | Gentler |

**Use Puppeteer:** Need CDP protocol access, Chrome-specific features, migration from existing Puppeteer code
**Use Playwright:** Modern selector APIs, cross-browser patterns, faster development

## Tier Limits Summary

| Limit | Free Tier | Paid Tier |
|-------|-----------|-----------|
| Daily browser time | 10 minutes | Unlimited* |
| Concurrent sessions | 3 | 30 |
| Requests per minute | 6 | 180 |

*Subject to fair-use policy. See [gotchas.md](gotchas.md) for details.

## Reading Order

**New to Browser Rendering:**
1. [configuration.md](configuration.md) - Setup and deployment
2. [patterns.md](patterns.md) - Common use cases with examples
3. [api.md](api.md) - API reference
4. [gotchas.md](gotchas.md) - Avoid common pitfalls

**Specific task:**
- **Setup/deployment** → [configuration.md](configuration.md)
- **API reference/endpoints** → [api.md](api.md)
- **Example code/patterns** → [patterns.md](patterns.md)
- **Debugging/troubleshooting** → [gotchas.md](gotchas.md)

**REST API users:**
- Start with [api.md](api.md) REST API section
- Check [gotchas.md](gotchas.md) for rate limits

**Workers users:**
- Start with [configuration.md](configuration.md)
- Review [patterns.md](patterns.md) for session management
- Reference [api.md](api.md) for Workers Bindings

## In This Reference

- **[configuration.md](configuration.md)** - Setup, deployment, wrangler config, compatibility
- **[api.md](api.md)** - REST API endpoints + Workers Bindings (Puppeteer/Playwright)
- **[patterns.md](patterns.md)** - Common patterns, use cases, real examples
- **[gotchas.md](gotchas.md)** - Troubleshooting, best practices, tier limits, common errors

## See Also

- [Cloudflare Docs](https://developers.cloudflare.com/browser-rendering/)

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/c3/README.md`)

# C3 (create-cloudflare)

Official CLI for scaffolding Cloudflare Workers and Pages projects with templates, TypeScript, and instant deployment.

## Quick Start

```bash
# Interactive (recommended for first-time)
npm create cloudflare@latest my-app

# Worker (API/WebSocket/Cron)
npm create cloudflare@latest my-api -- --type=hello-world --ts

# Pages (static/SSG/full-stack)
npm create cloudflare@latest my-site -- --type=web-app --framework=astro --platform=pages
```

## Platform Decision Tree

```
What are you building?

├─ API / WebSocket / Cron / Email handler
│   └─ Workers (default) - no --platform flag needed
│       npm create cloudflare@latest my-api -- --type=hello-world

├─ Static site / SSG / Documentation
│   └─ Pages - requires --platform=pages
│       npm create cloudflare@latest my-site -- --type=web-app --framework=astro --platform=pages

├─ Full-stack app (Next.js/Remix/SvelteKit)
│   ├─ Need Durable Objects, Queues, or Workers-only features?
│   │   └─ Workers (default)
│   └─ Otherwise use Pages for git integration and branch previews
│       └─ Add --platform=pages

└─ Convert existing project
    └─ npm create cloudflare@latest . -- --type=pre-existing --existing-script=./src/worker.ts
```

**Critical:** Pages projects require `--platform=pages` flag. Without it, C3 defaults to Workers.

## Interactive Flow

When run without flags, C3 prompts in this order:

1. **Project name** - Directory to create (defaults to current dir with `.`)
2. **Application type** - `hello-world`, `web-app`, `demo`, `pre-existing`, `remote-template`
3. **Platform** - `workers` (default) or `pages` (for web apps only)
4. **Framework** - If web-app: `next`, `remix`, `astro`, `react-router`, `solid`, `svelte`, etc.
5. **TypeScript** - `yes` (recommended) or `no`
6. **Git** - Initialize repository? `yes` or `no`
7. **Deploy** - Deploy now? `yes` or `no` (requires `wrangler login`)

## Installation Methods

```bash
# NPM
npm create cloudflare@latest

# Yarn
yarn create cloudflare

# PNPM
pnpm create cloudflare@latest
```

## In This Reference

| File | Purpose | Use When |
|------|---------|----------|
| **api.md** | Complete CLI flag reference | Scripting, CI/CD, advanced usage |
| **configuration.md** | Generated files, bindings, types | Understanding output, customization |
| **patterns.md** | Workflows, CI/CD, monorepos | Real-world integration |
| **gotchas.md** | Troubleshooting failures | Deployment blocked, errors |

## Reading Order

| Task | Read |
|------|------|
| Create first project | README only |
| Set up CI/CD | README → api → patterns |
| Debug failed deploy | gotchas |
| Understand generated files | configuration |
| Full CLI reference | api |
| Create custom template | patterns → configuration |
| Convert existing project | README → patterns |

## Post-Creation

```bash
cd my-app

# Local dev with hot reload
npm run dev

# Generate TypeScript types for bindings
npm run cf-typegen

# Deploy to Cloudflare
npm run deploy
```

## See Also

- **workers/README.md** - Workers runtime, bindings, APIs
- **workers-ai/README.md** - AI/ML models
- **pages/README.md** - Pages-specific features
- **wrangler/README.md** - Wrangler CLI beyond initial setup
- **d1/README.md** - SQLite database
- **r2/README.md** - Object storage

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/cache-reserve/README.md`)

# Cloudflare Cache Reserve

**Persistent cache storage built on R2 for long-term content retention**

## Smart Shield Integration

Cache Reserve is part of **Smart Shield**, Cloudflare's comprehensive security and performance suite:

- **Smart Shield Advanced tier**: Includes 2TB Cache Reserve storage
- **Standalone purchase**: Available separately if not using Smart Shield
- **Migration**: Existing standalone customers can migrate to Smart Shield bundles

**Decision**: Already on Smart Shield Advanced? Cache Reserve is included. Otherwise evaluate standalone purchase vs Smart Shield upgrade.

## Overview

Cache Reserve is Cloudflare's persistent, large-scale cache storage layer built on R2. It acts as the ultimate upper-tier cache, storing cacheable content for extended periods (30+ days) to maximize cache hits, reduce origin egress fees, and shield origins from repeated requests for long-tail content.

## Core Concepts

### What is Cache Reserve?

- **Persistent storage layer**: Built on R2, sits above tiered cache hierarchy
- **Long-term retention**: 30-day default retention, extended on each access
- **Automatic operation**: Works seamlessly with existing CDN, no code changes required
- **Origin shielding**: Dramatically reduces origin egress by serving cached content longer
- **Usage-based pricing**: Pay only for storage + read/write operations

### Cache Hierarchy

```
Visitor Request
    ↓
Lower-Tier Cache (closest to visitor)
    ↓ (on miss)
Upper-Tier Cache (closest to origin)
    ↓ (on miss)
Cache Reserve (R2 persistent storage)
    ↓ (on miss)
Origin Server
```

### How It Works

1. **On cache miss**: Content fetched from origin �� written to Cache Reserve + edge caches simultaneously
2. **On edge eviction**: Content may be evicted from edge cache but remains in Cache Reserve
3. **On subsequent request**: If edge cache misses but Cache Reserve hits → content restored to edge caches
4. **Retention**: Assets remain in Cache Reserve for 30 days since last access (configurable via TTL)

## When to Use Cache Reserve

```
Need persistent caching?
├─ High origin egress costs → Cache Reserve ✓
├─ Long-tail content (archives, media libraries) → Cache Reserve ✓
├─ Already using Smart Shield Advanced → Included! ✓
├─ Video streaming with seeking (range requests) → ✗ Not supported
├─ Dynamic/personalized content → ✗ Use edge cache only
├─ Need per-request cache control from Workers → ✗ Use R2 directly
└─ Frequently updated content (< 10hr lifetime) → ✗ Not eligible
```

## Asset Eligibility

Cache Reserve only stores assets meeting **ALL** criteria:

- Cacheable per Cloudflare's standard rules
- Minimum 10-hour TTL (36000 seconds)
- `Content-Length` header present
- Original files only (not transformed images)

### Eligibility Checklist

Use this checklist to verify if an asset is eligible:

- [ ] Zone has Cache Reserve enabled
- [ ] Zone has Tiered Cache enabled (required)
- [ ] Asset TTL ≥ 10 hours (36,000 seconds)
- [ ] `Content-Length` header present on origin response
- [ ] No `Set-Cookie` header (or uses private directive)
- [ ] `Vary` header is NOT `*` (can be `Accept-Encoding`)
- [ ] Not an image transformation variant (original images OK)
- [ ] Not a range request (no HTTP 206 support)
- [ ] Not O2O (Orange-to-Orange) proxied request

**All boxes must be checked for Cache Reserve eligibility.**

### Not Eligible

- Assets with TTL < 10 hours
- Responses without `Content-Length` header
- Image transformation variants (original images are eligible)
- Responses with `Set-Cookie` headers
- Responses with `Vary: *` header
- Assets from R2 public buckets on same zone
- O2O (Orange-to-Orange) setup requests
- **Range requests** (video seeking, partial content downloads)

## Quick Start

```bash
# Enable via Dashboard
https://dash.cloudflare.com/caching/cache-reserve
# Click "Enable Storage Sync" or "Purchase" button
```

**Prerequisites:**
- Paid Cache Reserve plan or Smart Shield Advanced required
- Tiered Cache required for optimal performance

## Essential Commands

```bash
# Check Cache Reserve status
curl -X GET "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/cache/cache_reserve" \
  -H "Authorization: Bearer $API_TOKEN"

# Enable Cache Reserve
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/cache/cache_reserve" \
  -H "Authorization: Bearer $API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"value": "on"}'

# Check asset cache status
curl -I https://example.com/asset.jpg | grep -i cache
```

## In This Reference

| Task | Files |
|------|-------|
| Evaluate if Cache Reserve fits your use case | README.md (this file) |
| Enable Cache Reserve for your zone | README.md + [configuration.md](./configuration.md) |
| Use with Workers (understand limitations) | [api.md](./api.md) |
| Setup via SDKs or IaC (TypeScript, Python, Terraform) | [configuration.md](./configuration.md) |
| Optimize costs and debug issues | [patterns.md](./patterns.md) + [gotchas.md](./gotchas.md) |
| Understand eligibility and troubleshoot | [gotchas.md](./gotchas.md) → [patterns.md](./patterns.md) |

**Files:**
- [configuration.md](./configuration.md) - Setup, API, SDKs, and Cache Rules
- [api.md](./api.md) - Purging, monitoring, Workers integration
- [patterns.md](./patterns.md) - Best practices, cost optimization, debugging
- [gotchas.md](./gotchas.md) - Common issues, limitations, troubleshooting

## See Also
- [r2](../r2/) - Cache Reserve built on R2 storage
- [workers](../workers/) - Workers integration with Cache API

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/containers/README.md`)

# Cloudflare Containers Skill Reference

**APPLIES TO: Cloudflare Containers ONLY - NOT general Cloudflare Workers**

Use when working with Cloudflare Containers: deploying containerized apps on Workers platform, configuring container-enabled Durable Objects, managing container lifecycle, or implementing stateful/stateless container patterns.

## Beta Status

⚠️ Containers is currently in **beta**. API may change without notice. No SLA guarantees. Custom instance types added Jan 2026.

## Core Concepts

**Container as Durable Object:** Each container is a Durable Object with persistent identity. Accessed via `getByName(id)` or `getRandom()`.

**Image deployment:** Images pre-fetched globally. Deployments use rolling strategy (not instant like Workers).

**Lifecycle:** cold start (2-3s) → running → `sleepAfter` timeout → stopped. No autoscaling - manual load balancing via `getRandom()`.

**Persistent identity, ephemeral disk:** Container ID persists, but disk resets on stop. Use Durable Object storage for persistence.

## Quick Start

```typescript
import { Container } from "@cloudflare/containers";

export class MyContainer extends Container {
  defaultPort = 8080;
  sleepAfter = "30m";
}

export default {
  async fetch(request: Request, env: Env) {
    const container = env.MY_CONTAINER.getByName("instance-1");
    await container.startAndWaitForPorts();
    return container.fetch(request);
  }
};
```

## Reading Order

| Task | Files |
|------|-------|
| Setup new container project | README → configuration.md |
| Implement container logic | README → api.md → patterns.md |
| Choose routing pattern | patterns.md (routing section) |
| Debug issues | gotchas.md |
| Production hardening | gotchas.md → patterns.md (lifecycle) |

## Routing Decision Tree

**How should requests reach containers?**

- **Same user/session → same container:** Use `getByName(sessionId)` for session affinity
- **Stateless, spread load:** Use `getRandom()` for load balancing
- **Job per container:** Use `getByName(jobId)` + explicit lifecycle management
- **Single global instance:** Use `getByName("singleton")`

## When to Use Containers vs Workers

**Use Containers when:**
- Need stateful, long-lived processes (sessions, WebSockets, games)
- Running existing containerized apps (Node.js, Python, custom binaries)
- Need filesystem access or specific system dependencies
- Per-user/session isolation with dedicated compute

**Use Workers when:**
- Stateless HTTP handlers
- Sub-millisecond cold starts required
- Auto-scaling to zero critical
- Simple request/response patterns

## In This Reference

- **[configuration.md](configuration.md)** - Wrangler config, instance types, Container class properties, environment variables, account limits
- **[api.md](api.md)** - Container class API, startup methods, communication (HTTP/TCP/WebSocket), routing helpers, lifecycle hooks, scheduling, state inspection
- **[patterns.md](patterns.md)** - Routing patterns (session affinity, load balancing, singleton), WebSocket forwarding, graceful shutdown, Workflow/Queue integration
- **[gotchas.md](gotchas.md)** - Critical gotchas (WebSocket, startup methods), common errors with solutions, specific limits, beta caveats

## See Also

- [Durable Objects](../durable-objects/) - Containers extend Durable Objects
- [Workflows](../workflows/) - Orchestrate container operations
- [Queues](../queues/) - Trigger containers from queue messages
- [Cloudflare Docs](https://developers.cloudflare.com/containers/)

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/cron-triggers/README.md`)

# Cloudflare Cron Triggers

Schedule Workers execution using cron expressions. Runs on Cloudflare's global network during underutilized periods.

## Key Features

- **UTC-only execution** - All schedules run on UTC time
- **5-field cron syntax** - Quartz scheduler extensions (L, W, #)
- **Global propagation** - 15min deployment delay
- **At-least-once delivery** - Rare duplicate executions possible
- **Workflow integration** - Trigger long-running multi-step tasks
- **Green Compute** - Optional carbon-aware scheduling during low-carbon periods

## Cron Syntax

```
 ┌─────────── minute (0-59)
 │ ┌───────── hour (0-23)
 │ │ ┌─────── day of month (1-31)
 │ │ │ ┌───── month (1-12, JAN-DEC)
 │ │ │ │ ┌─── day of week (1-7, SUN-SAT, 1=Sunday)
 * * * * *
```

**Special chars:** `*` (any), `,` (list), `-` (range), `/` (step), `L` (last), `W` (weekday), `#` (nth)

## Common Schedules

```bash
*/5 * * * *        # Every 5 minutes
0 * * * *          # Hourly
0 2 * * *          # Daily 2am UTC (off-peak)
0 9 * * MON-FRI    # Weekdays 9am UTC
0 0 1 * *          # Monthly 1st midnight UTC
0 9 L * *          # Last day of month 9am UTC
0 10 * * MON#2     # 2nd Monday 10am UTC
*/10 9-17 * * MON-FRI  # Every 10min, 9am-5pm weekdays
```

## Quick Start

**wrangler.jsonc:**
```jsonc
{
  "name": "my-cron-worker",
  "triggers": {
    "crons": ["*/5 * * * *", "0 2 * * *"]
  }
}
```

**Handler:**
```typescript
export default {
  async scheduled(
    controller: ScheduledController,
    env: Env,
    ctx: ExecutionContext,
  ): Promise<void> {
    console.log("Cron:", controller.cron);
    console.log("Time:", new Date(controller.scheduledTime));
    
    ctx.waitUntil(asyncTask(env)); // Non-blocking
  },
};
```

**Test locally:**
```bash
npx wrangler dev
curl "http://localhost:8787/__scheduled?cron=*/5+*+*+*+*"
```

## Limits

- **Free:** 3 triggers/worker, 10ms CPU
- **Paid:** Unlimited triggers, 50ms CPU
- **Propagation:** 15min global deployment
- **Timezone:** UTC only

## Reading Order

**New to cron triggers?** Start here:
1. This README - Overview and quick start
2. [configuration.md](./configuration.md) - Set up your first cron trigger
3. [api.md](./api.md) - Understand the handler API
4. [patterns.md](./patterns.md) - Common use cases and examples

**Troubleshooting?** Jump to [gotchas.md](./gotchas.md)

## In This Reference
- [configuration.md](./configuration.md) - wrangler config, env-specific schedules, Green Compute
- [api.md](./api.md) - ScheduledController, noRetry(), waitUntil, testing patterns
- [patterns.md](./patterns.md) - Use cases, monitoring, queue integration, Durable Objects
- [gotchas.md](./gotchas.md) - Timezone issues, idempotency, security, testing

## See Also
- [workflows](../workflows/) - Alternative for long-running scheduled tasks
- [workers](../workers/) - Worker runtime documentation

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/d1/README.md`)

# Cloudflare D1 Database

Expert guidance for Cloudflare D1, a serverless SQLite database designed for horizontal scale-out across multiple databases.

## Overview

D1 is Cloudflare's managed, serverless database with:
- SQLite SQL semantics and compatibility
- Built-in disaster recovery via Time Travel (30-day point-in-time recovery)
- Horizontal scale-out architecture (10 GB per database)
- Worker and HTTP API access
- Pricing based on query and storage costs only

**Architecture Philosophy**: D1 is optimized for per-user, per-tenant, or per-entity database patterns rather than single large databases.

## Quick Start

```bash
# Create database
wrangler d1 create <database-name>

# Execute migration
wrangler d1 migrations apply <db-name> --remote

# Local development
wrangler dev
```

## Core Query Methods

```typescript
// .all() - Returns all rows; .first() - First row or null; .first(col) - Single column value
// .run() - INSERT/UPDATE/DELETE; .raw() - Array of arrays (efficient)
const { results, success, meta } = await env.DB.prepare('SELECT * FROM users WHERE active = ?').bind(true).all();
const user = await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(userId).first();
```

## Batch Operations

```typescript
// Multiple queries in single round trip (atomic transaction)
const results = await env.DB.batch([
  env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(1),
  env.DB.prepare('SELECT * FROM posts WHERE author_id = ?').bind(1),
  env.DB.prepare('UPDATE users SET last_access = ? WHERE id = ?').bind(Date.now(), 1)
]);
```

## Sessions API (Paid Plans)

```typescript
// Create long-running session for analytics/migrations (up to 15 minutes)
const session = env.DB.withSession();
try {
  await session.prepare('CREATE INDEX idx_heavy ON large_table(column)').run();
  await session.prepare('ANALYZE').run();
} finally {
  session.close(); // Always close to release resources
}
```

## Read Replication (Paid Plans)

```typescript
// Read from nearest replica for lower latency (automatic failover)
const user = await env.DB_REPLICA.prepare('SELECT * FROM users WHERE id = ?').bind(userId).first();

// Writes always go to primary
await env.DB.prepare('UPDATE users SET last_login = ? WHERE id = ?').bind(Date.now(), userId).run();
```

## Platform Limits

| Limit | Free Tier | Paid Plans |
|-------|-----------|------------|
| Database size | 500 MB | 10 GB per database |
| Row size | 1 MB max | 1 MB max |
| Query timeout | 30 seconds | 30 seconds |
| Batch size | 1,000 statements | 10,000 statements |
| Time Travel retention | 7 days | 30 days |
| Read replicas | Not available | Yes (paid add-on) |

**Pricing**: $5/month per database beyond free tier + $0.001 per 1K reads + $1 per 1M writes + $0.75/GB storage/month

## CLI Commands

```bash
# Database management
wrangler d1 create <db-name>
wrangler d1 list
wrangler d1 delete <db-name>

# Migrations
wrangler d1 migrations create <db-name> <migration-name>    # Create new migration file
wrangler d1 migrations apply <db-name> --remote             # Apply pending migrations
wrangler d1 migrations apply <db-name> --local              # Apply locally
wrangler d1 migrations list <db-name> --remote              # Show applied migrations

# Direct SQL execution
wrangler d1 execute <db-name> --remote --command="SELECT * FROM users"
wrangler d1 execute <db-name> --local --file=./schema.sql

# Backups & Import/Export
wrangler d1 export <db-name> --remote --output=./backup.sql  # Full export with schema
wrangler d1 export <db-name> --remote --no-schema --output=./data.sql  # Data only
wrangler d1 time-travel restore <db-name> --timestamp="2024-01-15T14:30:00Z"  # Point-in-time recovery

# Development
wrangler dev --persist-to=./.wrangler/state
```

## Reading Order

**Start here**: Quick Start above → configuration.md (setup) → api.md (queries)

**Common tasks**:
- First time setup: configuration.md → Run migrations
- Adding queries: api.md → Prepared statements
- Pagination/caching: patterns.md
- Production optimization: Read Replication + Sessions API (this file)
- Debugging: gotchas.md

## In This Reference

- [configuration.md](./configuration.md) - wrangler.jsonc setup, migrations, TypeScript types, ORMs, local dev
- [api.md](./api.md) - Query methods (.all/.first/.run/.raw), batch, sessions, read replicas, error handling
- [patterns.md](./patterns.md) - Pagination, bulk operations, caching, multi-tenant, sessions, analytics
- [gotchas.md](./gotchas.md) - SQL injection, limits by plan tier, performance, common errors

## See Also

- [workers](../workers/) - Worker runtime and fetch handler patterns
- [hyperdrive](../hyperdrive/) - Connection pooling for external databases

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/ddos/README.md`)

# Cloudflare DDoS Protection

Autonomous, always-on protection against DDoS attacks across L3/4 and L7.

## Protection Types

- **HTTP DDoS (L7)**: Protects HTTP/HTTPS traffic, phase `ddos_l7`, zone/account level
- **Network DDoS (L3/4)**: UDP/SYN/DNS floods, phase `ddos_l4`, account level only
- **Adaptive DDoS**: Learns 7-day baseline, detects deviations, 4 profile types (Origins, User-Agents, Locations, Protocols)

## Plan Availability

| Feature | Free | Pro | Business | Enterprise | Enterprise Advanced |
|---------|------|-----|----------|------------|---------------------|
| HTTP DDoS (L7) | ✓ | ✓ | ✓ | ✓ | ✓ |
| Network DDoS (L3/4) | ✓ | ✓ | ✓ | ✓ | ✓ |
| Override rules | 1 | 1 | 1 | 1 | 10 |
| Custom expressions | ✗ | ✗ | ✗ | ✗ | ✓ |
| Log action | ✗ | ✗ | ✗ | ✗ | ✓ |
| Adaptive DDoS | ✗ | ✗ | ✗ | ✓ | ✓ |
| Alert filters | Basic | Basic | Basic | Advanced | Advanced |

## Actions & Sensitivity

- **Actions**: `block`, `managed_challenge`, `challenge`, `log` (Enterprise Advanced only)
- **Sensitivity**: `default` (high), `medium`, `low`, `eoff` (essentially off)
- **Override**: By category/tag or individual rule ID
- **Scope**: Zone-level overrides take precedence over account-level

## Reading Order

| File | Purpose | Start Here If... |
|------|---------|------------------|
| [configuration.md](./configuration.md) | Dashboard setup, rule structure, adaptive profiles | You're setting up DDoS protection for the first time |
| [api.md](./api.md) | API endpoints, SDK usage, ruleset ID discovery | You're automating configuration or need programmatic access |
| [patterns.md](./patterns.md) | Protection strategies, defense-in-depth, dynamic response | You need implementation patterns or layered security |
| [gotchas.md](./gotchas.md) | False positives, tuning, error handling | You're troubleshooting or optimizing existing protection |

## See Also
- [waf](../waf/) - Application-layer security rules
- [bot-management](../bot-management/) - Bot detection and mitigation

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/do-storage/README.md`)

# Cloudflare Durable Objects Storage

Persistent storage API for Durable Objects with SQLite and KV backends, PITR, and automatic concurrency control.

## Overview

DO Storage provides:
- SQLite-backed (recommended) or KV-backed
- SQL API + synchronous/async KV APIs
- Automatic input/output gates (race-free)
- 30-day point-in-time recovery (PITR)
- Transactions and alarms

**Use cases:** Stateful coordination, real-time collaboration, counters, sessions, rate limiters

**Billing:** Charged by request, GB-month storage, and rowsRead/rowsWritten for SQL operations

## Quick Start

```typescript
export class Counter extends DurableObject {
  sql: SqlStorage;
  
  constructor(ctx: DurableObjectState, env: Env) {
    super(ctx, env);
    this.sql = ctx.storage.sql;
    this.sql.exec('CREATE TABLE IF NOT EXISTS data(key TEXT PRIMARY KEY, value INTEGER)');
  }
  
  async increment(): Promise<number> {
    const result = this.sql.exec(
      'INSERT INTO data VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = value + 1 RETURNING value',
      'counter', 1
    ).one();
    return result?.value || 1;
  }
}
```

## Storage Backends

| Backend | Create Method | APIs | PITR |
|---------|---------------|------|------|
| SQLite (recommended) | `new_sqlite_classes` | SQL + sync KV + async KV | ✅ |
| KV (legacy) | `new_classes` | async KV only | ❌ |

## Core APIs

- **SQL API** (`ctx.storage.sql`): Full SQLite with extensions (FTS5, JSON, math)
- **Sync KV** (`ctx.storage.kv`): Synchronous key-value (SQLite only)
- **Async KV** (`ctx.storage`): Asynchronous key-value (both backends)
- **Transactions** (`transactionSync()`, `transaction()`)
- **PITR** (`getBookmarkForTime()`, `onNextSessionRestoreBookmark()`)
- **Alarms** (`setAlarm()`, `alarm()` handler)

## Reading Order

**New to DO storage:** configuration.md → api.md → patterns.md → gotchas.md  
**Building features:** patterns.md → api.md → gotchas.md  
**Debugging issues:** gotchas.md → api.md  
**Writing tests:** testing.md

## In This Reference

- [configuration.md](./configuration.md) - wrangler.jsonc migrations, SQLite vs KV setup, RPC binding
- [api.md](./api.md) - SQL exec/cursors, KV methods, storage options, transactions, alarms, PITR
- [patterns.md](./patterns.md) - Schema migrations, caching, rate limiting, batch processing, parent-child coordination
- [gotchas.md](./gotchas.md) - Concurrency gates, INTEGER precision, transaction rules, SQL limits
- [testing.md](./testing.md) - vitest-pool-workers setup, testing DOs with SQL/alarms/PITR

## See Also

- [durable-objects](../durable-objects/) - DO fundamentals and coordination patterns
- [workers](../workers/) - Worker runtime for DO stubs
- [d1](../d1/) - Shared database alternative to per-DO storage

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/durable-objects/README.md`)

# Cloudflare Durable Objects

Expert guidance for building stateful applications with Cloudflare Durable Objects.

## Reading Order

1. **First time?** Read this overview + Quick Start
2. **Setting up?** See [Configuration](./configuration.md)
3. **Building features?** Use decision trees below → [Patterns](./patterns.md)
4. **Debugging issues?** Check [Gotchas](./gotchas.md)
5. **Deep dive?** [API](./api.md) and [DO Storage](../do-storage/README.md)

## Overview

Durable Objects combine compute with storage in globally-unique, strongly-consistent packages:
- **Globally unique instances**: Each DO has unique ID for multi-client coordination
- **Co-located storage**: Fast, strongly-consistent storage with compute
- **Automatic placement**: Objects spawn near first request location
- **Stateful serverless**: In-memory state + persistent storage
- **Single-threaded**: Serial request processing (no race conditions)

## Rules of Durable Objects

Critical rules preventing most production issues:

1. **One alarm per DO** - Schedule multiple events via queue pattern
2. **~1K req/s per DO max** - Shard for higher throughput
3. **Constructor runs every wake** - Keep initialization light; use lazy loading
4. **Hibernation clears memory** - In-memory state lost; persist critical data
5. **Use `ctx.waitUntil()` for cleanup** - Ensures completion after response sent
6. **No setTimeout for persistence** - Use `setAlarm()` for reliable scheduling

## Core Concepts

### Class Structure
All DOs extend `DurableObject` base class with constructor receiving `DurableObjectState` (storage, WebSockets, alarms) and `Env` (bindings).

### Lifecycle States

```
[Not Created] → [Active] ⇄ [Hibernated] → [Evicted]
                   ↓
              [Destroyed]
```

- **Not Created**: DO ID exists but instance never spawned
- **Active**: Processing requests, in-memory state valid, billed per GB-hour
- **Hibernated**: WebSocket connections open but zero compute, zero cost
- **Evicted**: Removed from memory; next request triggers cold start
- **Destroyed**: Data deleted via migration or manual deletion

### Accessing from Workers
Workers use bindings to get stubs, then call RPC methods directly (recommended) or use fetch handler (legacy).

**RPC vs fetch() decision:**
```
├─ New project + compat ≥2024-04-03 → RPC (type-safe, simpler)
├─ Need HTTP semantics (headers, status) → fetch()
├─ Proxying requests to DO → fetch()
└─ Legacy compatibility → fetch()
```

See [Patterns: RPC vs fetch()](./patterns.md) for examples.

### ID Generation
- `idFromName()`: Deterministic, named coordination (rate limiting, locks)
- `newUniqueId()`: Random IDs for sharding high-throughput workloads
- `idFromString()`: Derive from existing IDs
- Jurisdiction option: Data locality compliance

### Storage Options

**Which storage API?**
```
├─ Structured data, relations, transactions → SQLite (recommended)
├─ Simple KV on SQLite DO → ctx.storage.kv (sync KV)
└─ Legacy KV-only DO → ctx.storage (async KV)
```

- **SQLite** (recommended): Structured data, transactions, 10GB/DO
- **Synchronous KV API**: Simple key-value on SQLite objects
- **Asynchronous KV API**: Legacy/advanced use cases

See [DO Storage](../do-storage/README.md) for deep dive.

### Special Features
- **Alarms**: Schedule future execution per-DO (1 per DO - use queue pattern for multiple)
- **WebSocket Hibernation**: Zero-cost idle connections (memory cleared on hibernation)
- **Point-in-Time Recovery**: Restore to any point in 30 days (SQLite only)

## Quick Start

```typescript
import { DurableObject } from "cloudflare:workers";

export class Counter extends DurableObject<Env> {
  async increment(): Promise<number> {
    const result = this.ctx.storage.sql.exec(
      `INSERT INTO counters (id, value) VALUES (1, 1)
       ON CONFLICT(id) DO UPDATE SET value = value + 1
       RETURNING value`
    ).one();
    return result.value;
  }
}

// Worker access
export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const id = env.COUNTER.idFromName("global");
    const stub = env.COUNTER.get(id);
    const count = await stub.increment();
    return new Response(`Count: ${count}`);
  }
};
```

## Decision Trees

### What do you need?

```
├─ Coordinate requests (rate limit, lock, session)
│   → idFromName(identifier) → [Patterns: Rate Limiting/Locks](./patterns.md)
│
├─ High throughput (>1K req/s)
│   → Sharding with newUniqueId() or hash → [Patterns: Sharding](./patterns.md)
│
├─ Real-time updates (WebSocket, chat, collab)
│   → WebSocket hibernation + room pattern → [Patterns: Real-time](./patterns.md)
│
├─ Background work (cleanup, notifications, scheduled tasks)
│   → Alarms + queue pattern (1 alarm/DO) → [Patterns: Multiple Events](./patterns.md)
│
└─ User sessions with expiration
    → Session pattern + alarm cleanup → [Patterns: Session Management](./patterns.md)
```

### Which access pattern?

```
├─ New project + typed methods → RPC (compat ≥2024-04-03)
├─ Need HTTP semantics → fetch()
├─ Proxying to DO → fetch()
└─ Legacy compat → fetch()
```

See [Patterns: RPC vs fetch()](./patterns.md) for examples.

### Which storage?

```
├─ Structured data, SQL queries, transactions → SQLite (recommended)
├─ Simple KV on SQLite DO → ctx.storage.kv (sync API)
└─ Legacy KV-only DO → ctx.storage (async API)
```

See [DO Storage](../do-storage/README.md) for complete guide.

## Essential Commands

```bash
npx wrangler dev              # Local dev with DOs
npx wrangler dev --remote     # Test against prod DOs
npx wrangler deploy           # Deploy + auto-apply migrations
```

## Resources

**Docs**: https://developers.cloudflare.com/durable-objects/  
**API Reference**: https://developers.cloudflare.com/durable-objects/api/  
**Examples**: https://developers.cloudflare.com/durable-objects/examples/

## In This Reference

- **[Configuration](./configuration.md)** - wrangler.jsonc setup, migrations, bindings, environments
- **[API](./api.md)** - Class structure, ctx methods, alarms, WebSocket hibernation
- **[Patterns](./patterns.md)** - Sharding, rate limiting, locks, real-time, sessions
- **[Gotchas](./gotchas.md)** - Limits, hibernation caveats, common errors

## See Also

- **[DO Storage](../do-storage/README.md)** - SQLite, KV, transactions (detailed storage guide)
- **[Workers](../workers/README.md)** - Core Workers runtime features
- **[WebSockets](../websockets/README.md)** - WebSocket APIs and patterns

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/email-routing/README.md`)

# Cloudflare Email Routing Skill Reference

## Overview

Cloudflare Email Routing enables custom email addresses for your domain that route to verified destination addresses. It's free, privacy-focused (no storage/access), and includes Email Workers for programmatic email processing.

**Available to all Cloudflare customers using Cloudflare as authoritative nameserver.**

## Quick Start

```typescript
// Basic email handler
export default {
  async email(message, env, ctx) {
    // CRITICAL: Must consume stream before response
    const parser = new PostalMime.default();
    const email = await parser.parse(await message.raw.arrayBuffer());
    
    // Process email
    console.log(`From: ${message.from}, Subject: ${email.subject}`);
    
    // Forward or reject
    await message.forward("verified@destination.com");
  }
} satisfies ExportedHandler<Env>;
```

## Reading Order

**Start here based on your goal:**

1. **New to Email Routing?** → [configuration.md](configuration.md) → [patterns.md](patterns.md)
2. **Adding Workers?** → [api.md](api.md) § Worker Runtime API → [patterns.md](patterns.md)
3. **Sending emails?** → [api.md](api.md) § SendEmail Binding
4. **Managing via API?** → [api.md](api.md) § REST API Operations
5. **Debugging issues?** → [gotchas.md](gotchas.md)

## Decision Tree

```
Need to receive emails?
├─ Simple forwarding only? → Dashboard rules (configuration.md)
├─ Complex logic/filtering? → Email Workers (api.md + patterns.md)
└─ Parse attachments/body? → postal-mime library (patterns.md § Parse Email)

Need to send emails?
├─ From Worker? → SendEmail binding (api.md § SendEmail)
└─ From external app? → Use external SMTP/API service

Having issues?
├─ Email not arriving? → gotchas.md § Mail Authentication
├─ Worker crashing? → gotchas.md § Stream Consumption
└─ Forward failing? → gotchas.md § Destination Verification
```

## Key Concepts

**Routing Rules**: Pattern-based forwarding configured via Dashboard/API. Simple but limited.

**Email Workers**: Custom TypeScript handlers with full email access. Handles complex logic, parsing, storage, rejection.

**SendEmail Binding**: Outbound email API for Workers. Transactional email only (no marketing/bulk).

**ForwardableEmailMessage**: Runtime interface for incoming emails. Provides headers, raw stream, forward/reject methods.

## In This Reference

- **[configuration.md](configuration.md)** - Setup, deployment, wrangler config
- **[api.md](api.md)** - REST API + Worker runtime API + types
- **[patterns.md](patterns.md)** - Common patterns with working examples
- **[gotchas.md](gotchas.md)** - Critical pitfalls, troubleshooting, limits

## Architecture

```
Internet → MX Records → Cloudflare Email Routing
                            ├─ Routing Rules (dashboard)
                            └─ Email Worker (your code)
                                ├─ Forward to destination
                                ├─ Reject with reason
                                ├─ Store in R2/KV/D1
                                └─ Send outbound (SendEmail)
```

## See Also

- [Cloudflare Docs: Email Routing](https://developers.cloudflare.com/email-routing/)
- [Cloudflare Docs: Email Workers](https://developers.cloudflare.com/email-routing/email-workers/)
- [postal-mime npm package](https://www.npmjs.com/package/postal-mime)

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/email-workers/README.md`)

# Cloudflare Email Workers

Process incoming emails programmatically using Cloudflare Workers runtime.

## Overview

Email Workers enable custom email processing logic at the edge. Build spam filters, auto-responders, ticket systems, notification handlers, and more using the same Workers runtime you use for HTTP requests.

**Key capabilities**:
- Process inbound emails with full message access
- Forward to verified destinations
- Send replies with proper threading
- Parse MIME content and attachments
- Integrate with KV, R2, D1, and external APIs

## Quick Start

### Minimal ES Modules Handler

```typescript
export default {
  async email(message, env, ctx) {
    // Reject spam
    if (message.from.includes('spam.com')) {
      message.setReject('Blocked');
      return;
    }
    
    // Forward to inbox
    await message.forward('inbox@example.com');
  }
};
```

### Core Operations

| Operation | Method | Use Case |
|-----------|--------|----------|
| Forward | `message.forward(to, headers?)` | Route to verified destination |
| Reject | `message.setReject(reason)` | Block with SMTP error |
| Reply | `message.reply(emailMessage)` | Auto-respond with threading |
| Parse | postal-mime library | Extract subject, body, attachments |

## Reading Order

For comprehensive understanding, read files in this order:

1. **README.md** (this file) - Overview and quick start
2. **configuration.md** - Setup, deployment, bindings
3. **api.md** - Complete API reference
4. **patterns.md** - Real-world implementation examples
5. **gotchas.md** - Critical pitfalls and debugging

## In This Reference

| File | Description | Key Topics |
|------|-------------|------------|
| [api.md](./api.md) | Complete API reference | ForwardableEmailMessage, SendEmail bindings, reply() method, postal-mime/mimetext APIs |
| [configuration.md](./configuration.md) | Setup and configuration | wrangler.jsonc, bindings, deployment, dependencies |
| [patterns.md](./patterns.md) | Real-world examples | Allowlists from KV, auto-reply with threading, attachment extraction, webhook notifications |
| [gotchas.md](./gotchas.md) | Pitfalls and debugging | Stream consumption, ctx.waitUntil errors, security, limits |

## Architecture

```
Incoming Email → Email Routing → Email Worker
                                    ↓
                              Process + Decide
                                    ↓
                    ┌───────────────┼───────────────┐
                    ↓               ↓               ↓
                Forward          Reply          Reject
```

**Event flow**:
1. Email arrives at your domain
2. Email Routing matches route (e.g., `support@example.com`)
3. Bound Email Worker receives `ForwardableEmailMessage`
4. Worker processes and takes action (forward/reply/reject)
5. Email delivered or rejected based on worker logic

## Key Concepts

### Envelope vs Headers

- **Envelope addresses** (`message.from`, `message.to`): SMTP transport addresses (trusted)
- **Header addresses** (parsed from body): Display addresses (can be spoofed)

Use envelope addresses for security decisions.

### Single-Use Streams

`message.raw` is a ReadableStream that can only be read once. Buffer to ArrayBuffer for multiple uses.

```typescript
// Buffer first
const buffer = await new Response(message.raw).arrayBuffer();
const email = await PostalMime.parse(buffer);
```

See [gotchas.md](./gotchas.md#readablestream-can-only-be-consumed-once) for details.

### Verified Destinations

`forward()` only works with addresses verified in the Cloudflare Email Routing dashboard. Add destinations before deployment.

## Use Cases

- **Spam filtering**: Block based on sender, content, or reputation
- **Auto-responders**: Send acknowledgment replies with threading
- **Ticket creation**: Parse emails and create support tickets
- **Email archival**: Store in KV, R2, or D1
- **Notification routing**: Forward to Slack, Discord, or webhooks
- **Attachment processing**: Extract files to R2 storage
- **Multi-tenant routing**: Route based on recipient subdomain
- **Size filtering**: Reject oversized attachments

## Limits

| Limit | Value |
|-------|-------|
| Max message size | 25 MiB |
| Max routing rules | 200 |
| Max destinations | 200 |
| CPU time (free tier) | 10ms |
| CPU time (paid tier) | 50ms |

See [gotchas.md](./gotchas.md#limits-reference) for complete limits table.

## Prerequisites

Before deploying Email Workers:

1. **Enable Email Routing** in Cloudflare dashboard for your domain
2. **Verify destination addresses** for forwarding
3. **Configure DMARC/SPF** for sending domains (required for replies)
4. **Set up wrangler.jsonc** with SendEmail binding

See [configuration.md](./configuration.md) for detailed setup.

## Service Worker Syntax (Deprecated)

Modern projects should use ES modules format shown above. Service Worker syntax (`addEventListener('email', ...)`) is deprecated but still supported.

## See Also

- [Email Routing Documentation](https://developers.cloudflare.com/email-routing/)
- [Workers Platform](https://developers.cloudflare.com/workers/)
- [Wrangler CLI](https://developers.cloudflare.com/workers/wrangler/)
- [postal-mime on npm](https://www.npmjs.com/package/postal-mime)
- [mimetext on npm](https://www.npmjs.com/package/mimetext)

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/hyperdrive/README.md`)

# Hyperdrive

Accelerates database queries from Workers via connection pooling, edge setup, query caching.

## Key Features

- **Connection Pooling**: Persistent connections eliminate TCP/TLS/auth handshakes (~7 round-trips)
- **Edge Setup**: Connection negotiation at edge, pooling near origin
- **Query Caching**: Auto-cache non-mutating queries (default 60s TTL)
- **Support**: PostgreSQL, MySQL + compatibles (CockroachDB, Timescale, PlanetScale, Neon, Supabase)

## Architecture

```
Worker → Edge (setup) → Pool (near DB) → Origin
         ↓ cached reads
         Cache
```

## Quick Start

```bash
# Create config
npx wrangler hyperdrive create my-db \
  --connection-string="postgres://user:pass@host:5432/db"

# wrangler.jsonc
{
  "compatibility_flags": ["nodejs_compat"],
  "hyperdrive": [{"binding": "HYPERDRIVE", "id": "<ID>"}]
}
```

```typescript
import { Client } from "pg";

export default {
  async fetch(req: Request, env: Env): Promise<Response> {
    const client = new Client({
      connectionString: env.HYPERDRIVE.connectionString,
    });
    await client.connect();
    const result = await client.query("SELECT * FROM users WHERE id = $1", [123]);
    await client.end();
    return Response.json(result.rows);
  },
};
```

## When to Use

✅ Global access to single-region DBs, high read ratios, popular queries, connection-heavy loads
❌ Write-heavy, real-time data (<1s), single-region apps close to DB

**💡 Pair with Smart Placement** for Workers making multiple queries - executes near DB to minimize latency.

## Driver Choice

| Driver | Use When | Notes |
|--------|----------|-------|
| **pg** (recommended) | General use, TypeScript, ecosystem compatibility | Stable, widely used, works with most ORMs |
| **postgres.js** | Advanced features, template literals, streaming | Lighter than pg, `prepare: true` is default |
| **mysql2** | MySQL/MariaDB/PlanetScale | MySQL only, less mature support |

## Reading Order

| New to Hyperdrive | Implementing | Troubleshooting |
|-------------------|--------------|-----------------|
| 1. README (this) | 1. [configuration.md](./configuration.md) | 1. [gotchas.md](./gotchas.md) |
| 2. [configuration.md](./configuration.md) | 2. [api.md](./api.md) | 2. [patterns.md](./patterns.md) |
| 3. [api.md](./api.md) | 3. [patterns.md](./patterns.md) | 3. [api.md](./api.md) |

## In This Reference
- [configuration.md](./configuration.md) - Setup, wrangler config, Smart Placement
- [api.md](./api.md) - Binding APIs, query patterns, driver usage
- [patterns.md](./patterns.md) - Use cases, ORMs, multi-query optimization
- [gotchas.md](./gotchas.md) - Limits, troubleshooting, connection management

## See Also
- [smart-placement](../smart-placement/) - Optimize multi-query Workers near databases
- [d1](../d1/) - Serverless SQLite alternative for edge-native apps
- [workers](../workers/) - Worker runtime with database bindings

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/images/README.md`)

# Cloudflare Images Skill Reference

**Cloudflare Images** is an end-to-end image management solution providing storage, transformation, optimization, and delivery at scale via Cloudflare's global network.

## Quick Decision Tree

**Need to:**
- **Transform in Worker?** → [api.md](api.md#workers-binding-api-2026-primary-method) (Workers Binding API)
- **Upload from Worker?** → [api.md](api.md#upload-from-worker) (REST API)
- **Upload from client?** → [patterns.md](patterns.md#upload-from-client-direct-creator-upload) (Direct Creator Upload)
- **Set up variants?** → [configuration.md](configuration.md#variants-configuration)
- **Serve responsive images?** → [patterns.md](patterns.md#responsive-images)
- **Add watermarks?** → [patterns.md](patterns.md#watermarking)
- **Fix errors?** → [gotchas.md](gotchas.md#common-errors)

## Reading Order

**For building image upload/transform feature:**
1. [configuration.md](configuration.md) - Setup Workers binding
2. [api.md](api.md#workers-binding-api-2026-primary-method) - Learn transform API
3. [patterns.md](patterns.md#upload-from-client-direct-creator-upload) - Direct upload pattern
4. [gotchas.md](gotchas.md) - Check limits and errors

**For URL-based transforms:**
1. [configuration.md](configuration.md#variants-configuration) - Create variants
2. [api.md](api.md#url-transform-api) - URL syntax
3. [patterns.md](patterns.md#responsive-images) - Responsive patterns

**For troubleshooting:**
1. [gotchas.md](gotchas.md#common-errors) - Error messages
2. [gotchas.md](gotchas.md#limits) - Size/format limits

## Core Methods

| Method | Use Case | Location |
|--------|----------|----------|
| `env.IMAGES.input().transform()` | Transform in Worker | [api.md:11](api.md) |
| REST API `/images/v1` | Upload images | [api.md:57](api.md) |
| Direct Creator Upload | Client-side upload | [api.md:127](api.md) |
| URL transforms | Static image delivery | [api.md:112](api.md) |

## In This Reference

- **[api.md](api.md)** - Complete API: Workers binding, REST endpoints, URL transforms
- **[configuration.md](configuration.md)** - Setup: wrangler.toml, variants, auth, signed URLs
- **[patterns.md](patterns.md)** - Patterns: responsive images, watermarks, format negotiation, caching
- **[gotchas.md](gotchas.md)** - Troubleshooting: limits, errors, best practices

## Key Features

- **Automatic Optimization** - AVIF/WebP format negotiation
- **On-the-fly Transforms** - Resize, crop, blur, sharpen via URL or API
- **Workers Binding** - Transform images in Workers (2026 primary method)
- **Direct Upload** - Secure client-side uploads without backend proxy
- **Global Delivery** - Cached at 300+ Cloudflare data centers
- **Watermarking** - Overlay images programmatically

## See Also

- [Official Docs](https://developers.cloudflare.com/images/)
- [Workers Examples](https://developers.cloudflare.com/images/tutorials/)

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/kv/README.md`)

# Cloudflare Workers KV

Globally-distributed, eventually-consistent key-value store optimized for high read volume and low latency.

## Overview

KV provides:
- Eventual consistency (60s global propagation)
- Read-optimized performance
- 25 MiB value limit per key
- Auto-replication to Cloudflare edge
- Metadata support (1024 bytes)

**Use cases:** Config storage, user sessions, feature flags, caching, A/B testing

## When to Use KV

| Need | Recommendation |
|------|----------------|
| Strong consistency | → [Durable Objects](../durable-objects/) |
| SQL queries | → [D1](../d1/) |
| Object storage (files) | → [R2](../r2/) |
| High read, low write volume | → KV ✅ |
| Sub-10ms global reads | → KV ✅ |

**Quick comparison:**

| Feature | KV | D1 | Durable Objects |
|---------|----|----|-----------------|
| Consistency | Eventual | Strong | Strong |
| Read latency | <10ms | ~50ms | <1ms |
| Write limit | 1/s per key | Unlimited | Unlimited |
| Use case | Config, cache | Relational data | Coordination |

## Quick Start

```bash
wrangler kv namespace create MY_NAMESPACE
# Add binding to wrangler.jsonc
```

```typescript
// Write
await env.MY_KV.put("key", "value", { expirationTtl: 300 });

// Read
const value = await env.MY_KV.get("key");
const json = await env.MY_KV.get<Config>("config", "json");
```

## Core Operations

| Method | Purpose | Returns |
|--------|---------|---------|
| `get(key, type?)` | Single read | `string \| null` |
| `get(keys, type?)` | Bulk read (≤100) | `Map<string, T \| null>` |
| `put(key, value, options?)` | Write | `Promise<void>` |
| `delete(key)` | Delete | `Promise<void>` |
| `list(options?)` | List keys | `{ keys, list_complete, cursor? }` |
| `getWithMetadata(key)` | Get + metadata | `{ value, metadata }` |

## Consistency Model

- **Write visibility:** Immediate in same location, ≤60s globally
- **Read path:** Eventually consistent
- **Write rate:** 1 write/second per key (429 on exceed)

## Reading Order

| Task | Files to Read |
|------|---------------|
| Quick start | README → configuration.md |
| Implement feature | README → api.md → patterns.md |
| Debug issues | gotchas.md → api.md |
| Batch operations | api.md (bulk section) → patterns.md |
| Performance tuning | gotchas.md (performance) → patterns.md (caching) |

## In This Reference

- [configuration.md](./configuration.md) - wrangler.jsonc setup, namespace creation, TypeScript types
- [api.md](./api.md) - KV methods, bulk operations, cacheTtl, content types
- [patterns.md](./patterns.md) - Caching, sessions, rate limiting, A/B testing
- [gotchas.md](./gotchas.md) - Eventual consistency, concurrent writes, value limits

## See Also

- [workers](../workers/) - Worker runtime for KV access
- [d1](../d1/) - Use D1 for strong consistency needs
- [durable-objects](../durable-objects/) - Strongly consistent alternative

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/miniflare/README.md`)

# Miniflare

Local simulator for Cloudflare Workers development/testing. Runs Workers in workerd sandbox implementing runtime APIs - no internet required.

## Features

- Full-featured: KV, Durable Objects, R2, D1, WebSockets, Queues
- Fully-local: test without internet, instant reload
- TypeScript-native: detailed logging, source maps
- Advanced testing: dispatch events without HTTP, simulate Worker connections

## When to Use

**Decision tree for testing Workers:**

```
Need to test Workers?
│
├─ Unit tests for business logic only?
│  └─ getPlatformProxy (Vitest/Jest) → [patterns.md](./patterns.md#getplatformproxy)
│     Fast, no HTTP, direct binding access
│
├─ Integration tests with full runtime?
│  ├─ Single Worker?
│  │  └─ Miniflare API → [Quick Start](#quick-start)
│  │     Full control, programmatic access
│  │
│  ├─ Multiple Workers + service bindings?
│  │  └─ Miniflare workers array → [configuration.md](./configuration.md#multiple-workers)
│  │     Shared storage, inter-worker calls
│  │
│  └─ Vitest test runner integration?
│     └─ vitest-pool-workers → [patterns.md](./patterns.md#vitest-pool-workers)
│        Full Workers env in Vitest
│
└─ Local dev server?
   └─ wrangler dev (not Miniflare)
      Hot reload, automatic config
```

**Use Miniflare for:**
- Integration tests with full Worker runtime
- Testing bindings/storage locally
- Multiple Workers with service bindings
- Programmatic event dispatch (fetch, queue, scheduled)

**Use getPlatformProxy for:**
- Fast unit tests of business logic
- Testing without HTTP overhead
- Vitest/Jest environments

**Use Wrangler for:**
- Local development workflow
- Production deployments

## Setup

```bash
npm i -D miniflare
```

Requires ES modules in `package.json`:
```json
{"type": "module"}
```

## Quick Start

```js
import { Miniflare } from "miniflare";

const mf = new Miniflare({
  modules: true,
  script: `
    export default {
      async fetch(request, env, ctx) {
        return new Response("Hello Miniflare!");
      }
    }
  `,
});

const res = await mf.dispatchFetch("http://localhost:8787/");
console.log(await res.text()); // Hello Miniflare!
await mf.dispose();
```

## Reading Order

**New to Miniflare?** Start here:
1. [Quick Start](#quick-start) - Running in 2 minutes
2. [When to Use](#when-to-use) - Choose your testing approach
3. [patterns.md](./patterns.md) - Testing patterns (getPlatformProxy, Vitest, node:test)
4. [configuration.md](./configuration.md) - Configure bindings, storage, multiple workers

**Troubleshooting:**
- [gotchas.md](./gotchas.md) - Common errors and debugging

**API reference:**
- [api.md](./api.md) - Complete method reference

## See Also
- [wrangler](../wrangler/) - CLI tool that embeds Miniflare for `wrangler dev`
- [workerd](../workerd/) - Runtime that powers Miniflare
- [workers](../workers/) - Workers runtime API documentation

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/network-interconnect/README.md`)

# Cloudflare Network Interconnect (CNI)

Private, high-performance connectivity to Cloudflare's network. **Enterprise-only**.

## Connection Types

**Direct**: Physical fiber in shared datacenter. 10/100 Gbps. You order cross-connect.

**Partner**: Virtual via Console Connect, Equinix, Megaport, etc. Managed via partner SDN.

**Cloud**: AWS Direct Connect or GCP Cloud Interconnect. Magic WAN only.

## Dataplane Versions

**v1 (Classic)**: GRE tunnel support, VLAN/BFD/LACP, asymmetric MTU (1500↓/1476↑), peering support.

**v2 (Beta)**: No GRE, 1500 MTU both ways, no VLAN/BFD/LACP yet, ECMP instead.

## Use Cases

- **Magic Transit DSR**: DDoS protection, egress via ISP (v1/v2)
- **Magic Transit + Egress**: DDoS + egress via CF (v1/v2)
- **Magic WAN + Zero Trust**: Private backbone (v1 needs GRE, v2 native)
- **Peering**: Public routes at PoP (v1 only)
- **App Security**: WAF/Cache/LB (v1/v2 over Magic Transit)

## Prerequisites

- Enterprise plan
- IPv4 /24+ or IPv6 /48+ prefixes
- BGP ASN for v1
- See [locations PDF](https://developers.cloudflare.com/network-interconnect/static/cni-locations-2026-01.pdf)

## Specs

- /31 point-to-point subnets
- 10km max optical distance
- 10G: 10GBASE-LR single-mode
- 100G: 100GBASE-LR4 single-mode
- **No SLA** (free service)
- Backup Internet required

## Throughput

| Direction | 10G | 100G |
|-----------|-----|------|
| CF → Customer | 10 Gbps | 100 Gbps |
| Customer → CF (peering) | 10 Gbps | 100 Gbps |
| Customer → CF (Magic) | 1 Gbps/tunnel or CNI | 1 Gbps/tunnel or CNI |

## Timeline

2-4 weeks typical. Steps: request → config review → order connection → configure → test → enable health checks → activate → monitor.

## In This Reference
- [configuration.md](./configuration.md) - BGP, routing, setup
- [api.md](./api.md) - API endpoints, SDKs
- [patterns.md](./patterns.md) - HA, hybrid cloud, failover
- [gotchas.md](./gotchas.md) - Troubleshooting, limits

## Reading Order by Task

| Task | Files to Load |
|------|---------------|
| Initial setup | README → configuration.md → api.md |
| Create interconnect via API | api.md → gotchas.md |
| Design HA architecture | patterns.md → README |
| Troubleshoot connection | gotchas.md → configuration.md |
| Cloud integration (AWS/GCP) | configuration.md → patterns.md |
| Monitor + alerts | configuration.md |

## Automation Boundary

**API-Automatable:**
- List/create/delete interconnects (Direct, Partner)
- List available slots
- Get interconnect status
- Download LOA PDF
- Create/update CNI objects (BGP config)
- Query settings

**Requires Account Team:**
- Initial request approval
- AWS Direct Connect setup (send LOA+VLAN to CF)
- GCP Cloud Interconnect final activation
- Partner interconnect acceptance (Equinix, Megaport)
- VLAN assignment (v1)
- Configuration document generation (v1)
- Escalations + troubleshooting support

**Cannot Be Automated:**
- Physical cross-connect installation (Direct)
- Partner portal operations (virtual circuit ordering)
- AWS/GCP portal operations
- Maintenance window coordination

## See Also
- [tunnel](../tunnel/) - Alternative for private network connectivity
- [spectrum](../spectrum/) - Layer 4 proxy for TCP/UDP traffic

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/observability/README.md`)

# Cloudflare Observability Skill Reference

**Purpose**: Comprehensive guidance for implementing observability in Cloudflare Workers, covering traces, logs, metrics, and analytics.

**Scope**: Cloudflare Observability features ONLY - Workers Logs, Traces, Analytics Engine, Logpush, Metrics & Analytics, and OpenTelemetry exports.

---

## Decision Tree: Which File to Load?

Use this to route to the correct file without loading all content:

```
├─ "How do I enable/configure X?"           → configuration.md
├─ "What's the API/method/binding for X?"   → api.md
├─ "How do I implement X pattern?"          → patterns.md
│   ├─ Usage tracking/billing               → patterns.md
│   ├─ Error tracking                       → patterns.md
│   ├─ Performance monitoring               → patterns.md
│   ├─ Multi-tenant tracking                → patterns.md
│   ├─ Tail Worker filtering                → patterns.md
│   └─ OpenTelemetry export                 → patterns.md
└─ "Why isn't X working?" / "Limits?"       → gotchas.md
```

## Reading Order

Load files in this order based on task:

| Task Type | Load Order | Reason |
|-----------|------------|--------|
| **Initial setup** | configuration.md → gotchas.md | Setup first, avoid pitfalls |
| **Implement feature** | patterns.md → api.md → gotchas.md | Pattern → API details → edge cases |
| **Debug issue** | gotchas.md → configuration.md | Common issues first |
| **Query data** | api.md → patterns.md | API syntax → query examples |

## Product Overview

### Workers Logs
- **What:** Console output from Workers (console.log/warn/error)
- **Access:** Dashboard (Real-time Logs), Logpush, Tail Workers
- **Cost:** Free (included with all Workers)
- **Retention:** Real-time only (no historical storage in dashboard)

### Workers Traces
- **What:** Execution traces with timing, CPU usage, outcome
- **Access:** Dashboard (Workers Analytics → Traces), Logpush
- **Cost:** $0.10/1M spans (GA pricing starts March 1, 2026), 10M free/month
- **Retention:** 14 days included

### Analytics Engine
- **What:** High-cardinality event storage and SQL queries
- **Access:** SQL API, Dashboard (Analytics → Analytics Engine)
- **Cost:** $0.25/1M writes beyond 10M free/month
- **Retention:** 90 days (configurable up to 1 year)

### Tail Workers
- **What:** Workers that receive logs/traces from other Workers
- **Use Cases:** Log filtering, transformation, external export
- **Cost:** Standard Workers pricing

### Logpush
- **What:** Stream logs to external storage (S3, R2, Datadog, etc.)
- **Access:** Dashboard, API
- **Cost:** Requires Business/Enterprise plan

## Pricing Summary (2026)

| Feature | Free Tier | Cost Beyond Free Tier | Plan Requirement |
|---------|-----------|----------------------|------------------|
| Workers Logs | Unlimited | Free | Any |
| Workers Traces | 10M spans/month | $0.10/1M spans | Paid Workers (GA: March 1, 2026) |
| Analytics Engine | 10M writes/month | $0.25/1M writes | Paid Workers |
| Logpush | N/A | Included in plan | Business/Enterprise |

## In This Reference

- **[configuration.md](configuration.md)** - Setup, deployment, configuration (Logs, Traces, Analytics Engine, Tail Workers, Logpush)
- **[api.md](api.md)** - API endpoints, methods, interfaces (GraphQL, SQL, bindings, types)
- **[patterns.md](patterns.md)** - Common patterns, use cases, examples (billing, monitoring, error tracking, exports)
- **[gotchas.md](gotchas.md)** - Troubleshooting, best practices, limitations (common errors, performance gotchas, pricing)

## See Also

- [Cloudflare Workers Docs](https://developers.cloudflare.com/workers/)
- [Analytics Engine Docs](https://developers.cloudflare.com/analytics/analytics-engine/)
- [Workers Traces Docs](https://developers.cloudflare.com/workers/observability/traces/)

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/pages-functions/README.md`)

# Cloudflare Pages Functions

Serverless functions on Cloudflare Pages using Workers runtime. Full-stack dev with file-based routing.

## Quick Navigation

**Need to...**
| Task | Go to |
|------|-------|
| Set up TypeScript types | [configuration.md](./configuration.md) - TypeScript Setup |
| Configure bindings (KV, D1, R2) | [configuration.md](./configuration.md) - wrangler.jsonc |
| Access request/env/params | [api.md](./api.md) - EventContext |
| Add middleware or auth | [patterns.md](./patterns.md) - Middleware, Auth |
| Background tasks (waitUntil) | [patterns.md](./patterns.md) - Background Tasks |
| Debug errors or check limits | [gotchas.md](./gotchas.md) - Common Errors, Limits |

## Decision Tree: Is This Pages Functions?

```
Need serverless backend? 
├─ Yes, for a static site → Pages Functions
├─ Yes, standalone API → Workers
└─ Just static hosting → Pages (no functions)

Have existing Worker?
├─ Complex routing logic → Use _worker.js (Advanced Mode)
└─ Simple routes → Migrate to /functions (File-Based)

Framework-based?
├─ Next.js/SvelteKit/Remix → Uses _worker.js automatically
└─ Vanilla/HTML/React SPA → Use /functions
```

## File-Based Routing

```
/functions
  ├── index.js              → /
  ├── api.js                → /api
  ├── users/
  │   ├── index.js          → /users/
  │   ├── [user].js         → /users/:user
  │   └── [[catchall]].js   → /users/*
  └── _middleware.js        → runs on all routes
```

**Rules:**
- `index.js` → directory root
- Trailing slash optional
- Specific routes precede catch-alls
- Falls back to static if no match

## Dynamic Routes

**Single segment** `[param]` → string:
```js
// /functions/users/[user].js
export function onRequest(context) {
  return new Response(`Hello ${context.params.user}`);
}
// Matches: /users/nevi
```

**Multi-segment** `[[param]]` → array:
```js
// /functions/users/[[catchall]].js
export function onRequest(context) {
  return new Response(JSON.stringify(context.params.catchall));
}
// Matches: /users/nevi/foobar → ["nevi", "foobar"]
```

## Key Features

- **Method handlers:** `onRequestGet`, `onRequestPost`, etc.
- **Middleware:** `_middleware.js` for cross-cutting concerns
- **Bindings:** KV, D1, R2, Durable Objects, Workers AI, Service bindings
- **TypeScript:** Full type support via `wrangler types` command
- **Advanced mode:** Use `_worker.js` for custom routing logic

## Reading Order

**New to Pages Functions?** Start here:
1. [README.md](./README.md) - Overview, routing, decision tree (you are here)
2. [configuration.md](./configuration.md) - TypeScript setup, wrangler.jsonc, bindings
3. [api.md](./api.md) - EventContext, handlers, bindings reference
4. [patterns.md](./patterns.md) - Middleware, auth, CORS, rate limiting, caching
5. [gotchas.md](./gotchas.md) - Common errors, debugging, limits

**Quick reference lookup:**
- Bindings table → [api.md](./api.md)
- Error diagnosis → [gotchas.md](./gotchas.md)
- TypeScript setup → [configuration.md](./configuration.md)

## See Also
- [pages](../pages/) - Pages platform overview and static site deployment
- [workers](../workers/) - Workers runtime API reference
- [d1](../d1/) - D1 database integration with Pages Functions

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/pages/README.md`)

# Cloudflare Pages

JAMstack platform for full-stack apps on Cloudflare's global network.

## Key Features

- **Git-based deploys**: Auto-deploy from GitHub/GitLab
- **Preview deployments**: Unique URL per branch/PR
- **Pages Functions**: File-based serverless routing (Workers runtime)
- **Static + dynamic**: Smart asset caching + edge compute
- **Smart Placement**: Automatic function optimization based on traffic patterns
- **Framework optimized**: SvelteKit, Astro, Nuxt, Qwik, Solid Start

## Deployment Methods

### 1. Git Integration (Production)
Dashboard → Workers & Pages → Create → Connect to Git → Configure build

### 2. Direct Upload
```bash
npx wrangler pages deploy ./dist --project-name=my-project
npx wrangler pages deploy ./dist --project-name=my-project --branch=staging
```

### 3. C3 CLI
```bash
npm create cloudflare@latest my-app
# Select framework → auto-setup + deploy
```

## vs Workers

- **Pages**: Static sites, JAMstack, frameworks, git workflow, file-based routing
- **Workers**: Pure APIs, complex routing, WebSockets, scheduled tasks, email handlers
- **Combine**: Pages Functions use Workers runtime, can bind to Workers

## Quick Start

```bash
# Create
npm create cloudflare@latest

# Local dev
npx wrangler pages dev ./dist

# Deploy
npx wrangler pages deploy ./dist --project-name=my-project

# Types
npx wrangler types --path='./functions/types.d.ts'

# Secrets
echo "value" | npx wrangler pages secret put KEY --project-name=my-project

# Logs
npx wrangler pages deployment tail --project-name=my-project
```

## Resources

- [Pages Docs](https://developers.cloudflare.com/pages/)
- [Functions API](https://developers.cloudflare.com/pages/functions/api-reference/)
- [Framework Guides](https://developers.cloudflare.com/pages/framework-guides/)
- [Discord #functions](https://discord.com/channels/595317990191398933/910978223968518144)

## Reading Order

**New to Pages?** Start here:
1. README.md (you are here) - Overview & quick start
2. [configuration.md](./configuration.md) - Project setup, wrangler.jsonc, bindings
3. [api.md](./api.md) - Functions API, routing, context
4. [patterns.md](./patterns.md) - Common implementations
5. [gotchas.md](./gotchas.md) - Troubleshooting & pitfalls

**Quick reference?** Jump to relevant file above.

## In This Reference

- [configuration.md](./configuration.md) - wrangler.jsonc, build, env vars, Smart Placement
- [api.md](./api.md) - Functions API, bindings, context, advanced mode
- [patterns.md](./patterns.md) - Full-stack patterns, framework integration
- [gotchas.md](./gotchas.md) - Build issues, limits, debugging, framework warnings

## See Also

- [pages-functions](../pages-functions/) - File-based routing, middleware
- [d1](../d1/) - SQL database for Pages Functions
- [kv](../kv/) - Key-value storage for caching/state

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/pipelines/README.md`)

# Cloudflare Pipelines

ETL streaming platform for ingesting, transforming, and loading data into R2 with SQL transformations.

## Overview

Pipelines provides:
- **Streams**: Durable event buffers (HTTP/Workers ingestion)
- **Pipelines**: SQL-based transformations
- **Sinks**: R2 destinations (Iceberg tables or Parquet/JSON files)

**Status**: Open beta (Workers Paid plan)  
**Pricing**: No charge beyond standard R2 storage/operations

## Architecture

```
Data Sources → Streams → Pipelines (SQL) → Sinks → R2
                 ↑          ↓                ↓
            HTTP/Workers  Transform     Iceberg/Parquet
```

| Component | Purpose | Key Feature |
|-----------|---------|-------------|
| Streams | Event ingestion | Structured (validated) or unstructured |
| Pipelines | Transform with SQL | Immutable after creation |
| Sinks | Write to R2 | Exactly-once delivery |

## Quick Start

```bash
# Interactive setup (recommended)
npx wrangler pipelines setup
```

**Minimal Worker example:**
```typescript
interface Env {
  STREAM: Pipeline;
}

export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
    const event = { user_id: "123", event_type: "purchase", amount: 29.99 };
    
    // Fire-and-forget pattern
    ctx.waitUntil(env.STREAM.send([event]));
    
    return new Response('OK');
  }
} satisfies ExportedHandler<Env>;
```

## Which Sink Type?

```
Need SQL queries on data?
  → R2 Data Catalog (Iceberg)
    ✅ ACID transactions, time-travel, schema evolution
    ❌ More setup complexity (namespace, table, catalog token)

Just file storage/archival?
  → R2 Storage (Parquet)
    ✅ Simple, direct file access
    ❌ No built-in SQL queries

Using external tools (Spark/Athena)?
  → R2 Storage (Parquet with partitioning)
    ✅ Standard format, partition pruning for performance
    ❌ Must manage schema compatibility yourself
```

## Common Use Cases

- **Analytics pipelines**: Clickstream, telemetry, server logs
- **Data warehousing**: ETL into queryable Iceberg tables
- **Event processing**: Mobile/IoT with enrichment
- **Ecommerce analytics**: User events, purchases, views

## Reading Order

**New to Pipelines?** Start here:
1. [configuration.md](./configuration.md) - Setup streams, sinks, pipelines
2. [api.md](./api.md) - Send events, TypeScript types, SQL functions
3. [patterns.md](./patterns.md) - Best practices, integrations, complete example
4. [gotchas.md](./gotchas.md) - Critical warnings, troubleshooting

**Task-based routing:**
- Setup pipeline → [configuration.md](./configuration.md)
- Send/query data → [api.md](./api.md)
- Implement pattern → [patterns.md](./patterns.md)
- Debug issue → [gotchas.md](./gotchas.md)

## In This Reference

- [configuration.md](./configuration.md) - wrangler.jsonc bindings, schema definition, sink options, CLI commands
- [api.md](./api.md) - Pipeline binding interface, send() method, HTTP ingest, SQL function reference
- [patterns.md](./patterns.md) - Fire-and-forget, schema validation with Zod, integrations, performance tuning
- [gotchas.md](./gotchas.md) - Silent validation failures, immutable pipelines, latency expectations, limits

## See Also

- [r2](../r2/) - R2 storage backend for sinks
- [queues](../queues/) - Compare with Queues for async processing
- [workers](../workers/) - Worker runtime for event ingestion

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/pulumi/README.md`)

# Cloudflare Pulumi Provider

Expert guidance for Cloudflare Pulumi Provider (@pulumi/cloudflare).

## Overview

Programmatic management of Cloudflare resources: Workers, Pages, D1, KV, R2, DNS, Queues, etc.

**Packages:**
- TypeScript/JS: `@pulumi/cloudflare`
- Python: `pulumi-cloudflare`
- Go: `github.com/pulumi/pulumi-cloudflare/sdk/v6/go/cloudflare`
- .NET: `Pulumi.Cloudflare`

**Version:** v6.x

## Core Principles

1. Use API tokens (not legacy API keys)
2. Store accountId in stack config
3. Match binding names across code/config
4. Use `module: true` for ES modules
5. Set `compatibilityDate` to lock behavior

## Authentication

```typescript
import * as cloudflare from "@pulumi/cloudflare";

// API Token (recommended): CLOUDFLARE_API_TOKEN env
const provider = new cloudflare.Provider("cf", { apiToken: process.env.CLOUDFLARE_API_TOKEN });

// API Key (legacy): CLOUDFLARE_API_KEY + CLOUDFLARE_EMAIL env
const provider = new cloudflare.Provider("cf", { apiKey: process.env.CLOUDFLARE_API_KEY, email: process.env.CLOUDFLARE_EMAIL });

// API User Service Key: CLOUDFLARE_API_USER_SERVICE_KEY env
const provider = new cloudflare.Provider("cf", { apiUserServiceKey: process.env.CLOUDFLARE_API_USER_SERVICE_KEY });
```

## Setup

**Pulumi.yaml:**
```yaml
name: my-cloudflare-app
runtime: nodejs
config:
  cloudflare:apiToken:
    value: ${CLOUDFLARE_API_TOKEN}
```

**Pulumi.<stack>.yaml:**
```yaml
config:
  cloudflare:accountId: "abc123..."
```

**index.ts:**
```typescript
import * as pulumi from "@pulumi/pulumi";
import * as cloudflare from "@pulumi/cloudflare";
const accountId = new pulumi.Config("cloudflare").require("accountId");
```

## Common Resource Types
- `Provider` - Provider config
- `WorkerScript` - Worker
- `WorkersKvNamespace` - KV
- `R2Bucket` - R2
- `D1Database` - D1
- `Queue` - Queue
- `PagesProject` - Pages
- `DnsRecord` - DNS
- `WorkerRoute` - Worker route
- `WorkersDomain` - Custom domain

## Key Properties
- `accountId` - Required for most resources
- `zoneId` - Required for DNS/domain
- `name`/`title` - Resource identifier
- `*Bindings` - Connect resources to Workers

## Reading Order

| Order | File | What | When to Read |
|-------|------|------|--------------|
| 1 | [configuration.md](./configuration.md) | Resource config for Workers/KV/D1/R2/Queues/Pages | First time setup, resource reference |
| 2 | [patterns.md](./patterns.md) | Architecture patterns, multi-env, component resources | Building complex apps, best practices |
| 3 | [api.md](./api.md) | Outputs, dependencies, imports, dynamic providers | Advanced features, integrations |
| 4 | [gotchas.md](./gotchas.md) | Common errors, troubleshooting, limits | Debugging, deployment issues |

## In This Reference
- [configuration.md](./configuration.md) - Provider config, stack setup, Workers/bindings
- [api.md](./api.md) - Resource types, Workers script, KV/D1/R2/queues/Pages
- [patterns.md](./patterns.md) - Multi-env, secrets, CI/CD, stack management
- [gotchas.md](./gotchas.md) - State issues, deployment failures, limits

## See Also
- [terraform](../terraform/) - Alternative IaC for Cloudflare
- [wrangler](../wrangler/) - CLI deployment alternative
- [workers](../workers/) - Worker runtime documentation

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/queues/README.md`)

# Cloudflare Queues

Flexible message queuing for async task processing with guaranteed at-least-once delivery and configurable batching.

## Overview

Queues provide:
- At-least-once delivery guarantee
- Push-based (Worker) and pull-based (HTTP) consumers
- Configurable batching and retries
- Dead Letter Queues (DLQ)
- Delays up to 12 hours

**Use cases:** Async processing, API buffering, rate limiting, event workflows, deferred jobs

## Quick Start

```bash
wrangler queues create my-queue
wrangler queues consumer add my-queue my-worker
```

```typescript
// Producer
await env.MY_QUEUE.send({ userId: 123, action: 'notify' });

// Consumer (with proper error handling)
export default {
  async queue(batch: MessageBatch, env: Env): Promise<void> {
    for (const msg of batch.messages) {
      try {
        await process(msg.body);
        msg.ack();
      } catch (error) {
        msg.retry({ delaySeconds: 60 });
      }
    }
  }
};
```

## Critical Warnings

**Before using Queues, understand these production mistakes:**

1. **Uncaught errors retry ENTIRE batch** (not just failed message). Always use per-message try/catch.
2. **Messages not ack'd/retry'd will auto-retry forever** until max_retries. Always explicitly handle each message.

See [gotchas.md](./gotchas.md) for detailed solutions.

## Core Operations

| Operation | Purpose | Limit |
|-----------|---------|-------|
| `send(body, options?)` | Publish message | 128 KB |
| `sendBatch(messages)` | Bulk publish | 100 msgs/256 KB |
| `message.ack()` | Acknowledge success | - |
| `message.retry(options?)` | Retry with delay | - |
| `batch.ackAll()` | Ack entire batch | - |

## Architecture

```
[Producer Worker] → [Queue] → [Consumer Worker/HTTP] → [Processing]
```

- Max 10,000 queues per account
- 5,000 msgs/second per queue
- 4-14 day retention (configurable)

## Reading Order

**New to Queues?** Start here:
1. [configuration.md](./configuration.md) - Set up queues, bindings, consumers
2. [api.md](./api.md) - Send messages, handle batches, ack/retry patterns
3. [patterns.md](./patterns.md) - Real-world examples and integrations
4. [gotchas.md](./gotchas.md) - Critical warnings and troubleshooting

**Task-based routing:**
- Setup queue → [configuration.md](./configuration.md)
- Send/receive messages → [api.md](./api.md)
- Implement specific pattern → [patterns.md](./patterns.md)
- Debug/troubleshoot → [gotchas.md](./gotchas.md)

## In This Reference

- [configuration.md](./configuration.md) - wrangler.jsonc setup, producer/consumer config, DLQ, content types
- [api.md](./api.md) - Send/batch methods, queue handler, ack/retry rules, type-safe patterns
- [patterns.md](./patterns.md) - Async tasks, buffering, rate limiting, D1/Workflows/DO integrations
- [gotchas.md](./gotchas.md) - Critical batch error handling, idempotency, error classification

## See Also

- [workers](../workers/) - Worker runtime for producers/consumers
- [r2](../r2/) - Process R2 event notifications via queues
- [d1](../d1/) - Batch write to D1 from queue consumers

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/r2-data-catalog/README.md`)

# Cloudflare R2 Data Catalog Skill Reference

Expert guidance for Cloudflare R2 Data Catalog - Apache Iceberg catalog built into R2 buckets.

## Reading Order

**New to R2 Data Catalog?** Start here:
1. Read "What is R2 Data Catalog?" and "When to Use" below
2. [configuration.md](configuration.md) - Enable catalog, create tokens
3. [patterns.md](patterns.md) - PyIceberg setup and common patterns
4. [api.md](api.md) - REST API reference as needed
5. [gotchas.md](gotchas.md) - Troubleshooting when issues arise

**Quick reference?** Jump to:
- [Enable catalog on bucket](configuration.md#enable-catalog-on-bucket)
- [PyIceberg connection pattern](patterns.md#pyiceberg-connection-pattern)
- [Permission errors](gotchas.md#permission-errors)

## What is R2 Data Catalog?

R2 Data Catalog is a **managed Apache Iceberg REST catalog** built directly into R2 buckets. It provides:

- **Apache Iceberg tables** - ACID transactions, schema evolution, time-travel queries
- **Zero-egress costs** - Query from any cloud/region without data transfer fees
- **Standard REST API** - Works with Spark, PyIceberg, Snowflake, Trino, DuckDB
- **No infrastructure** - Fully managed, no catalog servers to run
- **Public beta** - Available to all R2 subscribers, no extra cost beyond R2 storage

### What is Apache Iceberg?

Open table format for analytics datasets in object storage. Features:
- **ACID transactions** - Safe concurrent reads/writes
- **Metadata optimization** - Fast queries without full scans
- **Schema evolution** - Add/rename/delete columns without rewrites
- **Time-travel** - Query historical snapshots
- **Partitioning** - Organize data for efficient queries

## When to Use

**Use R2 Data Catalog for:**
- **Log analytics** - Store and query application/system logs
- **Data lakes/warehouses** - Analytical datasets queried by multiple engines
- **BI pipelines** - Aggregate data for dashboards and reports
- **Multi-cloud analytics** - Share data across clouds without egress fees
- **Time-series data** - Event streams, metrics, sensor data

**Don't use for:**
- **Transactional workloads** - Use D1 or external database instead
- **Sub-second latency** - Iceberg optimized for batch/analytical queries
- **Small datasets (<1GB)** - Setup overhead not worth it
- **Unstructured data** - Store files directly in R2, not as Iceberg tables

## Architecture

```
┌─────────────────────────────────────────────────┐
│  Query Engines                                  │
│  (PyIceberg, Spark, Trino, Snowflake, DuckDB)  │
└────────────────┬────────────────────────────────┘
                 │
                 │ REST API (OAuth2 token)
                 ▼
┌─────────────────────────────────────────────────┐
│  R2 Data Catalog (Managed Iceberg REST Catalog)│
│  • Namespace/table metadata                     │
│  • Transaction coordination                     │
│  • Snapshot management                          │
└────────────────┬────────────────────────────────┘
                 │
                 │ Vended credentials
                 ▼
┌─────────────────────────────────────────────────┐
│  R2 Bucket Storage                              │
│  • Parquet data files                           │
│  • Metadata files                               │
│  • Manifest files                               │
└─────────────────────────────────────────────────┘
```

**Key concepts:**
- **Catalog URI** - REST endpoint for catalog operations (e.g., `https://<account-id>.r2.cloudflarestorage.com/iceberg/<bucket>`)
- **Warehouse** - Logical grouping of tables (typically same as bucket name)
- **Namespace** - Schema/database containing tables (e.g., `logs`, `analytics`)
- **Table** - Iceberg table with schema, data files, snapshots
- **Vended credentials** - Temporary S3 credentials catalog provides for data access

## Limits

| Resource | Limit | Notes |
|----------|-------|-------|
| Namespaces per catalog | No hard limit | Organize tables logically |
| Tables per namespace | <10,000 recommended | Performance degrades beyond this |
| Files per table | <100,000 recommended | Run compaction regularly |
| Snapshots per table | Configurable retention | Expire >7 days old |
| Partitions per table | 100-1,000 optimal | Too many = slow metadata ops |
| Table size | Same as R2 bucket | 10GB-10TB+ common |
| API rate limits | Standard R2 API limits | Shared with R2 storage operations |
| Target file size | 128-512 MB | After compaction |

## Current Status

**Public Beta** (as of Jan 2026)
- Available to all R2 subscribers
- No extra cost beyond standard R2 storage/operations
- Production-ready, but breaking changes possible
- Supports: namespaces, tables, snapshots, compaction, time-travel, table maintenance

## Decision Tree: Is R2 Data Catalog Right For You?

```
Start → Need analytics on object storage data?
         │
         ├─ No → Use R2 directly for object storage
         │
         └─ Yes → Dataset >1GB with structured schema?
                  │
                  ├─ No → Too small, use R2 + ad-hoc queries
                  │
                  └─ Yes → Need ACID transactions or schema evolution?
                           │
                           ├─ No → Consider simpler solutions (Parquet on R2)
                           │
                           └─ Yes → Need multi-cloud/multi-tool access?
                                    │
                                    ├─ No → D1 or external DB may be simpler
                                    │
                                    └─ Yes → ✅ Use R2 Data Catalog
```

**Quick check:** If you answer "yes" to all:
- Dataset >1GB and growing
- Structured/tabular data (logs, events, metrics)
- Multiple query tools or cloud environments
- Need versioning, schema changes, or concurrent access

→ R2 Data Catalog is a good fit.

## In This Reference

- **[configuration.md](configuration.md)** - Enable catalog, create API tokens, connect clients
- **[api.md](api.md)** - REST endpoints, operations, maintenance
- **[patterns.md](patterns.md)** - PyIceberg examples, common use cases
- **[gotchas.md](gotchas.md)** - Troubleshooting, best practices, limitations

## See Also

- [Cloudflare R2 Data Catalog Docs](https://developers.cloudflare.com/r2/data-catalog/)
- [Apache Iceberg Docs](https://iceberg.apache.org/)
- [PyIceberg Docs](https://py.iceberg.apache.org/)

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/r2-sql/README.md`)

# Cloudflare R2 SQL Skill Reference

Expert guidance for Cloudflare R2 SQL - serverless distributed query engine for Apache Iceberg tables.

## Reading Order

**New to R2 SQL?** Start here:
1. Read "What is R2 SQL?" and "When to Use" below
2. [configuration.md](configuration.md) - Enable catalog, create tokens
3. [patterns.md](patterns.md) - Wrangler CLI and integration examples
4. [api.md](api.md) - SQL syntax and query reference
5. [gotchas.md](gotchas.md) - Limitations and troubleshooting

**Quick reference?** Jump to:
- [Run a query via Wrangler](patterns.md#wrangler-cli-query)
- [SQL syntax reference](api.md#sql-syntax)
- [ORDER BY limitations](gotchas.md#order-by-limitations)

## What is R2 SQL?

R2 SQL is Cloudflare's **serverless distributed analytics query engine** for querying Apache Iceberg tables in R2 Data Catalog. Features:

- **Serverless** - No clusters to manage, no infrastructure
- **Distributed** - Leverages Cloudflare's global network for parallel execution
- **SQL interface** - Familiar SQL syntax for analytics queries
- **Zero egress fees** - Query from any cloud/region without data transfer costs
- **Open beta** - Free during beta (standard R2 storage costs apply)

### What is Apache Iceberg?

Open table format for large-scale analytics datasets in object storage:
- **ACID transactions** - Safe concurrent reads/writes
- **Metadata optimization** - Fast queries without full table scans
- **Schema evolution** - Add/rename/drop columns without rewrites
- **Partitioning** - Organize data for efficient pruning

## When to Use

**Use R2 SQL for:**
- **Log analytics** - Query application/system logs with WHERE filters and aggregations
- **BI dashboards** - Generate reports from large analytical datasets
- **Fraud detection** - Analyze transaction patterns with GROUP BY/HAVING
- **Multi-cloud analytics** - Query data from any cloud without egress fees
- **Ad-hoc exploration** - Run SQL queries on Iceberg tables via Wrangler CLI

**Don't use R2 SQL for:**
- **Workers/Pages runtime** - R2 SQL has no Workers binding, use HTTP API from external systems
- **Real-time queries (<100ms)** - Optimized for analytical batch queries, not OLTP
- **Complex joins/CTEs** - Limited SQL feature set (no JOINs, subqueries, CTEs currently)
- **Small datasets (<1GB)** - Setup overhead not justified

## Decision Tree: Need to Query R2 Data?

```
Do you need to query structured data in R2?
├─ YES, data is in Iceberg tables
│  ├─ Need SQL interface? → Use R2 SQL (this reference)
│  ├─ Need Python API? → See r2-data-catalog reference (PyIceberg)
│  └─ Need other engine? → See r2-data-catalog reference (Spark, Trino, etc.)
│
├─ YES, but not in Iceberg format
│  ├─ Streaming data? → Use Pipelines to write to Data Catalog, then R2 SQL
│  └─ Static files? → Use PyIceberg to create Iceberg tables, then R2 SQL
│
└─ NO, just need object storage → Use R2 reference (not R2 SQL)
```

## Architecture Overview

**Query Planner:**
- Top-down metadata investigation with multi-layer pruning
- Partition-level, column-level, and row-group pruning
- Streaming pipeline - execution starts before planning completes
- Early termination with LIMIT - stops when result complete

**Query Execution:**
- Coordinator distributes work to workers across Cloudflare network
- Workers run Apache DataFusion for parallel query execution
- Parquet column pruning - reads only required columns
- Ranged reads from R2 for efficiency

**Aggregation Strategies:**
- Scatter-gather - simple aggregations (SUM, COUNT, AVG)
- Shuffling - ORDER BY/HAVING on aggregates via hash partitioning

## Quick Start

```bash
# 1. Enable R2 Data Catalog on bucket
npx wrangler r2 bucket catalog enable my-bucket

# 2. Create API token (Admin Read & Write)
# Dashboard: R2 → Manage API tokens → Create API token

# 3. Set environment variable
export WRANGLER_R2_SQL_AUTH_TOKEN=<your-token>

# 4. Run query
npx wrangler r2 sql query "my-bucket" "SELECT * FROM default.my_table LIMIT 10"
```

## Important Limitations

**CRITICAL: No Workers Binding**
- R2 SQL cannot be called directly from Workers/Pages code
- For programmatic access, use HTTP API from external systems
- Or query via PyIceberg, Spark, etc. (see r2-data-catalog reference)

**SQL Feature Set:**
- No JOINs, CTEs, subqueries, window functions
- ORDER BY supports aggregation columns (not just partition keys)
- LIMIT max 10,000 (default 500)
- See [gotchas.md](gotchas.md) for complete limitations

## In This Reference

- **[configuration.md](configuration.md)** - Enable catalog, create API tokens
- **[api.md](api.md)** - SQL syntax, functions, operators, data types
- **[patterns.md](patterns.md)** - Wrangler CLI, HTTP API, Pipelines, PyIceberg
- **[gotchas.md](gotchas.md)** - Limitations, troubleshooting, performance tips

## See Also

- [r2-data-catalog](../r2-data-catalog/) - PyIceberg, REST API, external engines
- [pipelines](../pipelines/) - Streaming ingestion to Iceberg tables
- [r2](../r2/) - R2 object storage fundamentals
- [Cloudflare R2 SQL Docs](https://developers.cloudflare.com/r2-sql/)
- [R2 SQL Deep Dive Blog](https://blog.cloudflare.com/r2-sql-deep-dive/)

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/r2/README.md`)

# Cloudflare R2 Object Storage

S3-compatible object storage with zero egress fees, optimized for large file storage and delivery.

## Overview

R2 provides:
- S3-compatible API (Workers API + S3 REST)
- Zero egress fees globally
- Strong consistency for writes/deletes
- Storage classes (Standard/Infrequent Access)
- SSE-C encryption support

**Use cases:** Media storage, backups, static assets, user uploads, data lakes

## Quick Start

```bash
wrangler r2 bucket create my-bucket --location=enam
wrangler r2 object put my-bucket/file.txt --file=./local.txt
```

```typescript
// Upload
await env.MY_BUCKET.put(key, data, {
  httpMetadata: { contentType: 'image/jpeg' }
});

// Download
const object = await env.MY_BUCKET.get(key);
if (object) return new Response(object.body);
```

## Core Operations

| Method | Purpose | Returns |
|--------|---------|---------|
| `put(key, value, options?)` | Upload object | `R2Object \| null` |
| `get(key, options?)` | Download object | `R2ObjectBody \| R2Object \| null` |
| `head(key)` | Get metadata only | `R2Object \| null` |
| `delete(keys)` | Delete object(s) | `Promise<void>` |
| `list(options?)` | List objects | `R2Objects` |

## Storage Classes

- **Standard**: Frequent access, low latency reads
- **InfrequentAccess**: 30-day minimum storage, retrieval fees, lower storage cost

## Event Notifications

R2 integrates with Cloudflare Queues for reactive workflows:

```typescript
// wrangler.jsonc
{
  "event_notifications": [{
    "queue": "r2-notifications",
    "actions": ["PutObject", "DeleteObject"]
  }]
}

// Consumer
async queue(batch: MessageBatch, env: Env) {
  for (const message of batch.messages) {
    const event = message.body; // { action, bucket, object, timestamps }
    if (event.action === 'PutObject') {
      // Process upload: thumbnail generation, virus scan, etc.
    }
  }
}
```

## Reading Order

**First-time users:** README → configuration.md → api.md → patterns.md  
**Specific tasks:**
- Setup: configuration.md
- Client uploads: patterns.md (presigned URLs)
- Public static site: patterns.md (public access + custom domain)
- Processing uploads: README (event notifications) + queues reference
- Debugging: gotchas.md

## In This Reference

- [configuration.md](./configuration.md) - Bindings, S3 SDK, CORS, lifecycles, token scopes
- [api.md](./api.md) - Workers API, multipart, conditional requests, presigned URLs
- [patterns.md](./patterns.md) - Streaming, caching, client uploads, public buckets
- [gotchas.md](./gotchas.md) - List truncation, etag format, stream length, S3 SDK region

## See Also

- [workers](../workers/) - Worker runtime and fetch handlers
- [kv](../kv/) - Metadata storage for R2 objects
- [d1](../d1/) - Store R2 URLs in relational database
- [queues](../queues/) - Process R2 uploads asynchronously

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/realtime-sfu/README.md`)

# Cloudflare Realtime SFU Reference

Expert guidance for building real-time audio/video/data applications using Cloudflare Realtime SFU (Selective Forwarding Unit).

## Reading Order

| Task | Files | ~Tokens |
|------|-------|---------|
| New project | README → configuration | ~1200 |
| Implement publish/subscribe | README → api | ~1600 |
| Add PartyTracks | patterns (PartyTracks section) | ~800 |
| Build presence system | patterns (DO section) | ~800 |
| Debug connection issues | gotchas | ~700 |
| Scale to millions | patterns (Cascading section) | ~600 |
| Add simulcast | patterns (Advanced section) | ~500 |
| Configure TURN | configuration (TURN section) | ~400 |

## In This Reference

- **[configuration.md](configuration.md)** - Setup, deployment, environment variables, Wrangler config
- **[api.md](api.md)** - Sessions, tracks, endpoints, request/response patterns
- **[patterns.md](patterns.md)** - Architecture patterns, use cases, integration examples
- **[gotchas.md](gotchas.md)** - Common issues, debugging, performance, security

## Quick Start

Cloudflare Realtime SFU: WebRTC infrastructure on global network (310+ cities). Anycast routing, no regional constraints, pub/sub model.

**Core concepts:**
- **Sessions:** WebRTC PeerConnection to Cloudflare edge
- **Tracks:** Audio/video/data channels you publish or subscribe to
- **No rooms:** Build presence layer yourself via track sharing (see patterns.md)

**Mental model:** Your client establishes one WebRTC session, publishes tracks (audio/video), shares track IDs via your backend, others subscribe to your tracks using track IDs + your session ID.

## Choose Your Approach

| Approach | When to Use | Complexity |
|----------|-------------|------------|
| **PartyTracks** | Production apps with device switching, React | Low - Observable-based, handles reconnections |
| **Raw API** | Custom requirements, non-browser, learning | Medium - Full control, manual WebRTC lifecycle |
| **RealtimeKit** | End-to-end SDK with UI components | Lowest - Managed state, React hooks |

**Recommendation:** Start with PartyTracks for most production applications. See patterns.md for PartyTracks examples.

## SFU vs RealtimeKit

- **Realtime SFU:** WebRTC infrastructure (this reference). Build your own signaling, presence, UI.
- **RealtimeKit:** SDK layer on top of SFU. Includes React hooks, state management, UI components. Part of Cloudflare AI platform.

Use SFU directly when you need custom signaling or non-React framework. Use RealtimeKit for faster development with React.

## Setup

Dashboard: https://dash.cloudflare.com/?to=/:account/calls

Get `CALLS_APP_ID` and `CALLS_APP_SECRET` from dashboard, then see configuration.md for deployment.

## See Also

- [Orange Meets Demo](https://demo.orange.cloudflare.dev/)
- [Orange Source](https://github.com/cloudflare/orange)
- [Calls Examples](https://github.com/cloudflare/calls-examples)
- [API Reference](https://developers.cloudflare.com/api/resources/calls/)
- [RealtimeKit Docs](https://developers.cloudflare.com/workers-ai/realtimekit/)

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/realtimekit/README.md`)

# Cloudflare RealtimeKit

Expert guidance for building real-time video and audio applications using **Cloudflare RealtimeKit** - a comprehensive SDK suite for adding customizable live video and voice to web or mobile applications.

## Overview

RealtimeKit is Cloudflare's SDK suite built on Realtime SFU, abstracting WebRTC complexity with fast integration, pre-built UI components, global performance (300+ cities), and production features (recording, transcription, chat, polls).

**Use cases**: Team meetings, webinars, social video, audio calls, interactive plugins

## Core Concepts

- **App**: Workspace grouping meetings, participants, presets, recordings. Use separate Apps for staging/production
- **Meeting**: Re-usable virtual room. Each join creates new **Session**
- **Session**: Live meeting instance. Created on first join, ends after last leave
- **Participant**: User added via REST API. Returns `authToken` for client SDK. **Do not reuse tokens**
- **Preset**: Reusable permission/UI template (permissions, meeting type, theme). Applied at participant creation
- **Peer ID** (`id`): Unique per session, changes on rejoin
- **Participant ID** (`userId`): Persistent across sessions

## Quick Start

### 1. Create App & Meeting (Backend)

```bash
# Create app
curl -X POST 'https://api.cloudflare.com/client/v4/accounts/<account_id>/realtime/kit/apps' \
  -H 'Authorization: Bearer <api_token>' \
  -d '{"name": "My RealtimeKit App"}'

# Create meeting
curl -X POST 'https://api.cloudflare.com/client/v4/accounts/<account_id>/realtime/kit/<app_id>/meetings' \
  -H 'Authorization: Bearer <api_token>' \
  -d '{"title": "Team Standup"}'

# Add participant
curl -X POST 'https://api.cloudflare.com/client/v4/accounts/<account_id>/realtime/kit/<app_id>/meetings/<meeting_id>/participants' \
  -H 'Authorization: Bearer <api_token>' \
  -d '{"name": "Alice", "preset_name": "host"}'
# Returns: { authToken }
```

### 2. Client Integration

**React**:
```tsx
import { RtkMeeting } from '@cloudflare/realtimekit-react-ui';

function App() {
  return <RtkMeeting authToken="<participant_auth_token>" onLeave={() => {}} />;
}
```

**Core SDK**:
```typescript
import RealtimeKitClient from '@cloudflare/realtimekit';

const meeting = new RealtimeKitClient({ authToken: '<token>', video: true, audio: true });
await meeting.join();
```

## Reading Order

| Task | Files |
|------|-------|
| Quick integration | README only |
| Custom UI | README → patterns → api |
| Backend setup | README → configuration |
| Debug issues | gotchas |
| Advanced features | patterns → api |

## RealtimeKit vs Realtime SFU

| Choose | When |
|--------|------|
| **RealtimeKit** | Need pre-built UI, fast integration, React/Angular/HTML |
| **Realtime SFU** | Building from scratch, custom WebRTC, full control |

RealtimeKit is built on Realtime SFU but abstracts WebRTC complexity with UI components and SDKs.

## Which Package?

Need pre-built meeting UI?
- React → `@cloudflare/realtimekit-react-ui` (`<RtkMeeting>`)
- Angular → `@cloudflare/realtimekit-angular-ui`
- HTML/Vanilla → `@cloudflare/realtimekit-ui`

Need custom UI?
- Core SDK → `@cloudflare/realtimekit` (RealtimeKitClient) - full control

Need raw WebRTC control?
- See `realtime-sfu/` reference

## In This Reference

- [Configuration](./configuration.md) - Setup, installation, wrangler config
- [API](./api.md) - Meeting object, REST API, SDK methods
- [Patterns](./patterns.md) - Common workflows, code examples
- [Gotchas](./gotchas.md) - Common issues, troubleshooting

## See Also

- [Workers](../workers/) - Backend integration
- [D1](../d1/) - Meeting metadata storage
- [R2](../r2/) - Recording storage
- [KV](../kv/) - Session management

## Reference Links

- **Official Docs**: https://developers.cloudflare.com/realtime/realtimekit/
- **API Reference**: https://developers.cloudflare.com/api/resources/realtime_kit/
- **Examples**: https://github.com/cloudflare/realtimekit-web-examples
- **Dashboard**: https://dash.cloudflare.com/?to=/:account/realtime/kit

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/sandbox/README.md`)

# Cloudflare Sandbox SDK

Secure isolated code execution in containers on Cloudflare's edge. Run untrusted code, manage files, expose services, integrate with AI agents.

**Use cases**: AI code execution, interactive dev environments, data analysis, CI/CD, code interpreters, multi-tenant execution.

## Architecture

- Each sandbox = Durable Object + Container
- Persistent across requests (same ID = same sandbox)
- Isolated filesystem/processes/network
- Configurable sleep/wake for cost optimization

## Quick Start

```typescript
import { getSandbox, proxyToSandbox, type Sandbox } from '@cloudflare/sandbox';
export { Sandbox } from '@cloudflare/sandbox';

type Env = { Sandbox: DurableObjectNamespace<Sandbox>; };

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    // CRITICAL: proxyToSandbox MUST be called first for preview URLs
    const proxyResponse = await proxyToSandbox(request, env);
    if (proxyResponse) return proxyResponse;

    const sandbox = getSandbox(env.Sandbox, 'my-sandbox');
    const result = await sandbox.exec('python3 -c "print(2 + 2)"');
    return Response.json({ output: result.stdout });
  }
};
```

**wrangler.jsonc**:
```jsonc
{
  "name": "my-sandbox-worker",
  "main": "src/index.ts",
  "compatibility_date": "2025-01-01", // Use current date for new projects
  
  "containers": [{
    "class_name": "Sandbox",
    "image": "./Dockerfile",
    "instance_type": "lite",        // lite | standard | heavy
    "max_instances": 5
  }],
  
  "durable_objects": {
    "bindings": [{ "class_name": "Sandbox", "name": "Sandbox" }]
  },
  
  "migrations": [{
    "tag": "v1",
    "new_sqlite_classes": ["Sandbox"]
  }]
}
```

**Dockerfile**:
```dockerfile
FROM docker.io/cloudflare/sandbox:latest
RUN pip3 install --no-cache-dir pandas numpy matplotlib
EXPOSE 8080 3000  # Required for wrangler dev
```

## Core APIs

- `getSandbox(namespace, id, options?)` → Get/create sandbox
- `sandbox.exec(command, options?)` → Execute command
- `sandbox.readFile(path)` / `writeFile(path, content)` → File ops
- `sandbox.startProcess(command, options)` → Background process
- `sandbox.exposePort(port, options)` → Get preview URL
- `sandbox.createSession(options)` → Isolated session
- `sandbox.wsConnect(request, port)` → WebSocket proxy
- `sandbox.destroy()` → Terminate container
- `sandbox.mountBucket(bucket, path, options)` → Mount S3 storage

## Critical Rules

- ALWAYS call `proxyToSandbox()` first
- Same ID = reuse sandbox
- Use `/workspace` for persistent files
- `normalizeId: true` for preview URLs
- Retry on `CONTAINER_NOT_READY`

## In This Reference
- [configuration.md](./configuration.md) - Config, CLI, environment setup
- [api.md](./api.md) - Programmatic API, testing patterns
- [patterns.md](./patterns.md) - Common workflows, CI/CD integration
- [gotchas.md](./gotchas.md) - Issues, limits, best practices

## See Also
- [durable-objects](../durable-objects/) - Sandbox runs on DO infrastructure
- [containers](../containers/) - Container runtime fundamentals
- [workers](../workers/) - Entry point for sandbox requests

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/secrets-store/README.md`)

# Cloudflare Secrets Store

Account-level encrypted secret management for Workers and AI Gateway.

## Overview

**Secrets Store**: Centralized, account-level secrets, reusable across Workers
**Worker Secrets**: Per-Worker secrets (`wrangler secret put`)

### Architecture

- **Store**: Container (1/account in beta)
- **Secret**: String ≤1024 bytes
- **Scopes**: Permission boundaries controlling access
  - `workers`: For Workers runtime access
  - `ai-gateway`: For AI Gateway access
  - Secrets must have correct scope for binding to work
- **Bindings**: Connect secrets via `env` object

**Regional Availability**: Global except China Network (unavailable)

### Access Control

- **Super Admin**: Full access
- **Admin**: Create/edit/delete secrets, view metadata
- **Deployer**: View metadata + bindings
- **Reporter**: View metadata only

API Token permissions: `Account Secrets Store Edit/Read`

### Limits (Beta)

- 100 secrets/account
- 1 store/account
- 1024 bytes max/secret
- Production secrets count toward limit

## When to Use

**Use Secrets Store when:**
- Multiple Workers share same credential
- Centralized management needed
- Compliance requires audit trail
- Team collaboration on secrets

**Use Worker Secrets when:**
- Secret unique to one Worker
- Simple single-Worker project
- No cross-Worker sharing needed

## In This Reference

### Reading Order by Task

| Task | Start Here | Then Read |
|------|------------|-----------|
| Quick overview | README.md | - |
| First-time setup | README.md → configuration.md | api.md |
| Add secret to Worker | configuration.md | api.md |
| Implement access pattern | api.md | patterns.md |
| Debug errors | gotchas.md | api.md |
| Secret rotation | patterns.md | configuration.md |
| Best practices | gotchas.md | patterns.md |

### Files

- [configuration.md](./configuration.md) - Wrangler commands, binding config
- [api.md](./api.md) - Binding API, get/put/delete operations
- [patterns.md](./patterns.md) - Rotation, encryption, access control
- [gotchas.md](./gotchas.md) - Security issues, limits, best practices

## See Also
- [workers](../workers/) - Worker bindings integration
- [wrangler](../wrangler/) - CLI secret management commands

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/smart-placement/README.md`)

# Cloudflare Workers Smart Placement

Automatic workload placement optimization to minimize latency by running Workers closer to backend infrastructure rather than end users.

## Core Concept

Smart Placement automatically analyzes Worker request duration across Cloudflare's global network and intelligently routes requests to optimal data center locations. Instead of defaulting to the location closest to the end user, Smart Placement can forward requests to locations closer to backend infrastructure when this reduces overall request duration.

### When to Use

**Enable Smart Placement when:**
- Worker makes multiple round trips to backend services/databases
- Backend infrastructure is geographically concentrated
- Request duration dominated by backend latency rather than network latency from user
- Running backend logic in Workers (APIs, data aggregation, SSR with DB calls)
- Worker uses `fetch` handler (not RPC methods)

**Do NOT enable for:**
- Workers serving only static content or cached responses
- Workers without significant backend communication
- Pure edge logic (auth checks, redirects, simple transformations)
- Workers without fetch event handlers
- Workers with RPC methods or named entrypoints (only `fetch` handlers are affected)
- Pages/Assets Workers with `run_worker_first = true` (degrades asset serving)

### Decision Tree

```
Does your Worker have a fetch handler?
├─ No → Smart Placement won't work (skip)
└─ Yes
   │
   Does it make multiple backend calls (DB/API)?
   ├─ No → Don't enable (won't help)
   └─ Yes
      │
      Is backend geographically concentrated?
      ├─ No (globally distributed) → Probably won't help
      └─ Yes or uncertain
         │
         Does it serve static assets with run_worker_first=true?
         ├─ Yes → Don't enable (will hurt performance)
         └─ No → Enable Smart Placement
            │
            After 15min, check placement_status
            ├─ SUCCESS → Monitor metrics
            ├─ INSUFFICIENT_INVOCATIONS → Need more traffic
            └─ UNSUPPORTED_APPLICATION → Disable (hurting performance)
```

### Key Architecture Pattern

**Recommended:** Split full-stack applications into separate Workers:
```
User → Frontend Worker (at edge, close to user)
         ↓ Service Binding
       Backend Worker (Smart Placement enabled, close to DB/API)
         ↓
       Database/Backend Service
```

This maintains fast, reactive frontends while optimizing backend latency.

## Quick Start

```jsonc
// wrangler.jsonc
{
  "placement": {
    "mode": "smart"  // or "off" to explicitly disable
  }
}
```

Deploy and wait 15 minutes for analysis. Check status via API or dashboard metrics.

**To disable:** Set `"mode": "off"` or remove `placement` field entirely (both equivalent).

## Requirements

- Wrangler 2.20.0+
- Analysis time: Up to 15 minutes after enabling
- Traffic requirements: Consistent traffic from multiple global locations
- Available on all Workers plans (Free, Paid, Enterprise)

## Placement Status Values

```typescript
type PlacementStatus = 
  | undefined  // Not yet analyzed
  | 'SUCCESS'  // Successfully optimized
  | 'INSUFFICIENT_INVOCATIONS'  // Not enough traffic
  | 'UNSUPPORTED_APPLICATION';  // Made Worker slower (reverted)
```

## CLI Commands

```bash
# Deploy with Smart Placement
wrangler deploy

# Check placement status
curl -H "Authorization: Bearer $TOKEN" \
  https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/workers/services/$WORKER_NAME \
  | jq .result.placement_status

# Monitor
wrangler tail your-worker-name --header cf-placement
```

## Reading Order

**First time?** Start here:
1. This README - understand core concepts and when to use Smart Placement
2. [configuration.md](./configuration.md) - set up wrangler.jsonc and understand limitations
3. [patterns.md](./patterns.md) - see practical examples for your use case
4. [api.md](./api.md) - monitor and verify Smart Placement is working
5. [gotchas.md](./gotchas.md) - troubleshoot common issues

**Quick lookup:**
- "Should I enable Smart Placement?" → See "When to Use" above
- "How do I configure it?" → [configuration.md](./configuration.md)
- "How do I split frontend/backend?" → [patterns.md](./patterns.md)
- "Why isn't it working?" → [gotchas.md](./gotchas.md)

## In This Reference

- [configuration.md](./configuration.md) - wrangler.jsonc setup, mode values, validation rules
- [api.md](./api.md) - Placement Status API, cf-placement header, monitoring
- [patterns.md](./patterns.md) - Frontend/backend split, database workers, SSR patterns
- [gotchas.md](./gotchas.md) - Troubleshooting INSUFFICIENT_INVOCATIONS, performance issues

## See Also

- [workers](../workers/) - Worker runtime and fetch handlers
- [d1](../d1/) - D1 database that benefits from Smart Placement
- [durable-objects](../durable-objects/) - Durable Objects with backend logic
- [bindings](../bindings/) - Service bindings for frontend/backend split

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/snippets/README.md`)

# Cloudflare Snippets Skill Reference

## Description
Expert guidance for **Cloudflare Snippets ONLY** - a lightweight JavaScript-based edge logic platform for modifying HTTP requests and responses. Snippets run as part of the Ruleset Engine and are included at no additional cost on paid plans (Pro, Business, Enterprise).

## What Are Snippets?
Snippets are JavaScript functions executed at the edge as part of Cloudflare's Ruleset Engine. Key characteristics:
- **Execution time**: 5ms CPU limit per request
- **Size limit**: 32KB per snippet
- **Runtime**: V8 isolate (subset of Workers APIs)
- **Subrequests**: 2-5 fetch calls depending on plan
- **Cost**: Included with Pro/Business/Enterprise plans

## Snippets vs Workers Decision Matrix

| Factor | Choose Snippets If... | Choose Workers If... |
|--------|----------------------|---------------------|
| **Complexity** | Simple request/response modifications | Complex business logic, routing, middleware |
| **Execution time** | <5ms sufficient | Need >5ms or variable time |
| **Subrequests** | 2-5 fetch calls sufficient | Need >5 subrequests or complex orchestration |
| **Code size** | <32KB sufficient | Need >32KB or npm dependencies |
| **Cost** | Want zero additional cost | Can afford $5/mo + usage |
| **APIs** | Need basic fetch, headers, URL | Need KV, D1, R2, Durable Objects, cron triggers |
| **Deployment** | Need rule-based triggers | Want custom routing logic |

**Rule of thumb**: Use Snippets for modifications, Workers for applications.

## Execution Model
1. Request arrives at Cloudflare edge
2. Ruleset Engine evaluates snippet rules (filter expressions)
3. If rule matches, snippet executes within 5ms limit
4. Modified request/response continues through pipeline
5. Response returned to client

Snippets execute synchronously in the request path - performance is critical.

## Reading Order
1. **[configuration.md](configuration.md)** - Start here: setup, deployment methods (Dashboard/API/Terraform)
2. **[api.md](api.md)** - Core APIs: Request, Response, headers, `request.cf` properties
3. **[patterns.md](patterns.md)** - Real-world examples: geo-routing, A/B tests, security headers
4. **[gotchas.md](gotchas.md)** - Troubleshooting: common errors, performance tips, API limitations

## In This Reference

- **[configuration.md](configuration.md)** - Setup, deployment, configuration
- **[api.md](api.md)** - API endpoints, methods, interfaces
- **[patterns.md](patterns.md)** - Common patterns, use cases, examples
- **[gotchas.md](gotchas.md)** - Troubleshooting, best practices, limitations

## Quick Start
```javascript
// Snippet: Add security headers
export default {
  async fetch(request) {
    const response = await fetch(request);
    const newResponse = new Response(response.body, response);
    newResponse.headers.set("X-Frame-Options", "DENY");
    newResponse.headers.set("X-Content-Type-Options", "nosniff");
    return newResponse;
  }
}
```

Deploy via Dashboard (Rules → Snippets) or API/Terraform. See configuration.md for details.

## See Also

- [Cloudflare Docs](https://developers.cloudflare.com/rules/snippets/)

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/spectrum/README.md`)

# Cloudflare Spectrum Skill Reference

## Overview

Cloudflare Spectrum provides security and acceleration for ANY TCP or UDP-based application. It's a global Layer 4 (L4) reverse proxy running on Cloudflare's edge nodes that routes MQTT, email, file transfer, version control, games, and more through Cloudflare to mask origins and protect from DDoS attacks.

**When to Use Spectrum**: When your protocol isn't HTTP/HTTPS (use Cloudflare proxy for HTTP). Spectrum handles everything else: SSH, gaming, databases, MQTT, SMTP, RDP, custom protocols.

## Plan Capabilities

| Capability | Pro/Business | Enterprise |
|------------|--------------|------------|
| TCP protocols | Selected ports only | All ports (1-65535) |
| UDP protocols | Selected ports only | All ports (1-65535) |
| Port ranges | ❌ | ✅ |
| Argo Smart Routing | ✅ | ✅ |
| IP Firewall | ✅ | ✅ |
| Load balancer origins | ✅ | ✅ |

## Decision Tree

**What are you trying to do?**

1. **Create/manage Spectrum app**
   - Via Dashboard → See [Cloudflare Dashboard](https://dash.cloudflare.com)
   - Via API → See [api.md](api.md) - REST endpoints
   - Via SDK → See [api.md](api.md) - TypeScript/Python/Go examples
   - Via IaC → See [configuration.md](configuration.md) - Terraform/Pulumi

2. **Protect specific protocol**
   - SSH → See [patterns.md](patterns.md#1-ssh-server-protection)
   - Gaming (Minecraft, etc) → See [patterns.md](patterns.md#2-game-server)
   - MQTT/IoT → See [patterns.md](patterns.md#3-mqtt-broker)
   - SMTP/Email → See [patterns.md](patterns.md#4-smtp-relay)
   - Database → See [patterns.md](patterns.md#5-database-proxy)
   - RDP → See [patterns.md](patterns.md#6-rdp-remote-desktop)

3. **Choose origin type**
   - Direct IP (single server) → See [configuration.md](configuration.md#direct-ip-origin)
   - CNAME (hostname) → See [configuration.md](configuration.md#cname-origin)
   - Load balancer (HA/failover) → See [configuration.md](configuration.md#load-balancer-origin)

## Reading Order

1. Start with [patterns.md](patterns.md) for your specific protocol
2. Then [configuration.md](configuration.md) for your origin type
3. Check [gotchas.md](gotchas.md) before going to production
4. Use [api.md](api.md) for programmatic access

## See Also

- [Cloudflare Docs](https://developers.cloudflare.com/spectrum/)

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/static-assets/README.md`)

# Cloudflare Static Assets Skill Reference

Expert guidance for deploying and configuring static assets with Cloudflare Workers. This skill covers configuration patterns, routing architectures, asset binding usage, and best practices for SPAs, SSG sites, and full-stack applications.

## Quick Start

```jsonc
// wrangler.jsonc
{
  "name": "my-app",
  "main": "src/index.ts",
  "compatibility_date": "2025-01-01",
  "assets": {
    "directory": "./dist"
  }
}
```

```typescript
// src/index.ts
export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    return env.ASSETS.fetch(request);
  }
};
```

Deploy: `wrangler deploy`

## When to Use Workers Static Assets vs Pages

| Factor | Workers Static Assets | Cloudflare Pages |
|--------|----------------------|------------------|
| **Use case** | Hybrid apps (static + dynamic API) | Static sites, SSG |
| **Worker control** | Full control over routing | Limited (Functions) |
| **Configuration** | Code-first, flexible | Git-based, opinionated |
| **Dynamic routing** | Worker-first patterns | Functions (_functions/) |
| **Best for** | Full-stack apps, SPAs with APIs | Jamstack, static docs |

**Decision tree:**

- Need custom routing logic? → Workers Static Assets
- Pure static site or SSG? → Pages
- API routes + SPA? → Workers Static Assets
- Framework (Next, Nuxt, Remix)? → Pages

## Reading Order

1. **configuration.md** - Setup, wrangler.jsonc options, routing patterns
2. **api.md** - ASSETS binding API, request/response handling
3. **patterns.md** - Common patterns (SPA, API routes, auth, A/B testing)
4. **gotchas.md** - Limits, errors, performance tips

## In This Reference

- **[configuration.md](configuration.md)** - Setup, deployment, configuration
- **[api.md](api.md)** - API endpoints, methods, interfaces
- **[patterns.md](patterns.md)** - Common patterns, use cases, examples
- **[gotchas.md](gotchas.md)** - Troubleshooting, best practices, limitations

## See Also

- [Cloudflare Workers Docs](https://developers.cloudflare.com/workers/)
- [Static Assets Docs](https://developers.cloudflare.com/workers/static-assets/)
- [Cloudflare Pages](https://developers.cloudflare.com/pages/)

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/stream/README.md`)

# Cloudflare Stream

Serverless live and on-demand video streaming platform with one API.

## Overview

Cloudflare Stream provides video upload, storage, encoding, and delivery without managing infrastructure. Runs on Cloudflare's global network.

### Key Features
- **On-demand video**: Upload, encode, store, deliver
- **Live streaming**: RTMPS/SRT ingestion with ABR
- **Direct creator uploads**: End users upload without API keys
- **Signed URLs**: Token-based access control
- **Analytics**: Server-side metrics via GraphQL
- **Webhooks**: Processing notifications
- **Captions**: Upload or AI-generate subtitles
- **Watermarks**: Apply branding to videos
- **Downloads**: Enable MP4 offline viewing

## Core Concepts

### Video Upload Methods
1. **API Upload (TUS protocol)**: Direct server upload
2. **Upload from URL**: Import from external source
3. **Direct Creator Uploads**: User-generated content (recommended)

### Playback Options
1. **Stream Player (iframe)**: Built-in, optimized player
2. **Custom Player (HLS/DASH)**: Video.js, HLS.js integration
3. **Thumbnails**: Static or animated previews

### Access Control
- **Public**: No restrictions
- **requireSignedURLs**: Token-based access
- **allowedOrigins**: Domain restrictions
- **Access Rules**: Geo/IP restrictions in tokens

### Live Streaming
- RTMPS/SRT ingest from OBS, FFmpeg
- Automatic recording to on-demand
- Simulcast to YouTube, Twitch, etc.
- WebRTC support for browser streaming

## Quick Start

**Upload video via API**
```bash
curl -X POST \
  "https://api.cloudflare.com/client/v4/accounts/{account_id}/stream/copy" \
  -H "Authorization: Bearer <TOKEN>" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://example.com/video.mp4"}'
```

**Embed player**
```html
<iframe
  src="https://customer-<CODE>.cloudflarestream.com/<VIDEO_ID>/iframe"
  style="border: none;"
  height="720" width="1280"
  allow="accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture;"
  allowfullscreen="true"
></iframe>
```

**Create live input**
```bash
curl -X POST \
  "https://api.cloudflare.com/client/v4/accounts/{account_id}/stream/live_inputs" \
  -H "Authorization: Bearer <TOKEN>" \
  -H "Content-Type: application/json" \
  -d '{"recording": {"mode": "automatic"}}'
```

## Limits

- Max file size: 30 GB
- Max frame rate: 60 fps (recommended)
- Supported formats: MP4, MKV, MOV, AVI, FLV, MPEG-2 TS/PS, MXF, LXF, GXF, 3GP, WebM, MPG, QuickTime

## Pricing

- $5/1000 min stored
- $1/1000 min delivered

## Resources

- Dashboard: https://dash.cloudflare.com/?to=/:account/stream
- API Docs: https://developers.cloudflare.com/api/resources/stream/
- Stream Docs: https://developers.cloudflare.com/stream/

## Reading Order

| Order | File | Purpose | When to Use |
|-------|------|---------|-------------|
| 1 | [configuration.md](./configuration.md) | Setup SDKs, env vars, signing keys | Starting new project |
| 2 | [api.md](./api.md) | On-demand video APIs | Implementing uploads/playback |
| 3 | [api-live.md](./api-live.md) | Live streaming APIs | Building live streaming |
| 4 | [patterns.md](./patterns.md) | Full-stack flows, TUS, JWT signing | Implementing workflows |
| 5 | [gotchas.md](./gotchas.md) | Errors, limits, troubleshooting | Debugging issues |

## In This Reference

- [configuration.md](./configuration.md) - Setup, environment variables, wrangler config
- [api.md](./api.md) - On-demand video upload, playback, management APIs
- [api-live.md](./api-live.md) - Live streaming (RTMPS/SRT/WebRTC), simulcast
- [patterns.md](./patterns.md) - Full-stack flows, state management, best practices
- [gotchas.md](./gotchas.md) - Error codes, troubleshooting, limits

## See Also

- [workers](../workers/) - Deploy Stream APIs in Workers
- [pages](../pages/) - Integrate Stream with Pages
- [workers-ai](../workers-ai/) - AI-generate captions

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/tail-workers/README.md`)

# Cloudflare Tail Workers

Specialized Workers that consume execution events from producer Workers for logging, debugging, analytics, and observability.

## When to Use This Reference

- Implementing observability/logging for Cloudflare Workers
- Processing Worker execution events, logs, exceptions
- Building custom analytics or error tracking
- Configuring real-time event streaming
- Working with tail handlers or tail consumers

## Core Concepts

### What Are Tail Workers?

Tail Workers automatically process events from producer Workers (the Workers being monitored). They receive:
- HTTP request/response info
- Console logs (`console.log/error/warn/debug`)
- Uncaught exceptions
- Execution outcomes (`ok`, `exception`, `exceededCpu`, etc.)
- Diagnostic channel events

**Key characteristics:**
- Invoked AFTER producer finishes executing
- Capture entire request lifecycle including Service Bindings and Dynamic Dispatch sub-requests
- Billed by CPU time, not request count
- Available on Workers Paid and Enterprise tiers

### Alternative: OpenTelemetry Export

**Before using Tail Workers, consider OpenTelemetry:**

For batch exports to observability tools (Sentry, Grafana, Honeycomb):
- OTEL export sends logs/traces in batches (more efficient)
- Built-in integrations with popular platforms
- Lower overhead than Tail Workers
- **Use Tail Workers only for custom real-time processing**

## Decision Tree

```
Need observability for Workers?
├─ Batch export to known tools (Sentry/Grafana/Honeycomb)?
│  └─ Use OpenTelemetry export (not Tail Workers)
├─ Custom real-time processing needed?
│  ├─ Aggregated metrics?
│  │  └─ Use Tail Worker + Analytics Engine
│  ├─ Error tracking?
│  │  └─ Use Tail Worker + external service
│  ├─ Custom logging/debugging?
│  │  └─ Use Tail Worker + KV/HTTP endpoint
│  └─ Complex event processing?
│     └─ Use Tail Worker + Durable Objects
└─ Quick debugging?
   └─ Use `wrangler tail` (different from Tail Workers)
```

## Reading Order

1. **[configuration.md](configuration.md)** - Set up Tail Workers
2. **[api.md](api.md)** - Handler signature, types, redaction
3. **[patterns.md](patterns.md)** - Common use cases and integrations
4. **[gotchas.md](gotchas.md)** - Pitfalls and debugging tips

## Quick Example

```typescript
export default {
  async tail(events, env, ctx) {
    // Process events from producer Worker
    ctx.waitUntil(
      fetch(env.LOG_ENDPOINT, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(events),
      })
    );
  }
};
```

## Related Skills

- **observability** - General Workers observability patterns, OTEL export
- **analytics-engine** - Aggregated metrics storage for tail event data
- **durable-objects** - Stateful event processing, batching tail events
- **logpush** - Alternative for batch log export (non-real-time)
- **workers-for-platforms** - Dynamic dispatch with tail consumers

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/terraform/README.md`)

# Cloudflare Terraform Provider

**Expert guidance for Cloudflare Terraform Provider - infrastructure as code for Cloudflare resources.**

## Core Principles

- **Provider-first**: Use Terraform provider for ALL infrastructure - never mix with wrangler.jsonc for the same resources
- **State management**: Always use remote state (S3, Terraform Cloud, etc.) for team environments
- **Modular architecture**: Create reusable modules for common patterns (zones, workers, pages)
- **Version pinning**: Always pin provider version with `~>` for predictable upgrades
- **Secret management**: Use variables + environment vars for sensitive data - never hardcode API tokens

## Provider Version

| Version | Status | Notes |
|---------|--------|-------|
| 5.x | Current | Auto-generated from OpenAPI, breaking changes from v4 |
| 4.x | Legacy | Manual maintenance, deprecated |

**Critical:** v5 renamed many resources (`cloudflare_record` → `cloudflare_dns_record`, `cloudflare_worker_*` → `cloudflare_workers_*`). See [gotchas.md](./gotchas.md#v5-breaking-changes) for migration details.

## Provider Setup

### Basic Configuration

```hcl
terraform {
  required_version = ">= 1.0"
  
  required_providers {
    cloudflare = {
      source  = "cloudflare/cloudflare"
      version = "~> 5.15.0"
    }
  }
}

provider "cloudflare" {
  api_token = var.cloudflare_api_token  # or CLOUDFLARE_API_TOKEN env var
}
```

### Authentication Methods (priority order)

1. **API Token** (RECOMMENDED): `api_token` or `CLOUDFLARE_API_TOKEN`
   - Create: Dashboard → My Profile → API Tokens
   - Scope to specific accounts/zones for security
   
2. **Global API Key** (LEGACY): `api_key` + `api_email` or `CLOUDFLARE_API_KEY` + `CLOUDFLARE_EMAIL`
   - Less secure, use tokens instead
   
3. **User Service Key**: `user_service_key` for Origin CA certificates



## Quick Reference: Common Commands

```bash
terraform init          # Initialize provider
terraform plan          # Plan changes
terraform apply         # Apply changes
terraform destroy       # Destroy resources
terraform import cloudflare_zone.example <zone-id>  # Import existing
terraform state list    # List resources in state
terraform output        # Show outputs
terraform fmt -recursive  # Format code
terraform validate      # Validate configuration
```

## Import Existing Resources

Use cf-terraforming to generate configs from existing Cloudflare resources:

```bash
# Install
brew install cloudflare/cloudflare/cf-terraforming

# Generate HCL from existing resources
cf-terraforming generate --resource-type cloudflare_dns_record --zone <zone-id>

# Import into Terraform state
cf-terraforming import --resource-type cloudflare_dns_record --zone <zone-id>
```

## Reading Order

1. Start with [README.md](./README.md) for provider setup and authentication
2. Review [configuration.md](./configuration.md) for resource configurations
3. Check [api.md](./api.md) for data sources and existing resource queries
4. See [patterns.md](./patterns.md) for multi-environment and CI/CD patterns
5. Read [gotchas.md](./gotchas.md) for state drift, v5 breaking changes, and troubleshooting

## In This Reference
- [configuration.md](./configuration.md) - Resources for zones, DNS, workers, KV, R2, D1, Pages, rulesets
- [api.md](./api.md) - Data sources for existing resources
- [patterns.md](./patterns.md) - Architecture patterns, multi-env setup, CI/CD integration
- [gotchas.md](./gotchas.md) - Common issues, security, best practices

## See Also
- [pulumi](../pulumi/) - Alternative IaC tool for Cloudflare
- [wrangler](../wrangler/) - CLI deployment alternative
- [workers](../workers/) - Worker runtime documentation

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/tunnel/README.md`)

# Cloudflare Tunnel

Secure outbound-only connections between infrastructure and Cloudflare's global network.

## Overview

Cloudflare Tunnel (formerly Argo Tunnel) enables:
- **Outbound-only connections** - No inbound ports or firewall changes
- **Public hostname routing** - Expose local services to internet
- **Private network access** - Connect internal networks via WARP
- **Zero Trust integration** - Built-in access policies

**Architecture**: Tunnel (persistent object) → Replica (`cloudflared` process) → Origin services

**Terminology:**
- **Tunnel**: Named persistent object with UUID
- **Replica**: Individual `cloudflared` process connected to tunnel
- **Config Source**: Where ingress rules stored (local file vs Cloudflare dashboard)
- **Connector**: Legacy term for replica

## Quick Start

### Local Config
```bash
# Install cloudflared
brew install cloudflared  # macOS

# Authenticate
cloudflared tunnel login

# Create tunnel
cloudflared tunnel create my-tunnel

# Route DNS
cloudflared tunnel route dns my-tunnel app.example.com

# Run tunnel
cloudflared tunnel run my-tunnel
```

### Dashboard Config (Recommended)
1. **Zero Trust** > **Networks** > **Tunnels** > **Create**
2. Name tunnel, copy token
3. Configure routes in dashboard
4. Run: `cloudflared tunnel --no-autoupdate run --token <TOKEN>`

## Decision Tree

**Choose config source:**
```
Need centralized config updates?
├─ Yes → Token-based (dashboard config)
└─ No → Local config file

Multiple environments (dev/staging/prod)?
├─ Yes → Local config (version controlled)
└─ No → Either works

Need firewall approval?
└─ See networking.md first
```

## Core Commands

```bash
# Tunnel lifecycle
cloudflared tunnel create <name>
cloudflared tunnel list
cloudflared tunnel info <name>
cloudflared tunnel delete <name>

# DNS routing
cloudflared tunnel route dns <tunnel> <hostname>
cloudflared tunnel route list

# Private network
cloudflared tunnel route ip add 10.0.0.0/8 <tunnel>

# Run tunnel
cloudflared tunnel run <name>
```

## Configuration Example

```yaml
# ~/.cloudflared/config.yml
tunnel: 6ff42ae2-765d-4adf-8112-31c55c1551ef
credentials-file: /root/.cloudflared/6ff42ae2-765d-4adf-8112-31c55c1551ef.json

ingress:
  - hostname: app.example.com
    service: http://localhost:8000
  - hostname: api.example.com
    service: https://localhost:8443
    originRequest:
      noTLSVerify: true
  - service: http_status:404
```

## Reading Order

**New to Cloudflare Tunnel:**
1. This README (overview, quick start)
2. [networking.md](./networking.md) - Firewall rules, connectivity pre-checks
3. [configuration.md](./configuration.md) - Config file options, ingress rules
4. [patterns.md](./patterns.md) - Docker, Kubernetes, production deployment
5. [gotchas.md](./gotchas.md) - Troubleshooting, best practices

**Enterprise deployment:**
1. [networking.md](./networking.md) - Corporate firewall requirements
2. [gotchas.md](./gotchas.md) - HA setup, security best practices
3. [patterns.md](./patterns.md) - Kubernetes, rolling updates

**Programmatic control:**
1. [api.md](./api.md) - REST API, TypeScript SDK

## In This Reference

- [networking.md](./networking.md) - Firewall rules, ports, connectivity pre-checks
- [configuration.md](./configuration.md) - Config file options, ingress rules, TLS settings
- [api.md](./api.md) - REST API, TypeScript SDK, token-based tunnels
- [patterns.md](./patterns.md) - Docker, Kubernetes, Terraform, HA, use cases
- [gotchas.md](./gotchas.md) - Troubleshooting, limitations, best practices

## See Also

- [workers](../workers/) - Workers with Tunnel integration
- [access](../access/) - Zero Trust access policies
- [warp](../warp/) - WARP client for private networks

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/turn/README.md`)

# Cloudflare TURN Service

Expert guidance for implementing Cloudflare TURN Service in WebRTC applications.

## Overview

Cloudflare TURN (Traversal Using Relays around NAT) Service is a managed relay service for WebRTC applications. TURN acts as a relay point for traffic between WebRTC clients and SFUs, particularly when direct peer-to-peer communication is obstructed by NATs or firewalls. The service runs on Cloudflare's global anycast network across 310+ cities.

## Key Characteristics

- **Anycast Architecture**: Automatically connects clients to the closest Cloudflare location
- **Global Network**: Available across Cloudflare's entire network (excluding China Network)
- **Zero Configuration**: No need to manually select regions or servers
- **Protocol Support**: STUN/TURN over UDP, TCP, and TLS
- **Free Tier**: Free when used with Cloudflare Calls SFU, otherwise $0.05/GB outbound

## In This Reference

| File | Purpose |
|------|---------|
| [api.md](./api.md) | Credentials API, TURN key management, types, constraints |
| [configuration.md](./configuration.md) | Worker setup, wrangler.jsonc, env vars, IP allowlisting |
| [patterns.md](./patterns.md) | Implementation patterns, use cases, integration examples |
| [gotchas.md](./gotchas.md) | Troubleshooting, limits, security, common mistakes |

## Reading Order

| Task | Files to Read | Est. Tokens |
|------|---------------|-------------|
| Quick start | README only | ~500 |
| Generate credentials | README → api | ~1300 |
| Worker integration | README → configuration → patterns | ~2000 |
| Debug connection | gotchas | ~700 |
| Security review | api → gotchas | ~1500 |
| Enterprise firewall | configuration | ~600 |

## Service Addresses and Ports

### STUN over UDP
- **Primary**: `stun.cloudflare.com:3478/udp`
- **Alternate**: `stun.cloudflare.com:53/udp` (blocked by browsers, not recommended)

### TURN over UDP
- **Primary**: `turn.cloudflare.com:3478/udp`
- **Alternate**: `turn.cloudflare.com:53/udp` (blocked by browsers)

### TURN over TCP
- **Primary**: `turn.cloudflare.com:3478/tcp`
- **Alternate**: `turn.cloudflare.com:80/tcp`

### TURN over TLS
- **Primary**: `turn.cloudflare.com:5349/tcp`
- **Alternate**: `turn.cloudflare.com:443/tcp`

## Quick Start

1. **Create TURN key via API**: see [api.md#create-turn-key](./api.md#create-turn-key)
2. **Generate credentials**: see [api.md#generate-temporary-credentials](./api.md#generate-temporary-credentials)
3. **Configure Worker**: see [configuration.md#cloudflare-worker-integration](./configuration.md#cloudflare-worker-integration)
4. **Implement client**: see [patterns.md#basic-turn-configuration-browser](./patterns.md#basic-turn-configuration-browser)

## When to Use TURN

- **Restrictive NATs**: Symmetric NATs that block direct connections
- **Corporate firewalls**: Environments blocking WebRTC ports
- **Mobile networks**: Carrier-grade NAT scenarios
- **Predictable connectivity**: When reliability > efficiency

## Related Cloudflare Services

- **Cloudflare Calls SFU**: Managed Selective Forwarding Unit (TURN free when used with SFU)
- **Cloudflare Stream**: Video streaming with WHIP/WHEP support
- **Cloudflare Workers**: Backend for credential generation
- **Cloudflare KV**: Credential caching
- **Cloudflare Durable Objects**: Session state management

## Additional Resources

- [Cloudflare Calls Documentation](https://developers.cloudflare.com/calls/)
- [Cloudflare TURN Service Docs](https://developers.cloudflare.com/realtime/turn/)
- [Cloudflare API Reference](https://developers.cloudflare.com/api/resources/calls/subresources/turn/)
- [Orange Meets (Open Source Example)](https://github.com/cloudflare/orange)

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/turnstile/README.md`)

# Cloudflare Turnstile Implementation Skill Reference

Expert guidance for implementing Cloudflare Turnstile - a smart CAPTCHA alternative that protects websites from bots without showing traditional CAPTCHA puzzles.

## Overview

Turnstile is a user-friendly CAPTCHA alternative that runs challenges in the background without user interaction. It validates visitors automatically using signals like browser behavior, device fingerprinting, and machine learning.

## Widget Types

| Type | Interaction | Use Case |
|------|-------------|----------|
| **Managed** (default) | Shows checkbox when needed | Forms, logins - balance UX and security |
| **Non-Interactive** | Invisible, runs automatically | Frictionless UX, low-risk actions |
| **Invisible** | Hidden, triggered programmatically | Pre-clearance, API calls, headless |

## Quick Start

### Implicit Rendering (HTML-based)
```html

<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>


<form action="/submit" method="POST">
  <div class="cf-turnstile" data-sitekey="YOUR_SITE_KEY"></div>
  <button type="submit">Submit</button>
</form>
```

### Explicit Rendering (JavaScript-based)
```html
<div id="turnstile-container"></div>
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit"></script>
<script>
window.turnstile.render('#turnstile-container', {
  sitekey: 'YOUR_SITE_KEY',
  callback: (token) => console.log('Token:', token)
});
</script>
```

### Server Validation (Required)
```javascript
// Cloudflare Workers
export default {
  async fetch(request) {
    const formData = await request.formData();
    const token = formData.get('cf-turnstile-response');
    
    const result = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        secret: env.TURNSTILE_SECRET,
        response: token,
        remoteip: request.headers.get('CF-Connecting-IP')
      })
    });
    
    const validation = await result.json();
    if (!validation.success) {
      return new Response('Invalid CAPTCHA', { status: 400 });
    }
    // Process form...
  }
}
```

## Testing Keys

**Critical for development/testing:**

| Type | Key | Behavior |
|------|-----|----------|
| **Site Key (Always Passes)** | `1x00000000000000000000AA` | Widget succeeds, token validates |
| **Site Key (Always Blocks)** | `2x00000000000000000000AB` | Widget fails visibly |
| **Site Key (Force Challenge)** | `3x00000000000000000000FF` | Always shows interactive challenge |
| **Secret Key (Testing)** | `1x0000000000000000000000000000000AA` | Validates test tokens |

**Note:** Test keys work on `localhost` and any domain. Do NOT use in production.

## Key Constraints

- **Token expiry:** 5 minutes after generation
- **Single-use:** Each token can only be validated once
- **Server validation required:** Client-side checks are insufficient

## Reading Order

1. **[configuration.md](configuration.md)** - Setup, widget options, script loading
2. **[api.md](api.md)** - JavaScript API, siteverify endpoints, TypeScript types
3. **[patterns.md](patterns.md)** - Form integration, framework examples, validation patterns
4. **[gotchas.md](gotchas.md)** - Common errors, debugging, limitations

## See Also

- [Cloudflare Turnstile Docs](https://developers.cloudflare.com/turnstile/)
- [Dashboard](https://dash.cloudflare.com/?to=/:account/turnstile)

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/vectorize/README.md`)

# Cloudflare Vectorize

Globally distributed vector database for AI applications. Store and query vector embeddings for semantic search, recommendations, RAG, and classification.

**Status:** Generally Available (GA) | **Last Updated:** 2026-01-27

## Quick Start

```typescript
// 1. Create index
// npx wrangler vectorize create my-index --dimensions=768 --metric=cosine

// 2. Configure binding (wrangler.jsonc)
// { "vectorize": [{ "binding": "VECTORIZE", "index_name": "my-index" }] }

// 3. Query vectors
const matches = await env.VECTORIZE.query(queryVector, { topK: 5 });
```

## Key Features

- **10M vectors per index** (V2)
- Dimensions up to 1536 (32-bit float)
- Three distance metrics: cosine, euclidean, dot-product
- Metadata filtering (up to 10 indexes)
- Namespace support (50K namespaces paid, 1K free)
- Seamless Workers AI integration
- Global distribution

## Reading Order

| Task | Files to Read |
|------|---------------|
| New to Vectorize | README only |
| Implement feature | README + api + patterns |
| Setup/configure | README + configuration |
| Debug issues | gotchas |
| Integrate with AI | README + patterns |
| RAG implementation | README + patterns |

## File Guide

- **README.md** (this file): Overview, quick decisions
- **api.md**: Runtime API, types, operations (query/insert/upsert)
- **configuration.md**: Setup, CLI, metadata indexes
- **patterns.md**: RAG, Workers AI, OpenAI, LangChain, multi-tenant
- **gotchas.md**: Limits, pitfalls, troubleshooting

## Distance Metric Selection

Choose based on your use case:

```
What are you building?
├─ Text/semantic search → cosine (most common)
├─ Image similarity → euclidean
├─ Recommendation system → dot-product
└─ Pre-normalized vectors → dot-product
```

| Metric | Best For | Score Interpretation |
|--------|----------|---------------------|
| `cosine` | Text embeddings, semantic similarity | Higher = closer (1.0 = identical) |
| `euclidean` | Absolute distance, spatial data | Lower = closer (0.0 = identical) |
| `dot-product` | Recommendations, normalized vectors | Higher = closer |

**Note:** Index configuration is immutable. Cannot change dimensions or metric after creation.

## Multi-Tenancy Strategy

```
How many tenants?
├─ < 50K tenants → Use namespaces (recommended)
│   ├─ Fastest (filter before vector search)
│   └─ Strict isolation
├─ > 50K tenants → Use metadata filtering
│   ├─ Slower (post-filter after vector search)
│   └─ Requires metadata index
└─ Per-tenant indexes → Only if compliance mandated
    └─ 50K index limit per account (paid plan)
```

## Common Workflows

### Semantic Search

```typescript
// 1. Generate embedding
const result = await env.AI.run("@cf/baai/bge-base-en-v1.5", { text: [query] });

// 2. Query Vectorize
const matches = await env.VECTORIZE.query(result.data[0], {
  topK: 5,
  returnMetadata: "indexed"
});
```

### RAG Pattern

```typescript
// 1. Generate query embedding
const embedding = await env.AI.run("@cf/baai/bge-base-en-v1.5", { text: [query] });

// 2. Search Vectorize
const matches = await env.VECTORIZE.query(embedding.data[0], { topK: 5 });

// 3. Fetch full documents from R2/D1/KV
const docs = await Promise.all(matches.matches.map(m => 
  env.R2.get(m.metadata.key).then(obj => obj?.text())
));

// 4. Generate LLM response with context
const answer = await env.AI.run("@cf/meta/llama-3-8b-instruct", {
  prompt: `Context: ${docs.join("\n\n")}\n\nQuestion: ${query}\n\nAnswer:`
});
```

## Critical Gotchas

See `gotchas.md` for details. Most important:

1. **Async mutations**: Inserts take 5-10s to be queryable
2. **500 batch limit**: Workers API enforces 500 vectors per call (undocumented)
3. **Metadata truncation**: `"indexed"` returns first 64 bytes only
4. **topK with metadata**: Max 20 (not 100) when using returnValues or returnMetadata: "all"
5. **Metadata indexes first**: Must create before inserting vectors

## Resources

- [Official Docs](https://developers.cloudflare.com/vectorize/)
- [Client API Reference](https://developers.cloudflare.com/vectorize/reference/client-api/)
- [Workers AI Models](https://developers.cloudflare.com/workers-ai/models/#text-embeddings)
- [Discord: #vectorize](https://discord.cloudflare.com)

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/waf/README.md`)

# Cloudflare WAF Expert Skill Reference

**Expertise**: Cloudflare Web Application Firewall (WAF) configuration, custom rules, managed rulesets, rate limiting, attack detection, and API integration

## Overview

Cloudflare WAF protects web applications from attacks through managed rulesets and custom rules.

**Detection (Managed Rulesets)**
- Pre-configured rules maintained by Cloudflare
- CVE-based rules, OWASP Top 10 coverage
- Three main rulesets: Cloudflare Managed, OWASP CRS, Exposed Credentials
- Actions: log, block, challenge, js_challenge, managed_challenge

**Mitigation (Custom Rules & Rate Limiting)**
- Custom expressions using Wirefilter syntax
- Attack score-based blocking (`cf.waf.score`)
- Rate limiting with per-IP, per-user, or custom characteristics
- Actions: block, challenge, js_challenge, managed_challenge, log, skip

## Quick Start

### Deploy Cloudflare Managed Ruleset
```typescript
import Cloudflare from 'cloudflare';

const client = new Cloudflare({ apiToken: process.env.CF_API_TOKEN });

// Deploy managed ruleset to zone
await client.rulesets.create({
  zone_id: 'zone_id',
  kind: 'zone',
  phase: 'http_request_firewall_managed',
  name: 'Deploy Cloudflare Managed Ruleset',
  rules: [{
    action: 'execute',
    action_parameters: {
      id: 'efb7b8c949ac4650a09736fc376e9aee', // Cloudflare Managed Ruleset
    },
    expression: 'true',
    enabled: true,
  }],
});
```

### Create Custom Rule
```typescript
// Block requests with attack score >= 40
await client.rulesets.create({
  zone_id: 'zone_id',
  kind: 'zone',
  phase: 'http_request_firewall_custom',
  name: 'Custom WAF Rules',
  rules: [{
    action: 'block',
    expression: 'cf.waf.score gt 40',
    description: 'Block high attack scores',
    enabled: true,
  }],
});
```

### Create Rate Limit
```typescript
await client.rulesets.create({
  zone_id: 'zone_id',
  kind: 'zone',
  phase: 'http_ratelimit',
  name: 'API Rate Limits',
  rules: [{
    action: 'block',
    expression: 'http.request.uri.path eq "/api/login"',
    action_parameters: {
      ratelimit: {
        characteristics: ['cf.colo.id', 'ip.src'],
        period: 60,
        requests_per_period: 10,
        mitigation_timeout: 600,
      },
    },
    enabled: true,
  }],
});
```

## Managed Ruleset Quick Reference

| Ruleset Name | ID | Coverage |
|--------------|----|---------| 
| Cloudflare Managed | `efb7b8c949ac4650a09736fc376e9aee` | OWASP Top 10, CVEs |
| OWASP Core Ruleset | `4814384a9e5d4991b9815dcfc25d2f1f` | OWASP ModSecurity CRS |
| Exposed Credentials Check | `c2e184081120413c86c3ab7e14069605` | Credential stuffing |

## Phases

WAF rules execute in specific phases:
- `http_request_firewall_managed` - Managed rulesets
- `http_request_firewall_custom` - Custom rules
- `http_ratelimit` - Rate limiting rules
- `http_request_sbfm` - Super Bot Fight Mode (Pro+)

## Reading Order

1. **[api.md](api.md)** - SDK methods, expressions, actions, parameters
2. **[configuration.md](configuration.md)** - Setup with Wrangler, Terraform, Pulumi
3. **[patterns.md](patterns.md)** - Common patterns: deploy managed, rate limiting, skip, override
4. **[gotchas.md](gotchas.md)** - Execution order, limits, expression errors

## See Also

- [Cloudflare WAF Docs](https://developers.cloudflare.com/waf/)
- [Ruleset Engine](https://developers.cloudflare.com/ruleset-engine/)
- [Expression Reference](https://developers.cloudflare.com/ruleset-engine/rules-language/)

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/web-analytics/README.md`)

# Cloudflare Web Analytics

Privacy-first web analytics providing Core Web Vitals, traffic metrics, and user insights without compromising visitor privacy.

## Overview

Cloudflare Web Analytics provides:
- **Core Web Vitals** - LCP, FID, CLS, INP, TTFB monitoring
- **Page views & visits** - Traffic patterns without cookies
- **Referrers & paths** - Traffic sources and popular pages
- **Device & browser data** - User agent breakdown
- **Geographic data** - Country-level visitor distribution
- **Privacy-first** - No cookies, fingerprinting, or PII collection
- **Free** - No cost, unlimited pageviews

**Important:** Web Analytics is **dashboard-only**. No API exists for programmatic data access.

## Quick Start Decision Tree

```
Is your site proxied through Cloudflare?
├─ YES → Use automatic injection (configuration.md)
│   ├─ Enable auto-injection in dashboard
│   └─ No code changes needed (unless Cache-Control: no-transform)
│
└─ NO → Use manual beacon integration (integration.md)
    ├─ Add JS snippet to HTML
    ├─ Use spa: true for React/Vue/Next.js
    └─ Configure CSP if needed
```

## Reading Order

1. **[configuration.md](configuration.md)** - Setup for proxied vs non-proxied sites
2. **[integration.md](integration.md)** - Framework-specific beacon integration (React, Next.js, Vue, Nuxt, etc.)
3. **[patterns.md](patterns.md)** - Common use cases (performance monitoring, GDPR consent, multi-site tracking)
4. **[gotchas.md](gotchas.md)** - Troubleshooting (SPA tracking, CSP issues, hash routing limitations)

## When to Use Each File

- **Setting up for first time?** → Start with configuration.md
- **Using React/Next.js/Vue/Nuxt?** → Go to integration.md for framework code
- **Need GDPR consent loading?** → See patterns.md
- **Beacon not loading or no data?** → Check gotchas.md
- **SPA not tracking navigation?** → See integration.md for `spa: true` config

## Key Concepts

### Proxied vs Non-Proxied Sites

| Type | Description | Beacon Injection | Limit |
|------|-------------|------------------|-------|
| **Proxied** | DNS through Cloudflare (orange cloud) | Automatic or manual | Unlimited |
| **Non-proxied** | External hosting, manual beacon | Manual only | 10 sites max |

### SPA Mode

**Critical for modern frameworks:**
```json
{"token": "YOUR_TOKEN", "spa": true}
```

Without `spa: true`, client-side navigation (React Router, Vue Router, Next.js routing) will NOT be tracked. Only initial page loads will register.

### CSP Requirements

If using Content Security Policy, allow both domains:
```
script-src https://static.cloudflareinsights.com https://cloudflareinsights.com;
```

## Features

### Core Web Vitals Debugging
- **LCP (Largest Contentful Paint)** - Identifies slow-loading hero images/elements
- **FID (First Input Delay)** - Interaction responsiveness (legacy metric)
- **INP (Interaction to Next Paint)** - Modern interaction responsiveness metric
- **CLS (Cumulative Layout Shift)** - Visual stability issues
- **TTFB (Time to First Byte)** - Server response performance

Dashboard shows top 5 problematic elements with CSS selectors for debugging.

### Traffic Filters
- **Bot filtering** - Exclude automated traffic from metrics
- **Date ranges** - Custom time period analysis
- **Geographic** - Country-level filtering
- **Device type** - Desktop, mobile, tablet breakdown
- **Browser/OS** - User agent filtering

### Rules (Advanced - Plan-dependent)

Create custom tracking rules for advanced configurations:

**Sample Rate Rules:**
- Reduce data collection percentage for high-traffic sites
- Example: Track only 50% of visitors to reduce volume

**Path-Based Rules:**
- Different behavior per route
- Example: Exclude `/admin/*` or `/internal/*` from tracking

**Host-Based Rules:**
- Multi-domain configurations
- Example: Separate tracking for staging vs production subdomains

**Availability:** Rules feature depends on your Cloudflare plan. Check dashboard under Web Analytics → Rules to see if available. Free plans may have limited or no access.

## Plan Limits

| Feature | Free | Notes |
|---------|------|-------|
| Proxied sites | Unlimited | DNS through Cloudflare |
| Non-proxied sites | 10 | External hosting |
| Pageviews | Unlimited | No volume limits |
| Data retention | 6 months | Rolling window |
| Rules | Plan-dependent | Check dashboard |

## Privacy & Compliance

- **No cookies** - Zero client-side storage
- **No fingerprinting** - No tracking across sites
- **No PII** - IP addresses not stored
- **GDPR-friendly** - Minimal data collection
- **CCPA-compliant** - No personal data sale

**EU opt-out:** Dashboard option to exclude EU visitor data entirely.

## Limitations

- **Dashboard-only** - No API for programmatic access
- **No real-time** - 5-10 minute data delay
- **No custom events** - Automatic pageview/navigation tracking only
- **History API only** - Hash-based routing (`#/path`) not supported
- **No session replay** - Metrics only, no user recordings
- **No form tracking** - Page navigation tracking only

## See Also

- [Cloudflare Web Analytics Docs](https://developers.cloudflare.com/analytics/web-analytics/)
- [Core Web Vitals Guide](https://web.dev/vitals/)

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/workerd/README.md`)

# Workerd Runtime

V8-based JS/Wasm runtime powering Cloudflare Workers. Use as app server, dev tool, or HTTP proxy.

## ⚠️ IMPORTANT SECURITY NOTICE
**workerd is NOT a hardened sandbox.** Do not run untrusted code. It's designed for deploying YOUR code locally/self-hosted, not multi-tenant SaaS. Cloudflare production adds security layers not present in open-source workerd.

## Decision Tree: When to Use What

**95% of users:** Use Wrangler
- Local development: `wrangler dev` (uses workerd internally)
- Deployment: `wrangler deploy` (deploys to Cloudflare)
- Types: `wrangler types` (generates TypeScript types)

**Use raw workerd directly only if:**
- Self-hosting Workers runtime in production
- Embedding runtime in C++ application
- Custom tooling/testing infrastructure
- Debugging workerd-specific behavior

**Never use workerd for:**
- Running untrusted/user-submitted code
- Multi-tenant isolation (not hardened)
- Production without additional security layers

## Key Features
- **Standards-based**: Fetch API, Web Crypto, Streams, WebSocket
- **Nanoservices**: Service bindings with local call performance
- **Capability security**: Explicit bindings prevent SSRF
- **Backwards compatible**: Version = max compat date supported

## Architecture
```
Config (workerd.capnp)
├── Services (workers/endpoints)
├── Sockets (HTTP/HTTPS listeners)
└── Extensions (global capabilities)
```

## Quick Start
```bash
workerd serve config.capnp
workerd compile config.capnp myConfig -o binary
workerd test config.capnp
```

## Platform Support & Beta Status

| Platform | Status | Notes |
|----------|--------|-------|
| Linux (x64) | Stable | Primary platform |
| macOS (x64/ARM) | Stable | Full support |
| Windows | Beta | Use WSL2 for best results |
| Linux (ARM64) | Experimental | Limited testing |

workerd is in **active development**. Breaking changes possible. Pin versions in production.

## Core Concepts
- **Service**: Named endpoint (worker/network/disk/external)
- **Binding**: Capability-based resource access (KV/DO/R2/services)
- **Compatibility date**: Feature gate (always set!)
- **Modules**: ES modules (recommended) or service worker syntax

## Reading Order (Progressive Disclosure)

**Start here:**
1. This README (overview, decision tree)
2. [patterns.md](./patterns.md) - Common workflows, framework examples

**When you need details:**
3. [configuration.md](./configuration.md) - Config format, services, bindings
4. [api.md](./api.md) - Runtime APIs, TypeScript types
5. [gotchas.md](./gotchas.md) - Common errors, debugging

## Related References
- [workers](../workers/) - Workers runtime API documentation
- [miniflare](../miniflare/) - Testing tool built on workerd
- [wrangler](../wrangler/) - CLI that uses workerd for local dev

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/workers-ai/README.md`)

# Cloudflare Workers AI

Expert guidance for Cloudflare Workers AI - serverless GPU-powered AI inference at the edge.

## Overview

Workers AI provides:
- 50+ pre-trained models (LLMs, embeddings, image generation, speech-to-text, translation)
- Native Workers binding (no external API calls)
- Pay-per-use pricing (neurons consumed per inference)
- OpenAI-compatible REST API
- Streaming support for text generation
- Function calling with compatible models

**Architecture**: Inference runs on Cloudflare's GPU network. Models load on first request (cold start 1-3s), subsequent requests are faster.

## Quick Start

```typescript
interface Env {
  AI: Ai;
}

export default {
  async fetch(request: Request, env: Env) {
    const response = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', {
      messages: [{ role: 'user', content: 'What is Cloudflare?' }]
    });
    return Response.json(response);
  }
};
```

```bash
# Setup - add binding to wrangler.jsonc
wrangler dev --remote  # Must use --remote for AI
wrangler deploy
```

## Model Selection Decision Tree

### Text Generation (Chat/Completion)

**Quality Priority**:
- **Best quality**: `@cf/meta/llama-3.1-70b-instruct` (expensive, ~2000 neurons)
- **Balanced**: `@cf/meta/llama-3.1-8b-instruct` (good quality, ~200 neurons)
- **Fastest/cheapest**: `@cf/mistral/mistral-7b-instruct-v0.1` (~50 neurons)

**Function Calling**:
- Use `@cf/meta/llama-3.1-8b-instruct` or `@cf/meta/llama-3.1-70b-instruct` (native tool support)

**Code Generation**:
- Use `@cf/deepseek-ai/deepseek-coder-6.7b-instruct` (specialized for code)

### Embeddings (Semantic Search/RAG)

**English text**:
- **Best**: `@cf/baai/bge-large-en-v1.5` (1024 dims, highest quality)
- **Balanced**: `@cf/baai/bge-base-en-v1.5` (768 dims, good quality)
- **Fast**: `@cf/baai/bge-small-en-v1.5` (384 dims, lower quality but fast)

**Multilingual**:
- Use `@hf/sentence-transformers/paraphrase-multilingual-minilm-l12-v2`

### Image Generation

- **Stable Diffusion**: `@cf/stabilityai/stable-diffusion-xl-base-1.0` (~10,000 neurons)
- **Portraits**: `@cf/lykon/dreamshaper-8-lcm` (optimized for faces)

### Other Tasks

- **Speech-to-text**: `@cf/openai/whisper`
- **Translation**: `@cf/meta/m2m100-1.2b` (100 languages)
- **Image classification**: `@cf/microsoft/resnet-50`

## SDK Approach Decision Tree

### Native Binding (Recommended)

**When**: Building Workers/Pages with TypeScript  
**Why**: Zero external dependencies, best performance, native types

```typescript
await env.AI.run(model, input);
```

### REST API

**When**: External services, non-Workers environments, testing  
**Why**: Standard HTTP, works anywhere

```bash
curl https://api.cloudflare.com/client/v4/accounts/<ACCOUNT_ID>/ai/run/@cf/meta/llama-3.1-8b-instruct \
  -H "Authorization: Bearer <API_TOKEN>" \
  -d '{"messages":[{"role":"user","content":"Hello"}]}'
```

### Vercel AI SDK Integration

**When**: Using Vercel AI SDK features (streaming UI, tool calling abstractions)  
**Why**: Unified interface across providers

```typescript
import { openai } from '@ai-sdk/openai';

const model = openai('model-name', {
  baseURL: 'https://api.cloudflare.com/client/v4/accounts/<ACCOUNT_ID>/ai/v1',
  headers: { Authorization: 'Bearer <API_TOKEN>' }
});
```

## RAG vs Direct Generation

### Use RAG (Vectorize + Workers AI) When:
- Answering questions about specific documents/data
- Need factual accuracy from known corpus
- Context exceeds model's window (>4K tokens)
- Building knowledge base chat

### Use Direct Generation When:
- Creative writing, brainstorming
- General knowledge questions
- Small context fits in prompt (<4K tokens)
- Cost optimization (RAG adds embedding + vector search costs)

## Platform Limits

| Limit | Free Tier | Paid Plans |
|-------|-----------|------------|
| Neurons/day | 10,000 | Pay per use |
| Rate limit | Varies by model | Higher (contact support) |
| Context window | Model dependent (2K-8K) | Same |
| Streaming | ✅ Supported | ✅ Supported |
| Function calling | ✅ Supported (select models) | ✅ Supported |

**Pricing**: Free 10K neurons/day, then pay per neuron consumed (varies by model)

## Common Tasks

```typescript
// Streaming text generation
const stream = await env.AI.run(model, { messages, stream: true });
for await (const chunk of stream) {
  console.log(chunk.response);
}

// Embeddings for RAG
const { data } = await env.AI.run('@cf/baai/bge-base-en-v1.5', {
  text: ['Query text', 'Document 1', 'Document 2']
});

// Function calling
const response = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', {
  messages: [{ role: 'user', content: 'What is the weather?' }],
  tools: [{
    type: 'function',
    function: { name: 'getWeather', parameters: { ... } }
  }]
});
```

## Development Workflow

```bash
# Always use --remote for AI (local doesn't have models)
wrangler dev --remote

# Deploy to production
wrangler deploy

# View model catalog
# https://developers.cloudflare.com/workers-ai/models/
```

## Reading Order

**Start here**: Quick Start above → configuration.md (setup)

**Common tasks**:
- First time setup: configuration.md → Add binding + deploy
- Choose model: Model Selection Decision Tree (above) → api.md
- Build RAG: patterns.md → Vectorize integration
- Optimize costs: Model Selection + gotchas.md (rate limits)
- Debugging: gotchas.md → Common errors

## In This Reference

- [configuration.md](./configuration.md) - wrangler.jsonc setup, TypeScript types, bindings, environment variables
- [api.md](./api.md) - env.AI.run(), streaming, function calling, REST API, response types
- [patterns.md](./patterns.md) - RAG with Vectorize, prompt engineering, batching, error handling, caching
- [gotchas.md](./gotchas.md) - Deprecated @cloudflare/ai package, rate limits, pricing, common errors

## See Also

- [vectorize](../vectorize/) - Vector database for RAG patterns
- [ai-gateway](../ai-gateway/) - Caching, rate limiting, analytics for AI requests
- [workers](../workers/) - Worker runtime and fetch handler patterns

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/workers-for-platforms/README.md`)

# Cloudflare Workers for Platforms

Multi-tenant platform with isolated customer code execution at scale.

## Use Cases

- Multi-tenant SaaS running customer code
- AI-generated code execution in secure sandboxes
- Programmable platforms with isolated compute
- Edge functions/serverless platforms
- Website builders with static + dynamic content
- Unlimited app deployment at scale

**NOT for general Workers** - only for Workers for Platforms architecture.

## Quick Start

**One-click deploy:** [Platform Starter Kit](https://github.com/cloudflare/workers-for-platforms-example) deploys complete WfP setup with dispatch namespace, dispatch worker, and user worker example.

[](https://deploy.workers.cloudflare.com/?url=https://github.com/cloudflare/workers-for-platforms-example)

**Manual setup:** See [configuration.md](./configuration.md) for namespace creation and dispatch worker configuration.

## Key Features

- Unlimited Workers per namespace (no script limits)
- Automatic tenant isolation
- Custom CPU/subrequest limits per customer
- Hostname routing (subdomains/vanity domains)
- Egress/ingress control
- Static assets support
- Tags for bulk operations

## Architecture

**4 Components:**
1. **Dispatch Namespace** - Container for unlimited customer Workers, automatic isolation (untrusted mode by default - no request.cf access, no shared cache)
2. **Dynamic Dispatch Worker** - Entry point, routes requests, enforces platform logic (auth, limits, validation)
3. **User Workers** - Customer code in isolated sandboxes, API-deployed, optional bindings (KV/D1/R2/DO)
4. **Outbound Worker** (optional) - Intercepts external fetch, controls egress, logs subrequests (blocks TCP socket connect() API)

**Request Flow:**
```
Request → Dispatch Worker → Determines user Worker → env.DISPATCHER.get("customer") 
→ User Worker executes (Outbound Worker for external fetch) → Response → Dispatch Worker → Client
```

## Decision Trees

### When to Use Workers for Platforms
```
Need to run code?
├─ Your code only → Regular Workers
├─ Customer/AI code → Workers for Platforms
└─ Untrusted code in sandbox → Workers for Platforms OR Sandbox API
```

### Routing Strategy Selection
```
Hostname routing needed?
├─ Subdomains only (*.saas.com) → `*.saas.com/*` route + subdomain extraction
├─ Custom domains → `*/*` wildcard + Cloudflare for SaaS + KV/metadata routing
└─ Path-based (/customer/app) → Any route + path parsing
```

### Isolation Mode Selection
```
Worker mode?
├─ Running customer code → Untrusted (default)
├─ Need request.cf geolocation → Trusted mode
├─ Internal platform, controlled code → Trusted mode with cache key prefixes
└─ Maximum isolation → Untrusted + unique resources per customer
```

## In This Reference

| File | Purpose | When to Read |
|------|---------|--------------|
| [configuration.md](./configuration.md) | Namespace setup, dispatch worker config | First-time setup, changing limits |
| [api.md](./api.md) | User worker API, dispatch API, outbound worker | Deploying workers, SDK integration |
| [patterns.md](./patterns.md) | Multi-tenancy, routing, egress control | Planning architecture, scaling |
| [gotchas.md](./gotchas.md) | Limits, isolation issues, best practices | Debugging, production prep |

## See Also
- [workers](../workers/) - Core Workers runtime documentation
- [durable-objects](../durable-objects/) - Stateful multi-tenant patterns
- [sandbox](../sandbox/) - Alternative for untrusted code execution
- [Reference Architecture: Programmable Platforms](https://developers.cloudflare.com/reference-architecture/diagrams/serverless/programmable-platforms/)
- [Reference Architecture: AI Vibe Coding Platform](https://developers.cloudflare.com/reference-architecture/diagrams/ai/ai-vibe-coding-platform/)

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/workers-playground/README.md`)

# Cloudflare Workers Playground Skill Reference

## Overview

Cloudflare Workers Playground is a browser-based sandbox for instantly experimenting with, testing, and deploying Cloudflare Workers without authentication or setup. This skill provides patterns, APIs, and best practices specifically for Workers Playground development.

**URL:** [workers.cloudflare.com/playground](https://workers.cloudflare.com/playground)

## ⚠️ Playground Constraints

**Playground is NOT production-equivalent:**
- ✅ Real Workers runtime, instant testing, shareable URLs
- ❌ No TypeScript (JavaScript only)
- ❌ No bindings (KV, D1, R2, Durable Objects)
- ❌ No environment variables or secrets
- ❌ ES modules only (no Service Worker format)
- ⚠️ Safari broken (use Chrome/Firefox)

**For production:** Use `wrangler` CLI. Playground is for rapid prototyping.

## Quick Start

Minimal Worker:

```javascript
export default {
  async fetch(request, env, ctx) {
    return new Response('Hello World');
  }
};
```

JSON API:

```javascript
export default {
  async fetch(request, env, ctx) {
    const data = { message: 'Hello', timestamp: Date.now() };
    return Response.json(data);
  }
};
```

Proxy with modification:

```javascript
export default {
  async fetch(request, env, ctx) {
    const response = await fetch('https://example.com');
    const modified = new Response(response.body, response);
    modified.headers.set('X-Custom-Header', 'added-by-worker');
    return modified;
  }
};
```

Import from CDN:

```javascript
import { Hono } from 'https://esm.sh/hono@3';

export default {
  async fetch(request) {
    const app = new Hono();
    app.get('/', (c) => c.text('Hello Hono!'));
    return app.fetch(request);
  }
};
```

## Reading Order

1. **[configuration.md](configuration.md)** - Start here: playground setup, constraints, deployment
2. **[api.md](api.md)** - Core APIs: Request, Response, ExecutionContext, fetch, Cache
3. **[patterns.md](patterns.md)** - Common use cases: routing, proxying, A/B testing, multi-module code
4. **[gotchas.md](gotchas.md)** - Troubleshooting: errors, browser issues, limits, best practices

## In This Reference

- **[configuration.md](configuration.md)** - Setup, deployment, configuration
- **[api.md](api.md)** - API endpoints, methods, interfaces
- **[patterns.md](patterns.md)** - Common patterns, use cases, examples
- **[gotchas.md](gotchas.md)** - Troubleshooting, best practices, limitations

## Key Features

**No Setup Required:**
- Open URL and start coding
- No CLI, no account, no config files
- Code executes in real Cloudflare Workers runtime

**Instant Preview:**
- Live preview pane with browser tab or HTTP tester
- Auto-reload on code changes
- DevTools integration (right-click → Inspect)

**Share & Deploy:**
- Copy Link generates permanent shareable URL
- Deploy button publishes to production in ~30 seconds
- Get `*.workers.dev` subdomain immediately

## Common Use Cases

- **API development:** Test endpoints before wrangler setup
- **Learning Workers:** Experiment with APIs without local environment
- **Prototyping:** Quick POCs for edge logic
- **Sharing examples:** Generate shareable links for bug reports or demos
- **Framework testing:** Import from CDN (Hono, itty-router, etc.)

## Limitations vs Production

| Feature | Playground | Production (wrangler) |
|---------|------------|----------------------|
| Language | JavaScript only | JS + TypeScript |
| Bindings | None | KV, D1, R2, DO, AI, etc. |
| Environment vars | None | Full support |
| Module format | ES only | ES + Service Worker |
| CPU time | 10ms (Free plan) | 10ms Free / 50ms Paid |
| Custom domains | No | Yes |
| Analytics | No | Yes |

## See Also

- [Cloudflare Workers Docs](https://developers.cloudflare.com/workers/)
- [Workers Examples](https://developers.cloudflare.com/workers/examples/)
- [Wrangler CLI](https://developers.cloudflare.com/workers/wrangler/)
- [Workers API Reference](https://developers.cloudflare.com/workers/runtime-apis/)

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/workers-vpc/README.md`)

# Workers VPC Connectivity

Connect Cloudflare Workers to private networks and internal infrastructure using TCP Sockets.

## Overview

Workers VPC connectivity enables outbound TCP connections from Workers to private resources in AWS, Azure, GCP, on-premises datacenters, or any private network. This is achieved through the **TCP Sockets API** (`cloudflare:sockets`), which provides low-level network access for custom protocols and services.

**Key capabilities:**
- Direct TCP connections to private IPs and hostnames
- TLS/StartTLS support for encrypted connections
- Integration with Cloudflare Tunnel for secure private network access
- Full control over wire protocols (database protocols, SSH, MQTT, custom TCP)

**Note:** This reference documents the TCP Sockets API. For the newer Workers VPC Services product (HTTP-only service bindings with built-in SSRF protection), refer to separate documentation when available. VPC Services is currently in beta (2025+).

## Quick Decision: Which Technology?

Need private network connectivity from Workers?

| Requirement | Use | Why |
|------------|-----|-----|
| HTTP/HTTPS APIs in private network | VPC Services (beta, separate docs) | SSRF-safe, declarative bindings |
| PostgreSQL/MySQL databases | [Hyperdrive](../hyperdrive/) | Connection pooling, caching, optimized |
| Custom TCP protocols (SSH, MQTT, proprietary) | **TCP Sockets (this doc)** | Full protocol control |
| Simple HTTP with lowest latency | TCP Sockets + [Smart Placement](../smart-placement/) | Manual optimization |
| Expose on-prem to internet (inbound) | [Cloudflare Tunnel](../tunnel/) | Not Worker-specific |

## When to Use TCP Sockets

**Use TCP Sockets when you need:**
- ✅ Direct control over wire protocols (e.g., Postgres wire protocol, SSH, Redis RESP)
- ✅ Non-HTTP protocols (MQTT, SMTP, custom binary protocols)
- ✅ StartTLS or custom TLS negotiation
- ✅ Streaming binary data over TCP

**Don't use TCP Sockets when:**
- ❌ You just need HTTP/HTTPS (use `fetch()` or VPC Services)
- ❌ You need PostgreSQL/MySQL (use Hyperdrive for pooling)
- ❌ You need WebSocket (use native Workers WebSocket)

## Quick Start

```typescript
import { connect } from 'cloudflare:sockets';

export default {
  async fetch(req: Request): Promise<Response> {
    // Connect to private service
    const socket = connect(
      { hostname: "db.internal.company.net", port: 5432 },
      { secureTransport: "on" }
    );

    try {
      await socket.opened; // Wait for connection
      
      const writer = socket.writable.getWriter();
      await writer.write(new TextEncoder().encode("QUERY\r\n"));
      await writer.close();

      const reader = socket.readable.getReader();
      const { value } = await reader.read();
      
      return new Response(value);
    } finally {
      await socket.close();
    }
  }
};
```

## Architecture Pattern: Workers + Tunnel

Most private network connectivity combines TCP Sockets with Cloudflare Tunnel:

```
┌─────────┐     ┌─────────────┐     ┌──────────────┐     ┌─────────────┐
│ Worker  │────▶│ TCP Socket  │────▶│   Tunnel     │────▶│   Private   │
│         │     │ (this API)  │     │ (cloudflared)│     │   Network   │
└─────────┘     └─────────────┘     └──────────────┘     └─────────────┘
```

1. Worker opens TCP socket to Tunnel hostname
2. Tunnel endpoint routes to private IP
3. Response flows back through Tunnel to Worker

See [configuration.md](./configuration.md) for Tunnel setup details.

## Reading Order

1. **Start here (README.md)** - Overview and decision guide
2. **[api.md](./api.md)** - Socket interface, types, methods
3. **[configuration.md](./configuration.md)** - Wrangler setup, Tunnel integration
4. **[patterns.md](./patterns.md)** - Real-world examples (databases, protocols, error handling)
5. **[gotchas.md](./gotchas.md)** - Limits, blocked ports, common errors

## Key Limits

| Limit | Value |
|-------|-------|
| Max concurrent sockets per request | 6 |
| Blocked destinations | Cloudflare IPs, localhost, port 25 |
| Scope requirement | Must create in handler (not global) |

See [gotchas.md](./gotchas.md) for complete limits and troubleshooting.

## Best Practices

1. **Always close sockets** - Use try/finally blocks
2. **Validate destinations** - Prevent SSRF by allowlisting hosts
3. **Use Hyperdrive for databases** - Better performance than raw TCP
4. **Prefer fetch() for HTTP** - Only use TCP when necessary
5. **Combine with Smart Placement** - Reduce latency to private networks

## Related Technologies

- **[Hyperdrive](../hyperdrive/)** - PostgreSQL/MySQL with connection pooling
- **[Cloudflare Tunnel](../tunnel/)** - Secure private network access
- **[Smart Placement](../smart-placement/)** - Auto-locate Workers near backends
- **VPC Services (beta)** - HTTP-only service bindings with SSRF protection (separate docs)

## Reference

- [TCP Sockets API Documentation](https://developers.cloudflare.com/workers/runtime-apis/tcp-sockets/)
- [Connect to databases guide](https://developers.cloudflare.com/workers/tutorials/connect-to-postgres/)
- [Cloudflare Tunnel setup](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/)

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/workers/README.md`)

# Cloudflare Workers

Expert guidance for building, deploying, and optimizing Cloudflare Workers applications.

## Overview

Cloudflare Workers run on V8 isolates (NOT containers/VMs):
- Extremely fast cold starts (< 1ms)
- Global deployment across 300+ locations
- Web standards compliant (fetch, URL, Headers, Request, Response)
- Support JS/TS, Python, Rust, and WebAssembly

**Key principle**: Workers use web platform APIs wherever possible for portability.

## Module Worker Pattern (Recommended)

```typescript
export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
    return new Response('Hello World!');
  },
};
```

**Handler parameters**:
- `request`: Incoming HTTP request (standard Request object)
- `env`: Environment bindings (KV, D1, R2, secrets, vars)
- `ctx`: Execution context (`waitUntil`, `passThroughOnException`)

## Essential Commands

```bash
npx wrangler dev                    # Local dev
npx wrangler dev --remote           # Remote dev (actual resources)
npx wrangler deploy                 # Production
npx wrangler deploy --env staging   # Specific environment
npx wrangler tail                   # Stream logs
npx wrangler secret put API_KEY     # Set secret
```

## When to Use Workers

- API endpoints at the edge
- Request/response transformation
- Authentication/authorization layers
- Static asset optimization
- A/B testing and feature flags
- Rate limiting and security
- Proxy/routing logic
- WebSocket applications

## Quick Start

```bash
npm create cloudflare@latest my-worker -- --type hello-world
cd my-worker
npx wrangler dev
```

## Handler Signatures

```typescript
// HTTP requests
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response>

// Cron triggers
async scheduled(event: ScheduledEvent, env: Env, ctx: ExecutionContext): Promise<void>

// Queue consumer
async queue(batch: MessageBatch, env: Env, ctx: ExecutionContext): Promise<void>

// Tail consumer
async tail(events: TraceItem[], env: Env, ctx: ExecutionContext): Promise<void>
```

## Resources

**Docs**: https://developers.cloudflare.com/workers/  
**Examples**: https://developers.cloudflare.com/workers/examples/  
**Runtime APIs**: https://developers.cloudflare.com/workers/runtime-apis/

## In This Reference

- [Configuration](./configuration.md) - wrangler.jsonc setup, bindings, environments
- [API](./api.md) - Runtime APIs, bindings, execution context
- [Patterns](./patterns.md) - Common workflows, testing, optimization
- [Frameworks](./frameworks.md) - Hono, routing, validation
- [Gotchas](./gotchas.md) - Common issues, limits, troubleshooting

## Reading Order

| Task | Start With | Then Read |
|------|------------|-----------|
| First Worker | README → Configuration → API | Patterns |
| Add framework | Frameworks | Configuration (bindings) |
| Add storage/bindings | Configuration → API (binding usage) | See Also links |
| Debug issues | Gotchas | API (specific binding docs) |
| Production optimization | Patterns | API (caching, streaming) |
| Type safety | Configuration (TypeScript) | Frameworks (Hono typing) |

## See Also

- [KV](../kv/README.md) - Key-value storage
- [D1](../d1/README.md) - SQL database
- [R2](../r2/README.md) - Object storage
- [Durable Objects](../durable-objects/README.md) - Stateful coordination
- [Queues](../queues/README.md) - Message queues
- [Wrangler](../wrangler/README.md) - CLI tool reference

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/workflows/README.md`)

# Cloudflare Workflows

Durable multi-step applications with automatic retries, state persistence, and long-running execution.

## What It Does

- Chain steps with automatic retry logic
- Persist state between steps (minutes → weeks)
- Handle failures without losing progress
- Wait for external events/approvals
- Sleep without consuming resources

**Available:** Free & Paid Workers plans

## Core Concepts

**Workflow**: Class extending `WorkflowEntrypoint` with `run` method
**Instance**: Single execution with unique ID & independent state
**Steps**: Independently retriable units via `step.do()` - API calls, DB queries, AI invocations
**State**: Persisted from step returns; step name = cache key

## Quick Start

```typescript
import { WorkflowEntrypoint, WorkflowStep, WorkflowEvent } from 'cloudflare:workers';

type Env = { MY_WORKFLOW: Workflow; DB: D1Database };
type Params = { userId: string };

export class MyWorkflow extends WorkflowEntrypoint<Env, Params> {
  async run(event: WorkflowEvent<Params>, step: WorkflowStep) {
    const user = await step.do('fetch user', async () => {
      return await this.env.DB.prepare('SELECT * FROM users WHERE id = ?')
        .bind(event.params.userId).first();
    });
    
    await step.sleep('wait 7 days', '7 days');
    
    await step.do('send reminder', async () => {
      await sendEmail(user.email, 'Reminder!');
    });
  }
}
```

## Key Features

- **Durability**: Failed steps don't re-run successful ones
- **Retries**: Configurable backoff (constant/linear/exponential)
- **Events**: `waitForEvent()` for webhooks/approvals (timeout: 1h → 365d)
- **Sleep**: `sleep()` / `sleepUntil()` for scheduling (max 365d)
- **Parallel**: `Promise.all()` for concurrent steps
- **Idempotency**: Check-then-execute patterns

## Reading Order

**Getting Started:** configuration.md → api.md → patterns.md  
**Troubleshooting:** gotchas.md

## In This Reference
- [configuration.md](./configuration.md) - wrangler.jsonc setup, step config, bindings
- [api.md](./api.md) - Step APIs, instance management, sleep/parameters
- [patterns.md](./patterns.md) - Common workflows, testing, orchestration
- [gotchas.md](./gotchas.md) - Timeouts, limits, debugging strategies

## See Also
- [durable-objects](../durable-objects/) - Alternative stateful approach
- [queues](../queues/) - Message-driven workflows
- [workers](../workers/) - Entry point for workflow instances

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/wrangler/README.md`)

# Cloudflare Wrangler

Official CLI for Cloudflare Workers - develop, manage, and deploy Workers from the command line.

## What is Wrangler?

Wrangler is the Cloudflare Developer Platform CLI that allows you to:
- Create, develop, and deploy Workers
- Manage bindings (KV, D1, R2, Durable Objects, etc.)
- Configure routing and environments
- Run local development servers
- Execute migrations and manage resources
- Perform integration testing

## Installation

```bash
npm install wrangler --save-dev
# or globally
npm install wrangler
```

Run commands: `npx wrangler <command>` (or `pnpm`/`yarn wrangler`)

## Reading Order

| If you want to... | Start here |
|-------------------|------------|
| Create/deploy Worker quickly | Essential Commands below → [patterns.md](./patterns.md) §New Worker |
| Configure bindings (KV, D1, R2) | [configuration.md](./configuration.md) §Bindings |
| Write integration tests | [api.md](./api.md) §startWorker |
| Debug production issues | [gotchas.md](./gotchas.md) + Essential Commands §Monitoring |
| Set up multi-environment workflow | [configuration.md](./configuration.md) §Environments |

## Essential Commands

### Project & Development
```bash
wrangler init [name]              # Create new project
wrangler dev                      # Local dev server (fast, simulated)
wrangler dev --remote             # Dev with remote resources (production-like)
wrangler deploy                   # Deploy to production
wrangler deploy --env staging     # Deploy to environment
wrangler versions list            # List versions
wrangler rollback [id]            # Rollback deployment
wrangler login                    # OAuth login
wrangler whoami                   # Check auth status
```

## Resource Management

### KV
```bash
wrangler kv namespace create NAME
wrangler kv key put "key" "value" --namespace-id=<id>
wrangler kv key get "key" --namespace-id=<id>
```

### D1
```bash
wrangler d1 create NAME
wrangler d1 execute NAME --command "SQL"
wrangler d1 migrations create NAME "description"
wrangler d1 migrations apply NAME
```

### R2
```bash
wrangler r2 bucket create NAME
wrangler r2 object put BUCKET/key --file path
wrangler r2 object get BUCKET/key
```

### Other Resources
```bash
wrangler queues create NAME
wrangler vectorize create NAME --dimensions N --metric cosine
wrangler hyperdrive create NAME --connection-string "..."
wrangler workflows create NAME
wrangler constellation create NAME
wrangler pages project create NAME
wrangler pages deployment create --project NAME --branch main
```

### Secrets
```bash
wrangler secret put NAME          # Set Worker secret
wrangler secret list              # List Worker secrets
wrangler secret delete NAME       # Delete Worker secret
wrangler secret bulk FILE.json    # Bulk upload from JSON

# Secrets Store (centralized, reusable across Workers)
wrangler secret-store:secret put STORE_NAME SECRET_NAME
wrangler secret-store:secret list STORE_NAME
```

### Monitoring
```bash
wrangler tail                     # Real-time logs
wrangler tail --env production    # Tail specific env
wrangler tail --status error      # Filter by status
```

## In This Reference

- [auth.md](./auth.md) - Authentication setup (`wrangler login`, API tokens)
- [configuration.md](./configuration.md) - wrangler.jsonc setup, environments, bindings
- [api.md](./api.md) - Programmatic API (`startWorker`, `getPlatformProxy`, events)
- [patterns.md](./patterns.md) - Common workflows and development patterns
- [gotchas.md](./gotchas.md) - Common pitfalls, limits, and troubleshooting

## Quick Decision Tree

```
Need to test your Worker?
├─ Testing full Worker with bindings → api.md §startWorker
├─ Testing individual functions → api.md §getPlatformProxy
└─ Testing with Vitest → patterns.md §Testing with Vitest

Need to configure something?
├─ Bindings (KV, D1, R2, etc.) → configuration.md §Bindings
├─ Multiple environments → configuration.md §Environments
├─ Static files → configuration.md §Workers Assets
└─ Routing → configuration.md §Routing

Development not working?
├─ Local differs from production → Use `wrangler dev --remote`
├─ Bindings not available → gotchas.md §Binding Not Available
└─ Auth issues → auth.md

Authentication issues?
├─ "Not logged in" / "Unauthorized" → auth.md
├─ First time deploying → `wrangler login` (one-time OAuth)
└─ CI/CD setup → auth.md §API Token
```

## See Also

- [workers](../workers/) - Workers runtime API reference
- [miniflare](../miniflare/) - Local testing with Miniflare
- [workerd](../workerd/) - Runtime that powers `wrangler dev`

---

### Overview (`packages/autoskills/skills-registry/cloudflare-deploy/references/zaraz/README.md`)

# Cloudflare Zaraz

Expert guidance for Cloudflare Zaraz - server-side tag manager for loading third-party tools at the edge.

## What is Zaraz?

Zaraz offloads third-party scripts (analytics, ads, chat, marketing) to Cloudflare's edge, improving site speed, privacy, and security. Zero client-side performance impact.

**Core Concepts:**
- **Server-side execution** - Scripts run on Cloudflare, not user's browser
- **Single HTTP request** - All tools loaded via one endpoint
- **Privacy-first** - Control data sent to third parties
- **No client-side JS overhead** - Minimal browser impact

## Quick Start

1. Navigate to domain > Zaraz in Cloudflare dashboard
2. Click "Start setup"
3. Add tools (Google Analytics, Facebook Pixel, etc.)
4. Configure triggers (when tools fire)
5. Add tracking code to your site:

```javascript
// Track page view
zaraz.track('page_view');

// Track custom event
zaraz.track('button_click', { button_id: 'cta' });

// Set user properties
zaraz.set('userId', 'user_123');
```

## When to Use Zaraz

**Use Zaraz when:**
- Adding multiple third-party tools (analytics, ads, marketing)
- Site performance is critical (no client-side JS overhead)
- Privacy compliance required (GDPR, CCPA)
- Non-technical teams need to manage tools

**Use Workers directly when:**
- Building custom server-side tracking logic
- Need full control over data processing
- Integrating with complex backend systems
- Zaraz's tool library doesn't meet needs

## In This Reference

| File | Purpose | When to Read |
|------|---------|--------------|
| [api.md](./api.md) | Web API, zaraz object, consent methods | Implementing tracking calls |
| [configuration.md](./configuration.md) | Dashboard setup, triggers, tools | Initial setup, adding tools |
| [patterns.md](./patterns.md) | SPA, e-commerce, Worker integration | Best practices, common scenarios |
| [gotchas.md](./gotchas.md) | Troubleshooting, limits, pitfalls | Debugging issues |

## Reading Order by Task

| Task | Files to Read |
|------|---------------|
| Add analytics to site | README → configuration.md |
| Track custom events | README → api.md |
| Debug tracking issues | gotchas.md |
| SPA tracking | api.md → patterns.md (SPA section) |
| E-commerce tracking | api.md#ecommerce → patterns.md#ecommerce |
| Worker integration | patterns.md#worker-integration |
| GDPR compliance | api.md#consent → configuration.md#consent |

## Decision Tree

```
What do you need?

├─ Track events in browser → api.md
│   ├─ Page views, clicks → zaraz.track()
│   ├─ User properties → zaraz.set()
│   └─ E-commerce → zaraz.ecommerce()
│
├─ Configure Zaraz → configuration.md
│   ├─ Add GA4/Facebook → tools setup
│   ├─ When tools fire → triggers
│   └─ GDPR consent → consent purposes
│
├─ Integrate with Workers → patterns.md#worker-integration
│   ├─ Enrich context → Context Enrichers
│   └─ Inject tracking → HTML rewriting
│
└─ Debug issues → gotchas.md
    ├─ Events not firing → troubleshooting
    ├─ Consent issues → consent debugging
    └─ Performance → debugging tools
```

## Key Features

- **100+ Pre-built Tools** - GA4, Facebook, Google Ads, TikTok, etc.
- **Zero Client Impact** - Runs at Cloudflare's edge, not browser
- **Privacy Controls** - Consent management, data filtering
- **Custom Tools** - Build Managed Components for proprietary systems
- **Worker Integration** - Enrich context, compute dynamic values
- **Debug Mode** - Real-time event inspection

## Reference

- [Zaraz Docs](https://developers.cloudflare.com/zaraz/)
- [Web API](https://developers.cloudflare.com/zaraz/web-api/)
- [Managed Components](https://developers.cloudflare.com/zaraz/advanced/load-custom-managed-component/)

---

This skill focuses exclusively on Zaraz. For Workers development, see `cloudflare-workers` skill.

---

### Overview (`packages/autoskills/skills-registry/cloudflare/references/ai-gateway/README.md`)

# Cloudflare AI Gateway

Use AI Gateway to observe and control requests to AI providers through caching, rate limiting, logging, and routing.

Fetch the linked documentation before choosing endpoints, authentication headers, SDK options, model names, or limits. Keep implementation details in the current docs.

## Choose a task

| Task | Reference |
|------|-----------|
| Create a gateway or choose authentication and provider credentials | [Configuration](./configuration.md) |
| Integrate an SDK, direct HTTP, or a Worker binding | [SDK integration](./sdk-integration.md) |
| Configure caching, rate limits, security, billing, or logging | [Features](./features.md) |
| Add fallbacks, conditional routing, or traffic splits | [Dynamic routing](./dynamic-routing.md) |
| Diagnose failed requests, caching, or missing logs | [Troubleshooting](./troubleshooting.md) |

For new single-model calls, start with the [REST API](https://developers.cloudflare.com/ai-gateway/usage/rest-api/index.md) or [Workers bindings](https://developers.cloudflare.com/ai-gateway/usage/worker-binding-methods/index.md), depending on the runtime. Preserve provider-native integrations when their API shape is needed; use the corresponding [provider guide](https://developers.cloudflare.com/ai-gateway/usage/providers/index.md).

The [legacy Unified API](https://developers.cloudflare.com/ai-gateway/usage/chat-completion/index.md) is deprecated for single-model calls but remains required for dynamic routes. Check the task before changing an existing endpoint.

Gateway authentication and upstream provider credentials are separate concerns. Choose the endpoint first, then follow its authentication and billing requirements in [configuration](./configuration.md).

## Related references

- [Workers AI](../workers-ai/README.md) — model inference.
- [Agents SDK documentation](https://developers.cloudflare.com/agents/index.md) — stateful agents.
- [Vectorize](../vectorize/README.md) — vector search.

---

### Overview (`packages/autoskills/skills-registry/cloudflare/references/ai-search/README.md`)

# Cloudflare AI Search

Use AI Search for managed content indexing and retrieval, with optional answer generation. Start with [How AI Search works](https://developers.cloudflare.com/ai-search/concepts/how-ai-search-works/index.md).

## Choose the right product

- **Managed search or RAG over your content:** AI Search.
- **Custom embeddings and vector-index management:** [Vectorize](../vectorize/README.md).
- **Model inference without a managed retrieval pipeline:** [Workers AI](../workers-ai/README.md).

For freshness requirements, read [Syncing](https://developers.cloudflare.com/ai-search/configuration/indexing/syncing/index.md) for your data source before choosing an architecture. Use the current [limits and pricing](https://developers.cloudflare.com/ai-search/platform/limits-pricing/index.md) instead of assuming a fixed indexing interval or account limit.

## Find the right documentation

Read the linked page before implementing; these references route to the maintained documentation instead of copying API examples or configuration.

| Task | Start here |
|------|------------|
| Build a new Worker integration | [Workers binding quick start](https://developers.cloudflare.com/ai-search/get-started/workers/index.md) |
| Choose an API or maintain an existing integration | [API routes](api.md) |
| Connect data, configure indexing, or manage environments | [Configuration routes](configuration.md) |
| Choose retrieval, generation, or tenant isolation patterns | [Pattern routes](patterns.md) |
| Diagnose indexing, authentication, filters, or limits | [Troubleshooting routes](gotchas.md) |

Existing `env.AI.autorag()` integrations can continue to work. Use the [migration guide](https://developers.cloudflare.com/ai-search/api/migration/workers-binding/index.md) when upgrading; migration is not required just to maintain an existing integration.

---

### Overview (`packages/autoskills/skills-registry/cloudflare/references/analytics-engine/README.md`)

# Cloudflare Workers Analytics Engine Reference

Expert guidance for implementing unlimited-cardinality analytics at scale using Cloudflare Workers Analytics Engine.

## What is Analytics Engine?

Time-series analytics database designed for high-cardinality data (millions of unique dimensions). Write data points from Workers, query via SQL API. Use for:
- Custom user-facing analytics dashboards
- Usage-based billing & metering
- Per-customer/per-feature monitoring
- High-frequency instrumentation without performance impact

**Key Capability:** Track metrics with unlimited unique values (e.g., millions of user IDs, API keys) without performance degradation.

## Core Concepts

| Concept | Description | Example |
|---------|-------------|---------|
| **Dataset** | Logical table for related metrics | `api_requests`, `user_events` |
| **Data Point** | Single measurement with timestamp | One API request's metrics |
| **Blobs** | String dimensions (max 20) | endpoint, method, status, user_id |
| **Doubles** | Numeric values (max 20) | latency_ms, request_count, bytes |
| **Indexes** | Filtered blobs for efficient queries | customer_id, api_key |

## Reading Order

| Task | Start Here | Then Read |
|------|------------|-----------|
| **First-time setup** | [configuration.md](configuration.md) → [api.md](api.md) → [patterns.md](patterns.md) | |
| **Writing data** | [api.md](api.md) → [gotchas.md](gotchas.md) (sampling) | |
| **Querying data** | [api.md](api.md) (SQL API) → [patterns.md](patterns.md) (examples) | |
| **Debugging** | [gotchas.md](gotchas.md) → [api.md](api.md) (limits) | |
| **Optimization** | [patterns.md](patterns.md) (anti-patterns) → [gotchas.md](gotchas.md) | |

## When to Use Analytics Engine

```
Need to track metrics? → Yes
  ↓
Millions of unique dimension values? → Yes
    ↓
  Need real-time queries? → Yes
      ↓
    Use Analytics Engine ✓

Alternative scenarios:
- Low cardinality (<10k unique values) → Workers Analytics (free tier)
- Complex joins/relations → D1 Database
- Logs/debugging → Tail Workers (logpush)
- External tools → Send to external analytics (Datadog, etc.)
```

## Quick Start

1. Add binding to `wrangler.jsonc`:
```jsonc
{
  "analytics_engine_datasets": [
    { "binding": "ANALYTICS", "dataset": "my_events" }
  ]
}
```

2. Write data points (fire-and-forget, no await):
```typescript
env.ANALYTICS.writeDataPoint({
  blobs: ["/api/users", "GET", "200"],
  doubles: [145.2, 1],  // latency_ms, count
  indexes: [customerId]
});
```

3. Query via SQL API (HTTP):
```sql
SELECT blob1, SUM(double2) AS total_requests
FROM my_events
WHERE index1 = 'customer_123'
  AND timestamp >= NOW() - INTERVAL '7' DAY
GROUP BY blob1
ORDER BY total_requests DESC
```

## In This Reference

- **[configuration.md](configuration.md)** - Setup, bindings, TypeScript types, limits
- **[api.md](api.md)** - `writeDataPoint()`, SQL API, query syntax
- **[patterns.md](patterns.md)** - Use cases, examples, anti-patterns
- **[gotchas.md](gotchas.md)** - Sampling, index selection, troubleshooting

## See Also

- [Cloudflare Analytics Engine Docs](https://developers.cloudflare.com/analytics/analytics-engine/index.md)
- [GraphQL Analytics API Reference](../graphql-api/) - Query built-in Cloudflare analytics (HTTP, Workers, DNS, Firewall, etc.)
- [Observability Reference](../observability/) - Workers Logs, Traces, and real-time debugging

---

### Overview (`packages/autoskills/skills-registry/cloudflare/references/bindings/README.md`)

# Cloudflare Workers Bindings

Bindings grant a Worker access to configured resources through its environment. Prefer a product's binding for supported operations inside Workers; use the REST API when the caller or operation requires it.

Read the relevant current documentation before implementing. These references route to maintained APIs and configuration rather than copying binding catalogs, type tables, or limits.

## Start here

- [Bindings overview and catalog](https://developers.cloudflare.com/workers/runtime-apis/bindings/index.md): capability model, available products, environment access, and binding lifecycle.
- [Storage options](https://developers.cloudflare.com/workers/platform/storage-options/index.md): choose storage from consistency, query, and coordination requirements.
- [api.md](./api.md): environment access, generated types, and product APIs.
- [configuration.md](./configuration.md): binding configuration, environments, secrets, and local development.
- [patterns.md](./patterns.md): Worker-to-Worker calls, testing, and resource selection.
- [gotchas.md](./gotchas.md): missing bindings, stale clients, development differences, and limits.

Treat each binding as a capability granted to code. Select only the resources the Worker needs, and confirm which environment and resource each binding targets before using it.

---

### Overview (`packages/autoskills/skills-registry/cloudflare/references/browser-rendering/README.md`)

# Browser Run (formerly Browser Rendering)

Use Browser Run for screenshots, PDFs, rendered content extraction, and browser automation. Read the relevant current documentation before implementing; use the [documentation index](https://developers.cloudflare.com/browser-run/llms.txt) to discover additional guides.

Choose the integration by the work and runtime:

- For a self-contained screenshot, PDF, or extraction, start with Quick Actions. They are available through REST and Workers bindings; check the chosen action's supported interface.
- For multi-step interactions or persistent state, use browser sessions. In Workers, use Cloudflare's Puppeteer or Playwright package; from external scripts or CI, use the CDP integration.
- When adapting existing automation, preserve its library where supported and check installed versions against the corresponding guide.

Read only the reference needed for the task:

| Task | Reference |
|------|-----------|
| Set up bindings, dependencies, or development | [configuration.md](configuration.md) |
| Select an endpoint or browser client API | [api.md](api.md) |
| Implement a workflow or manage reusable sessions | [patterns.md](patterns.md) |
| Diagnose failures or plan capacity and cost | [gotchas.md](gotchas.md) |

---

### Overview (`packages/autoskills/skills-registry/cloudflare/references/c3/README.md`)

# C3 (create-cloudflare)

Official CLI for scaffolding Cloudflare Workers and Pages projects with templates, TypeScript, and instant deployment.

## Quick Start

```bash
# Interactive (recommended for first-time)
npm create cloudflare@latest my-app

# Worker (API/WebSocket/Cron)
npm create cloudflare@latest my-api -- --type=hello-world --ts

# Pages (static/SSG)
npm create cloudflare@latest my-site -- --type=web-app --framework=astro --platform=pages
```

## Platform Decision Tree

```
What are you building?

├─ API / WebSocket / Cron / Email handler
│   └─ Workers (default) - no --platform flag needed
│       npm create cloudflare@latest my-api -- --type=hello-world

├─ Static site / SSG / Documentation
│   └─ Pages - requires --platform=pages
│       npm create cloudflare@latest my-site -- --type=web-app --framework=astro --platform=pages

├─ Full-stack app (Next.js/Remix/SvelteKit)
│   └─ Follow the current framework guide below

└─ Convert existing project
    └─ npm create cloudflare@latest . -- --type=pre-existing --existing-script=./src/worker.ts
```

**Critical:** Pages projects require `--platform=pages` flag. Without it, C3 defaults to Workers.

## Framework Setup

Fetch the [Workers framework guide](https://developers.cloudflare.com/workers/framework-guides/index.md) for the chosen framework before scaffolding or adapting an existing app. For Next.js, follow [Next.js on Workers](https://developers.cloudflare.com/workers/framework-guides/web-apps/nextjs/index.md); use the [Pages static export guide](https://developers.cloudflare.com/pages/framework-guides/nextjs/deploy-a-static-nextjs-site/index.md) only when targeting a Next.js static export on Pages.

## Interactive Flow

When run without flags, C3 prompts in this order:

1. **Project name** - Directory to create (defaults to current dir with `.`)
2. **Application type** - `hello-world`, `web-app`, `demo`, `pre-existing`, `remote-template`
3. **Platform** - `workers` (default) or `pages` (for web apps only)
4. **Framework** - If web-app: `next`, `remix`, `astro`, `react-router`, `solid`, `svelte`, etc.
5. **TypeScript** - `yes` (recommended) or `no`
6. **Git** - Initialize repository? `yes` or `no`
7. **Deploy** - Deploy now? `yes` or `no` (requires `wrangler login`)

## Installation Methods

```bash
# NPM
npm create cloudflare@latest

# Yarn
yarn create cloudflare

# PNPM
pnpm create cloudflare@latest
```

## In This Reference

| File | Purpose | Use When |
|------|---------|----------|
| **api.md** | Complete CLI flag reference | Scripting, CI/CD, advanced usage |
| **configuration.md** | Generated files, bindings, types | Understanding output, customization |
| **patterns.md** | Workflows, CI/CD, monorepos | Real-world integration |
| **gotchas.md** | Troubleshooting failures | Deployment blocked, errors |

## Reading Order

| Task | Read |
|------|------|
| Create first project | README only |
| Set up CI/CD | README → api → patterns |
| Debug failed deploy | gotchas |
| Understand generated files | configuration |
| Full CLI reference | api |
| Create custom template | patterns → configuration |
| Convert existing project | README → patterns |

## Post-Creation

```bash
cd my-app

# Local dev with hot reload
npm run dev

# Generate TypeScript types for bindings
npm run cf-typegen

# Deploy to Cloudflare
npm run deploy
```

## See Also

- **workers/README.md** - Workers runtime, bindings, APIs
- **workers-ai/README.md** - AI/ML models
- **pages/README.md** - Pages-specific features
- **wrangler/README.md** - Wrangler CLI beyond initial setup
- **d1/README.md** - SQLite database
- **r2/README.md** - Object storage

---

### Overview (`packages/autoskills/skills-registry/cloudflare/references/containers/README.md`)

# Cloudflare Containers

Use this reference for containerized applications on the Workers platform, including container-enabled Durable Objects, lifecycle management, and request routing.

## Choose the runtime

Use [Containers](https://developers.cloudflare.com/containers/index.md) for existing container images, custom runtimes, system dependencies, full filesystem access, or workloads needing additional CPU and memory. Use [Workers](https://developers.cloudflare.com/workers/index.md) when the application fits the Workers runtime without those requirements.

Containers are controlled through [Durable Objects](https://developers.cloudflare.com/durable-objects/index.md). An instance's identity does not make its filesystem persistent: design for restarts and store durable data outside the container disk. Read [Container lifecycle](https://developers.cloudflare.com/containers/concepts/architecture/index.md) and [Container interface](https://developers.cloudflare.com/containers/api/container-class/index.md) for the relationship between the process, its Durable Object, and persistent storage.

## Find the documentation for the task

Read the linked page before writing code or configuration; use its current API, examples, and constraints rather than reconstructing them from memory.

| Task | Start here |
| --- | --- |
| Create a project and deploy the first container | [Get started](https://developers.cloudflare.com/containers/get-started/index.md) |
| Configure images, bindings, instance sizes, and deployments | [Configuration](configuration.md) |
| Control startup, requests, lifecycle, and scheduling | [API](api.md) |
| Choose routing or connect other services | [Patterns](patterns.md) |
| Diagnose startup, persistence, capacity, or rollout issues | [Gotchas](gotchas.md) |

For additional topics, consult the [Containers documentation index](https://developers.cloudflare.com/containers/llms.txt).

---

### Overview (`packages/autoskills/skills-registry/cloudflare/references/cron-triggers/README.md`)

# Cloudflare Cron Triggers

Use Cron Triggers to start periodic Worker jobs. Fetch the relevant current documentation before implementing; configuration, API signatures, examples, and limits belong in the docs.

- **Set up a recurring job:** [Cron Triggers](https://developers.cloudflare.com/workers/configuration/cron-triggers/index.md) covers scheduling, deployment, and execution history.
- **Implement the job:** [Scheduled handler](https://developers.cloudflare.com/workers/runtime-apis/handlers/scheduled/index.md) covers controller properties, asynchronous work, and multiple schedules.
- **Schedule durable work:** [Trigger Workflows](https://developers.cloudflare.com/workflows/build/trigger-workflows/index.md) covers direct Workflow schedules and starting instances from a Worker. Check this before introducing a Worker whose only job is to start a Workflow.
- **Check capacity:** fetch [Workers limits](https://developers.cloudflare.com/workers/platform/limits/index.md) for the target plan and invocation type.

## In This Reference

- [configuration.md](./configuration.md) — schedule setup, environments, removal, and Green Compute
- [api.md](./api.md) — handler implementation, asynchronous completion, and tests
- [patterns.md](./patterns.md) — choosing execution boundaries and integrations
- [gotchas.md](./gotchas.md) — investigating timing, failures, and repeated work

## See Also

- [Workflows](../workflows/README.md) — durable multi-step jobs
- [Queues](../queues/README.md) — asynchronous message processing

---

### Overview (`packages/autoskills/skills-registry/cloudflare/references/d1/README.md`)

# Cloudflare D1 Database

Use D1 for managed relational application data with SQLite semantics. For an existing external database, consider [Hyperdrive](../hyperdrive/); for per-entity coordination, consider [Durable Objects](https://developers.cloudflare.com/workers/platform/storage-options/index.md#sql-in-durable-objects-vs-d1). See [storage options](https://developers.cloudflare.com/workers/platform/storage-options/index.md) before choosing a product.

Read the relevant current documentation before implementing. These references route tasks to the source of truth rather than maintaining copies of APIs, configuration, or plan tables.

## Start here

- [Get started](https://developers.cloudflare.com/d1/get-started/index.md): create a database, bind it to a Worker, and run a first query.
- [configuration.md](./configuration.md): bindings, environments, migrations, local development, and ORM integration.
- [api.md](./api.md): parameterized queries, batches, sessions, HTTP access, and testing.
- [patterns.md](./patterns.md): query design, caching, tenant isolation, replication, and recovery.
- [gotchas.md](./gotchas.md): errors, types, constraints, performance, and limits.

Check [limits](https://developers.cloudflare.com/d1/platform/limits/index.md) and [pricing](https://developers.cloudflare.com/d1/platform/pricing/index.md) for capacity, allowances, and plan availability; do not infer them from old examples.

---

### Overview (`packages/autoskills/skills-registry/cloudflare/references/graphql-api/README.md`)

# Cloudflare GraphQL Analytics API

Query analytics data across all Cloudflare products via a single GraphQL endpoint. Covers HTTP requests, Workers metrics, DNS, Firewall events, Network Analytics, and 70+ other datasets.

## Overview

- **Single endpoint** for all analytics: `https://api.cloudflare.com/client/v4/graphql`
- **1,400+ schema types** spanning every Cloudflare product
- **Two scopes**: zone-level (per-domain) and account-level (cross-domain)
- **Adaptive sampling** on high-traffic datasets with confidence intervals
- **No mutations** - read-only analytics (the Mutation type is a stub)
- **Cost-based rate limiting** - default 300 queries per 5 minutes per user (max 320, varies by query cost)

## Quick Decision Tree

```
Need analytics data from Cloudflare?
├─ HTTP traffic (requests, bandwidth, cache) → httpRequestsAdaptiveGroups (zone or account)
├─ Workers performance (CPU, wall time, errors) → workersInvocationsAdaptive (account)
├─ Firewall/WAF events → firewallEventsAdaptive / firewallEventsAdaptiveGroups (zone or account)
├─ DNS query analytics → dnsAnalyticsAdaptive / dnsAnalyticsAdaptiveGroups (zone or account)
├─ Network layer (DDoS, Magic Transit) → *NetworkAnalyticsAdaptiveGroups (account)
├─ Storage (R2, KV, D1, DO) → r2OperationsAdaptiveGroups / kvOperationsAdaptiveGroups / etc. (account)
├─ AI (Workers AI, AI Gateway) → aiInferenceAdaptive / aiGatewayRequestsAdaptiveGroups (account)
├─ Load Balancing → loadBalancingRequestsAdaptiveGroups (zone)
├─ Custom high-cardinality metrics → Workers Analytics Engine (see ../analytics-engine/)
└─ Need raw logs, not aggregates → Logpush (see Cloudflare docs)
```

## Core Concepts

| Concept | Description |
|---------|-------------|
| **Endpoint** | `POST https://api.cloudflare.com/client/v4/graphql` |
| **Explorer** | [graphql.cloudflare.com](https://graphql.cloudflare.com/) - interactive query builder |
| **Viewer** | Root query object: `viewer { zones(...) { ... } }` or `viewer { accounts(...) { ... } }` |
| **Dataset (Node)** | A queryable table under a zone or account (e.g., `httpRequestsAdaptiveGroups`) |
| **Dimensions** | Fields to group by (time buckets, country, status code, script name, etc.) |
| **Metrics** | Aggregation fields: `count`, `sum { ... }`, `avg { ... }`, `quantiles { ... }`, `ratio { ... }` |
| **Filter** | Input object constraining results by time range, dimensions, etc. |
| **Limit** | Maximum rows returned per dataset node (required, max varies by dataset) |
| **OrderBy** | Enum-based sorting: `[field_ASC]` or `[field_DESC]` |
| **Adaptive Sampling** | Nodes with `Adaptive` in the name use ABR sampling; results are statistically representative |

## Query Structure

Every query follows this pattern:

```graphql
{
  viewer {
    # Zone-scoped
    zones(filter: { zoneTag: "ZONE_ID" }) {
      datasetName(
        filter: { datetime_gt: "...", datetime_lt: "..." }
        limit: 1000
        orderBy: [datetimeFiveMinutes_DESC]
      ) {
        count
        dimensions { ... }
        sum { ... }
      }
    }
    # Account-scoped
    accounts(filter: { accountTag: "ACCOUNT_ID" }) {
      datasetName(filter: { ... }, limit: 100) {
        count
        dimensions { ... }
        sum { ... }
      }
    }
  }
}
```

## Dataset Naming Convention

Dataset names follow a consistent pattern visible in the schema:

| Pattern | Meaning | Example |
|---------|---------|---------|
| `*Adaptive` | Raw rows with adaptive sampling; some (e.g., `workersInvocationsAdaptive`) also support aggregation fields (`sum`, `quantiles`, `avg`) | `httpRequestsAdaptive`, `workersInvocationsAdaptive` |
| `*AdaptiveGroups` | Aggregated data with adaptive sampling | `httpRequestsAdaptiveGroups` |
| `*1hGroups` | Hourly rollups (pre-aggregated) | `httpRequests1hGroups` |
| `*1dGroups` | Daily rollups (pre-aggregated) | `httpRequests1dGroups` |
| `*1mGroups` | Minutely rollups | `httpRequests1mGroups` |
| `Zone*` prefix | Zone-scoped dataset | `ZoneHttpRequestsAdaptiveGroups` |
| `Account*` prefix | Account-scoped dataset | `AccountWorkersInvocationsAdaptive` |

**Prefer `*AdaptiveGroups` nodes** for most use cases - they support flexible time grouping via dimension fields (`datetimeFiveMinutes`, `datetimeHour`, etc.) and are the most commonly used.

## Key Datasets by Product

### Zone-Scoped (per-domain)

| Dataset | Description |
|---------|-------------|
| `httpRequestsAdaptiveGroups` | HTTP traffic: requests, bytes, cache status, bot scores, WAF scores |
| `httpRequests1hGroups` / `1dGroups` / `1mGroups` | Pre-aggregated HTTP rollups (hourly/daily/minutely) |
| `firewallEventsAdaptiveGroups` | WAF, rate limiting, bot management, firewall rule events |
| `dnsAnalyticsAdaptiveGroups` | DNS query volumes, response codes, query types |
| `loadBalancingRequestsAdaptiveGroups` | Load Balancer origin request metrics |
| `pageShieldReportsAdaptiveGroups` | Page Shield CSP reports |

### Account-Scoped (cross-domain)

| Dataset | Description |
|---------|-------------|
| `workersInvocationsAdaptive` | Workers: requests, errors, CPU time, wall time, subrequests |
| `durableObjectsInvocationsAdaptiveGroups` | DO invocations |
| `durableObjectsStorageGroups` / `durableObjectsPeriodicGroups` | DO storage and periodic metrics |
| `d1AnalyticsAdaptiveGroups` / `d1QueriesAdaptiveGroups` | D1 database analytics |
| `r2OperationsAdaptiveGroups` / `r2StorageAdaptiveGroups` | R2 operations and storage |
| `kvOperationsAdaptiveGroups` / `kvStorageAdaptiveGroups` | KV operations and storage |
| `aiInferenceAdaptiveGroups` | Workers AI inference metrics |
| `aiGatewayRequestsAdaptiveGroups` | AI Gateway request analytics |
| `pagesFunctionsInvocationsAdaptiveGroups` | Pages Functions metrics |
| `magicTransitNetworkAnalyticsAdaptiveGroups` | Magic Transit packet/byte analytics |
| `spectrumNetworkAnalyticsAdaptiveGroups` | Spectrum TCP/UDP analytics |
| `gatewayL7RequestsAdaptiveGroups` | Zero Trust Gateway HTTP metrics |
| `gatewayResolverQueriesAdaptiveGroups` | Zero Trust Gateway DNS metrics |

## Reading Order

| Task | Start Here | Then Read |
|------|------------|-----------|
| **First query** | [configuration.md](configuration.md) (auth) -> this README (structure) | [api.md](api.md) |
| **Build a dashboard** | [patterns.md](patterns.md) (time-series, top-N) | [api.md](api.md) (aggregation fields) |
| **Debug query issues** | [gotchas.md](gotchas.md) | [api.md](api.md) (filtering) |
| **Understand sampling** | [gotchas.md](gotchas.md) (sampling section) | [api.md](api.md) (confidence intervals) |
| **Product-specific metrics** | [patterns.md](patterns.md) (per-product examples) | [api.md](api.md) (dataset reference) |

## In This Reference

- **[api.md](api.md)** - Query structure, aggregation fields (sum/avg/quantiles/count), filtering operators, dimensions, dataset details
- **[configuration.md](configuration.md)** - Authentication, API tokens, client setup (curl, JS, Python), introspection
- **[patterns.md](patterns.md)** - Common queries: time-series, top-N, Workers metrics, HTTP analytics, firewall events, multi-zone
- **[gotchas.md](gotchas.md)** - Rate limits, sampling caveats, query cost, common errors, plan-based limits

## See Also

- [GraphQL Analytics API Docs](https://developers.cloudflare.com/analytics/graphql-api/index.md)
- [GraphQL API Explorer](https://graphql.cloudflare.com/)
- [Observability Reference](../observability/) - Workers Logs, Tail Workers, console logging
- [Analytics Engine Reference](../analytics-engine/) - Custom high-cardinality analytics via Workers
- [Web Analytics docs](https://developers.cloudflare.com/web-analytics/index.md) - Client-side (RUM) analytics
- [Cloudflare API docs](https://developers.cloudflare.com/fundamentals/api/index.md) - REST API, SDKs, authentication basics

---

### Overview (`packages/autoskills/skills-registry/cloudflare/references/hyperdrive/README.md`)

# Hyperdrive

Use Hyperdrive to connect Workers to an existing PostgreSQL or MySQL database with connection pooling and optional query caching. It does not replace the origin database or replicate its data. Start with [how Hyperdrive works](https://developers.cloudflare.com/hyperdrive/concepts/how-hyperdrive-works/index.md) and [supported databases and features](https://developers.cloudflare.com/hyperdrive/reference/supported-databases-and-features/index.md) to assess fit.

## Retrieve current documentation

Fetch the relevant official page before implementing. Driver versions, compatibility settings, API shapes, CLI flags, cache settings, and limits belong in the docs rather than this reference. Use the [Hyperdrive documentation index](https://developers.cloudflare.com/hyperdrive/llms.txt) to discover additional pages. Retrieve a page as Markdown by sending `Accept: text/markdown` to its URL.

## Choose the next reference

| Task | Reference |
|------|-----------|
| Create a configuration, bind it, connect privately, or develop locally | [configuration.md](./configuration.md) |
| Choose a driver, use binding credentials, or integrate an ORM | [api.md](./api.md) |
| Decide read freshness, connection lifetime, or query placement | [patterns.md](./patterns.md) |
| Diagnose connection, cache, latency, or capacity problems | [gotchas.md](./gotchas.md) |

## Decisions to preserve

- Choose a driver for the database engine and existing application stack; verify supported versions and Worker requirements in its guide.
- Create database clients inside each handler invocation. Hyperdrive manages the underlying origin pool; consult [connection lifecycle](https://developers.cloudflare.com/hyperdrive/concepts/connection-lifecycle/index.md) for cleanup behavior.
- Choose caching by read freshness. Disabling caching still allows connection pooling; a write does not invalidate cached reads. See [query caching](https://developers.cloudflare.com/hyperdrive/concepts/query-caching/index.md).

## See also

- [D1](../d1/) for a managed SQLite alternative.
- [Workers](https://developers.cloudflare.com/workers/index.md) for the runtime and bindings.

---

### Overview (`packages/autoskills/skills-registry/cloudflare/references/images/README.md`)

# Cloudflare Images

Choose the image source and operation before selecting an API. Hosted-image management, remote URL transformations, and the Workers optimization binding have different contracts. Retrieve the documentation for the path the project uses.

| Task | Start here |
|------|------------|
| Optimize image bytes in a Worker or manage hosted images | [API selection](api.md) |
| Configure a binding, variants, or private delivery | [Configuration](configuration.md) |
| Accept client uploads, serve responsive images, watermark, or store results in R2 | [Patterns](patterns.md) |
| Diagnose failures, check limits, or investigate caching | [Troubleshooting](gotchas.md) |

For new work, inspect the project's installed Wrangler version, compatibility settings, existing image storage, and public/private access requirements. Read only the relevant linked pages and adapt them to the project; preserve existing conventions and verify behavior with representative images.

---

### Overview (`packages/autoskills/skills-registry/cloudflare/references/kv/README.md`)

# Cloudflare Workers KV

Use KV for read-heavy configuration, preferences, and application caches that tolerate stale data. Read [how KV works](https://developers.cloudflare.com/kv/concepts/how-kv-works/index.md) before choosing it: reads are eventually consistent, including cached missing keys, and immediate visibility is not guaranteed even in the location of a write.

For atomic updates or coordination, consider [Durable Objects](https://developers.cloudflare.com/durable-objects/index.md); for relational queries, [D1](../d1/); for large objects, [R2](../r2/). Use the [storage comparison](https://developers.cloudflare.com/workers/platform/storage-options/index.md) to choose based on requirements.

Read the current documentation for the task before implementing. Use the [KV documentation index](https://developers.cloudflare.com/kv/llms.txt) to discover additional guides; these files preserve task routes rather than copies of APIs, commands, or numeric limits.

## Start here

- [Get started](https://developers.cloudflare.com/kv/get-started/index.md): create a namespace, bind it, and read and write data.
- [configuration.md](./configuration.md): bindings, environments, types, local development, CLI, and REST access.
- [api.md](./api.md): reads, writes, metadata, deletion, bulk operations, and pagination.
- [patterns.md](./patterns.md): caching, sessions, key design, versioning, and fallback decisions.
- [gotchas.md](./gotchas.md): stale reads, concurrent writes, missing values, performance, limits, and pricing.

---

### Overview (`packages/autoskills/skills-registry/cloudflare/references/miniflare/README.md`)

# Miniflare

Miniflare provides programmatic control of local Workers simulation. Read the linked documentation before choosing APIs, configuration, or a migration path.

## Choose the testing tool

| Need | Start here |
|------|------------|
| Unit tests that execute in the Workers runtime | [Workers Vitest setup](https://developers.cloudflare.com/workers/testing/vitest-integration/write-your-first-test/index.md) |
| Integration tests against built Workers | [Integration test harness](https://developers.cloudflare.com/workers/testing/test-harness/index.md) |
| Low-level simulator control for a custom harness | [Miniflare testing guide](https://developers.cloudflare.com/workers/testing/miniflare/writing-tests/index.md) |
| Binding access from a Node.js process | [Wrangler getPlatformProxy](https://developers.cloudflare.com/workers/wrangler/api/index.md#getplatformproxy) |

For interactive local development, use the project's Wrangler or Cloudflare Vite workflow. Direct Miniflare is useful when the higher-level testing tools do not expose the control needed.

## Read for the task

- [Get started](https://developers.cloudflare.com/workers/testing/miniflare/get-started/index.md) — installation, scripts, lifecycle, and event dispatch.
- [API routing](./api.md) — events and access to local resources.
- [Configuration](./configuration.md) — modules, bindings, compatibility, and multiple Workers.
- [Testing patterns](./patterns.md) — runtime choice, mocking, and test lifecycle.
- [Troubleshooting and migrations](./gotchas.md) — build/configuration differences and existing test suites.

---

### Overview (`packages/autoskills/skills-registry/cloudflare/references/observability/README.md`)

# Cloudflare Observability

Use this reference to choose a telemetry signal and find the maintained implementation guide. Fetch the linked documentation before writing configuration, queries, or export code; it is the source of truth for APIs, availability, retention, limits, and pricing.

## Choose a signal

| Need | Start here |
| --- | --- |
| Store, search, and investigate historical Worker logs | [Workers Logs](https://developers.cloudflare.com/workers/observability/logs/workers-logs/index.md) |
| Watch a deployment or reproduce an issue live | [Real-time logs and Wrangler tail](https://developers.cloudflare.com/workers/observability/logs/real-time-logs/index.md) |
| Understand request flows and dependency latency | [Workers Traces](https://developers.cloudflare.com/workers/observability/traces/index.md) |
| Monitor built-in request, error, and CPU metrics | [Metrics and analytics](https://developers.cloudflare.com/workers/observability/metrics-and-analytics/index.md) |
| Record custom events and tenant-level usage for SQL analysis | [Analytics Engine](https://developers.cloudflare.com/analytics/analytics-engine/get-started/index.md) |
| Export logs and traces to an observability provider | [OpenTelemetry export](https://developers.cloudflare.com/observability/export/opentelemetry/index.md) |
| Apply custom filtering, transformation, or delivery logic | [Tail Workers](https://developers.cloudflare.com/workers/observability/logs/tail-workers/index.md) |
| Deliver Workers Trace Events to a supported log storage destination | [Workers Logpush](https://developers.cloudflare.com/workers/observability/logs/logpush/index.md) |

Workers Logs supports retained historical data; live tailing is a separate debugging workflow. Choose persistence, sampling, and export destinations deliberately rather than assuming that every signal is stored or included without usage charges.

## Load only what the task needs

- [configuration.md](configuration.md): enable collection, bindings, environments, and exports.
- [api.md](api.md): logging, telemetry types, SQL, GraphQL, and Logpush APIs.
- [patterns.md](patterns.md): billing, performance, errors, tenant tracking, and export decisions.
- [gotchas.md](gotchas.md): missing data, sampling, timing, privacy, and cost checks.

For broader product tasks, see [Analytics Engine](../analytics-engine/README.md), [GraphQL API](../graphql-api/README.md), and [Tail Workers](../tail-workers/README.md).

---

### Overview (`packages/autoskills/skills-registry/cloudflare/references/pages-functions/README.md`)

# Cloudflare Pages Functions

Use this reference for server-side behavior in an existing Pages project. For new applications, follow the Workers recommendation in the [Pages framework guidance](https://developers.cloudflare.com/pages/framework-guides/index.md).

| Task | Documentation |
| --- | --- |
| Identify filesystem routes and invocation boundaries | [Routing](https://developers.cloudflare.com/pages/functions/routing/index.md) |
| Implement request handlers | [API reference](https://developers.cloudflare.com/pages/functions/api-reference/index.md) |
| Understand generated Worker output | [Advanced mode](https://developers.cloudflare.com/pages/functions/advanced-mode/index.md) |

Inspect whether the project uses a Functions directory or framework-generated advanced mode before selecting a routing approach. Fetch current documentation for signatures, supported bindings, configuration, and examples.

## In This Reference

- [api.md](./api.md) — handlers, context, middleware, and assets
- [configuration.md](./configuration.md) — bindings, environments, types, and local development
- [patterns.md](./patterns.md) — request ownership and shared logic
- [gotchas.md](./gotchas.md) — route, binding, and runtime investigation

See [Pages](../pages/README.md) for builds and deployment decisions.

---

### Overview (`packages/autoskills/skills-registry/cloudflare/references/pages/README.md`)

# Cloudflare Pages

Use this reference when maintaining an existing Pages project. For new applications, start with Workers as recommended in the [Pages framework guidance](https://developers.cloudflare.com/pages/framework-guides/index.md). Fetch current documentation before implementing.

| Task | Documentation |
| --- | --- |
| Configure the existing build | [Build configuration](https://developers.cloudflare.com/pages/configuration/build-configuration/index.md) |
| Manage automatic deployments from a repository | [Git integration](https://developers.cloudflare.com/pages/configuration/git-integration/index.md) |
| Deploy prebuilt output | [Direct Upload](https://developers.cloudflare.com/pages/get-started/direct-upload/index.md) |
| Implement server-side requests | [Functions API reference](https://developers.cloudflare.com/pages/functions/api-reference/index.md) |
| Plan a move to Workers | [Migrate from Pages to Workers](https://developers.cloudflare.com/workers/static-assets/migration-guides/migrate-from-pages/index.md) |

## In This Reference

- [configuration.md](./configuration.md) — build output, environments, and static rules
- [api.md](./api.md) — request handling and framework integration
- [patterns.md](./patterns.md) — project decisions and migration
- [gotchas.md](./gotchas.md) — build, routing, and deployment investigation

See [Pages Functions](../pages-functions/README.md) for handler-focused navigation. Identify the existing deployment method and framework before proposing changes.

---

### Overview (`packages/autoskills/skills-registry/cloudflare/references/queues/README.md`)

# Cloudflare Queues

Use Queues to decouple producers from asynchronous consumers and buffer bursts of work. Design consumers for duplicate delivery; use Workflows when the task needs durable multi-step orchestration.

Fetch the relevant documentation below before implementing. Treat current Cloudflare docs as the source of truth for API signatures, acknowledgement semantics, configuration, limits, and pricing.

## Choose a consumer

- Use a Worker push consumer when processing runs on Workers.
- Use an HTTP pull consumer when processing runs in another environment; plan for polling, visibility timeouts, and acknowledgement leases.
- Choose a message encoding the consumer can decode. Check serialization and compatibility-date behavior before sending existing application objects.

See [How Queues works](https://developers.cloudflare.com/queues/reference/how-queues-works/index.md) and [delivery guarantees](https://developers.cloudflare.com/queues/reference/delivery-guarantees/index.md) before choosing ordering or deduplication strategies.

## Read by task

| Task | Reference |
|------|-----------|
| Create queues, bind producers, and configure consumers | [configuration.md](./configuration.md) |
| Send messages and implement acknowledgement or retries | [api.md](./api.md) |
| Buffer APIs, defer jobs, or integrate with storage and orchestration | [patterns.md](./patterns.md) |
| Diagnose delivery failures, duplicates, or capacity issues | [gotchas.md](./gotchas.md) |

For a first application, fetch [Getting started](https://developers.cloudflare.com/queues/get-started/index.md). Retrieve [limits](https://developers.cloudflare.com/queues/platform/limits/index.md) and [pricing](https://developers.cloudflare.com/queues/platform/pricing/index.md) before sizing throughput, retention, or cost; plan-specific values are not maintained here.

---

### Overview (`packages/autoskills/skills-registry/cloudflare/references/r2/README.md`)

# Cloudflare R2 Object Storage

Use R2 for objects such as uploads, media, backups, and static assets. Fetch the linked documentation before implementing; API signatures, configuration, limits, and pricing belong in the current docs.

## Choose an access path

- Use a Workers binding for object access inside a Worker: [Workers API setup](https://developers.cloudflare.com/r2/get-started/workers-api/index.md).
- Use the S3-compatible API for existing S3 clients or direct client access through presigned URLs: [S3 setup](https://developers.cloudflare.com/r2/get-started/s3/index.md). Check supported operations rather than assuming full S3 parity.
- Decide whether objects need application authorization, temporary access, or public delivery before exposing the bucket. See [patterns.md](./patterns.md).

## Find the task

| Task | Reference |
|------|-----------|
| Bindings, credentials, local development, bucket settings | [configuration.md](./configuration.md) |
| Object operations, metadata, conditions, multipart, CLI | [api.md](./api.md) |
| Uploads, streaming, caching, public delivery, event processing | [patterns.md](./patterns.md) |
| Pagination, conditional responses, failed uploads, limits | [gotchas.md](./gotchas.md) |

For other topics, discover pages through the [R2 documentation index](https://developers.cloudflare.com/r2/llms.txt). Check [pricing](https://developers.cloudflare.com/r2/pricing/index.md) before estimating costs.

## See also

- [Workers](https://developers.cloudflare.com/workers/index.md) for request handling.
- [KV](../kv/) or [D1](../d1/) for application metadata associated with objects.
- [Queues](../queues/) for asynchronous processing of object events.

---

### Overview (`packages/autoskills/skills-registry/cloudflare/references/secrets-store/README.md`)

# Cloudflare Secrets Store

Use Secrets Store for account-level credentials shared across Workers or supported integrations. Use [Worker secrets](https://developers.cloudflare.com/workers/configuration/secrets/index.md) when credentials belong to one Worker and do not need centralized sharing.

Fetch the relevant documentation before implementing. Current Cloudflare docs are the source of truth for binding APIs, management commands, permissions, availability, and quotas. Use the [Secrets Store documentation index](https://developers.cloudflare.com/secrets-store/llms.txt) to discover additional guidance.

## Choose the scope

- Share a secret only among services that should use the same credential and rotate together.
- Separate development, staging, and production credentials; select the intended account and environment before managing or binding a secret.
- Grant only the management permissions and consuming-service scopes needed. Permission to view metadata does not imply permission to bind or retrieve a value; fetch [access control](https://developers.cloudflare.com/secrets-store/access-control/index.md) for the current rules.

## Read by task

| Task | Reference |
|------|-----------|
| Create secrets, configure bindings, or prepare local development | [configuration.md](./configuration.md) |
| Read a secret in a Worker or automate management | [api.md](./api.md) |
| Plan rotation, migration, encryption, or auditing | [patterns.md](./patterns.md) |
| Diagnose access, deployment, or quota failures | [gotchas.md](./gotchas.md) |

Fetch the [product overview](https://developers.cloudflare.com/secrets-store/index.md) for current availability and supported integrations. For AI Gateway provider credentials, use [Bring your own keys](https://developers.cloudflare.com/ai-gateway/configuration/bring-your-own-keys/index.md).

---

### Overview (`packages/autoskills/skills-registry/cloudflare/references/smart-placement/README.md`)

# Cloudflare Workers Smart Placement

Automatic workload placement optimization to minimize latency by running Workers closer to backend infrastructure rather than end users.

## Core Concept

Smart Placement automatically analyzes Worker request duration across Cloudflare's global network and intelligently routes requests to optimal data center locations. Instead of defaulting to the location closest to the end user, Smart Placement can forward requests to locations closer to backend infrastructure when this reduces overall request duration.

### When to Use

**Enable Smart Placement when:**
- Worker makes multiple round trips to backend services/databases
- Backend infrastructure is geographically concentrated
- Request duration dominated by backend latency rather than network latency from user
- Running backend logic in Workers (APIs, data aggregation, SSR with DB calls)
- Worker uses `fetch` handler (not RPC methods)

**Do NOT enable for:**
- Workers serving only static content or cached responses
- Workers without significant backend communication
- Pure edge logic (auth checks, redirects, simple transformations)
- Workers without fetch event handlers
- Workers with RPC methods or named entrypoints (only `fetch` handlers are affected)
- Pages/Assets Workers with `run_worker_first = true` (degrades asset serving)

### Decision Tree

```
Does your Worker have a fetch handler?
├─ No → Smart Placement won't work (skip)
└─ Yes
   │
   Does it make multiple backend calls (DB/API)?
   ├─ No → Don't enable (won't help)
   └─ Yes
      │
      Is backend geographically concentrated?
      ├─ No (globally distributed) → Probably won't help
      └─ Yes or uncertain
         │
         Does it serve static assets with run_worker_first=true?
         ├─ Yes → Don't enable (will hurt performance)
         └─ No → Enable Smart Placement
            │
            After 15min, check placement_status
            ├─ SUCCESS → Monitor metrics
            ├─ INSUFFICIENT_INVOCATIONS → Need more traffic
            └─ UNSUPPORTED_APPLICATION → Disable (hurting performance)
```

### Key Architecture Pattern

**Recommended:** Split full-stack applications into separate Workers:
```
User → Frontend Worker (at edge, close to user)
         ↓ Service Binding
       Backend Worker (Smart Placement enabled, close to DB/API)
         ↓
       Database/Backend Service
```

This maintains fast, reactive frontends while optimizing backend latency.

## Quick Start

```jsonc
// wrangler.jsonc
{
  "placement": {
    "mode": "smart"  // or "off" to explicitly disable
  }
}
```

Deploy and wait 15 minutes for analysis. Check status via API or dashboard metrics.

**To disable:** Set `"mode": "off"` or remove `placement` field entirely (both equivalent).

## Requirements

- Wrangler 2.20.0+
- Analysis time: Up to 15 minutes after enabling
- Traffic requirements: Consistent traffic from multiple global locations
- Available on all Workers plans (Free, Paid, Enterprise)

## Placement Status Values

```typescript
type PlacementStatus = 
  | undefined  // Not yet analyzed
  | 'SUCCESS'  // Successfully optimized
  | 'INSUFFICIENT_INVOCATIONS'  // Not enough traffic
  | 'UNSUPPORTED_APPLICATION';  // Made Worker slower (reverted)
```

## CLI Commands

```bash
# Deploy with Smart Placement
wrangler deploy

# Check placement status
curl -H "Authorization: Bearer $TOKEN" \
  https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/workers/services/$WORKER_NAME \
  | jq .result.placement_status

# Monitor
wrangler tail your-worker-name --header cf-placement
```

## Reading Order

**First time?** Start here:
1. This README - understand core concepts and when to use Smart Placement
2. [configuration.md](./configuration.md) - set up wrangler.jsonc and understand limitations
3. [patterns.md](./patterns.md) - see practical examples for your use case
4. [api.md](./api.md) - monitor and verify Smart Placement is working
5. [gotchas.md](./gotchas.md) - troubleshoot common issues

**Quick lookup:**
- "Should I enable Smart Placement?" → See "When to Use" above
- "How do I configure it?" → [configuration.md](./configuration.md)
- "How do I split frontend/backend?" → [patterns.md](./patterns.md)
- "Why isn't it working?" → [gotchas.md](./gotchas.md)

## In This Reference

- [configuration.md](./configuration.md) - wrangler.jsonc setup, mode values, validation rules
- [api.md](./api.md) - Placement Status API, cf-placement header, monitoring
- [patterns.md](./patterns.md) - Frontend/backend split, database workers, SSR patterns
- [gotchas.md](./gotchas.md) - Troubleshooting INSUFFICIENT_INVOCATIONS, performance issues

## See Also

- [workers](https://developers.cloudflare.com/workers/index.md) - Worker runtime and fetch handlers
- [d1](../d1/) - D1 database that benefits from Smart Placement
- [durable-objects](https://developers.cloudflare.com/durable-objects/index.md) - Durable Objects with backend logic
- [bindings](../bindings/) - Service bindings for frontend/backend split

---

### Overview (`packages/autoskills/skills-registry/cloudflare/references/static-assets/README.md`)

# Workers Static Assets

Use Workers Static Assets for new static sites, SPAs, generated sites, and applications combining assets with server logic. Inspect the framework, build output, and existing deployment configuration before changing routing.

| Task | Documentation |
|------|---------------|
| Set up and deploy a static site or application | [Get started](https://developers.cloudflare.com/workers/static-assets/get-started/index.md) |
| Choose configuration and an optional asset binding | [Configuration and bindings](https://developers.cloudflare.com/workers/static-assets/binding/index.md) |
| Serve a client-rendered application | [SPA routing](https://developers.cloudflare.com/workers/static-assets/routing/single-page-application/index.md) |
| Serve generated HTML and custom error pages | [SSG routing](https://developers.cloudflare.com/workers/static-assets/routing/static-site-generation/index.md) |
| Use a full-stack framework | [Full-stack application guides](https://developers.cloudflare.com/workers/static-assets/routing/full-stack-application/index.md) |
| Evaluate moving an existing Pages project | [Pages migration guide](https://developers.cloudflare.com/workers/static-assets/migration-guides/migrate-from-pages/index.md) |

Do not choose a platform solely from the framework name. For an existing Pages project, inspect its current features and migration requirements before proposing a move.

## Reading Order

1. [configuration.md](configuration.md) — build output and routing configuration.
2. [api.md](api.md) — fetch assets and handle responses.
3. [patterns.md](patterns.md) — choose a routing design.
4. [gotchas.md](gotchas.md) — diagnose routing, caching, and deployment issues.

---

### Overview (`packages/autoskills/skills-registry/cloudflare/references/stream/README.md`)

# Cloudflare Stream

Use Stream for on-demand video upload and playback or live broadcasting. Start with the application's upload source, player, and access requirements, then read the corresponding documentation before writing code.

## Choose a Workflow

| Task | Read |
|---|---|
| Let users upload without exposing an API token | [Direct creator uploads](https://developers.cloudflare.com/stream/uploading-videos/direct-creator-uploads/index.md) |
| Choose server upload, resumable upload, or import from a URL | [Upload methods and supported formats](https://developers.cloudflare.com/stream/uploading-videos/index.md) |
| Embed playback or integrate an existing player | [Stream Player](https://developers.cloudflare.com/stream/viewing-videos/using-the-stream-player/index.md) or [HLS/DASH players](https://developers.cloudflare.com/stream/viewing-videos/using-own-player/index.md) |
| Restrict viewing to authorized users or embedding origins | [Secure your Stream](https://developers.cloudflare.com/stream/viewing-videos/securing-your-stream/index.md) |
| Broadcast live, replay recordings, or simulcast | [Live workflow routing](./api-live.md) |
| Check usage, costs, or upload constraints | [Analytics](https://developers.cloudflare.com/stream/getting-analytics/index.md), [pricing](https://developers.cloudflare.com/stream/pricing/index.md), and [upload requirements](https://developers.cloudflare.com/stream/uploading-videos/index.md) |

## In This Reference

- [configuration.md](./configuration.md): project setup and access decisions.
- [api.md](./api.md): upload, playback, editing, and library operations.
- [api-live.md](./api-live.md): live inputs, outputs, recording, and WebRTC.
- [patterns.md](./patterns.md): application workflow decisions.
- [gotchas.md](./gotchas.md): troubleshooting routes.

---

### Overview (`packages/autoskills/skills-registry/cloudflare/references/tail-workers/README.md`)

# Cloudflare Tail Workers

Use Tail Workers when execution events need custom processing. Fetch the current documentation before implementing handlers, configuration, or integrations.

| Task | Documentation |
| --- | --- |
| Decide whether custom processing is needed | [Tail Workers](https://developers.cloudflare.com/workers/observability/logs/tail-workers/index.md) |
| Export logs and traces to an observability destination | [OpenTelemetry export](https://developers.cloudflare.com/observability/export/opentelemetry/index.md) |
| Inspect a deployment interactively | [Real-time logs](https://developers.cloudflare.com/workers/observability/logs/real-time-logs/index.md) |
| Implement the consumer | [Tail handler](https://developers.cloudflare.com/workers/runtime-apis/handlers/tail/index.md) |

Before adding a Tail Worker, check whether built-in OpenTelemetry export meets the destination’s needs. Use the Tail Workers guide for the tradeoff, then identify the custom filtering or transformation that remains necessary.

## In This Reference

- [configuration.md](./configuration.md) — producer, consumer, destination, and environment setup
- [api.md](./api.md) — event fields, execution outcomes, and redaction
- [patterns.md](./patterns.md) — destination and filtering decisions
- [gotchas.md](./gotchas.md) — connection, data, and delivery investigation

See [observability](../observability/README.md) for broader logging and tracing choices.

---

### Overview (`packages/autoskills/skills-registry/cloudflare/references/tunnel/README.md`)

# Cloudflare Tunnel

Use Tunnel to connect origin services to Cloudflare. Inspect the existing tunnel, management mode, and intended audience before choosing a setup. Fetch current docs for commands, configuration, and limits.

| Task | Documentation |
| --- | --- |
| Create a remotely-managed tunnel or a temporary development tunnel | [Setup](https://developers.cloudflare.com/tunnel/get-started/index.md) |
| Maintain a tunnel managed through local files | [Create a locally-managed tunnel](https://developers.cloudflare.com/tunnel/features/locally-managed-tunnels/create-local-tunnel/index.md) |
| Publish an application and check protocol requirements | [Routing](https://developers.cloudflare.com/tunnel/concepts/routing/index.md) |
| Choose private networking, Workers VPC, or Access integration | [Integrations](https://developers.cloudflare.com/tunnel/integrations/index.md) |

Decide whether the goal is a public application, authenticated private access, or connectivity from a Worker. Then identify who owns configuration and how it will be deployed; multiple environments alone do not require local management.

## In This Reference

- [configuration.md](./configuration.md) — management mode, ingress, and origin settings
- [networking.md](./networking.md) — firewall, connectivity, and private-network investigation
- [api.md](./api.md) — programmatic setup and tunnel operations
- [patterns.md](./patterns.md) — deployment and availability decisions
- [gotchas.md](./gotchas.md) — troubleshooting and operational checks

---

### Overview (`packages/autoskills/skills-registry/cloudflare/references/turn/README.md`)

# Cloudflare TURN Service

Expert guidance for implementing Cloudflare TURN Service in WebRTC applications.

## Overview

Cloudflare TURN (Traversal Using Relays around NAT) Service is a managed relay service for WebRTC applications. TURN acts as a relay point for traffic between WebRTC clients and SFUs, particularly when direct peer-to-peer communication is obstructed by NATs or firewalls. The service runs on Cloudflare's global anycast network across 310+ cities.

## Key Characteristics

- **Anycast Architecture**: Automatically connects clients to the closest Cloudflare location
- **Global Network**: Available across Cloudflare's entire network (excluding China Network)
- **Zero Configuration**: No need to manually select regions or servers
- **Protocol Support**: STUN/TURN over UDP, TCP, and TLS
- **Free Tier**: Free when used with Cloudflare Calls SFU, otherwise $0.05/GB outbound

## In This Reference

| File | Purpose |
|------|---------|
| [api.md](./api.md) | Credentials API, TURN key management, types, constraints |
| [configuration.md](./configuration.md) | Worker setup, wrangler.jsonc, env vars, IP allowlisting |
| [patterns.md](./patterns.md) | Implementation patterns, use cases, integration examples |
| [gotchas.md](./gotchas.md) | Troubleshooting, limits, security, common mistakes |

## Reading Order

| Task | Files to Read | Est. Tokens |
|------|---------------|-------------|
| Quick start | README only | ~500 |
| Generate credentials | README → api | ~1300 |
| Worker integration | README → configuration → patterns | ~2000 |
| Debug connection | gotchas | ~700 |
| Security review | api → gotchas | ~1500 |
| Enterprise firewall | configuration | ~600 |

## Service Addresses and Ports

### STUN over UDP
- **Primary**: `stun.cloudflare.com:3478/udp`
- **Alternate**: `stun.cloudflare.com:53/udp` (blocked by browsers, not recommended)

### TURN over UDP
- **Primary**: `turn.cloudflare.com:3478/udp`
- **Alternate**: `turn.cloudflare.com:53/udp` (blocked by browsers)

### TURN over TCP
- **Primary**: `turn.cloudflare.com:3478/tcp`
- **Alternate**: `turn.cloudflare.com:80/tcp`

### TURN over TLS
- **Primary**: `turn.cloudflare.com:5349/tcp`
- **Alternate**: `turn.cloudflare.com:443/tcp`

## Quick Start

1. **Create TURN key via API**: see [api.md#create-turn-key](./api.md#create-turn-key)
2. **Generate credentials**: see [api.md#generate-temporary-credentials](./api.md#generate-temporary-credentials)
3. **Configure Worker**: see [configuration.md#cloudflare-worker-integration](./configuration.md#cloudflare-worker-integration)
4. **Implement client**: see [patterns.md#basic-turn-configuration-browser](./patterns.md#basic-turn-configuration-browser)

## When to Use TURN

- **Restrictive NATs**: Symmetric NATs that block direct connections
- **Corporate firewalls**: Environments blocking WebRTC ports
- **Mobile networks**: Carrier-grade NAT scenarios
- **Predictable connectivity**: When reliability > efficiency

## Related Cloudflare Services

- **Cloudflare Calls SFU**: Managed Selective Forwarding Unit (TURN free when used with SFU)
- **Cloudflare Stream**: Video streaming with WHIP/WHEP support
- **Cloudflare Workers**: Backend for credential generation
- **Cloudflare KV**: Credential caching
- **Cloudflare Durable Objects**: Session state management

## Additional Resources

- [Cloudflare Calls Documentation](https://developers.cloudflare.com/realtime/index.md)
- [Cloudflare TURN Service Docs](https://developers.cloudflare.com/realtime/turn/index.md)
- [Cloudflare API Reference](https://developers.cloudflare.com/api/resources/calls/subresources/turn/index.md)
- [Orange Meets (Open Source Example)](https://github.com/cloudflare/orange)

---

### Overview (`packages/autoskills/skills-registry/cloudflare/references/vectorize/README.md`)

# Cloudflare Vectorize

Use Vectorize when you need to control embeddings, vector indexing, and retrieval for semantic search, recommendations, or RAG. For a managed retrieval pipeline, see [AI Search](../ai-search/README.md).

Fetch current documentation before implementing. Start with the [Vectorize documentation index](https://developers.cloudflare.com/vectorize/llms.txt) to discover pages; load only those relevant to the task. Treat the docs as the source of truth for APIs, configuration, models, limits, and pricing.

## Task routing

| Task | Read |
|------|------|
| Create an index and connect a Worker | [Configuration](configuration.md) and [Introduction to Vectorize](https://developers.cloudflare.com/vectorize/get-started/intro/index.md) |
| Insert, update, query, retrieve, or delete vectors | [API routes](api.md) |
| Generate embeddings, build RAG, or partition tenant data | [Patterns](patterns.md) |
| Diagnose missing matches, metadata, or rejected requests | [Gotchas](gotchas.md) |

## Decisions to make first

- Use a consistent embedding model and preprocessing for stored vectors and queries. Matching dimensions alone does not make different models' embeddings compatible.
- Choose dimensions from the embedding output and a distance metric appropriate to that model. Changing either requires a new index; check [index configuration and scoring semantics](https://developers.cloudflare.com/vectorize/best-practices/create-indexes/index.md) before choosing thresholds.
- Plan filterable metadata before ingestion. Adding an index later requires re-upserting existing vectors to index that metadata; see [metadata filtering](https://developers.cloudflare.com/vectorize/reference/metadata-filtering/index.md).
- A namespace partitions search; your application must authorize access and derive tenant scope from trusted identity. See [tenant patterns](patterns.md).
- Design for asynchronous mutation visibility rather than assuming a completed write is already searchable. See [mutation semantics](https://developers.cloudflare.com/vectorize/reference/client-api/index.md).

---

### Overview (`packages/autoskills/skills-registry/cloudflare/references/waf/README.md`)

# Cloudflare WAF

Use this reference for managed protection, custom request policies, rate limiting, and investigation of blocked traffic. Read the relevant developer documentation before implementing; it owns schemas, expressions, ruleset IDs, phase order, and plan availability.

| Task | Start here |
|------|------------|
| Choose and enable WAF protections | [Get started](https://developers.cloudflare.com/waf/get-started/index.md) |
| Deploy managed protection | [Managed rules deployment](https://developers.cloudflare.com/waf/managed-rules/deploy-api/index.md) |
| Match application-specific requests | [Custom rules](https://developers.cloudflare.com/waf/custom-rules/create-api/index.md) |
| Limit request volume | [Rate limiting](https://developers.cloudflare.com/waf/rate-limiting-rules/create-api/index.md) |
| Understand score-based detection | [Attack score](https://developers.cloudflare.com/waf/detections/attack-score/index.md) |
| Diagnose blocked or unmitigated requests | [Managed rules troubleshooting](https://developers.cloudflare.com/waf/managed-rules/troubleshooting/index.md) |

Identify the target account or zone and inspect existing rules before planning a change. Keep the requested traffic scope explicit, especially for exceptions and account-wide deployments.

## Reading Order

1. [configuration.md](configuration.md) — deployment method and existing configuration.
2. [api.md](api.md) — API workflows and expression references.
3. [patterns.md](patterns.md) — choose a protection or exception workflow.
4. [gotchas.md](gotchas.md) — diagnose ordering, scope, and false positives.

---

### Overview (`packages/autoskills/skills-registry/cloudflare/references/workerd/README.md`)

# Workerd Runtime

V8-based JS/Wasm runtime powering Cloudflare Workers. Use as app server, dev tool, or HTTP proxy.

## ⚠️ IMPORTANT SECURITY NOTICE
**workerd is NOT a hardened sandbox.** Do not run untrusted code. It's designed for deploying YOUR code locally/self-hosted, not multi-tenant SaaS. Cloudflare production adds security layers not present in open-source workerd.

## Decision Tree: When to Use What

**95% of users:** Use Wrangler
- Local development: `wrangler dev` (uses workerd internally)
- Deployment: `wrangler deploy` (deploys to Cloudflare)
- Types: `wrangler types` (generates TypeScript types)

**Use raw workerd directly only if:**
- Self-hosting Workers runtime in production
- Embedding runtime in C++ application
- Custom tooling/testing infrastructure
- Debugging workerd-specific behavior

**Never use workerd for:**
- Running untrusted/user-submitted code
- Multi-tenant isolation (not hardened)
- Production without additional security layers

## Key Features
- **Standards-based**: Fetch API, Web Crypto, Streams, WebSocket
- **Nanoservices**: Service bindings with local call performance
- **Capability security**: Explicit bindings prevent SSRF
- **Backwards compatible**: Version = max compat date supported

## Architecture
```
Config (workerd.capnp)
├── Services (workers/endpoints)
├── Sockets (HTTP/HTTPS listeners)
└── Extensions (global capabilities)
```

## Quick Start
```bash
workerd serve config.capnp
workerd compile config.capnp myConfig -o binary
workerd test config.capnp
```

## Platform Support & Beta Status

| Platform | Status | Notes |
|----------|--------|-------|
| Linux (x64) | Stable | Primary platform |
| macOS (x64/ARM) | Stable | Full support |
| Windows | Beta | Use WSL2 for best results |
| Linux (ARM64) | Experimental | Limited testing |

workerd is in **active development**. Breaking changes possible. Pin versions in production.

## Core Concepts
- **Service**: Named endpoint (worker/network/disk/external)
- **Binding**: Capability-based resource access (KV/DO/R2/services)
- **Compatibility date**: Feature gate (always set!)
- **Modules**: ES modules (recommended) or service worker syntax

## Reading Order (Progressive Disclosure)

**Start here:**
1. This README (overview, decision tree)
2. [patterns.md](./patterns.md) - Common workflows, framework examples

**When you need details:**
3. [configuration.md](./configuration.md) - Config format, services, bindings
4. [api.md](./api.md) - Runtime APIs, TypeScript types
5. [gotchas.md](./gotchas.md) - Common errors, debugging

## Related References
- [workers](https://developers.cloudflare.com/workers/index.md) - Workers runtime API documentation
- [miniflare](../miniflare/) - Testing tool built on workerd
- [wrangler](https://developers.cloudflare.com/workers/wrangler/index.md) - CLI that uses workerd for local dev

---

### Overview (`packages/autoskills/skills-registry/cloudflare/references/workers-ai/README.md`)

# Cloudflare Workers AI

Use Workers AI for managed model inference from Workers or an external service. Fetch the relevant documentation before choosing a model or writing integration code; model availability, schemas, capabilities, limits, and prices change independently.

## Choose a model

Start with the [model catalog](https://developers.cloudflare.com/workers-ai/models/index.md) and open the selected model's page for its exact identifier, input/output schema, context window, and supported features. Compare candidates on the user's task, language, quality requirements, latency, and [current pricing](https://developers.cloudflare.com/workers-ai/platform/pricing/index.md). Evaluate with representative inputs rather than treating model size as a quality or cost ranking.

For tool use, streaming, or structured output, confirm support for the selected model and integration. For embeddings, check output dimensions and compatibility with the existing index; changing the model may require re-embedding stored documents, even if dimensions match.

## Route by task

- [configuration.md](./configuration.md): choose an integration, configure bindings and types, or set up development.
- [api.md](./api.md): find inference schemas, streaming, tool calling, and structured output.
- [patterns.md](./patterns.md): choose direct generation or RAG, and find integration examples.
- [gotchas.md](./gotchas.md): diagnose binding, schema, limit, pricing, and SDK issues.

If a topic is missing, use the [Workers AI documentation index](https://developers.cloudflare.com/workers-ai/llms.txt) to find its current page.

## Related products

- [Vectorize](../vectorize/): vector storage and retrieval.
- [AI Gateway](../ai-gateway/): inference analytics, caching, and request controls.
- [Workers](https://developers.cloudflare.com/workers/index.md): runtime and application hosting.

---

### Overview (`packages/autoskills/skills-registry/cloudflare/references/workflows/README.md`)

# Cloudflare Workflows

Use Workflows for durable, multi-step jobs that must retry, wait, and resume without losing completed work. An instance is one execution; steps define persistence and retry boundaries.

Fetch the relevant current documentation before implementing. API shapes, configuration, testing helpers, limits, and examples belong in the docs rather than in this reference.

- **Start a project:** [Build your first Workflow](https://developers.cloudflare.com/workflows/get-started/guide/index.md) covers scaffolding, configuration, deployment, and a first instance.
- **Design durable execution:** [Rules of Workflows](https://developers.cloudflare.com/workflows/build/rules-of-workflows/index.md) covers step boundaries, replay, state, and idempotency.
- **Implement or manage an instance:** [Workers API](https://developers.cloudflare.com/workflows/build/workers-api/index.md) covers steps, instance operations, parameters, and return types.
- **Check capacity and cost:** fetch [limits](https://developers.cloudflare.com/workflows/reference/limits/index.md) and [pricing](https://developers.cloudflare.com/workflows/reference/pricing/index.md) for the target plan.

## In This Reference

- [configuration.md](./configuration.md) — setup, bindings, retry configuration, and local development
- [api.md](./api.md) — steps, instance lifecycle, events, CLI, and REST operations
- [patterns.md](./patterns.md) — design decisions, examples, orchestration, and tests
- [gotchas.md](./gotchas.md) — failures, timeouts, replay, and capacity investigation

## See Also

- [Durable Objects](https://developers.cloudflare.com/durable-objects/index.md) — stateful coordination
- [Queues](../queues/README.md) — asynchronous message delivery
- [Workers](https://developers.cloudflare.com/workers/index.md) — application entry points that trigger instances

---

### Overview (`packages/autoskills/skills-registry/cloudflare/references/zaraz/README.md`)

# Cloudflare Zaraz

Expert guidance for Cloudflare Zaraz - server-side tag manager for loading third-party tools at the edge.

## What is Zaraz?

Zaraz offloads third-party scripts (analytics, ads, chat, marketing) to Cloudflare's edge, improving site speed, privacy, and security. Zero client-side performance impact.

**Core Concepts:**
- **Server-side execution** - Scripts run on Cloudflare, not user's browser
- **Single HTTP request** - All tools loaded via one endpoint
- **Privacy-first** - Control data sent to third parties
- **No client-side JS overhead** - Minimal browser impact

## Quick Start

1. Navigate to domain > Zaraz in Cloudflare dashboard
2. Click "Start setup"
3. Add tools (Google Analytics, Facebook Pixel, etc.)
4. Configure triggers (when tools fire)
5. Add tracking code to your site:

```javascript
// Track page view
zaraz.track('page_view');

// Track custom event
zaraz.track('button_click', { button_id: 'cta' });

// Set user properties
zaraz.set('userId', 'user_123');
```

## When to Use Zaraz

**Use Zaraz when:**
- Adding multiple third-party tools (analytics, ads, marketing)
- Site performance is critical (no client-side JS overhead)
- Privacy compliance required (GDPR, CCPA)
- Non-technical teams need to manage tools

**Use Workers directly when:**
- Building custom server-side tracking logic
- Need full control over data processing
- Integrating with complex backend systems
- Zaraz's tool library doesn't meet needs

## In This Reference

| File | Purpose | When to Read |
|------|---------|--------------|
| [api.md](./api.md) | Web API, zaraz object, consent methods | Implementing tracking calls |
| [configuration.md](./configuration.md) | Dashboard setup, triggers, tools | Initial setup, adding tools |
| [patterns.md](./patterns.md) | SPA, e-commerce, Worker integration | Best practices, common scenarios |
| [gotchas.md](./gotchas.md) | Troubleshooting, limits, pitfalls | Debugging issues |

## Reading Order by Task

| Task | Files to Read |
|------|---------------|
| Add analytics to site | README → configuration.md |
| Track custom events | README → api.md |
| Debug tracking issues | gotchas.md |
| SPA tracking | api.md → patterns.md (SPA section) |
| E-commerce tracking | api.md#ecommerce → patterns.md#ecommerce |
| Worker integration | patterns.md#worker-integration |
| GDPR compliance | api.md#consent → configuration.md#consent |

## Decision Tree

```
What do you need?

├─ Track events in browser → api.md
│   ├─ Page views, clicks → zaraz.track()
│   ├─ User properties → zaraz.set()
│   └─ E-commerce → zaraz.ecommerce()
│
├─ Configure Zaraz → configuration.md
│   ├─ Add GA4/Facebook → tools setup
│   ├─ When tools fire → triggers
│   └─ GDPR consent → consent purposes
│
├─ Integrate with Workers → patterns.md#worker-integration
│   ├─ Enrich context → Context Enrichers
│   └─ Inject tracking → HTML rewriting
│
└─ Debug issues → gotchas.md
    ├─ Events not firing → troubleshooting
    ├─ Consent issues → consent debugging
    └─ Performance → debugging tools
```

## Key Features

- **100+ Pre-built Tools** - GA4, Facebook, Google Ads, TikTok, etc.
- **Zero Client Impact** - Runs at Cloudflare's edge, not browser
- **Privacy Controls** - Consent management, data filtering
- **Custom Tools** - Build Managed Components for proprietary systems
- **Worker Integration** - Enrich context, compute dynamic values
- **Debug Mode** - Real-time event inspection

## Reference

- [Zaraz Docs](https://developers.cloudflare.com/zaraz/index.md)
- [Web API](https://developers.cloudflare.com/zaraz/web-api/index.md)
- [Managed Components](https://developers.cloudflare.com/zaraz/advanced/load-custom-managed-component/index.md)

---

This skill focuses exclusively on Zaraz. For Workers development, see `cloudflare-workers` skill.

---

### Overview (`packages/autoskills/skills-registry/azure-deploy/references/recipes/azcli/README.md`)

# Azure CLI Deploy Recipe

Deploy to Azure using Azure CLI.

## Prerequisites

- `az` CLI installed → Run `mcp_azure_mcp_extension_cli_install` with `cli-type: az` if needed
- `.azure/deployment-plan.md` exists with status `Validated`
- Bicep/ARM templates exist in `infra/`
- **Subscription and location confirmed** → See [Pre-Deploy Checklist](../../pre-deploy-checklist.md)

## Workflow

| Step | Task | Command |
|------|------|---------|
| 1 | **[Pre-deploy checklist](../../pre-deploy-checklist.md)** | Confirm subscription/location with user |
| 2 | Deploy infrastructure | `az deployment sub create` |
| 3 | Deploy application | Service-specific commands |
| 4 | Verify | `az resource list` |
| 5 | **Report** | Present deployed endpoint URLs to the user — see [Verification](verify.md) |

## Infrastructure Deployment

### Subscription-Level (Recommended)

```bash
az deployment sub create \
  --location eastus2 \
  --template-file ./infra/main.bicep \
  --parameters environmentName=dev
```

### Resource Group Level

```bash
az group create --name rg-myapp-dev --location eastus2

az deployment group create \
  --resource-group rg-myapp-dev \
  --template-file ./infra/main.bicep \
  --parameters environmentName=dev
```

## Application Deployment

### Container Apps

```bash
az containerapp update \
  --name <app-name> \
  --resource-group <rg-name> \
  --image <acr-name>.azurecr.io/myapp:latest
```

### App Service

```bash
az webapp deploy \
  --name <app-name> \
  --resource-group <rg-name> \
  --src-path ./publish.zip
```

### Azure Functions

```bash
func azure functionapp publish <function-app-name>
```

## References

- [Verification steps](./verify.md)
- [Error handling](./errors.md)

---

### Overview (`packages/autoskills/skills-registry/azure-deploy/references/recipes/azd/README.md`)

# AZD Deploy Recipe

Deploy to Azure using Azure Developer CLI (azd).

> 💡 **Note:** azd supports both Bicep and Terraform as IaC providers. The deployment workflow is identical regardless of which you use.

## Prerequisites

- `azd` CLI installed → Run `mcp_azure_mcp_extension_cli_install` with `cli-type: azd` if needed
- `.azure/deployment-plan.md` exists with status `Validated`
- `azure.yaml` exists and validated
- Infrastructure files exist (Bicep: `infra/main.bicep`, Terraform: `infra/*.tf`)
- **AZD environment configured** → Done in azure-validate
- **Subscription and location confirmed** → See [Pre-deploy Checklist](../../pre-deploy-checklist.md)

## Workflow

| Step | Task | Command |
|------|------|---------|
| 1 | **Verify environment** | `azd env get-values` — Confirm AZURE_SUBSCRIPTION_ID and AZURE_LOCATION set |
| 2 | **Provision infrastructure** | `azd provision --no-prompt` |
| 3 | **RBAC health check** *(Container Apps + ACR only)* | After provisioning, verify `AcrPull` role has propagated before deploying — see [Pre-Deploy Checklist](../../pre-deploy-checklist.md#container-apps--acr--pre-deploy-rbac-health-check) |
| 4 | **Deploy application** | `azd deploy --no-prompt` |
| 5 | **Post-Deploy** | [Post-Deployment Steps](post-deployment.md) — If using SQL + managed identity |
| 6 | **Verify** | See [Verification](verify.md) |
| 7 | **Report** | Present deployed endpoint URLs to the user — see [Verification](verify.md) Step 3 |

> ⚠️ **Important:** For Container Apps that use a managed identity to pull from ACR, always run `azd provision` and `azd deploy` as **separate steps** (not `azd up`) and complete the RBAC health check between them. This ensures the managed identity `AcrPull` role assignment has propagated before the Container App revision attempts to pull the image.

> ⚠️ **Important:** For .NET Aspire projects or projects using azd "limited mode" (no explicit `infra/` folder), verify that `azd provision` populated all required environment variables. If `azd deploy` fails with errors about missing `AZURE_CONTAINER_REGISTRY_ENDPOINT`, `AZURE_CONTAINER_REGISTRY_MANAGED_IDENTITY_ID`, or `MANAGED_IDENTITY_CLIENT_ID`, see [Error Handling](errors.md#missing-container-registry-variables) for the resolution.

## Common Mistakes

| ❌ Wrong | Why It Fails |
|----------|-------------|
| `azd up --location eastus2` | `--location` is not a valid flag for `azd up` |
| `azd up` without `azd env new` | Prompts for input, fails with `--no-prompt` |
| `mkdir .azure` then `azd env new --no-prompt` | Creates env folder structure incorrectly |
| Setting AZURE_LOCATION without checking RG | "Invalid resource group location" if RG exists elsewhere |
| Ignoring `azd-service-name` tag conflicts in same RG | "found '2' resources tagged with..." error |
| `language: html` or `language: static` | Not valid - use `language: js` with `dist: .` for static sites |

## Deployment Commands

> ⚠️ `azd up` takes 5-15 min. Run with output **streamed visibly to the user** — do NOT run silently or suppress output. The user must see provisioning progress in real time.

### Full Deployment

Provisions infrastructure AND deploys application:

```bash
azd up --no-prompt
```

### Infrastructure Only

```bash
azd provision --no-prompt
```

### Application Only

Deploy code to existing infrastructure:

```bash
azd deploy --no-prompt
```

### Single Service

```bash
azd deploy api --no-prompt
```

## References

- [Pre-deploy Checklist](../../pre-deploy-checklist.md) — **REQUIRED**
- [Post-Deployment Steps](post-deployment.md) — SQL + managed identity setup
- [Azure Functions Deployment](functions-deploy.md)
- [Verification](verify.md)
- [Error Handling](errors.md)

---

### Overview (`packages/autoskills/skills-registry/azure-deploy/references/recipes/bicep/README.md`)

# Bicep Deploy Recipe

Deploy to Azure using Bicep templates directly.

## Prerequisites

- `az` CLI installed with Bicep extension
- `.azure/deployment-plan.md` exists with status `Validated`
- Bicep templates exist in `infra/`
- **Subscription and location confirmed** → See [Pre-Deploy Checklist](../../pre-deploy-checklist.md)

## Workflow

| Step | Task | Command |
|------|------|---------|
| 1 | **[Pre-deploy checklist](../../pre-deploy-checklist.md)** | Confirm subscription/location with user |
| 2 | Build (optional) | `az bicep build --file main.bicep` |
| 3 | Deploy | `az deployment sub create` |
| 4 | Verify | `az resource list` |
| 5 | **Report** | Present deployed endpoint URLs to the user — see [Verification](verify.md) |

## Deployment Commands

### Subscription-Level Deployment

```bash
az deployment sub create \
  --location eastus2 \
  --template-file ./infra/main.bicep \
  --parameters ./infra/main.parameters.json
```

### Resource Group Deployment

```bash
az deployment group create \
  --resource-group rg-myapp-dev \
  --template-file ./infra/main.bicep \
  --parameters ./infra/main.parameters.json
```

### With Inline Parameters

```bash
az deployment sub create \
  --location eastus2 \
  --template-file ./infra/main.bicep \
  --parameters environmentName=dev location=eastus2
```

### What-If (Preview Changes)

```bash
az deployment sub what-if \
  --location eastus2 \
  --template-file ./infra/main.bicep \
  --parameters environmentName=dev
```

## Get Deployment Outputs

```bash
az deployment sub show \
  --name main \
  --query properties.outputs
```

## References

- [Verification steps](./verify.md)
- [Error handling](./errors.md)

## MCP Tools

| Tool | Purpose |
|------|---------|
| `mcp_bicep_get_bicep_best_practices` | Best practices |
| `mcp_bicep_get_az_resource_type_schema` | Resource schemas |
| `mcp_bicep_list_avm_metadata` | Azure Verified Modules |

## AVM Verification Before Deploy

Before running deployment commands, verify generated templates followed AVM-first module selection:

1. AVM Bicep Pattern Modules (prefer AVM+AZD patterns)
2. AVM Bicep Resource Modules
3. AVM Bicep Utility Modules

If no AVM+AZD pattern module is available, fallback must remain within AVM modules (resource -> utility).

## Cleanup (DESTRUCTIVE)

```bash
az group delete --name <rg-name> --yes
```

⚠️ Permanently deletes ALL resources in the group.

---

### Overview (`packages/autoskills/skills-registry/azure-deploy/references/recipes/cicd/README.md`)

# CI/CD Deploy Recipe

Deploy to Azure using automated pipelines.

## Prerequisites

- `.azure/deployment-plan.md` exists with status `Validated`
- Azure Service Principal or federated credentials configured
- Pipeline file exists (`.github/workflows/` or `azure-pipelines.yml`)

## GitHub Actions

| Example | Description |
|---------|-------------|
| [github-azd.yml](examples/github-azd.yml) | AZD deployment workflow |
| [github-bicep.yml](examples/github-bicep.yml) | Bicep infrastructure deployment |

## Azure DevOps

| Example | Description |
|---------|-------------|
| [azdo-azd.yml](examples/azdo-azd.yml) | Basic AZD pipeline |
| [azdo-multistage.yml](examples/azdo-multistage.yml) | Multi-stage with approvals |

## Setup Requirements

### GitHub Actions

1. Create Azure Service Principal with federated credentials
2. Add secrets: `AZURE_CLIENT_ID`, `AZURE_TENANT_ID`, `AZURE_SUBSCRIPTION_ID`
3. Add variables: `AZURE_ENV_NAME`, `AZURE_LOCATION`
4. Create environments with protection rules

### Azure DevOps

1. Create Service Connection to Azure
2. Create Variable Groups per environment
3. Create Environments with approval gates

## References

- [Verification steps](./verify.md)
- [Error handling](./errors.md)

---

### Overview (`packages/autoskills/skills-registry/azure-deploy/references/recipes/terraform/README.md`)

# Terraform Deploy Recipe

Deploy to Azure using Terraform.

## Prerequisites

- Terraform CLI installed
- `.azure/deployment-plan.md` exists with status `Validated`
- Terraform initialized (`terraform init`)
- Plan validated (`terraform plan`)
- **Subscription and location confirmed** → See [Pre-Deploy Checklist](../../pre-deploy-checklist.md)

## Workflow

| Step | Task | Command |
|------|------|---------|
| 1 | **[Pre-deploy checklist](../../pre-deploy-checklist.md)** | Confirm subscription/location with user |
| 2 | Select workspace | `terraform workspace select <env>` |
| 3 | Apply | `terraform apply tfplan` |
| 4 | Get outputs | `terraform output` |
| 5 | Deploy app | Service-specific commands |
| 6 | **Report** | Present deployed endpoint URLs to the user — see [Verification](verify.md) |

## Deployment Commands

### Apply with Plan File (Recommended)

```bash
terraform plan -out=tfplan
terraform apply tfplan
```

### Auto-Approve (CI/CD)

```bash
terraform apply -auto-approve
```

### With Variables

```bash
terraform apply \
  -var="environment=prod" \
  -var="location=westus2" \
  -auto-approve
```

### Target Specific Resource

```bash
terraform apply -target=azurerm_container_app.api
```

## Get Outputs

```bash
terraform output
terraform output -json
terraform output api_url
```

## Application Deployment

After infrastructure is deployed:

### Container Apps (Two-Phase Deployment)

Container Apps with ACR require a two-phase flow because the app image doesn't exist in ACR during initial `terraform apply`. See the **azure-prepare** skill's `references/services/container-apps/terraform.md` for the full pattern.

```bash
ACR_NAME=$(terraform output -raw acr_name)
ACR_SERVER=$(terraform output -raw acr_login_server)
APP_NAME=$(terraform output -raw container_app_name)
RG_NAME=$(terraform output -raw resource_group_name)

# 1. Build and push the application image to ACR
az acr build --registry $ACR_NAME --image myapp:latest ./src/api

# 2. Configure the registry/identity link (managed identity, no passwords)
az containerapp registry set \
  --name $APP_NAME \
  --resource-group $RG_NAME \
  --server $ACR_SERVER \
  --identity system

# 3. Update the Container App to use the real image
az containerapp update \
  --name $APP_NAME \
  --resource-group $RG_NAME \
  --image $ACR_SERVER/myapp:latest
```

**PowerShell:**
```powershell
$AcrName = terraform output -raw acr_name
$AcrServer = terraform output -raw acr_login_server
$AppName = terraform output -raw container_app_name
$RgName = terraform output -raw resource_group_name

az acr build --registry $AcrName --image myapp:latest ./src/api

az containerapp registry set `
  --name $AppName `
  --resource-group $RgName `
  --server $AcrServer `
  --identity system

az containerapp update `
  --name $AppName `
  --resource-group $RgName `
  --image "$AcrServer/myapp:latest"
```

> ⚠️ **Warning:** Step 2 requires the `AcrPull` role assignment to have propagated (1–5 minutes). If the update fails, wait and retry. See the [RBAC propagation health check](../../pre-deploy-checklist.md#container-apps--acr--pre-deploy-rbac-health-check).

## References

- [Verification steps](./verify.md)
- [Error handling](./errors.md)

---

--- METRICS ---
- Files Extracted: 111
- Estimated Token Budget: ~94095 tokens
- Canonical Reference: https://codewiki.google/github.com/midudev/autoskills
