---
name: go
description: "Language-specific super-code guidelines for go."
risk: safe
source: community
date_added: "2026-06-16"
---
# Go: Idiomatic Efficiency Reference

## When to Use
- Use this skill when the task matches this description: Language-specific super-code guidelines for go.

## Table of Contents
1. [Error Handling](#errors)
2. [Slices & Maps](#slices)
3. [Goroutines & Channels](#concurrency)
4. [Structs & Interfaces](#structs)
5. [Functions & Closures](#functions)
6. [Anti-patterns specific to Go](#antipatterns)

---

## 1. Error Handling {#errors}

```go
// ❌ Ignoring errors
result, _ := os.Open(path)

// ✅ — always handle; only use _ when error is provably irrelevant
result, err := os.Open(path)
if err != nil {
    return fmt.Errorf("open %s: %w", path, err)
}
```

```go
// ❌ Redundant error variable
err := doA()
if err != nil { return err }
err = doB()
if err != nil { return err }

// ✅ — each :=/:  is fine; this is idiomatic Go. Don't try to "fix" it.
// What you CAN simplify: collapsing to one-liners where the if body is a single return
if err := doA(); err != nil { return err }
if err := doB(); err != nil { return err }
```

```go
// ❌ Custom error type with no added value
type MyError struct{ msg string }
func (e MyError) Error() string { return e.msg }

// ✅ — use errors.New or fmt.Errorf unless callers need to inspect type
var ErrNotFound = errors.New("not found")
return fmt.Errorf("lookup %q: %w", key, ErrNotFound)
```

**Wrap errors with `%w` (not `%v`) so callers can use `errors.Is` / `errors.As`.**

---

## 2. Slices & Maps {#slices}

```go
// ❌ Growing a slice without pre-allocation when size is known
var result []string
for _, item := range items {
    result = append(result, item.Name)
}

// ✅
result := make([]string, 0, len(items))
for _, item := range items {
    result = append(result, item.Name)
}
```

```go
// ❌ Manual existence check before map write
if _, ok := m[key]; !ok {
    m[key] = []string{}
}
m[key] = append(m[key], value)

// ✅ — append to nil slice is valid Go
m[key] = append(m[key], value)
```

```go
// ❌ Copying a map by assignment (copies reference)
copy := original

// ✅
copy := make(map[K]V, len(original))
for k, v := range original { copy[k] = v }
```

---

## 3. Goroutines & Channels {#concurrency}

```go
// ❌ Fire-and-forget goroutine with no lifecycle
go doWork()

// ✅ — use errgroup or WaitGroup to track completion
var wg sync.WaitGroup
wg.Add(1)
go func() {
    defer wg.Done()
    doWork()
}()
wg.Wait()
```

```go
// ❌ Unbuffered channel causing unnecessary goroutine block
ch := make(chan Result)
go func() { ch <- compute() }()
result := <-ch

// ✅ — for single-result, buffered channel avoids goroutine leak if receiver exits early
ch := make(chan Result, 1)
go func() { ch <- compute() }()
result := <-ch
```

```go
// ❌ select with a busy-wait default
for {
    select {
    case v := <-ch:
        process(v)
    default:
        // spin
    }
}

// ✅ — blocking select unless you genuinely need non-blocking
for v := range ch {
    process(v)
}
```

**Use `golang.org/x/sync/errgroup` for fan-out with error collection.**

---

## 4. Structs & Interfaces {#structs}

```go
// ❌ Large interface
type Storage interface {
    Get(key string) ([]byte, error)
    Set(key string, val []byte) error
    Delete(key string) error
    List(prefix string) ([]string, error)
    // ... 10 more methods
}

// ✅ — small, composable interfaces
type Getter interface { Get(key string) ([]byte, error) }
type Setter interface { Set(key string, val []byte) error }
type Storage interface { Getter; Setter }
```

```go
// ❌ Returning concrete struct from constructor (ties callers to implementation)
func NewStore() *RedisStore { ... }

// ✅ — return interface when you have or anticipate multiple implementations
func NewStore() Storage { return &RedisStore{...} }
```

```go
// ❌ Pointer receiver for tiny value types
func (p *Point) X() float64 { return p.x }

// ✅ — value receiver for small immutable types
func (p Point) X() float64 { return p.x }
```

**Rule: pointer receiver when method mutates state OR struct is large (>3 fields of non-trivial size). Value receiver otherwise.**

---

## 5. Functions & Closures {#functions}

```go
// ❌ Named return values used just to avoid a variable declaration
func divide(a, b float64) (result float64, err error) {
    result = a / b
    return
}

// ✅ — named returns are worth it only for deferred mutation or documentation
func divide(a, b float64) (float64, error) {
    if b == 0 { return 0, errors.New("division by zero") }
    return a / b, nil
}
```

```go
// ❌ Closure capturing loop variable (classic Go bug, fixed in Go 1.22+)
// Pre-1.22: each goroutine captures the same i
for i := 0; i < n; i++ {
    go func() { use(i) }()
}

// ✅ (Go <1.22 — pass as parameter)
for i := 0; i < n; i++ {
    go func(i int) { use(i) }(i)
}
// Go 1.22+: loop variable scoped per iteration, so the original is safe
```

---

## 6. Anti-patterns specific to Go {#antipatterns}

| Anti-pattern | Preferred |
|---|---|
| `if err != nil { return err }` repeated 5+ times | acceptable — it's idiomatic Go |
| `panic` for expected errors | `return err` |
| `init()` with side effects | explicit initialization in `main` or constructors |
| `interface{}` / `any` without generics | use generics (Go 1.18+) or typed interfaces |
| Mutex field not adjacent to the data it protects | put `mu` directly above the field it guards |
| Channel of channels | usually a sign of over-engineering; redesign |
| `time.Sleep` in tests | use `testing` hooks or channels for synchronization |
| Exported types with unexported fields (when fields are the whole point) | `record`-style structs with all-exported fields |
| `log.Fatal` outside `main` | return errors up the stack |

## Limitations
- These are language-specific guidelines and do not cover overall architectural decisions.
- Over-compression might reduce readability; apply judgement.


---
name: go-concurrency-patterns
description: "Master Go concurrency with goroutines, channels, sync primitives, and context. Use when building concurrent Go applications, implementing worker pools, or debugging race conditions."
risk: safe
source: community
date_added: "2026-02-27"
---

# Go Concurrency Patterns

Production patterns for Go concurrency including goroutines, channels, synchronization primitives, and context management.

## Use this skill when

- Building concurrent Go applications
- Implementing worker pools and pipelines
- Managing goroutine lifecycles
- Using channels for communication
- Debugging race conditions
- Implementing graceful shutdown

## Do not use this skill when

- The task is unrelated to go concurrency patterns
- You need a different domain or tool outside this scope

## Instructions

- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.

## Resources

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

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


---
name: go-in-depth
description: Go in depth harness — fan-out web searches, fetch sources, adversarially verify claims, synthesize a cited report.
risk: safe
source: self
source_type: self
date_added: "2026-07-07"
---

# Go In Depth

## Overview

Go in depth harness — fan-out web searches, fetch sources, adversarially verify claims, synthesize a cited report. Run the "go-in-depth" workflow.

## When to Use

When the user wants a deep, multi-source, fact-checked research report on any topic. BEFORE invoking, check if the question is specific enough to research directly — if underspecified (e.g., "what car to buy" without budget/use-case/region), ask 2-3 clarifying questions to narrow scope. Then pass the refined question as args, weaving the answers in.

## How It Works

Phases:
- Scope: Decompose question (from args) into 5 search angles
- Search: 5 parallel WebSearch agents, one per angle
- Fetch: URL-dedup, fetch top 15 sources, extract falsifiable claims
- Verify: 3-vote adversarial verification per claim (need 2/3 refutes to kill)
- Synthesize: Merge semantic dupes, rank by confidence, cite sources

## Examples

### Example 1: Run go-in-depth workflow
```
Workflow({ name: "go-in-depth" })
```

### Example 2: Research with refined question
```
Workflow({ name: "go-in-depth", args: { query: "best hybrid cars under $30k in the US for families" } })
```

### Example 3: Deep dive into a technical concept
```
Workflow({ name: "go-in-depth", args: { query: "how does the transformer architecture handle positional encoding?" } })
```

### Example 4: Fact-checking a medical claim
```
Workflow({ name: "go-in-depth", args: { query: "efficacy of intermittent fasting for long-term weight loss in adults" } })
```

## Workflow Script

[scripts/workflow-script.js](scripts/workflow-script.js)

## Limitations

- **Slow execution**: Multi-agent searches, fetching, and 3-vote verification take significant time. Not for quick facts.
- **Context intensive**: Analyzing 15 full sources uses large context limits.
- **Synthesis risks**: May struggle if source material is weak or equally conflicting.


---
name: go-playwright
description: "Expert capability for robust, stealthy, and efficient browser automation using Playwright Go."
risk: safe
source: "https://github.com/playwright-community/playwright-go"
date_added: "2026-02-27"
---

# Playwright Go Automation Expert

## Overview
This skill provides a comprehensive framework for writing high-performance, production-grade browser automation scripts using `github.com/playwright-community/playwright-go`. It enforces architectural best practices (contexts over instances), robust error handling, structured logging (Zap), and advanced human-emulation techniques to bypass anti-bot systems.

## When to Use This Skill
- Use when the user asks to "scrape," "automate," or "test" a website using Go.
- Use when the target site has complex dynamic content (SPA, React, Vue) requiring a real browser.
- Use when the user mentions "stealth," "avoiding detection," "cloudflare," or "human-like" behavior.
- Use when debugging existing Playwright scripts.

## Safety & Risk
**Risk Level: 🔵 Safe**

- **Sandboxed Execution:** Browser contexts are isolated; they do not persist data to the host machine unless explicitly saved.
- **Resource Management:** Designed to close browsers and contexts via `defer` to prevent memory leaks.
- **No External State-Change:** Default behavior is read-only (scraping/testing) unless the script is explicitly designed to submit forms or modify data.

## Limitations
- **Environment Dependencies:** Requires Playwright drivers and browsers to be installed (`go run github.com/playwright-community/playwright-go/cmd/playwright@latest install --with-deps`).
- **Resource Intensity:** Launching full browser instances (even headless) consumes significant RAM/CPU. Use single-browser/multi-context architecture.
- **Bot Detection:** While this skill includes stealth techniques, extremely strict anti-bot systems (e.g., rigorous Cloudflare settings) may still detect automation.
- **CAPTCHAs:** Does not include built-in CAPTCHA solving capabilities.

## Strategic Implementation Guidelines

### 1. Architecture: Contexts vs. Browsers
**CRITICAL:** Never launch a new `Browser` instance for every task.
- **Pattern:** Launch the `Browser` *once* (singleton). Create a new `BrowserContext` for each distinct session or task.
- **Why:** Contexts are lightweight and created in milliseconds. Browsers take seconds to launch.
- **Isolation:** Contexts provide complete isolation (cookies, cache, storage) without the overhead of a new process.

### 2. Logging & Observability
- **Library:** Use `go.uber.org/zap` exclusively.
- **Rule:** Do not use `fmt.Println`.
- **Modes:**
  - **Dev:** `zap.NewDevelopment()` (Console friendly)
  - **Prod:** `zap.NewProduction()` (JSON structured)
- **Traceability:** Log every navigation, click, and input with context fields (e.g., `logger.Info("clicking button", zap.String("selector", sel))`).

### 3. Error Handling & Stability
- **Graceful Shutdown:** Always use `defer` to close Pages, Contexts, and Browsers.
- **Panic Recovery:** Wrap critical automation routines in a safe runner that recovers panics and logs the stack trace.
- **Timeouts:** Never rely on default timeouts. Set explicit timeouts (e.g., `playwright.PageClickOptions{Timeout: playwright.Float(5000)}`).

### 4. Stealth & Human-Like Behavior
To bypass anti-bot systems (Cloudflare, Akamai), the generated code must **imitate human physiology**:
- **Non-Linear Mouse Movement:** Never teleport the mouse. Implement a helper that moves the mouse along a Bezier curve with random jitter.
- **Input Latency:** never use `Fill()`. Use `Type()` with random delays between keystrokes (50ms–200ms).
- **Viewport Randomization:** Randomize the viewport size slightly (e.g., 1920x1080 ± 15px) to avoid fingerprinting.
- **Behavioral Noise:** Randomly scroll, focus/unfocus the window, or hover over irrelevant elements ("idling") during long waits.
- **User-Agent:** Rotate User-Agents for every new Context.

### 5. Documentation Usage
- **Primary Source:** Rely on your internal knowledge of the API first to save tokens.
- **Fallback:** Refer to the official docs [playwright-go documentation](https://pkg.go.dev/github.com/playwright-community/playwright-go#section-documentation) ONLY if:
  - You encounter an unknown error.
  - You need to implement complex network interception or authentication flows.
  - The API has changed significantly.

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

### Summary Checklist for Agent
 - Is Debug Mode on? -> `Headless=false`, `SlowMo=100+`.
 - Is it a new user identity? -> `NewContext`, apply new Proxy, rotate `User-Agent`.
 - Is the action critical? -> Wrap in `SafeAction` with Zap logging.
 - Is the target guarded (Cloudflare/Akamai)? -> Enable `HumanType`, `BezierMouse`, and Stealth Scripts.


---
name: go-rod-master
description: "Comprehensive guide for browser automation and web scraping with go-rod (Chrome DevTools Protocol) including stealth anti-bot-detection patterns."
risk: safe
source: "https://github.com/go-rod/rod"
date_added: "2026-02-27"
---

# Go-Rod Browser Automation Master

## Overview

[Rod](https://github.com/go-rod/rod) is a high-level Go driver built directly on the [Chrome DevTools Protocol](https://chromedevtools.github.io/devtools-protocol/) for browser automation and web scraping. Unlike wrappers around other tools, Rod communicates with the browser natively via CDP, providing thread-safe operations, chained context design for timeouts/cancellation, auto-wait for elements, correct iframe/shadow DOM handling, and zero zombie browser processes.

The companion library [go-rod/stealth](https://github.com/go-rod/stealth) injects anti-bot-detection evasions based on [puppeteer-extra stealth](https://github.com/nichochar/puppeteer-extra/tree/master/packages/extract-stealth-evasions), hiding headless browser fingerprints from detection systems.

## When to Use This Skill

- Use when the user asks to **scrape**, **automate**, or **test** a website using Go.
- Use when the user needs a **headless browser** for dynamic/SPA content (React, Vue, Angular).
- Use when the user mentions **stealth**, **anti-bot**, **avoiding detection**, **Cloudflare**, or **bot detection bypass**.
- Use when the user wants to work with the **Chrome DevTools Protocol (CDP)** directly from Go.
- Use when the user needs to **intercept** or **hijack** network requests in a browser context.
- Use when the user asks about **concurrent browser scraping** or **page pooling** in Go.
- Use when the user is migrating from **chromedp** or **Playwright Go** and wants a simpler API.

## Safety & Risk

**Risk Level: 🔵 Safe**

- **Read-Only by Default:** Default behavior is navigating and reading page content (scraping/testing).
- **Isolated Contexts:** Browser contexts are sandboxed; cookies and storage do not persist unless explicitly saved.
- **Resource Cleanup:** Designed around Go's `defer` pattern — browsers and pages close automatically.
- **No External Mutations:** Does not modify external state unless the script explicitly submits forms or POSTs data.

## Installation

```bash
# Core rod library
go get github.com/go-rod/rod@latest

# Stealth anti-detection plugin (ALWAYS include for production scraping)
go get github.com/go-rod/stealth@latest
```

Rod auto-downloads a compatible Chromium binary on first run. To pre-download:

```bash
go run github.com/nichochar/go-rod.github.io/cmd/launcher@latest
```

## Core Concepts

### Browser Lifecycle

Rod manages three layers: **Browser → Page → Element**.

```go
// Launch and connect to a browser
browser := rod.New().MustConnect()
defer browser.MustClose()

// Create a page (tab)
page := browser.MustPage("https://example.com")

// Find an element
el := page.MustElement("h1")
fmt.Println(el.MustText())
```

### Must vs Error Patterns

Rod provides two API styles for every operation:

| Style | Method | Use Case |
|:------|:-------|:---------|
| **Must** | `MustElement()`, `MustClick()`, `MustText()` | Scripting, debugging, prototyping. Panics on error. |
| **Error** | `Element()`, `Click()`, `Text()` | Production code. Returns `error` for explicit handling. |

**Production pattern:**

```go
el, err := page.Element("#login-btn")
if err != nil {
    return fmt.Errorf("login button not found: %w", err)
}
if err := el.Click(proto.InputMouseButtonLeft, 1); err != nil {
    return fmt.Errorf("click failed: %w", err)
}
```

**Scripting pattern with Try:**

```go
err := rod.Try(func() {
    page.MustElement("#login-btn").MustClick()
})
if errors.Is(err, context.DeadlineExceeded) {
    log.Println("timeout finding login button")
}
```

### Context & Timeout

Rod uses Go's `context.Context` for cancellation and timeouts. Context propagates recursively to all child operations.

```go
// Set a 5-second timeout for the entire operation chain
page.Timeout(5 * time.Second).
    MustWaitLoad().
    MustElement("title").
    CancelTimeout(). // subsequent calls are not bound by the 5s timeout
    Timeout(30 * time.Second).
    MustText()
```

### Element Selectors

Rod supports multiple selector strategies:

```go
// CSS selector (most common)
page.MustElement("div.content > p.intro")

// CSS selector with text regex matching
page.MustElementR("button", "Submit|Send")

// XPath
page.MustElementX("//div[@class='content']//p")

// Search across iframes and shadow DOM (like DevTools Ctrl+F)
page.MustSearch(".deeply-nested-element")
```

### Auto-Wait

Rod automatically retries element queries until the element appears or the context times out. You do not need manual sleeps:

```go
// This will automatically wait until the element exists
el := page.MustElement("#dynamic-content")

// Wait until the element is stable (position/size not changing)
el.MustWaitStable().MustClick()

// Wait until page has no pending network requests
wait := page.MustWaitRequestIdle()
page.MustElement("#search").MustInput("query")
wait()
```

---

## Stealth & Anti-Bot Detection (go-rod/stealth)

> **IMPORTANT:** For any production scraping or automation against real websites, ALWAYS use `stealth.MustPage()` instead of `browser.MustPage()`. This is the single most important step for avoiding bot detection.

### How Stealth Works

The `go-rod/stealth` package injects JavaScript evasions into every new page that:

- **Remove `navigator.webdriver`** — the primary headless detection signal.
- **Spoof WebGL vendor/renderer** — presents real GPU info (e.g., "Intel Inc." / "Intel Iris OpenGL Engine") instead of headless markers like "Google SwiftShader".
- **Fix Chrome plugin array** — reports proper `PluginArray` type with realistic plugin count.
- **Patch permissions API** — returns `"prompt"` instead of bot-revealing values.
- **Set realistic languages** — reports `en-US,en` instead of empty arrays.
- **Fix broken image dimensions** — headless browsers report 0x0; stealth fixes this to 16x16.

### Usage

**Creating a stealth page (recommended for all production use):**

```go
import (
    "github.com/go-rod/rod"
    "github.com/go-rod/stealth"
)

browser := rod.New().MustConnect()
defer browser.MustClose()

// Use stealth.MustPage instead of browser.MustPage
page := stealth.MustPage(browser)
page.MustNavigate("https://bot.sannysoft.com")
```

**With error handling:**

```go
page, err := stealth.Page(browser)
if err != nil {
    return fmt.Errorf("failed to create stealth page: %w", err)
}
page.MustNavigate("https://example.com")
```

**Using stealth.JS directly (advanced — for custom page creation):**

```go
// If you need to create the page yourself (e.g., with specific options),
// inject stealth.JS manually via EvalOnNewDocument
page := browser.MustPage()
page.MustEvalOnNewDocument(stealth.JS)
page.MustNavigate("https://example.com")
```

### Verifying Stealth

Navigate to a bot detection test page to verify evasions:

```go
page := stealth.MustPage(browser)
page.MustNavigate("https://bot.sannysoft.com")
page.MustScreenshot("stealth_test.png")
```

Expected results for a properly stealth-configured browser:
- **WebDriver**: `missing (passed)`
- **Chrome**: `present (passed)`
- **Plugins Length**: `3` (not `0`)
- **Languages**: `en-US,en`

---

## Implementation Guidelines

### 1. Launcher Configuration

Use the `launcher` package to customize browser launch flags:

```go
import "github.com/go-rod/rod/lib/launcher"

url := launcher.New().
    Headless(true).             // false for debugging
    Proxy("127.0.0.1:8080").    // upstream proxy
    Set("disable-gpu", "").     // custom Chrome flag
    Delete("use-mock-keychain"). // remove a default flag
    MustLaunch()

browser := rod.New().ControlURL(url).MustConnect()
defer browser.MustClose()
```

**Debugging mode (visible browser + slow motion):**

```go
l := launcher.New().
    Headless(false).
    Devtools(true)
defer l.Cleanup()

browser := rod.New().
    ControlURL(l.MustLaunch()).
    Trace(true).
    SlowMotion(2 * time.Second).
    MustConnect()
```

### 2. Proxy Support

```go
// Set proxy at launch
url := launcher.New().
    Proxy("socks5://127.0.0.1:1080").
    MustLaunch()

browser := rod.New().ControlURL(url).MustConnect()

// Handle proxy authentication
go browser.MustHandleAuth("username", "password")()

// Ignore SSL certificate errors (for MITM proxies)
browser.MustIgnoreCertErrors(true)
```

### 3. Input Simulation

```go
import "github.com/go-rod/rod/lib/input"

// Type into an input field (replaces existing value)
page.MustElement("#email").MustInput("user@example.com")

// Simulate keyboard keys
page.Keyboard.MustType(input.Enter)

// Press key combinations
page.Keyboard.MustPress(input.ControlLeft)
page.Keyboard.MustType(input.KeyA)
page.Keyboard.MustRelease(input.ControlLeft)

// Mouse click at coordinates
page.Mouse.MustClick(input.MouseLeft)
page.Mouse.MustMoveTo(100, 200)
```

### 4. Network Request Interception (Hijacking)

```go
router := browser.HijackRequests()
defer router.MustStop()

// Block all image requests
router.MustAdd("*.png", func(ctx *rod.Hijack) {
    ctx.Response.Fail(proto.NetworkErrorReasonBlockedByClient)
})

// Modify request headers
router.MustAdd("*api.example.com*", func(ctx *rod.Hijack) {
    ctx.Request.Req().Header.Set("Authorization", "Bearer token123")
    ctx.MustLoadResponse()
})

// Modify response body
router.MustAdd("*.js", func(ctx *rod.Hijack) {
    ctx.MustLoadResponse()
    ctx.Response.SetBody(ctx.Response.Body() + "\n// injected")
})

go router.Run()
```

### 5. Waiting Strategies

```go
// Wait for page load event
page.MustWaitLoad()

// Wait for no pending network requests (AJAX idle)
wait := page.MustWaitRequestIdle()
page.MustElement("#search").MustInput("query")
wait()

// Wait for element to be stable (not animating)
page.MustElement(".modal").MustWaitStable().MustClick()

// Wait for element to become invisible
page.MustElement(".loading").MustWaitInvisible()

// Wait for JavaScript condition
page.MustWait(`() => document.title === 'Ready'`)

// Wait for specific navigation/event
wait := page.WaitEvent(&proto.PageLoadEventFired{})
page.MustNavigate("https://example.com")
wait()
```

### 6. Race Selectors (Multiple Outcomes)

Handle pages where the result can be one of several outcomes (e.g., login success vs error):

```go
page.MustElement("#username").MustInput("user")
page.MustElement("#password").MustInput("pass").MustType(input.Enter)

// Race between success and error selectors
elm := page.Race().
    Element(".dashboard").MustHandle(func(e *rod.Element) {
        fmt.Println("Login successful:", e.MustText())
    }).
    Element(".error-message").MustDo()

if elm.MustMatches(".error-message") {
    log.Fatal("Login failed:", elm.MustText())
}
```

### 7. Screenshots & PDF

```go
// Full-page screenshot
page.MustScreenshot("page.png")

// Custom screenshot (JPEG, specific region)
img, _ := page.Screenshot(true, &proto.PageCaptureScreenshot{
    Format:  proto.PageCaptureScreenshotFormatJpeg,
    Quality: gson.Int(90),
    Clip: &proto.PageViewport{
        X: 0, Y: 0, Width: 1280, Height: 800, Scale: 1,
    },
})
utils.OutputFile("screenshot.jpg", img)

// Scroll screenshot (captures full scrollable page)
img, _ := page.MustWaitStable().ScrollScreenshot(nil)
utils.OutputFile("full_page.jpg", img)

// PDF export
page.MustPDF("output.pdf")
```

### 8. Concurrent Page Pool

```go
pool := rod.NewPagePool(5) // max 5 concurrent pages

create := func() *rod.Page {
    return browser.MustIncognito().MustPage()
}

var wg sync.WaitGroup
for _, url := range urls {
    wg.Add(1)
    go func(u string) {
        defer wg.Done()

        page := pool.MustGet(create)
        defer pool.Put(page)

        page.MustNavigate(u).MustWaitLoad()
        fmt.Println(page.MustInfo().Title)
    }(url)
}
wg.Wait()

pool.Cleanup(func(p *rod.Page) { p.MustClose() })
```

### 9. Event Handling

```go
// Listen for console.log output
go page.EachEvent(func(e *proto.RuntimeConsoleAPICalled) {
    if e.Type == proto.RuntimeConsoleAPICalledTypeLog {
        fmt.Println(page.MustObjectsToJSON(e.Args))
    }
})()

// Wait for a specific event before proceeding
wait := page.WaitEvent(&proto.PageLoadEventFired{})
page.MustNavigate("https://example.com")
wait()
```

### 10. File Download

```go
wait := browser.MustWaitDownload()

page.MustElementR("a", "Download PDF").MustClick()

data := wait()
utils.OutputFile("downloaded.pdf", data)
```

### 11. JavaScript Evaluation

```go
// Execute JS on the page
page.MustEval(`() => console.log("hello")`)

// Pass parameters and get return value
result := page.MustEval(`(a, b) => a + b`, 1, 2)
fmt.Println(result.Int()) // 3

// Eval on a specific element ("this" = the DOM element)
title := page.MustElement("title").MustEval(`() => this.innerText`).String()

// Direct CDP calls for features Rod doesn't wrap
proto.PageSetAdBlockingEnabled{Enabled: true}.Call(page)
```

### 12. Loading Chrome Extensions

```go
extPath, _ := filepath.Abs("./my-extension")

u := launcher.New().
    Set("load-extension", extPath).
    Headless(false). // extensions require headed mode
    MustLaunch()

browser := rod.New().ControlURL(u).MustConnect()
```

---

## Examples

See the `examples/` directory for complete, runnable Go files:
- `examples/basic_scrape.go` — Minimal scraping example
- `examples/stealth_page.go` — Anti-detection with go-rod/stealth
- `examples/request_hijacking.go` — Intercepting and modifying network requests
- `examples/concurrent_pages.go` — Page pool for concurrent scraping

---

## Best Practices

- ✅ **ALWAYS use `stealth.MustPage(browser)`** instead of `browser.MustPage()` for real-world sites.
- ✅ **ALWAYS `defer browser.MustClose()`** immediately after connecting.
- ✅ Use the error-returning API (not `Must*`) in production code.
- ✅ Set explicit timeouts with `.Timeout()` — never rely on defaults for production.
- ✅ Use `browser.MustIncognito().MustPage()` for isolated sessions.
- ✅ Use `PagePool` for concurrent scraping instead of spawning unlimited pages.
- ✅ Use `MustWaitStable()` before clicking elements that might be animating.
- ✅ Use `MustWaitRequestIdle()` after actions that trigger AJAX calls.
- ✅ Use `launcher.New().Headless(false).Devtools(true)` for debugging.
- ❌ **NEVER** use `time.Sleep()` for waiting — use Rod's built-in wait methods.
- ❌ **NEVER** create a new `Browser` per task — create one Browser, use multiple `Page` instances.
- ❌ **NEVER** use `browser.MustPage()` for production scraping — use `stealth.MustPage()`.
- ❌ **NEVER** ignore errors in production — always handle them explicitly.
- ❌ **NEVER** forget to defer-close browsers, pages, and hijack routers.

## Common Pitfalls

- **Problem:** Element not found even though it exists on the page.
  **Solution:** The element may be inside an iframe or shadow DOM. Use `page.MustSearch()` instead of `page.MustElement()` — it searches across all iframes and shadow DOMs.

- **Problem:** Click doesn't work because the element is animating.
  **Solution:** Call `el.MustWaitStable()` before `el.MustClick()`.

- **Problem:** Bot detection despite using stealth.
  **Solution:** Combine `stealth.MustPage()` with: randomized viewport sizes, realistic User-Agent strings, human-like input delays between keystrokes, and random idle behaviors (scroll, hover).

- **Problem:** Browser process leaks (zombie processes).
  **Solution:** Always `defer browser.MustClose()`. Rod uses [leakless](https://github.com/ysmood/leakless) to kill zombies after main process crash, but explicit cleanup is preferred.

- **Problem:** Timeout errors on slow pages.
  **Solution:** Use chained context: `page.Timeout(30 * time.Second).MustWaitLoad()`. For AJAX-heavy pages, use `MustWaitRequestIdle()` instead of `MustWaitLoad()`.

- **Problem:** HijackRequests router not intercepting requests.
  **Solution:** You must call `go router.Run()` after setting up routes, and `defer router.MustStop()` for cleanup.

## Limitations

- **CAPTCHAs:** Rod does not include CAPTCHA solving. External services (2captcha, etc.) must be integrated separately.
- **Extreme Anti-Bot:** While `go-rod/stealth` handles common detection (WebDriver, plugin fingerprints, WebGL), extremely strict systems (some Cloudflare configurations, Akamai Bot Manager) may still detect automation. Additional measures (residential proxies, human-like behavioral patterns) may be needed.
- **DRM Content:** Cannot interact with DRM-protected media (e.g., Widevine).
- **Resource Usage:** Each browser instance consumes significant RAM (~100-300MB+). Use `PagePool` and limit concurrency on memory-constrained systems.
- **Extensions in Headless:** Chrome extensions do not work in headless mode. Use `Headless(false)` with XVFB for server environments.
- **Platform:** Requires a Chromium-compatible browser. Does not support Firefox or Safari.

## Documentation References

- [Official Documentation](https://go-rod.github.io/) — Guides, tutorials, FAQ
- [Go API Reference](https://pkg.go.dev/github.com/go-rod/rod) — Complete type and method documentation
- [go-rod/stealth](https://github.com/go-rod/stealth) — Anti-bot detection plugin
- [Examples (source)](https://github.com/go-rod/rod/blob/main/examples_test.go) — Official example tests
- [Rod vs Chromedp Comparison](https://github.com/nichochar/go-rod.github.io/blob/main/lib/examples/compare-chromedp) — Migration reference
- [Chrome DevTools Protocol Docs](https://chromedevtools.github.io/devtools-protocol/) — Underlying protocol reference
- [Chrome CLI Flags Reference](https://peter.sh/experiments/chromium-command-line-switches) — Launcher flag documentation
- `references/api-reference.md` — Quick-reference cheat sheet


---
name: go-rust-reverse
description: "Reverse engineer stripped Go and Rust binaries: runtime recognition, pclntab/module metadata recovery, panic-string analysis, and idiomatic decompilation strategies."
risk: safe
source: "https://github.com/zhaoxuya520/reverse-skill"
source_repo: "zhaoxuya520/reverse-skill"
source_type: community
date_added: "2026-08-25"
license: "MIT"
license_source: "https://github.com/zhaoxuya520/reverse-skill/blob/main/LICENSE"
---
# Go / Rust Binary Reverse Engineering
## When to Use

- Analyzing a stripped Go or Rust binary where symbols are absent.
- Recovering function boundaries and names from language-specific metadata.

## 适用场景

- 剥离符号的 Go 恶意软件/工具
- Rust 发行二进制、panic 字符串驱动分析
- 与通用 ida/ghidra 互补的语言专用方法

## 工作流

### Go

```text
□ 识别 go.buildid、runtime 符号残留、pclntab
□ GoReSym / redress / IDA Go 插件恢复函数名
□ 注意 interface、slice、string 结构在反编译中的形态
□ 网络/加密库路径：crypto/* net/http
```

### Rust

```text
□ panic 字符串、rust_begin_unwind、crate 路径暗示
□ 范型实例化导致的代码膨胀；先定位字符串 xref
□ 异步/tokio 状态机需结合交叉引用
```

### 动态

```text
□ 仍可用 Frida；注意 Go 栈与调度
□ 优先日志与配置字符串驱动断点
```

## 工具链

| 工具 | 用途 |
|------|------|
| GoReSym | Go 元数据 |
| IDA/Ghidra + Go/Rust 插件 | 反编译 |
| radare2 | 快速字符串 |
| strings / rabin2 | 分诊 |

## 参考

- `references/go-rust-notes.md`
- `../reverse-engineering/go-reverse.md` `../ida-reverse/` `../ghidra-reverse/`
- seed: `field-journal/seed-002_go-malware-stripped.md`

## 路由上下文

**上游**: MASTER R33
**下游**: 恶意样本流程 `malware-analysis`；通用 RE `reverse-engineering`

## 任务完成自检

- [ ] 是否恢复关键函数名或等价映射？
- [ ] 是否标注语言运行时证据？
- [ ] Checklist？

## Limitations

- New compiler versions change metadata layouts; tooling must be kept current.
- Aggressive inlining still yields large, hard-to-read decompilation.

> Adapted from [zhaoxuya520/reverse-skill](https://github.com/zhaoxuya520/reverse-skill) (MIT).


---
name: goal-analyzer
description: 分析健康目标数据、识别目标模式、评估目标进度,并提供个性化目标管理建议。支持与营养、运动、睡眠等健康数据的关联分析。
allowed-tools: Read, Grep, Glob, Write
risk: critical
source: community
---

# 健康目标分析器技能

分析健康目标数据,识别目标模式和进度,评估目标达成情况,并提供个性化目标管理建议。

## When to Use
- 你需要评估健康目标是否符合 SMART 原则，并识别目标设定中的薄弱点。
- 你想跟踪目标进度，并结合营养、运动、睡眠等健康数据做关联分析。
- 你需要面向个人健康管理的目标优化建议、风险提示和阶段性调整方案。

## 功能

### 1. SMART目标验证

验证设定的新目标是否符合SMART原则。

**验证维度**:
- **S**pecific(具体性)
  - 目标是否明确具体
  - 是否有清晰的定义
  - 是否避免模糊表述

- **M**easurable(可衡量性)
  - 是否有可量化的指标
  - 是否有明确的衡量标准
  - 是否可以追踪进度

- **A**chievable(可实现性)
  - 目标是否现实可行
  - 是否考虑了当前状况
  - 是否在合理时间范围内
  - 减重目标:建议每周0.5-1公斤
  - 运动目标:建议每周3-5次,每次30-60分钟

- **R**elevant(相关性)
  - 目标是否与健康相关
  - 是否符合用户整体健康计划
  - 是否与现有目标协调

- **T**ime-bound(有时限)
  - 是否有明确的截止日期
  - 时间框架是否合理
  - 是否有阶段性里程碑

**输出**:
- SMART评分(每个维度1-5分)
- 总体评分和等级(S级/A级/B级/C级)
- 改进建议
- 目标优化方案

**示例评估**:
```json
{
  "goal": "6个月内减重5公斤",
  "smart_scores": {
    "specific": 5,
    "measurable": 5,
    "achievable": 4,
    "relevant": 5,
    "time_bound": 5
  },
  "overall_score": 4.8,
  "grade": "A",
  "assessment": "优秀的SMART目标",
  "suggestions": [
    "建议设定阶段性里程碑(每2个月减重1.5-2公斤)",
    "建议配合运动计划和饮食调整"
  ]
}
```

---

### 2. 目标进度追踪

追踪和分析目标的完成进度。

**追踪内容**:
- **当前进度**
  - 完成百分比
  - 当前数值vs目标数值
  - 剩余差距

- **时间进度**
  - 已用时间占比
  - 剩余时间
  - 进度超前/落后判断

- **速度分析**
  - 平均进度速度(每周/每月)
  - 预计完成时间
  - 是否需要调整计划

- **趋势识别**
  - 进度趋势(加速/稳定/减速)
  - 周期性模式
  - 异常波动检测

**输出**:
- 进度可视化(进度条、百分比)
- 完成概率预测
- 时间预估(乐观/中性/悲观)
- 调整建议

**进度评级**:
- 🟢 **优秀** - 进度超前,预计提前完成
- 🟡 **正常** - 进度符合预期
- 🟠 **落后** - 进度略慢,需要加快
- 🔴 **严重落后** - 进度严重滞后,建议调整目标

---

### 3. 习惯养成分析

分析习惯的养成情况和连续性。

**分析内容**:
- **连续天数追踪**
  - 当前连续天数
  - 历史最长连续天数
  - 平均连续天数

- **完成率统计**
  - 总体完成率
  - 每周完成率
  - 每月完成率
  - 特定星期几完成率

- **习惯强度评估**
  - 习惯固化程度(1-10分)
  - 习惯稳定性评分
  - 自动化程度评估

- **习惯模式识别**
  - 最佳触发时间
  - 常见中断原因
  - 成功因素识别

**习惯养成阶段**:
- **第1-7天** - 启动期(最容易放弃)
- **第8-21天** - 形成期(逐渐稳定)
- **第22-30天** - 巩固期(接近自动化)
- **第31-66天** - 习惯期(基本养成)
- **第67天+** - 自动化期(完全自动化)

**输出**:
- 习惯热图(日历视图)
- 连续天数统计
- 完成率趋势图
- 习惯强度评分
- 习惯堆叠建议

**示例分析**:
```json
{
  "habit": "morning-stretch",
  "current_streak": 21,
  "longest_streak": 21,
  "completion_rate": 95.2,
  "strength_score": 7.5,
  "stage": "巩固期",
  "assessment": "习惯即将形成,继续保持!",
  "next_milestone": 30,
  "suggestions": [
    "继续保持,即将达到30天里程碑",
    "可以尝试添加新的相关习惯"
  ]
}
```

---

### 4. 动机评估与管理

评估和管理用户的动机水平。

**评估内容**:
- **动机评分追踪**
  - 当前动机水平(1-10分)
  - 动机变化趋势
  - 动机波动周期

- **动机因素分析**
  - 内在动机(健康、自我实现)
  - 外在动机(奖励、认可)
  - 社会支持(家人朋友鼓励)

- **动机低谷识别**
  - 动机下降信号
  - 常见低谷时间点
  - 风险时段预警

**动机提升策略**:
- **第2-3周** - 动机下降,需要强调已完成进度
- **第1-2个月** - 疲劳期,需要调整目标和奖励
- **3个月后** - 倦怠期,需要新鲜感和挑战

**输出**:
- 动机趋势图
- 动机低谷预警
- 个性化激励建议
- 奖励机制建议

**激励建议示例**:
- 当动机<5分:回顾初心,降低短期目标
- 当动机5-7分:强调进步,设置小奖励
- 当动机>7分:设定挑战,追求卓越

---

### 5. 成就系统管理

管理基础成就系统的解锁和进度。

**成就类型**:
- **目标相关成就**
  - 🏆 首次目标 - 完成第一个健康目标
  - 🎯 半程达成 - 任意目标完成50%
  - 🎉 目标达成 - 完成一个健康目标
  - ⚡ 提前完成 - 提前完成目标
  - 📈 超额完成 - 超额完成目标

- **习惯相关成就**
  - 🔥 连续7天 - 任意习惯连续7天打卡
  - 💪 连续21天 - 任意习惯连续21天打卡
  - ⭐ 连续30天 - 任意习惯连续30天打卡
  - 🌟 连续66天 - 任意习惯连续66天打卡(完全养成)

- **综合成就**
  - 🏅 多目标并行 - 同时完成3个目标
  - 💎 完美坚持 - 30天习惯完成率100%
  - 🚀 快速进步 - 单周进步最大
  - 👑 长期坚持 - 持续追踪180天

**成就追踪**:
- 已解锁成就列表
- 未解锁成就进度
- 成就解锁时间
- 成就相关建议

**输出**:
- 成就徽章展示
- 成就完成进度
- 下一个可解锁成就
- 成就达成建议

---

### 6. 障碍识别与建议

识别阻碍目标达成的因素,提供解决方案。

**障碍类型**:
- **时间障碍**
  - 忙碌、时间不足
  - 建议:缩短单次时长,增加频率;利用碎片时间

- **动机障碍**
  - 缺乏动力、拖延
  - 建议:设置提醒;寻找伙伴;调整目标

- **环境障碍**
  - 缺乏支持、诱惑过多
  - 建议:改变环境;寻找替代方案;建立支持系统

- **能力障碍**
  - 目标太难、缺乏知识
  - 建议:降低难度;学习知识;寻求专业帮助

- **身体障碍**
  - 疲劳、不适、受伤
  - 建议:休息恢复;调整计划;咨询医生

**输出**:
- 主要障碍识别
- 障碍频率统计
- 个性化解决方案
- 预防性建议

---

### 7. 数据关联分析

将健康目标与其他健康数据进行关联分析。

**关联维度**:
- **减重目标关联**
  - 营养摄入(卡路里、宏量营养素)
  - 运动消耗(频率、强度、时长)
  - 睡眠质量(时长、深度)
  - 体重变化趋势

- **运动目标关联**
  - 睡眠质量(恢复情况)
  - 营养摄入(蛋白质、碳水)
  - 身体指标(体重、体脂率)

- **饮食目标关联**
  - 营养素摄入(维生素、矿物质)
  - 身体指标(血压、血糖)
  - 运动表现

- **睡眠目标关联**
  - 运动时间(晚间运动影响)
  - 饮食时间(晚餐时间、咖啡因)
  - 屏幕时间(蓝光影响)

**分析方法**:
- 相关性分析(Pearson相关系数)
- 回归分析(预测模型)
- 趋势匹配(趋势同步性)
- 因果推断(潜在因果关系)

**输出**:
- 关联强度(强/中/弱)
- 正/负相关关系
- 因果关系推断
- 优化建议

**示例关联**:
```json
{
  "goal": "weight-loss",
  "correlations": [
    {
      "factor": "daily_calories",
      "correlation": -0.75,
      "strength": "强负相关",
      "insight": "每日卡路里摄入与减重进度呈强负相关,降低摄入加速进度"
    },
    {
      "factor": "exercise_frequency",
      "correlation": 0.68,
      "strength": "强正相关",
      "insight": "运动频率与减重进度呈强正相关,建议保持每周4次以上"
    },
    {
      "factor": "sleep_duration",
      "correlation": 0.45,
      "strength": "中等正相关",
      "insight": "睡眠时长影响减重,建议保证7-8小时睡眠"
    }
  ],
  "recommendations": [
    "重点控制卡路里摄入,保持当前运动频率",
    "优化睡眠时长,以提升减重效果"
  ]
}
```

---

### 8. 可视化报告生成

生成包含ECharts图表的HTML交互式报告。

**报告类型**:

#### A. 进度趋势报告
- 折线图展示目标进度随时间变化
- 里程碑标注
- 预测完成时间区间
- 进度速度分析

#### B. 习惯热图报告
- 日历热图展示习惯完成情况
- 颜色深浅表示完成频率
- 连续天数标注
- 完成率统计

#### C. 多目标对比报告
- 环形图展示多个目标完成率
- 优先级排序
- 资源分配建议
- 进度同步性分析

#### D. 动机趋势报告
- 折线图展示动机变化
- 动机与进度相关性
- 动机低谷预警
- 激励建议

#### E. 综合报告
- 包含以上所有图表
- 整体健康状况评估
- 综合改进建议
- 下阶段目标建议

**报告特点**:
- 响应式设计,支持移动端
- 深色/浅色主题切换
- 交互式图表(缩放、筛选)
- 数据表格展示
- 导出PDF功能
- 完全本地化,无需联网

**ECharts图表配置**:
```javascript
// 进度趋势折线图
{
  type: 'line',
  xAxis: { type: 'category', data: ['1月', '2月', '3月', ...] },
  yAxis: { type: 'value', name: '完成%' },
  series: [{
    name: '目标进度',
    type: 'line',
    data: [0, 15, 35, 50, 70, 85, 100],
    smooth: true,
    markLine: {
      data: [{ yAxis: 50, name: '50%里程碑' }]
    }
  }]
}

// 习惯热图
{
  type: 'heatmap',
  xAxis: { type: 'category', data: ['周一', '周二', ...] },
  yAxis: { type: 'category', data: ['第1周', '第2周', ...] },
  visualMap: {
    min: 0, max: 1,
    inRange: { color: ['#ebedf0', '#216e39'] }
  },
  series: [{
    type: 'heatmap',
    data: [[0, 0, 1], [1, 0, 1], [2, 0, 0], ...]
  }]
}

// 目标达成率环形图
{
  type: 'pie',
  radius: ['50%', '70%'],
  series: [{
    type: 'pie',
    radius: ['50%', '70%'],
    data: [
      { value: 70, name: '已完成' },
      { value: 30, name: '未完成' }
    ],
    label: { formatter: '{b}: {c}%' }
  }]
}
```

**输出**:
- HTML文件(包含完整的CSS、JS、ECharts)
- 图表交互功能
- 数据表格
- 分析文本
- 建议列表

---

## 医学安全边界

### 能力范围声明
- ✅ 辅助设定健康目标
- ✅ 追踪和分析目标进度
- ✅ 识别健康行为模式
- ✅ 提供一般性健康改善建议
- ✅ 生成可视化报告

- ❌ 不提供医疗诊断
- ❌ 不开具治疗处方
- ❌ 不替代专业医疗建议
- ❌ 不处理进食障碍或强迫行为

### 危险信号识别
**极端目标警告**:
- 减重目标>每周1公斤
- 增重目标>每周0.5公斤
- 极端卡路里限制(<1200卡/天)
- 过度运动(>2小时/天,7天/周)

**不健康行为迹象**:
- 完成率<30%持续3周
- 动机评分<3分持续2周
- 身体不适报告
- 强迫性行为模式

**转介建议**:
- 出现危险信号时,建议咨询医生
- 有慢性疾病时,建议咨询相关专科
- 设定饮食目标时,建议咨询营养师
- 设定运动目标时,建议咨询健身教练

---

## 输出格式

### 目标分析报告
```markdown
# 健康目标分析报告

## 目标概览
- 目标: 6个月内减重5公斤
- 开始日期: 2025-01-01
- 目标日期: 2025-06-30
- 当前日期: 2025-03-20

## SMART评估
- 具体性: ⭐⭐⭐⭐⭐ (5/5)
- 可衡量性: ⭐⭐⭐⭐⭐ (5/5)
- 可实现性: ⭐⭐⭐⭐ (4/5)
- 相关性: ⭐⭐⭐⭐⭐ (5/5)
- 有时限: ⭐⭐⭐⭐⭐ (5/5)

**总体评分: A (4.8/5)**

## 进度分析
- 当前进度: 70%
- 已完成: 3.5公斤 / 5.0公斤
- 时间进度: 27% (79天/180天)
- 进度评级: 🟢 优秀 (进度超前)

### 趋势分析
- 平均速度: 0.77公斤/月
- 预计完成: 2025-05-20 (提前40天)
- 进度趋势: 稳定上升

## 习惯追踪
### 早上拉伸习惯
- 当前连续: 21天 🔥
- 历史最长: 21天
- 完成率: 95.2%
- 习惯阶段: 巩固期
- 下一个里程碑: 30天 ⭐

## 动机评估
- 当前动机: 8/10
- 动机趋势: 稳定
- 动机状态: 良好

## 数据关联分析
### 强相关因素(影响度>60%)
1. 每日卡路里摄入 (负相关 -0.75)
2. 每周运动频次 (正相关 +0.68)
3. 睡眠时长 (正相关 +0.45)

### 建议
- 保持当前卡路里摄入水平
- 继续保持每周4次运动频率
- 优化睡眠时长至7-8小时

## 障碍识别
主要障碍: 社交活动饮食控制

解决方案:
- 社交活动前提前规划饮食
- 选择健康餐厅
- 适量控制份量

## 成就解锁
🔥 连续21天 - 早上拉伸习惯达成!
🎯 半程达成 - 减重目标完成50%!

## 下一步行动
1. 保持当前进度
2. 关注社交活动饮食控制
3. 继续养成早操习惯
4. 准备达成30天里程碑
```

---

## 技术实现要点

### 数据读取
- 读取主数据文件: `data-example/health-goals-tracker.json`
- 读取日志文件: `data-example/health-goals-logs/YYYY-MM/YYYY-MM-DD.json`
- 关联数据: `data-example/nutrition-tracker.json`, `fitness-tracker.json` 等

### 数据处理
- 计算完成百分比: `(current_value / target_value) * 100`
- 计算时间进度: `(days_elapsed / total_days) * 100`
- 计算连续天数: 遍历日志,统计连续完成天数
- 计算完成率: `(completed_days / total_days) * 100`
- 计算习惯强度: 基于完成率和连续天数的复合评分

### SMART验证算法
```python
def validate_smart_goal(goal):
    scores = {
        'specific': check_specificity(goal),
        'measurable': check_measurability(goal),
        'achievable': check_achievability(goal),
        'relevant': check_relevance(goal),
        'time_bound': check_time_bound(goal)
    }
    overall = sum(scores.values()) / len(scores)
    grade = get_grade(overall)
    return scores, overall, grade
```

### HTML报告生成
- 使用ECharts 5.x CDN
- 响应式CSS布局
- JavaScript处理图表交互
- 支持深色/浅色主题切换
- 数据从JSON文件动态加载

---

**使用此技能时,始终优先考虑用户的健康和安全!**

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


---
name: goal-loop
description: "Draft and explain persistent goal-loop prompts for long-running agent work with clear stop conditions."
category: agent-orchestration
risk: safe
source: community
source_repo: davidondrej/skills
source_type: community
date_added: "2026-07-07"
author: davidondrej
tags: [goals, autonomy, planning]
tools: [claude, codex]
license: "MIT"
license_source: "https://github.com/davidondrej/skills/blob/main/LICENSE"
---

# Agent `/goal` Loop

## What `/goal` is

`/goal` is a slash command that turns an agent prompt into a **persistent agent** looping `plan → act → test → review → iterate` until a stop condition is met, the user pauses, or the token budget runs out. Internally called the "Ralph loop."

Agents with the `/goal` feature right now: **Codex, Claude Code, and Hermes Agent**.

Key difference from a normal prompt: when a turn ends but the goal isn't met, the agent **auto-continues** instead of waiting for input.

**Lifecycle states:** `pursuing`, `paused`, `achieved`, `unmet`, `budget-limited`.

When monitoring a running `/goal`, every check should include a one-line update to the user: what the agent is doing and whether it is on track. Keep it extremely concise.

**Not:** a budget command, a safety boundary, "run forever", or a replacement for `/plan`. It's a contract enforcer with a verification loop.

## Requirements

- An agent with the `/goal` feature — right now: Codex, Claude Code, or Hermes Agent
- The goals feature enabled in the agent's config
- **Subscription auth** — API-key auth does **not** work. A pro-tier plan is the realistic minimum for long runs.

## When to Use it

Use only when **all three** are true:
1. Task is >30 min of mechanical work.
2. There's a **verifiable stop condition** (tests pass, coverage hit, eval ≥ X, build green).
3. Repo is agent-ready (working build, decent tests, `AGENTS.md` present).

Fits: migrations, coverage lifts, TDD feature builds, refactors with contract tests, prompt/eval optimization, deploy retry loops, bug-repro-then-fix.

Bad fits: exploratory work, vague "improve this", anything without a "done" definition, prod credentials, destructive shared-infra ops.

## The 5-part contract (every goal needs this)

1. **Objective** — one sentence, one concrete outcome.
2. **Constraints** — what must NOT change (public API, files, libs, conventions).
3. **Validation command** — the exact shell command that proves progress (`pytest -q`, `pnpm test`, etc.).
4. **Stop condition** — verifiable: "Stop when X passes" OR "when further changes need human/product input."
5. **Documentation** — one sentence instructing the agent to write concise, targeted docs for every change, either creating new `.md` files or updating existing ones.

Plus: tell the agent what to read first, ask it to work in checkpoints with a short progress log.

## Writing a goal (the core deliverable)

When the user wants a quick `/goal` instruction, produce a structured markdown block with one line per contract item (proper newlines, not flowing prose). **Do not prefix the output with `/goal`** — the user adds the slash command themselves in the composer. Emit only the contract body. Template:

```
**Objective:** <one-sentence objective>
**Read first:** <files/PLAN.md/issue>
**Constraints:** <what not to change, libs, conventions>
**Validate:** `<exact command>` after each change
**Document:** Write concise, targeted documentation for all changes — create new `.md` files or update existing docs as needed.
**Checkpoints:** work in checkpoints and log progress briefly
**Stop when:** <verifiable condition>, OR when further changes require human/product input
```

### Example (migration)

```
**Objective:** Migrate this project from Pydantic v1 to v2.
**Read first:** pyproject.toml, src/, tests/
**Constraints:** no public API changes; keep imports backwards-compatible via shims if needed; no new dependencies
**Validate:** `pytest -q` after each change
**Checkpoints:** work in checkpoints; log progress briefly
**Stop when:** full suite passes with zero deprecation warnings, OR when a change requires architecture decisions
```

### Example (coverage lift)

```
**Objective:** Raise coverage in src/auth/ from ~38% to ≥75%.
**Read first:** src/auth/, tests/auth/, AGENTS.md
**Constraints:** no new deps; mirror existing test style; do not modify production code unless strictly required for testability
**Validate:** `pytest --cov=src/auth --cov-report=term-missing`
**Checkpoints:** work in checkpoints; log coverage delta each one
**Stop when:** coverage ≥75% AND all tests pass, OR when uncovered code needs design changes
```

### Writing rules
- **One objective, one stop condition.** Not a backlog.
- **Documentation is mandatory.** Every `/goal` prompt must include a single sentence committing the agent to concise, targeted docs — new `.md` files or focused updates to existing docs.
- **Never instruct the agent to create new ADRs** — ADRs require the user's explicit approval, so goal prompts must not pre-approve or encourage them.
- **Forbid reward-hacking explicitly:** "Do not delete, skip, weaken, or narrow tests to make the goal pass." Otherwise the agent may game the stop condition.
- **4,000-char limit** on the objective. If longer, put detail in a file (`PLAN.md`/`GOAL_BRIEF.md`) and make the goal point to it — keep the goal itself compact.
- Use **literal strings** for paths, commands, issue numbers — exact.
- Forbid scope creep explicitly: "Do not refactor unrelated code. Do not add dependencies."
- Tell the agent when to pause: "If <condition>, pause and ask before proceeding."
- Short, vague goals burn tokens for no extra value vs. a normal prompt.

### Meta-prompting trick (highest-leverage)

Hand-written goals under-specify. Ask a second AI session (Claude with the codebase loaded, ChatGPT with project connected, or a separate agent thread in the same dir) to: (1) inspect the codebase, (2) surface hidden assumptions/constraints/edge cases, (3) emit a structured `/goal` markdown block using the 4-part contract. Paste that into the agent. Order-of-magnitude better runs.

Claude Code cmux note: after Claude finishes, it may prefill a predicted next user message; that draft is Claude, not the user speaking.

### Self-goal setting

The agent can now write and set its own goal natively (the `create_goal` tool). Instead of crafting the contract yourself, give it your high-level intent and tell it to set the goal: "Inspect this repo, then write yourself a `/goal` with a verifiable stop condition and pursue it." It's the meta-prompting trick done inline — the agent turns your intent into the contract. Still give it the same raw materials (files to read, constraints, the validation command) so the goal it writes is grounded. Add: "ask clarifying questions before committing if the intent is underspecified" — catches ambiguity up front and prevents the self-set goal from drifting.

## Launching

1. `cd <repo>` (goals run scoped to the working directory).
2. Launch the agent bare (opens the TUI). **Not** exec/headless mode — `/goal` is a TUI slash command only.
3. Sign in with subscription auth (not an API key).
4. Type `/goal <your contract>` in the composer, Enter.
5. Walk away.

## Controlling a running goal

| Command | Effect |
|---|---|
| `/goal` (alone) | Status: current checkpoint, what's verified, what remains, blockers |
| `/goal pause` | Freeze |
| `/goal resume` | Unfreeze (paused goals never auto-resume) |
| `/goal clear` | Kill the goal |
| `/goal <new>` | Replace the current goal |
| Ctrl+C / any typed message | Auto-pauses; user input always wins priority |

Resuming across sessions: goal state is persisted server-side. `cd` back into the repo, launch the agent, `/goal` for status, `/goal resume`.

Budget-limited state: the agent doesn't stop abruptly — it summarizes, notes what's left, saves state. `/goal resume` works after budget refresh or upgrade.

## When a goal drifts

- **Minor drift:** just type a correction in the composer (auto-pauses, folds it in, resumes).
- **Loose objective:** `/goal pause`, read status, then `/goal <tighter version>` — replaces the contract. Don't pile instructions on a vague goal.
- **Bad mess:** `/goal clear`, `git status` or `git stash`, rewrite with the meta-prompting trick, restart.

Don't let a drifting goal keep running "to see where it goes." Tokens burn, diffs compound.

## Operational tips

- Inspect status periodically with bare `/goal`.
- **Always review the diff** before merging — long autonomy means more code to validate, not less. Human oversight becomes more critical, not optional.
- Keep approvals/sandboxing tight; default permissions are correct.
- First run: pick a 30-min scoped task so you learn how `/goal` actually stops before trusting it overnight.
- Bake recurring policy into `AGENTS.md` so every goal inherits it without restating: adversarial self-review before declaring done, an extra QA pass even when tests pass, and the standard validation command. Saves repeating it in each goal paragraph.

## Troubleshooting

| Symptom | Fix |
|---|---|
| `/goal` missing from slash popup | Update the agent to a version that supports `/goal` |
| Feature flag on but command missing | Quit and restart the agent fully |
| Typed `/goals` | It's singular: `/goal` |
| Doesn't activate | Sign out, sign back in with subscription auth (not API key) |
| Stopped with progress summary | Budget-limited — `/goal resume` after refresh, or tighten scope |
| `/goal resume` says no active goal | Terminal state or cleared — start fresh with `/goal <new>` |
| Goal looks active but won't auto-continue | Stuck in Plan mode — plan-only work doesn't trigger continuation. Draft the plan, then switch to Goal execution |

## Mental model

`/goal` is a **contract enforcer with a verification loop**, not a "run forever" button. The shift: stop writing prompts, start writing **specifications with stop conditions**. Spend the time upfront defining "done"; the run takes care of itself.

## Limitations

- Adapted from `davidondrej/skills`; verify local paths, tools, credentials, and agent features before acting.
- For commands, remote access, scheduling, browser automation, or file-changing workflows, get explicit user approval and confirm the target environment first.


---
name: godot-4-migration
description: "Specialized guide for migrating Godot 3.x projects to Godot 4 (GDScript 2.0), covering syntax changes, Tweens, and exports."
risk: safe
source: community
date_added: "2026-02-27"
---

# Godot 4 Migration Guide

## Overview

A critical guide for developers transitioning from Godot 3.x to Godot 4. This skill focuses on the major syntax changes in GDScript 2.0, the new `Tween` system, and `export` annotation updates.

## When to Use This Skill

- Use when porting a Godot 3 project to Godot 4.
- Use when encountering syntax errors after upgrading.
- Use when replacing deprecated nodes (like `Tween` node vs `create_tween`).
- Use when updating `export` variables to `@export` annotations.

## Key Changes

### 1. Annotations (`@`)

Godot 4 uses `@` for keywords that modify behavior.
- `export var x` -> `@export var x`
- `onready var y` -> `@onready var y`
- `tool` -> `@tool` (at top of file)

### 2. Setters and Getters

Properties now define setters/getters inline.

**Godot 3:**
```gdscript
var health setget set_health, get_health

func set_health(value):
    health = value
```

**Godot 4:**
```gdscript
var health: int:
    set(value):
        health = value
        emit_signal("health_changed", health)
    get:
        return health
```

### 3. Tween System

The `Tween` node is deprecated. Use `create_tween()` in code.

**Godot 3:**
```gdscript
$Tween.interpolate_property(...)
$Tween.start()
```

**Godot 4:**
```gdscript
var tween = create_tween()
tween.tween_property($Sprite, "position", Vector2(100, 100), 1.0)
tween.parallel().tween_property($Sprite, "modulate:a", 0.0, 1.0)
```

### 4. Signal Connections

String-based connections are discouraged. Use callables.

**Godot 3:**
```gdscript
connect("pressed", self, "_on_pressed")
```

**Godot 4:**
```gdscript
pressed.connect(_on_pressed)
```

## Examples

### Example 1: Typed Arrays

GDScript 2.0 supports typed arrays for better performance and type safety.

```gdscript
# Godot 3
var enemies = []

# Godot 4
var enemies: Array[Node] = []

func _ready():
    for child in get_children():
        if child is Enemy:
            enemies.append(child)
```

### Example 2: Awaiting Signals (Coroutines)

`yield` is replaced by `await`.

**Godot 3:**
```gdscript
yield(get_tree().create_timer(1.0), "timeout")
```

**Godot 4:**
```gdscript
await get_tree().create_timer(1.0).timeout
```

## Best Practices

- ✅ **Do:** Use `@export_range`, `@export_file`, etc., for better inspector UI.
- ✅ **Do:** Type all variables (`var x: int`) for performance gains in GDScript 2.0.
- ✅ **Do:** Use `super()` to call parent methods instead of `.function_name()`.
- ❌ **Don't:** Use string names for signals (`emit_signal("name")`) if you can use the signal object (`name.emit()`).

## Troubleshooting

**Problem:** "Identifier 'Tween' is not a valid type."
**Solution:** `Tween` is now `SceneTreeTween` or just an object returned by `create_tween()`. You rarely type it explicitly, just use `var tween = create_tween()`.

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


---
name: godot-gdscript-patterns
description: "Master Godot 4 GDScript patterns including signals, scenes, state machines, and optimization. Use when building Godot games, implementing game systems, or learning GDScript best practices."
risk: safe
source: community
date_added: "2026-02-27"
---

# Godot GDScript Patterns

Production patterns for Godot 4.x game development with GDScript, covering architecture, signals, scenes, and optimization.

## Use this skill when

- Building games with Godot 4
- Implementing game systems in GDScript
- Designing scene architecture
- Managing game state
- Optimizing GDScript performance
- Learning Godot best practices

## Do not use this skill when

- The task is unrelated to godot gdscript patterns
- You need a different domain or tool outside this scope

## Instructions

- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.

## Resources

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

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


---
name: golang-pro
description: Master Go 1.21+ with modern patterns, advanced concurrency, performance optimization, and production-ready microservices.
risk: critical
source: community
date_added: '2026-02-27'
---
You are a Go expert specializing in modern Go 1.21+ development with advanced concurrency patterns, performance optimization, and production-ready system design.

## Use this skill when

- Building Go services, CLIs, or microservices
- Designing concurrency patterns and performance optimizations
- Reviewing Go architecture and production readiness

## Do not use this skill when

- You need another language or runtime
- You only need basic Go syntax explanations
- You cannot change Go tooling or build configuration

## Instructions

1. Confirm Go version, tooling, and runtime constraints.
2. Choose concurrency and architecture patterns.
3. Implement with testing and profiling.
4. Optimize for latency, memory, and reliability.

## Purpose
Expert Go developer mastering Go 1.21+ features, modern development practices, and building scalable, high-performance applications. Deep knowledge of concurrent programming, microservices architecture, and the modern Go ecosystem.

## Capabilities

### Modern Go Language Features
- Go 1.21+ features including improved type inference and compiler optimizations
- Generics (type parameters) for type-safe, reusable code
- Go workspaces for multi-module development
- Context package for cancellation and timeouts
- Embed directive for embedding files into binaries
- New error handling patterns and error wrapping
- Advanced reflection and runtime optimizations
- Memory management and garbage collector understanding

### Concurrency & Parallelism Mastery
- Goroutine lifecycle management and best practices
- Channel patterns: fan-in, fan-out, worker pools, pipeline patterns
- Select statements and non-blocking channel operations
- Context cancellation and graceful shutdown patterns
- Sync package: mutexes, wait groups, condition variables
- Memory model understanding and race condition prevention
- Lock-free programming and atomic operations
- Error handling in concurrent systems

### Performance & Optimization
- CPU and memory profiling with pprof and go tool trace
- Benchmark-driven optimization and performance analysis
- Memory leak detection and prevention
- Garbage collection optimization and tuning
- CPU-bound vs I/O-bound workload optimization
- Caching strategies and memory pooling
- Network optimization and connection pooling
- Database performance optimization

### Modern Go Architecture Patterns
- Clean architecture and hexagonal architecture in Go
- Domain-driven design with Go idioms
- Microservices patterns and service mesh integration
- Event-driven architecture with message queues
- CQRS and event sourcing patterns
- Dependency injection and wire framework
- Interface segregation and composition patterns
- Plugin architectures and extensible systems

### Web Services & APIs
- HTTP server optimization with net/http and fiber/gin frameworks
- RESTful API design and implementation
- gRPC services with protocol buffers
- GraphQL APIs with gqlgen
- WebSocket real-time communication
- Middleware patterns and request handling
- Authentication and authorization (JWT, OAuth2)
- Rate limiting and circuit breaker patterns

### Database & Persistence
- SQL database integration with database/sql and GORM
- NoSQL database clients (MongoDB, Redis, DynamoDB)
- Database connection pooling and optimization
- Transaction management and ACID compliance
- Database migration strategies
- Connection lifecycle management
- Query optimization and prepared statements
- Database testing patterns and mock implementations

### Testing & Quality Assurance
- Comprehensive testing with testing package and testify
- Table-driven tests and test generation
- Benchmark tests and performance regression detection
- Integration testing with test containers
- Mock generation with mockery and gomock
- Property-based testing with gopter
- End-to-end testing strategies
- Code coverage analysis and reporting

### DevOps & Production Deployment
- Docker containerization with multi-stage builds
- Kubernetes deployment and service discovery
- Cloud-native patterns (health checks, metrics, logging)
- Observability with OpenTelemetry and Prometheus
- Structured logging with slog (Go 1.21+)
- Configuration management and feature flags
- CI/CD pipelines with Go modules
- Production monitoring and alerting

### Modern Go Tooling
- Go modules and version management
- Go workspaces for multi-module projects
- Static analysis with golangci-lint and staticcheck
- Code generation with go generate and stringer
- Dependency injection with wire
- Modern IDE integration and debugging
- Air for hot reloading during development
- Task automation with Makefile and just

### Security & Best Practices
- Secure coding practices and vulnerability prevention
- Cryptography and TLS implementation
- Input validation and sanitization
- SQL injection and other attack prevention
- Secret management and credential handling
- Security scanning and static analysis
- Compliance and audit trail implementation
- Rate limiting and DDoS protection

## Behavioral Traits
- Follows Go idioms and effective Go principles consistently
- Emphasizes simplicity and readability over cleverness
- Uses interfaces for abstraction and composition over inheritance
- Implements explicit error handling without panic/recover
- Writes comprehensive tests including table-driven tests
- Optimizes for maintainability and team collaboration
- Leverages Go's standard library extensively
- Documents code with clear, concise comments
- Focuses on concurrent safety and race condition prevention
- Emphasizes performance measurement before optimization

## Knowledge Base
- Go 1.21+ language features and compiler improvements
- Modern Go ecosystem and popular libraries
- Concurrency patterns and best practices
- Microservices architecture and cloud-native patterns
- Performance optimization and profiling techniques
- Container orchestration and Kubernetes patterns
- Modern testing strategies and quality assurance
- Security best practices and compliance requirements
- DevOps practices and CI/CD integration
- Database design and optimization patterns

## Response Approach
1. **Analyze requirements** for Go-specific solutions and patterns
2. **Design concurrent systems** with proper synchronization
3. **Implement clean interfaces** and composition-based architecture
4. **Include comprehensive error handling** with context and wrapping
5. **Write extensive tests** with table-driven and benchmark tests
6. **Consider performance implications** and suggest optimizations
7. **Document deployment strategies** for production environments
8. **Recommend modern tooling** and development practices

## Example Interactions
- "Design a high-performance worker pool with graceful shutdown"
- "Implement a gRPC service with proper error handling and middleware"
- "Optimize this Go application for better memory usage and throughput"
- "Create a microservice with observability and health check endpoints"
- "Design a concurrent data processing pipeline with backpressure handling"
- "Implement a Redis-backed cache with connection pooling"
- "Set up a modern Go project with proper testing and CI/CD"
- "Debug and fix race conditions in this concurrent Go code"

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


---
name: google-analytics-automation
description: "Automate Google Analytics tasks via Rube MCP (Composio): run reports, list accounts/properties, funnels, pivots, key events. Always search tools first for current schemas."
risk: critical
source: community
date_added: "2026-02-27"
---

# Google Analytics Automation via Rube MCP

Automate Google Analytics 4 (GA4) reporting and property management through Composio's Google Analytics toolkit via Rube MCP.

## Prerequisites

- Rube MCP must be connected (RUBE_SEARCH_TOOLS available)
- Active Google Analytics connection via `RUBE_MANAGE_CONNECTIONS` with toolkit `google_analytics`
- Always call `RUBE_SEARCH_TOOLS` first to get current tool schemas

## Setup

**Get Rube MCP**: Add `https://rube.app/mcp` as an MCP server in your client configuration. No API keys needed — just add the endpoint and it works.

1. Verify Rube MCP is available by confirming `RUBE_SEARCH_TOOLS` responds
2. Call `RUBE_MANAGE_CONNECTIONS` with toolkit `google_analytics`
3. If connection is not ACTIVE, follow the returned auth link to complete Google OAuth
4. Confirm connection status shows ACTIVE before running any workflows

## Core Workflows

### 1. List Accounts and Properties

**When to use**: User wants to discover available GA4 accounts and properties

**Tool sequence**:
1. `GOOGLE_ANALYTICS_LIST_ACCOUNTS` - List all accessible GA4 accounts [Required]
2. `GOOGLE_ANALYTICS_LIST_PROPERTIES` - List properties under an account [Required]

**Key parameters**:
- `pageSize`: Number of results per page
- `pageToken`: Pagination token from previous response
- `filter`: Filter expression for properties (e.g., `parent:accounts/12345`)

**Pitfalls**:
- Property IDs are numeric strings prefixed with 'properties/' (e.g., 'properties/123456')
- Account IDs are prefixed with 'accounts/' (e.g., 'accounts/12345')
- Always list accounts first, then properties under each account
- Pagination required for organizations with many properties

### 2. Run Standard Reports

**When to use**: User wants to query metrics and dimensions from GA4 data

**Tool sequence**:
1. `GOOGLE_ANALYTICS_LIST_PROPERTIES` - Get property ID [Prerequisite]
2. `GOOGLE_ANALYTICS_GET_METADATA` - Discover available dimensions and metrics [Optional]
3. `GOOGLE_ANALYTICS_CHECK_COMPATIBILITY` - Verify dimension/metric compatibility [Optional]
4. `GOOGLE_ANALYTICS_RUN_REPORT` - Execute the report query [Required]

**Key parameters**:
- `property`: Property ID (e.g., 'properties/123456')
- `dateRanges`: Array of date range objects with `startDate` and `endDate`
- `dimensions`: Array of dimension objects with `name` field
- `metrics`: Array of metric objects with `name` field
- `dimensionFilter` / `metricFilter`: Filter expressions
- `orderBys`: Sort order configuration
- `limit`: Maximum rows to return
- `offset`: Row offset for pagination

**Pitfalls**:
- Date format is 'YYYY-MM-DD' or relative values like 'today', 'yesterday', '7daysAgo', '30daysAgo'
- Not all dimensions and metrics are compatible; use CHECK_COMPATIBILITY first
- Use GET_METADATA to discover valid dimension and metric names
- Maximum 9 dimensions per report request
- Row limit defaults vary; set explicitly for large datasets
- `offset` is for result pagination, not date pagination

### 3. Run Batch Reports

**When to use**: User needs multiple different reports from the same property in one call

**Tool sequence**:
1. `GOOGLE_ANALYTICS_LIST_PROPERTIES` - Get property ID [Prerequisite]
2. `GOOGLE_ANALYTICS_BATCH_RUN_REPORTS` - Execute multiple reports at once [Required]

**Key parameters**:
- `property`: Property ID (required)
- `requests`: Array of individual report request objects (same structure as RUN_REPORT)

**Pitfalls**:
- Maximum 5 report requests per batch call
- All reports in a batch must target the same property
- Each individual report has the same dimension/metric limits as RUN_REPORT
- Batch errors may affect all reports; check individual report responses

### 4. Run Pivot Reports

**When to use**: User wants cross-tabulated data (rows vs columns) like pivot tables

**Tool sequence**:
1. `GOOGLE_ANALYTICS_LIST_PROPERTIES` - Get property ID [Prerequisite]
2. `GOOGLE_ANALYTICS_RUN_PIVOT_REPORT` - Execute pivot report [Required]

**Key parameters**:
- `property`: Property ID (required)
- `dateRanges`: Date range objects
- `dimensions`: All dimensions used in any pivot
- `metrics`: Metrics to aggregate
- `pivots`: Array of pivot definitions with `fieldNames`, `limit`, and `orderBys`

**Pitfalls**:
- Dimensions used in pivots must also be listed in top-level `dimensions`
- Pivot `fieldNames` reference dimension names from the top-level list
- Complex pivots with many dimensions can produce very large result sets
- Each pivot has its own independent `limit` and `orderBys`

### 5. Run Funnel Reports

**When to use**: User wants to analyze conversion funnels and drop-off rates

**Tool sequence**:
1. `GOOGLE_ANALYTICS_LIST_PROPERTIES` - Get property ID [Prerequisite]
2. `GOOGLE_ANALYTICS_RUN_FUNNEL_REPORT` - Execute funnel analysis [Required]

**Key parameters**:
- `property`: Property ID (required)
- `dateRanges`: Date range objects
- `funnel`: Funnel definition with `steps` array
- `funnelBreakdown`: Optional dimension to break down funnel by

**Pitfalls**:
- Funnel steps are ordered; each step defines a condition users must meet
- Steps use filter expressions similar to dimension/metric filters
- Open funnels allow entry at any step; closed funnels require sequential progression
- Funnel reports may take longer to process than standard reports

### 6. Manage Key Events

**When to use**: User wants to view or manage conversion events (key events) in GA4

**Tool sequence**:
1. `GOOGLE_ANALYTICS_LIST_PROPERTIES` - Get property ID [Prerequisite]
2. `GOOGLE_ANALYTICS_LIST_KEY_EVENTS` - List all key events for the property [Required]

**Key parameters**:
- `parent`: Property resource name (e.g., 'properties/123456')
- `pageSize`: Number of results per page
- `pageToken`: Pagination token

**Pitfalls**:
- Key events were previously called "conversions" in GA4
- Property must have key events configured to return results
- Key event names correspond to GA4 event names

## Common Patterns

### ID Resolution

**Account name -> Account ID**:
```
1. Call GOOGLE_ANALYTICS_LIST_ACCOUNTS
2. Find account by displayName
3. Extract name field (e.g., 'accounts/12345')
```

**Property name -> Property ID**:
```
1. Call GOOGLE_ANALYTICS_LIST_PROPERTIES with filter
2. Find property by displayName
3. Extract name field (e.g., 'properties/123456')
```

### Dimension/Metric Discovery

```
1. Call GOOGLE_ANALYTICS_GET_METADATA with property ID
2. Browse available dimensions and metrics
3. Call GOOGLE_ANALYTICS_CHECK_COMPATIBILITY to verify combinations
4. Use verified dimensions/metrics in RUN_REPORT
```

### Pagination

- Reports: Use `offset` and `limit` for row pagination
- Accounts/Properties: Use `pageToken` from response
- Continue until `pageToken` is absent or `rowCount` reached

### Common Dimensions and Metrics

**Dimensions**: `date`, `city`, `country`, `deviceCategory`, `sessionSource`, `sessionMedium`, `pagePath`, `pageTitle`, `eventName`

**Metrics**: `activeUsers`, `sessions`, `screenPageViews`, `eventCount`, `conversions`, `totalRevenue`, `bounceRate`, `averageSessionDuration`

## Known Pitfalls

**Property IDs**:
- Always use full resource name format: 'properties/123456'
- Numeric ID alone will cause errors
- Resolve property names to IDs via LIST_PROPERTIES

**Date Ranges**:
- Format: 'YYYY-MM-DD' or relative ('today', 'yesterday', '7daysAgo', '30daysAgo')
- Data processing delay means today's data may be incomplete
- Maximum date range varies by property configuration

**Compatibility**:
- Not all dimensions work with all metrics
- Always verify with CHECK_COMPATIBILITY before complex reports
- Custom dimensions/metrics have specific naming patterns

**Response Parsing**:
- Report data is nested in `rows` array with `dimensionValues` and `metricValues`
- Values are returned as strings; parse numbers explicitly
- Empty reports return no `rows` key (not an empty array)

## Quick Reference

| Task | Tool Slug | Key Params |
|------|-----------|------------|
| List accounts | GOOGLE_ANALYTICS_LIST_ACCOUNTS | pageSize, pageToken |
| List properties | GOOGLE_ANALYTICS_LIST_PROPERTIES | filter, pageSize |
| Get metadata | GOOGLE_ANALYTICS_GET_METADATA | property |
| Check compatibility | GOOGLE_ANALYTICS_CHECK_COMPATIBILITY | property, dimensions, metrics |
| Run report | GOOGLE_ANALYTICS_RUN_REPORT | property, dateRanges, dimensions, metrics |
| Batch reports | GOOGLE_ANALYTICS_BATCH_RUN_REPORTS | property, requests |
| Pivot report | GOOGLE_ANALYTICS_RUN_PIVOT_REPORT | property, dateRanges, pivots |
| Funnel report | GOOGLE_ANALYTICS_RUN_FUNNEL_REPORT | property, dateRanges, funnel |
| List key events | GOOGLE_ANALYTICS_LIST_KEY_EVENTS | parent, pageSize |

## When to Use
This skill is applicable to execute the workflow or actions described in the overview.

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


---
name: google-calendar-automation
description: "Lightweight Google Calendar integration with standalone OAuth authentication. No MCP server required."
license: Apache-2.0
risk: critical
source: community
metadata:
  author: sanjay3290
  version: "1.0"
---

# Google Calendar

Lightweight Google Calendar integration with standalone OAuth authentication. No MCP server required.

> **⚠ Requires Google Workspace account.** Personal Gmail accounts are not supported.

## When to Use
- You need to list, create, inspect, or update Google Calendar events from local scripts.
- The task requires OAuth-backed calendar automation without standing up an MCP server.
- You need quick operational access to calendars, schedules, attendees, or event details in a Workspace environment.

## First-Time Setup

Authenticate with Google (opens browser):
```bash
python scripts/auth.py login
```

Check authentication status:
```bash
python scripts/auth.py status
```

Logout when needed:
```bash
python scripts/auth.py logout
```

## Commands

All operations via `scripts/gcal.py`. Auto-authenticates on first use if not logged in.

### List Calendars
```bash
python scripts/gcal.py list-calendars
```

### List Events
```bash
# List events from primary calendar (default: next 30 days)
python scripts/gcal.py list-events

# List events with specific time range
python scripts/gcal.py list-events --time-min 2024-01-15T00:00:00Z --time-max 2024-01-31T23:59:59Z

# List events from a specific calendar
python scripts/gcal.py list-events --calendar "work@example.com"

# Limit results
python scripts/gcal.py list-events --max-results 10
```

### Get Event Details
```bash
python scripts/gcal.py get-event EVENT_ID
python scripts/gcal.py get-event EVENT_ID --calendar "work@example.com"
```

### Create Event
```bash
# Basic event
python scripts/gcal.py create-event "Team Meeting" "2024-01-15T10:00:00Z" "2024-01-15T11:00:00Z"

# Event with description and location
python scripts/gcal.py create-event "Team Meeting" "2024-01-15T10:00:00Z" "2024-01-15T11:00:00Z" \
    --description "Weekly sync" --location "Conference Room A"

# Event with attendees
python scripts/gcal.py create-event "Team Meeting" "2024-01-15T10:00:00Z" "2024-01-15T11:00:00Z" \
    --attendees user1@example.com user2@example.com

# Event on specific calendar
python scripts/gcal.py create-event "Meeting" "2024-01-15T10:00:00Z" "2024-01-15T11:00:00Z" \
    --calendar "work@example.com"
```

### Update Event
```bash
# Update event title
python scripts/gcal.py update-event EVENT_ID --summary "New Title"

# Update event time
python scripts/gcal.py update-event EVENT_ID --start "2024-01-15T14:00:00Z" --end "2024-01-15T15:00:00Z"

# Update multiple fields
python scripts/gcal.py update-event EVENT_ID \
    --summary "Updated Meeting" --description "New agenda" --location "Room B"

# Update attendees
python scripts/gcal.py update-event EVENT_ID --attendees user1@example.com user3@example.com
```

### Delete Event
```bash
python scripts/gcal.py delete-event EVENT_ID
python scripts/gcal.py delete-event EVENT_ID --calendar "work@example.com"
```

### Find Free Time
Find the first available slot for a meeting with specified attendees:
```bash
# Find 30-minute slot for yourself
python scripts/gcal.py find-free-time \
    --attendees me \
    --time-min "2024-01-15T09:00:00Z" \
    --time-max "2024-01-15T17:00:00Z" \
    --duration 30

# Find 60-minute slot with multiple attendees
python scripts/gcal.py find-free-time \
    --attendees me user1@example.com user2@example.com \
    --time-min "2024-01-15T09:00:00Z" \
    --time-max "2024-01-19T17:00:00Z" \
    --duration 60
```

### Respond to Event Invitation
```bash
# Accept an invitation
python scripts/gcal.py respond-to-event EVENT_ID accepted

# Decline an invitation
python scripts/gcal.py respond-to-event EVENT_ID declined

# Mark as tentative
python scripts/gcal.py respond-to-event EVENT_ID tentative

# Respond without notifying organizer
python scripts/gcal.py respond-to-event EVENT_ID accepted --no-notify
```

## Date/Time Format

All times use ISO 8601 format with timezone:
- UTC: `2024-01-15T10:30:00Z`
- With offset: `2024-01-15T10:30:00-05:00` (EST)

## Calendar ID Format

- Primary calendar: Use `primary` or omit the `--calendar` flag
- Other calendars: Use the calendar ID from `list-calendars` (usually an email address)

## Token Management

Tokens stored securely using the system keyring:
- **macOS**: Keychain
- **Windows**: Windows Credential Locker
- **Linux**: Secret Service API (GNOME Keyring, KDE Wallet, etc.)

Service name: `google-calendar-skill-oauth`

Tokens are automatically refreshed when expired using Google's cloud function.

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


---
name: google-docs-automation
description: "Lightweight Google Docs integration with standalone OAuth authentication. No MCP server required."
license: Apache-2.0
risk: critical
source: community
metadata:
  author: sanjay3290
  version: "1.0"
---

# Google Docs

Lightweight Google Docs integration with standalone OAuth authentication. No MCP server required.

> **⚠ Requires Google Workspace account.** Personal Gmail accounts are not supported.

## When to Use
- You need to create, search, read, or edit Google Docs from local automation scripts.
- The task involves document text extraction, append/insert operations, or content replacement in Workspace docs.
- You want direct Docs automation without relying on an MCP server.

## First-Time Setup

Authenticate with Google (opens browser):
```bash
python scripts/auth.py login
```

Check authentication status:
```bash
python scripts/auth.py status
```

Logout when needed:
```bash
python scripts/auth.py logout
```

## Commands

All operations via `scripts/docs.py`. Auto-authenticates on first use if not logged in.

```bash
# Create a new document
python scripts/docs.py create "Meeting Notes"

# Create a document with initial content
python scripts/docs.py create "Project Plan" --content "# Overview\n\nThis is the project plan."

# Find documents by title
python scripts/docs.py find "meeting" --limit 10

# Get text content of a document
python scripts/docs.py get-text 1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms

# Get text using a full URL
python scripts/docs.py get-text "https://docs.google.com/document/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit"

# Append text to end of document
python scripts/docs.py append-text 1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms "New paragraph at the end."

# Insert text at beginning of document
python scripts/docs.py insert-text 1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms "Text at the beginning.\n\n"

# Replace text in document
python scripts/docs.py replace-text 1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms "old text" "new text"
```

## Document ID Format

Google Docs uses document IDs like `1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms`. You can:
- Use the full URL (the ID will be extracted automatically)
- Use just the document ID
- Get document IDs from the `find` command results

## Token Management

Tokens stored securely using the system keyring:
- **macOS**: Keychain
- **Windows**: Windows Credential Locker
- **Linux**: Secret Service API (GNOME Keyring, KDE Wallet, etc.)

Service name: `google-docs-skill-oauth`

Access tokens are automatically refreshed when expired using Google's cloud function.

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


---
name: google-drive-automation
description: "Lightweight Google Drive integration with standalone OAuth authentication. No MCP server required. Full read/write access."
license: Apache-2.0
risk: critical
source: community
metadata:
  author: sanjay3290
  version: "1.0"
---

# Google Drive

Lightweight Google Drive integration with standalone OAuth authentication. No MCP server required. Full read/write access.

> **Requires Google Workspace account.** Personal Gmail accounts are not supported.

## When to Use
- You need to search, list, upload, download, move, or organize Google Drive files and folders.
- The task requires direct Drive read/write automation through local scripts in a Workspace account.
- You want file-level Drive operations without introducing an MCP server dependency.

## First-Time Setup

Authenticate with Google (opens browser):
```bash
python scripts/auth.py login
```

Check authentication status:
```bash
python scripts/auth.py status
```

Logout when needed:
```bash
python scripts/auth.py logout
```

## Read Commands

All operations via `scripts/drive.py`. Auto-authenticates on first use if not logged in.

```bash
# Search for files (full-text search)
python scripts/drive.py search "quarterly report"

# Search by title only
python scripts/drive.py search "title:budget"

# Search using Google Drive URL (extracts ID automatically)
python scripts/drive.py search "https://drive.google.com/drive/folders/1ABC123..."

# Search files shared with you
python scripts/drive.py search --shared-with-me

# Search with pagination
python scripts/drive.py search "report" --limit 5 --page-token "..."

# Find a folder by exact name
python scripts/drive.py find-folder "Project Documents"

# List files in root Drive
python scripts/drive.py list

# List files in a specific folder
python scripts/drive.py list 1ABC123xyz --limit 20

# Download a file
python scripts/drive.py download 1ABC123xyz ./downloads/report.pdf
```

## Write Commands

```bash
# Upload a file to Drive root
python scripts/drive.py upload ~/Documents/report.pdf

# Upload to a specific folder
python scripts/drive.py upload ~/Documents/report.pdf --folder 1ABC123xyz

# Upload with a custom name
python scripts/drive.py upload ~/Documents/report.pdf --name "Q4 Report.pdf"

# Create a new folder
python scripts/drive.py create-folder "Project Documents"

# Create a folder inside another folder
python scripts/drive.py create-folder "Attachments" --parent 1ABC123xyz

# Move a file to a different folder
python scripts/drive.py move FILE_ID DESTINATION_FOLDER_ID

# Copy a file
python scripts/drive.py copy FILE_ID
python scripts/drive.py copy FILE_ID --name "Report Copy" --folder 1ABC123xyz

# Rename a file or folder
python scripts/drive.py rename FILE_ID "New Name.pdf"

# Move a file to trash
python scripts/drive.py trash FILE_ID
```

## Search Query Formats

The search command supports multiple query formats:

| Format | Example | Description |
|--------|---------|-------------|
| Full-text | `"quarterly report"` | Searches file contents and names |
| Title | `"title:budget"` | Searches file names only |
| URL | `https://drive.google.com/...` | Extracts and uses file/folder ID |
| Folder ID | `1ABC123...` | Lists folder contents (25+ char IDs) |
| Native query | `mimeType='application/pdf'` | Pass-through Drive query syntax |

## File ID Format

Google Drive uses long IDs like `1ABC123xyz_-abc123`. Get IDs from:
- `search` results
- `find-folder` results
- `list` results
- Google Drive URLs

## Download Limitations

- Regular files (PDFs, images, etc.) download directly
- Google Docs/Sheets/Slides cannot be downloaded via this tool
- For Google Workspace files, use export or dedicated tools

## Token Management

Tokens stored securely using the system keyring:
- **macOS**: Keychain
- **Windows**: Windows Credential Locker
- **Linux**: Secret Service API (GNOME Keyring, KDE Wallet, etc.)

Service name: `google-drive-skill-oauth`

Automatically refreshes expired tokens using Google's cloud function.

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


---
name: google-sheets-automation
description: "Lightweight Google Sheets integration with standalone OAuth authentication. No MCP server required. Full read/write access."
risk: critical
source: community
license: Apache-2.0
metadata:
  author: sanjay3290
  version: "1.0"
---

# Google Sheets

Lightweight Google Sheets integration with standalone OAuth authentication. No MCP server required. Full read/write access.

> **Requires Google Workspace account.** Personal Gmail accounts are not supported.

## First-Time Setup

Authenticate with Google (opens browser):
```bash
python scripts/auth.py login
```

Check authentication status:
```bash
python scripts/auth.py status
```

Logout when needed:
```bash
python scripts/auth.py logout
```

## Read Commands

All operations via `scripts/sheets.py`. Auto-authenticates on first use if not logged in.

```bash
# Get spreadsheet content as plain text (default)
python scripts/sheets.py get-text SPREADSHEET_ID

# Get spreadsheet content as CSV
python scripts/sheets.py get-text SPREADSHEET_ID --format csv

# Get spreadsheet content as JSON
python scripts/sheets.py get-text SPREADSHEET_ID --format json

# Get values from a specific range (A1 notation)
python scripts/sheets.py get-range SPREADSHEET_ID "Sheet1!A1:D10"
python scripts/sheets.py get-range SPREADSHEET_ID "A1:C5"

# Find spreadsheets by search query
python scripts/sheets.py find "budget 2024"
python scripts/sheets.py find "sales report" --limit 5

# Get spreadsheet metadata (sheets, dimensions, etc.)
python scripts/sheets.py get-metadata SPREADSHEET_ID
```

## Write Commands

```bash
# Update a range of cells with values (JSON 2D array)
python scripts/sheets.py update-range SPREADSHEET_ID "Sheet1!A1:B2" '[["Hello","World"],["Foo","Bar"]]'

# Update with RAW input (no formula parsing, treats everything as literal text)
python scripts/sheets.py update-range SPREADSHEET_ID "Sheet1!A1:B1" '[["=SUM(A1:A5)","text"]]' --raw

# Append rows after the last data row
python scripts/sheets.py append-rows SPREADSHEET_ID "Sheet1!A:Z" '[["New Row Col A","New Row Col B"]]'

# Clear values from a range (keeps formatting)
python scripts/sheets.py clear-range SPREADSHEET_ID "Sheet1!A1:B10"

# Batch update (advanced - for formatting, merging, etc.)
python scripts/sheets.py batch-update SPREADSHEET_ID '[{"updateCells":{"range":{"sheetId":0},"fields":"userEnteredValue"}}]'
```

## Spreadsheet ID

You can use either:
- The spreadsheet ID: `1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms`
- The full URL: `https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit`

The script automatically extracts the ID from URLs.

## Output Formats

### Text (default)
Human-readable format with pipe separators:
```
Spreadsheet Title: Sales Data
Sheet Name: Q1
Name | Revenue | Units
Product A | 10000 | 50
Product B | 15000 | 75
```

### CSV
Standard CSV format, suitable for further processing:
```
Name,Revenue,Units
Product A,10000,50
Product B,15000,75
```

### JSON
Structured data format:
```json
{
  "Q1": [
    ["Name", "Revenue", "Units"],
    ["Product A", "10000", "50"]
  ]
}
```

## A1 Notation Examples

- `Sheet1!A1:B10` - Range A1 to B10 on Sheet1
- `Sheet1!A:A` - All of column A on Sheet1
- `Sheet1!1:1` - All of row 1 on Sheet1
- `A1:C5` - Range on the first sheet

## Value Input Options

- **USER_ENTERED** (default): Values are parsed as if typed by a user. Numbers, dates, and formulas are interpreted.
- **RAW** (`--raw` flag): Values are stored exactly as provided. No parsing of formulas or number formatting.

## Token Management

Tokens stored securely using the system keyring:
- **macOS**: Keychain
- **Windows**: Windows Credential Locker
- **Linux**: Secret Service API (GNOME Keyring, KDE Wallet, etc.)

Service name: `google-sheets-skill-oauth`

Tokens automatically refresh when expired using Google's cloud function.

## When to Use
Use this skill when tackling tasks related to its primary domain or functionality as described above.

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


---
name: google-slides-automation
description: "Lightweight Google Slides integration with standalone OAuth authentication. No MCP server required. Full read/write access."
license: Apache-2.0
risk: critical
source: community
metadata:
  author: sanjay3290
  version: "1.0"
---

# Google Slides

Lightweight Google Slides integration with standalone OAuth authentication. No MCP server required. Full read/write access.

> **Requires Google Workspace account.** Personal Gmail accounts are not supported.

## When to Use
- You need to create, inspect, or modify Google Slides presentations from local automation.
- The task involves reading slide text, adding/removing slides, or batch updating presentation content.
- You want Slides automation for Workspace documents without using an MCP server.

## First-Time Setup

Authenticate with Google (opens browser):
```bash
python scripts/auth.py login
```

Check authentication status:
```bash
python scripts/auth.py status
```

Logout when needed:
```bash
python scripts/auth.py logout
```

## Read Commands

All operations via `scripts/slides.py`. Auto-authenticates on first use if not logged in.

```bash
# Get all text content from a presentation
python scripts/slides.py get-text "1abc123xyz789"
python scripts/slides.py get-text "https://docs.google.com/presentation/d/1abc123xyz789/edit"

# Find presentations by search query
python scripts/slides.py find "quarterly report"
python scripts/slides.py find "project proposal" --limit 5

# Get presentation metadata (title, slide count, slide object IDs)
python scripts/slides.py get-metadata "1abc123xyz789"
```

## Write Commands

```bash
# Create a new empty presentation
python scripts/slides.py create "Q4 Sales Report"

# Add a blank slide to the end
python scripts/slides.py add-slide "1abc123xyz789"

# Add a slide with a specific layout
python scripts/slides.py add-slide "1abc123xyz789" --layout TITLE_AND_BODY

# Add a slide at a specific position (0-based index)
python scripts/slides.py add-slide "1abc123xyz789" --layout TITLE --at 0

# Find and replace text across all slides
python scripts/slides.py replace-text "1abc123xyz789" "old text" "new text"
python scripts/slides.py replace-text "1abc123xyz789" "Draft" "Final" --match-case

# Delete a slide by object ID (use get-metadata to find IDs)
python scripts/slides.py delete-slide "1abc123xyz789" "g123abc456"

# Batch update (advanced - for formatting, inserting shapes, images, etc.)
python scripts/slides.py batch-update "1abc123xyz789" '[{"replaceAllText":{"containsText":{"text":"foo"},"replaceText":"bar"}}]'
```

## Slide Layouts

Available layouts for `add-slide --layout`:
- `BLANK` - Empty slide (default)
- `TITLE` - Title slide
- `TITLE_AND_BODY` - Title with body text
- `TITLE_AND_TWO_COLUMNS` - Title with two text columns
- `TITLE_ONLY` - Title bar only
- `SECTION_HEADER` - Section divider
- `ONE_COLUMN_TEXT` - Single column text
- `MAIN_POINT` - Main point highlight
- `BIG_NUMBER` - Large number display

## Presentation ID Format

You can use either:
- Direct presentation ID: `1abc123xyz789`
- Full Google Slides URL: `https://docs.google.com/presentation/d/1abc123xyz789/edit`

The scripts automatically extract the ID from URLs.

## Output Format

### get-text
Returns extracted text from all slides, including:
- Presentation title
- Text from shapes/text boxes on each slide
- Table data with cell contents

### find
Returns list of matching presentations:
```json
{
  "presentations": [
    {"id": "1abc...", "name": "Q4 Report", "modifiedTime": "2024-01-15T..."}
  ],
  "nextPageToken": "..."
}
```

### get-metadata
Returns presentation details:
```json
{
  "presentationId": "1abc...",
  "title": "My Presentation",
  "slideCount": 15,
  "pageSize": {"width": {...}, "height": {...}},
  "hasMasters": true,
  "hasLayouts": true
}
```

## Token Management

Tokens stored securely using the system keyring:
- **macOS**: Keychain
- **Windows**: Windows Credential Locker
- **Linux**: Secret Service API (GNOME Keyring, KDE Wallet, etc.)

Service name: `google-slides-skill-oauth`

Automatically refreshes expired tokens using Google's cloud function.

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