# danicat/skills (Full Instructions Catalog) > Complete collection of all Agent Skills. --- # Skill: ebitengineer (game-dev) > Engineering architecture and best practices for building 2D games in Go using Ebitengine (v2). Covers modular game architecture, scene state machines, virtual resolution scaling, delta-time physics, zero-allocation draw loops, Kage shaders, and WebAssembly audio synchronization. Activate when designing, building, optimizing, or debugging 2D games in Go, implementing game systems with Ebitengine, or compiling games to WebAssembly. **Web Page**: https://skills.danicat.dev/game-dev/ebitengineer/ **Source**: https://skills.danicat.dev/game-dev/ebitengineer/SKILL.md **Version**: 0.2.0 **Digest**: sha256:a46fac4ab155ee6eec7b642e51e32687514b7d79fbd23f0b3a2b7197f6852194 **Install**: `npx skills add danicat/skills --skill ebitengineer -y` ## Instructions # Ebitengine 2D Game Development Guide (ebitengineer) Comprehensive engineering guidelines for building modular, high-performance, cross-platform 2D games in Go using [Ebitengine v2](https://ebitengine.org/). --- ## Trigger Conditions Activate this skill whenever: - Designing or implementing 2D game architecture, scene flow, or rendering in Go. - Working with Ebitengine interfaces (`ebiten.Game`), state machines, input management, audio, or custom typography. - Optimizing cycle timing, WASM audio synchronization, touch controls, server architecture, or writing unit tests for Go game components. --- ## Core Architecture & Guidelines ### 1. Modular Architecture (`internal/`) Organize the codebase into modular subsystems under `internal/`. Avoid monolithic single-file games. - For complete directory tree and package responsibilities, see [`references/project_structure.md`](references/project_structure.md). --- ## Engine Reference Modules For deep technical patterns, Go code implementations, and mathematical algorithms, consult these modular reference guides: | Module | Reference File | Key Topics Covered | | :--- | :--- | :--- | | **Project Structure** | [`references/project_structure.md`](references/project_structure.md) | Package tree and `internal/` subsystem responsibilities. | | **Server & Cloud Run** | [`references/server_architecture.md`](references/server_architecture.md) | WebAssembly build, Docker multi-stage, and Cloud Run REST API. | | **Physics & Collision** | [`references/physics_and_collision.md`](references/physics_and_collision.md) | AABB sweep tests, spatial hashing grid, and platformer slope math. | | **Tilemaps & Levels** | [`references/tilemaps_and_levels.md`](references/tilemaps_and_levels.md) | Tiled/LDtk parsing, 16-pipe autotiling, and frustum tile culling. | | **UI & HUD System** | [`references/ui_and_hud.md`](references/ui_and_hud.md) | 9-slice panel scaling, flex anchoring, progress bars, and widget FSM. | | **Input Action Mapping** | [`references/input_action_mapping.md`](references/input_action_mapping.md) | Rebindable action maps, analog deadzones, and input device abstraction. | | **Entity Management** | [`references/entity_management.md`](references/entity_management.md) | Slice pools, deferred deletion buffers, and light component ECS. | | **Pathfinding & AI** | [`references/pathfinding_and_ai.md`](references/pathfinding_and_ai.md) | A* grid pathfinding, steering behaviors (seek/arrive), and enemy FSM. | ### 2. Asset Embedding & Validation Standards - **Zero-Dependency Embedding**: Embed all game assets (sprites, TTF fonts, audio MP3s/OGGs, Kage shaders) directly into the compiled Go binary using Go 1.16+ `embed.FS` (`assets.FS`). - **Mandatory Asset Validation**: AI agents and developers must **always validate asset files using file identifying tools** (such as the `file` CLI utility, `mimetype` inspection tools, or `http.DetectContentType` in Go) during asset ingestion and preloading. Unvalidated or misrepresented asset files will cause silent decoding failures or a black screen on WebAssembly (WASM). Always convert or correct misrepresented files to match the codebase's intended image format. ### 3. Aspect Ratio & Virtual Pixel Canvas - **16:9 Widescreen Priority**: Unless explicitly specified otherwise, always target a **16:9 aspect ratio** (`320x180`, `640x360`, `1280x720`, `1920x1080`). - **Virtual Pixel Canvas**: Operating on a fixed internal virtual pixel resolution. All entity physics, collision math, camera coordinates, and UI layouts operate strictly in this virtual coordinate system. - **Automatic Multi-Resolution Scaling**: `Layout(outsideWidth, outsideHeight int)` returns constant virtual dimensions (`virtualWidth, virtualHeight`). Ebitengine handles scaling to fit any display configuration. ### 4. Cycle Timing & Frame Synchronization - **Target Frame Rate**: Standard target is **60 FPS** (`ebiten.SetTPS(60)`). - **Cycle Timing over Tick Sync**: Use delta time / cycle timing ($dt$) to calculate movement deltas to ensure identical game speed across varying hardware and refresh rates (e.g. 144Hz monitors). - **Frame Skipping**: Accumulate elapsed cycle time in `Update()` and handle catch-up physics steps if rendering lags behind logic updates. ### 5. Windowing & Fullscreen Toggle Support windowed and fullscreen modes with a toggle hotkey (`F11` or `Alt+Enter`): ```go if inpututil.IsKeyJustPressed(ebiten.KeyF11) || (ebiten.IsKeyPressed(ebiten.KeyAlt) && inpututil.IsKeyJustPressed(ebiten.KeyEnter)) { ebiten.SetFullscreen(!ebiten.IsFullscreen()) } ``` --- ## Game State Machine & Scene Flow ### Finite State Machine (FSM) Lifecycle Model all scenes using a State interface with strict lifecycle hooks (`Enter()`, `Update(dt)`, `Draw(screen)`, `Exit()`). ### Standard Scene Progression ```text Boot (Company Logo) -> Intro -> Title Screen -> Game Play -> Game Win (or Game Over) -> Title Screen ``` ### Transition Cleanliness (No Leaks) Upon `Exit()`, every state **must**: - Stop or fade out BGM/SFX channels belonging to that scene. - Flush active particle emitters, animations, and camera shakes. - Reset transient input buffers so button presses do not carry over into the next state. ### Attract / Demo Mode (Arcade Style) 1. **Idle Timeout**: On `Title Screen`, if no input is received after a timeout (e.g. 10s), transition to `Demo Mode` (CPU plays the game). 2. **Interrupt**: Any user input in `Demo Mode` interrupts execution immediately back to `Title Screen`. 3. **Alternating Flow**: Consecutive Title Screen idle timeouts alternate between launching `Demo Mode` and re-playing `Intro`. --- ## WebAssembly (WASM) & Server Architecture ### Audio Context Initialization & Late-Sync - **Browser Autoplay Restriction**: WebAudio contexts are blocked until the user performs their first gesture (touch, click, keypress). - **Late Touch Synchronization**: Game timers continue running during silent load. When unlocked upon first interaction, BGM playback must **skip ahead** (seek to current elapsed game time $dt$) rather than starting at `0:00`, preventing audio-visual desynchronization. ### Touch Controls & WASM Server - **Touch Input**: Query touch points via `ebiten.AppendTouchIDs(nil)`. Virtual D-pads and virtual keyboards are optional. - **Cloud Run Hosting & High Score API**: Target **Google Cloud Run** for serverless hosting of embedded WASM static assets (`//go:embed web/*`) and REST API endpoints (e.g. `/api/v1/scores`) for global leaderboards and cloud state. - For complete Cloud Run server architecture, multi-stage Dockerfile, and Go server implementation, see [`references/server_architecture.md`](references/server_architecture.md). --- ## Input, Camera, Shaders & Typography - **Input & Gamepads**: Detect gamepads via `ebiten.AppendGamepadIDs(nil)` and map buttons/axes in `internal/input`. - **Camera & Viewport**: Decouple world coordinates from screen coordinates. Use camera lerp for smooth tracking and transient offsets for screen shake. - **Audio Channels**: Maintain separate volume multipliers for Master, BGM (`audio.NewInfiniteLoop`), and SFX channels. - **Custom Shaders**: Write post-processing effects (CRT scanlines, palette swapping, screen flash) using custom Kage shaders (`ebiten.NewShader`). - **Save State Persistence**: Use `os.UserConfigDir()` on desktop, `localStorage` on WASM, or server API for cloud saves. - **Custom Typography (No Debug Prints)**: Do **NOT** use `ebitenutil.DebugPrint` for user-facing game text. Load custom TTF/OTF fonts matching game vibe using `golang.org/x/image/font` or `ebiten/v2/text`. --- ## Unit Testing Requirements Write unit tests for all testable non-rendering logic components: - State Machine transitions and scene sequence flow. - Physics, collision detection, and math. - Score tracking, inventory, and stats. - AI / CPU controller logic for `Demo Mode`. - Input mapping and server API score sorting. --- ## Core Performance Rules 1. **Zero Allocations in `Draw()`**: Never allocate `ebiten.NewImage()`, slices, or format strings inside `Draw()`. Pre-allocate all buffers. 2. **Decouple Logic & Render**: Keep logic strictly in `Update()`. `Draw()` must be read-only relative to game state. 3. **Preload Assets**: Load images, fonts, and audio during `Boot` state initialization. --- # Skill: game-design (game-dev) > Interactive game design workflow and Game Design Document (GDD) authoring guide for 2D games. Structures game ideation through interactive probing interviews, defining core gameplay loops, win and loss conditions, control schemes, visual asset pipelines, and audio strategies into a clean GDD.md. Activate when conceptualizing a new game, defining gameplay mechanics, conducting game design interviews (/grill-me), or authoring a Game Design Document. **Web Page**: https://skills.danicat.dev/game-dev/game-design/ **Source**: https://skills.danicat.dev/game-dev/game-design/SKILL.md **Version**: 0.2.0 **Digest**: sha256:9c24f6789900777849dda51cd6897f2ab519e9566d9d0546205b4492abf5d5cc **Install**: `npx skills add danicat/skills --skill game-design -y` ## Instructions # Game Design & Interactive GDD Creation Guide (Game Designer Role) This skill equips AI agents acting in the **Game Designer Role** with structured interview protocols, probing frameworks, and templates to guide users from initial game ideas to a production-ready **Game Design Document (`GDD.md`)**. --- ## 1. Game Designer Role & Interactive Probing Protocol The **Game Designer Agent** aligns the user's vision before code or assets are generated: 1. **Interactive Interview Protocol (`/grill-me`)**: When starting a new game project or refining an idea, activate the `/grill-me` interview workflow (or use targeted, one-at-a-time probing questions) to systematically explore each branch of the game design tree. 2. **Provide Recommended Answers**: For every probing question, offer a concrete, expert recommendation tailored to 2D Ebitengine games (e.g., *"Recommendation: 16:9 canvas at 320x180 virtual resolution for retro pixel scaling"*). 3. **Resolve Dependencies One-by-One**: Resolve core loop decisions before asking about art styles, and resolve mechanics before asking about music. 4. **Produce Authoritative `GDD.md`**: Summarize all agreed decisions into a structured `GDD.md` saved in the workspace root. --- ## 2. Interactive Interview Branching Tree (`/grill-me` Workflow) Follow this sequential branching tree when interviewing the user: ```text Branch 1: Core Concept & Elevator Pitch ├── What is the 1-sentence hook / elevator pitch? └── What classic game(s) serve as primary inspiration? Branch 2: Gameplay Loop & Mechanics ├── What is the primary action cycle? (Action -> Challenge -> Reward) ├── What are the exact win and loss conditions? └── What hazards, enemies, or time pressures exist? Branch 3: Controls & Input Mapping ├── What input devices are supported? (Keyboard / Gamepad / Mouse / Touch) └── What are the primary action buttons? Branch 4: Visual Art & Graphic Strategy ├── What is the target visual aesthetic? (Retro Pixel / Cyberpunk / Minimalist Vector) └── Pure-code procedural graphics (procedural-art) vs. Gemini AI assets (nano-banana)? Branch 5: Audio & Soundscape Strategy ├── High-fidelity CD music (lyria) vs. Pure-code DSP chiptunes (procedural-composer)? └── What sound effects (SFX) are required for gameplay feedback? Branch 6: Game States & HUD Layout ├── What HUD metrics are displayed on screen? (Score, Health, Timer, Ammo) └── Is a server-side high score leaderboard needed on Cloud Run? ``` --- ## 3. Template & Technical Standards For the complete, production-grade Game Design Document template, consult: | Module | Reference File | Key Topics Covered | | :--- | :--- | :--- | | **GDD Template** | [`references/gdd_template.md`](references/gdd_template.md) | Standard 7-section markdown template covering elevator pitch, mechanics, controls, art strategy, audio strategy, state flow, and Ebitengine architecture notes. | --- ## 4. Probing Question Templates with Recommendations Use these interview question templates during the `/grill-me` session: ### Question 1: Core Loop & Hook > *"What is the core 1-sentence pitch for your game, and what is the main mechanic?"* > **Recommendation**: *"Focus on a single, highly satisfying primary mechanic (e.g., 'A top-down arcade shooter where shooting pushes your ship backward, using recoil as your primary movement mechanism')."* ### Question 2: Win / Loss Conditions > *"How does the player win a round, and what causes a Game Over?"* > **Recommendation**: *"Keep game jam rounds short (1–3 minutes per run). Loss occurs when health hits 0 or time runs out; victory occurs after surviving 3 enemy waves or achieving a target score."* ### Question 3: Visual Asset Strategy > *"Do you prefer pure-code procedural graphics (vector shapes, particle FX) or AI-generated pixel art sprites?"* > **Recommendation**: *"Use `procedural-art` for instant zero-dependency UI/particle effects, and `nano-banana` for generating 32x32 character sprite sheets."* ### Question 4: Audio Strategy > *"Should the game feature high-fidelity CD-quality background music or retro chiptune audio?"* > **Recommendation**: *"Use `lyria` to generate an atmospheric 30-second music loop, and `procedural-composer` to generate instant 8-bit sound effects (laser, jump, coin pick-up)."* --- ## 5. GDD Generation Checklist Before handing off the generated `GDD.md` to technical skills (`ebitengineer`, `procedural-art`, `nano-banana`, `lyria`, `procedural-composer`): - [ ] **Elevator Pitch Defined**: Clear 1-sentence hook established. - [ ] **Core Loop Explicit**: Player actions, challenges, and rewards mapped out. - [ ] **Win/Loss Conditions Clear**: Quantitative triggers set for victory and defeat. - [ ] **Controls Mapped**: Actions bound across Keyboard, Gamepad, and Touch. - [ ] **Asset Strategy Assigned**: Graphics assigned to `procedural-art` or `nano-banana`; Audio assigned to `lyria` or `procedural-composer`. - [ ] **Saved to Disk**: Document committed as `GDD.md` in workspace root. --- # Skill: procedural-art (game-dev) > Pure-code procedural graphics, sprite generation, and visual effects (VFX) guide for 2D games. Generates sprites, tilesets, particle systems, and vector shapes in memory without external image files, enforcing 2D matrix transformation order, sub-frame animation easing, and pre-allocated particle pools. Activate when creating procedural 2D sprites, building zero-asset games, designing particle effects, or implementing 2D matrix transformations. **Web Page**: https://skills.danicat.dev/game-dev/procedural-art/ **Source**: https://skills.danicat.dev/game-dev/procedural-art/SKILL.md **Version**: 0.2.0 **Digest**: sha256:30369dd1a96ea3be7bcb7ea12770d3c027eb63c4ff28ce66b1ff559ec17f65bd **Install**: `npx skills add danicat/skills --skill procedural-art -y` ## Instructions # Procedural Art: Pure-Code 2D Sprites, Tiles, Particle Systems & Vector Graphics Guide This skill provides complete mathematical, graphical, and software architecture patterns for generating high-quality 2D sprites, tilesets, vector shapes, particle systems, and visual effects (VFX) purely in code—without relying on external `.png`, `.jpg`, or `.svg` asset files. > [!TIP] > **Reference Implementation**: > * **Procedural Art Driver**: [`references/art.go`](references/art.go) > * **Matrix Order & Easing Tests**: [`references/art_test.go`](references/art_test.go) --- ## 1. Core Architectural Principles & Zero-Asset Strategy Procedural art generates graphical textures in memory at startup or renders vector shapes dynamically during game frames: * **Zero disk I/O**: Eliminates asset loading delays, missing file errors, and large download sizes. * **Infinite Resolution Scaling**: Vector math and Signed Distance Fields (SDFs) scale cleanly to high-DPI displays. * **Dynamic Palette Tinting**: Real-time palette swapping for elemental states (poison, frozen, lava, shadow, elite buff). --- ## 2. "Retro-HD" Visual Style Benchmark & Color Theory We target the aesthetic richness of classic 16-bit/32-bit console art (SNES, Sega Saturn, Neo Geo, PS1) **combined with modern "Retro-HD" rendering capabilities**: * **Relaxing Color Limits**: Rather than restricting sprites to strict 16-color indexed hardware palettes, use **full 32-bit truecolor RGBA** for smooth lighting gradients, soft ambient occlusion, sub-pixel antialiasing, and alpha glow overlays—while preserving crisp pixel outlines and strong silhouettes. ### 2.1 Color Ramp Structure Every material in a procedural sprite (metal, cloth, wood, skin, fire) should use a 4-to-5 step color ramp: 1. **Dark Outline / Ambient Occlusion**: Very dark, low saturation (e.g. `#0F0C1C`). 2. **Deep Shadow**: Primary color tinted towards cool blue/purple. 3. **Base Tone**: Core material color. 4. **Light Highlight**: Primary color shifted towards warm yellow/white. 5. **High Specular**: Crisp 1-pixel highlight dot for metallic/glossy surfaces. --- ## 3. Transformation Mathematics & Order of Operations (CRITICAL) In 2D graphics programming (e.g., Ebitengine `ebiten.GeoM`), **the order in which transformation matrices are multiplied is mathematically non-commutative**. Applying operations in the wrong order will cause sprites to orbit wildly or scale off-screen! ### 3.1 Why Order of Operations Matters * **Correct Sequence: Pivot $\rightarrow$ Scale $\rightarrow$ Rotate $\rightarrow$ World Translation**: $$\mathbf{M}_{\text{correct}} = \mathbf{T}(X + O_x, Y + O_y) \cdot \mathbf{R}(\theta) \cdot \mathbf{S}(S_x, S_y) \cdot \mathbf{T}(-O_x, -O_y)$$ 1. Translate sprite origin to center pivot $(-O_x, -O_y)$. 2. Scale dimensions relative to the pivot $(S_x, S_y)$. 3. Rotate around the pivot $(\theta)$. 4. Translate the scaled and rotated sprite to world coordinate $(X, Y)$. * **Incorrect Sequence: World Translation $\rightarrow$ Scale**: $$\mathbf{M}_{\text{wrong}} = \mathbf{S}(S_x, S_y) \cdot \mathbf{T}(X, Y)$$ Translating to $(X, Y)$ *before* scaling causes the scaling matrix to multiply the translation vector itself ($X' = X \cdot S_x, Y' = Y \cdot S_y$), flinging the sprite away from its intended position on screen! --- ## 4. Animations, Fluid Motion & Sub-Frame Interpolation Fluid animations require sub-frame delta time ($dt$) integration and non-linear easing curves rather than linear step jumps. ### 4.1 Transition Frames & Easing Functions Always use easing functions to model physical weight, momentum, and elasticity: * **Linear**: $f(t) = t$ (Constant motion; suitable for conveyor belts or UI tickers). * **Ease-In Quadratic**: $f(t) = t^2$ (Slow start, accelerating; falling under gravity). * **Ease-Out Quadratic**: $f(t) = t(2 - t)$ (Fast start, decelerating; sliding friction). * **Ease-InOut Cubic**: $f(t) = 4t^3 \text{ if } t < 0.5 \text{ else } 1 - \frac{(-2t+2)^3}{2}$ (Smooth natural organic motion). * **Elastic Overshoot**: $f(t) = 2^{-10t} \sin\left(\frac{(t - 0.075) \cdot 2\pi}{0.3}\right) + 1$ (Springy UI pop-ups, sword swings). --- ## 5. Retro-HD Sprite Sheet Architecture & Frame Requirements To generate fluid, professional character animations, AI models must produce complete sprite sheet frame sets spanning all cardinal directions and action states. ### 5.1 Standard Directional Layouts * **4-Directional Grid**: Down (0), Left (1), Right (2), Up (3). * **8-Directional Grid**: Down (0), Down-Left (1), Left (2), Up-Left (3), Up (4), Up-Right (5), Right (6), Down-Right (7). * **Grid Storage**: Matrix array `[State][Direction][Frame]*ebiten.Image` or a combined sprite sheet texture (`ImageWidth = FrameWidth * NumFrames`, `ImageHeight = FrameHeight * NumDirections`). ### 5.2 Mandatory Animation States & Frame Count Benchmark | Animation State | Required Frames / Dir | Keyframes & Pose Progression | Easing / Timing Guidelines | | :--- | :--- | :--- | :--- | | **Idle / Breathing** | $4 - 8\text{ frames}$ | Subtle chest rise, shoulder dip, weapon idle shimmer. | Slow, smooth Ease-InOut Cubic ($1.2\text{s} - 1.8\text{s}$ cycle). | | **Walk / Run Cycle** | $8 - 12\text{ frames}$ | Contact $\rightarrow$ Recoil $\rightarrow$ Passing $\rightarrow$ High Point (both left & right legs). | Rhythmic, continuous loop ($0.6\text{s} - 0.9\text{s}$ cycle). | | **Attack / Strike** | $6 - 10\text{ frames}$ | 1. Wind-up/Anticipation (pull back) $\rightarrow$ 2. Fast Strike/Impact $\rightarrow$ 3. Follow-through $\rightarrow$ 4. Recovery. | **Fast Ease-In to Impact** ($1-2\text{ frames}$), then Ease-Out Recovery ($3-4\text{ frames}$). | | **Hurt / Hit Recoil** | $3 - 5\text{ frames}$ | Sharp backward tilt, flash white/red frame, recovery. | High speed ($0.15\text{s} - 0.25\text{s}$ total). | | **Death / Collapse** | $6 - 10\text{ frames}$ | Stagger back $\rightarrow$ Knees buckle $\rightarrow$ Ground impact $\rightarrow$ Dissolve/Settle. | Heavy Ease-In gravity drop, non-looping final resting frame. | | **Cast / Special Skill**| $8 - 12\text{ frames}$ | Energy gather (glow aura) $\rightarrow$ Power release pose $\rightarrow$ Dissipation hold. | Pulse aura w/ additive particles, smooth hold pose. | --- ## 6. Particle Systems & Graphical Effects (VFX) High-performance visual effects (explosions, magic trails, sparks, fire) require pre-allocated particle pools to avoid memory allocation spikes and Garbage Collection frame stutters. ### 6.1 Pre-Allocated Particle Pool Pattern ```go type Particle struct { X, Y float64 VX, VY float64 Life, Age float64 StartSize, EndSize float64 StartColor, EndColor color.RGBA Additive bool Active bool } type ParticleSystem struct { pool []Particle } func (ps *ParticleSystem) Update(dt float64) { for i := range ps.pool { p := &ps.pool[i] if p.Active { p.Age += dt if p.Age >= p.Life { p.Active = false continue } p.X += p.VX * dt p.Y += p.VY * dt } } } ``` ### 6.2 Additive Blending for Energy Glows For fire, lasers, explosions, and magic spells, use **Additive Blending** (`ebiten.BlendLighter`). --- ## 7. Direct Bitmap Pixel Crafting & Procedural Rasterization When procedural vector drawing is insufficient, craft pixel textures directly in memory by manipulating RGBA byte buffers. ### 7.1 Direct Bitmap Techniques * **Perlin / Simplex Noise**: Generate natural ground tiles (grass, sand, obsidian, water ripples). * **2D Signed Distance Fields (SDFs)**: Mathematically render crisp circles, rounded rectangles, and polygons. * **4-Neighbor Outline Algorithm (`ApplyPixelOutline`)**: Automatically draw a 1-pixel dark border around solid pixels to give retro pixel-art definition. > [!IMPORTANT] > **Direct Memory Pixel Generation**: > Direct memory pixel manipulation (`image.NewRGBA` and `ebiten.NewImageFromImage`) allows rasterizing custom shapes, procedural noise, and raw byte buffers into Ebitengine images at startup. --- ## 8. Mandatory Quality Directives for AI Art Generation When an AI agent uses this skill to generate procedural graphics or sprite rendering code: 1. **MANDATORY Full Sprite Sheet Frame Sets**: * Character generators MUST output complete frame sets ($8\text{--}12\text{ frames}$ for walk/run, $6\text{--}10\text{ frames}$ for attack, $4\text{--}8\text{ frames}$ for idle) across all required directions. 2. **MANDATORY Correct Matrix Transformation Order**: * Transformations MUST execute in order: `Translate(-pivot) -> Scale -> Rotate -> Translate(+pivot + pos)`. 3. **MANDATORY Pre-Allocated Particle Pools**: * Particle systems MUST allocate fixed particle array slices on boot. Never instantiate `new Particle` or slices during frame `Update`/`Draw`. 4. **MANDATORY Retro-HD Color Ramps**: * Sprites MUST use 32-bit truecolor RGBA with 4-step material shading ramps and cool shadow / warm highlight shifts. 5. **MANDATORY Non-Linear Motion Easing**: * Animations MUST integrate delta time ($dt$) and easing curves (Ease-Out, Elastic) for fluid sub-frame movement. --- ## 9. Gotchas & Engineering Best Practices * **Allocation Spikes in Render Loop**: Calling `image.NewRGBA` or `ebiten.NewImage` inside `Draw()` or `Update()` causes massive GC frame drops. Always pre-render textures into a persistent cache at boot. * **Premultiplied Alpha Artifacts**: In Ebitengine, custom RGBA pixel buffers drawn with alpha must properly premultiply color channels ($R' = R \cdot A / 255$) to avoid dark fringe borders around semi-transparent pixels. * **Matrix Order Flaws**: Scaling after world translation multiplies world coordinates, causing sprites to fly off-screen. Always scale before translating! --- ## 10. Summary Checklist for Procedural Art Quality 1. **Pre-render Full Animation Frame Sheets at Boot**: Pre-generate all Idle ($4-8\text{f}$), Walk ($8-12\text{f}$), Attack ($6-10\text{f}$), and Death ($6-10\text{f}$) frame sets across cardinal directions. 2. **Apply Retro-HD Truecolor Shading**: Use 32-bit RGBA color ramps with cool shadow / warm highlight shifts. 3. **Verify Matrix Order**: Enforce `Pivot -> Scale -> Rotate -> World Translation` on every `ebiten.GeoM` call. 4. **Pre-allocate VFX Particle Pools**: Use fixed particle arrays with zero heap allocations during frame updates. 5. **Apply Additive Blending to Spells**: Enable `ebiten.BlendLighter` for fire, lasers, and magical energy glows. --- ## 📚 Progressive Disclosure & References - **Procedural Art Driver**: [`references/art.go`](references/art.go) — In-memory sprite rasterization, 32-bit RGBA color palettes, SDF shapes, and particle systems. - **Matrix Order & Easing Tests**: [`references/art_test.go`](references/art_test.go) — Mathematical unit test suite verifying transformation order ($T \cdot R \cdot S \cdot T_{pivot}$) and non-linear easing functions. --- # Skill: procedural-composer (game-dev) > Pure-code procedural audio synthesis guide for sound effects (SFX) and polyphonic background music (BGM) in games. Generates 16-bit stereo PCM audio in memory without external audio files, featuring multi-channel polyphonic composition, ADSR envelopes, frequency modulation, and declarative JSON sound definitions with a CLI player and WAV exporter. Activate when synthesizing sound effects, composing chiptune background music, building zero-asset audio engines, or exporting procedural sounds to WAV. **Web Page**: https://skills.danicat.dev/game-dev/procedural-composer/ **Source**: https://skills.danicat.dev/game-dev/procedural-composer/SKILL.md **Version**: 0.2.0 **Digest**: sha256:79acfc87c486d85db571948f05d903bd0fe56e67d809abfa9d96b0bf4f4f0450 **Install**: `npx skills add danicat/skills --skill procedural-composer -y` ## Instructions # Procedural Composer: Pure-Code Audio Synthesis & Chiptune/Game Sound Engine Guide This skill provides complete mathematical, musical, and software architecture patterns for generating high-quality sound effects (SFX) and polyphonic background music (BGM) purely in code—without relying on external `.wav`, `.mp3`, or `.ogg` audio files. --- ## Available scripts - `scripts/sound.go`: Sound engine driver and declarative JSON audio definition parser. - `scripts/sound_test.go`: Go unit tests and example BGM/SFX composition recipes. - `scripts/play.go`: CLI audio player and WAV export utility. --- ## 1. Core Architectural Principles & DSP Foundations ### 1.1 Zero-Asset Engine Strategy Procedural audio synthesizes audio samples on-the-fly or bakes them into PCM buffers in memory at application startup: * **Zero disk I/O**: Eliminates asset loading failures and missing file errors. * **Minimal footprint**: Thousands of sounds and complex soundtracks require only kilobytes of code. * **Dynamic runtime control**: Real-time manipulation of pitch, tempo, filter cutoff, vibrato, and volume based on game state. ### 1.2 Output Format Standard Standard audio output uses 16-bit signed Little-Endian PCM stereo at 44,100 Hz (or 48,000 Hz): * **Sample Rate ($f_s$)**: $44,100 \text{ Hz}$ (44,100 samples per second per channel). * **Channels**: 2 (Stereo: Left [bytes 0–1], Right [bytes 2–3]). * **Bits Per Sample**: 16-bit signed integer range $[-32,768 \text{ to } +32,767]$. --- ## 2. SECTION 1: Background Music (BGM) Composition & Architecture ### 2.1 Yamaha YM2612 Benchmark & Multi-Channel Richness Standard To achieve rich, professional game soundtrack quality, procedural music generators should mimic or exceed the complexity of classic 16-bit sound chips such as the **Yamaha YM2612** (Sega Genesis) and **SNES SPC700**. #### The YM2612 6-Channel Standard A music track should feature **at least 6 distinct polyphonic channels/instrument layers** mixed simultaneously: 1. **FM Channel 1 (Lead Melody)**: Primary lead line (sawtooth or low-duty pulse wave with LFO vibrato). 2. **FM Channel 2 (Counter-Melody)**: Secondary counterpoint or call-and-response lead line. 3. **FM Channel 3 (Harmony Pad / Strings)**: Sustaining chord pad holding harmonic progression. 4. **FM Channel 4 (Bassline)**: Driving octave or walking bassline (square, saw, or triangle sub-bass). 5. **FM Channel 5 (Arpeggiator / Motion)**: Rapid 16th or 32nd note arpeggio runs for movement. 6. **FM Channel 6 / Noise (Drums / Percussion / SFX Stinger)**: Filtered noise bursts for snare/hi-hat or kick transients. --- ### 2.2 Dual Music Playback Architecture: One-Off vs. Looped Playback The audio playback subsystem (`SoundSystem` in [`scripts/sound.go`](scripts/sound.go)) explicitly supports two distinct playback modes: * **Looped Playback (`Play(pcm, true)`)**: For stage themes, boss battles, title screens, and menus where music must loop continuously without audible gaps using an infinite reader wrapper (`audio.NewInfiniteLoop`). * **One-Off / Single Play (`Play(pcm, false)`)**: Default mode for game over music, stage clear fanfares, calamity alerts, and victory stingers that play once to completion and then stop without looping. --- ### 2.3 Style-Based Reference Baselines for Duration & Tempo (BPM) Tempo (BPM) and track length are **heavily dictated by game style, genre, narrative mood, and scene context** (e.g., bullet-hell shmup vs. ambient puzzle vs. epic RPG). The table below offers flexible reference baselines rather than rigid rules: #### BPM to Note Duration Calculation $$t_{\text{beat}} = \frac{60}{\text{BPM}}$$ * **Quarter Note ($1/4$)**: $t_{\text{beat}}$ * **Eighth Note ($1/8$)**: $t_{\text{beat}} / 2$ * **Sixteenth Note ($1/16$)**: $t_{\text{beat}} / 4$ * **Measure ($4/4$ time)**: $240 / \text{BPM}$ seconds #### Flexible Scene Reference Table | Scene / Event Type | Playback Mode | Typical Duration Baseline | Typical BPM Range | Composition Style & Musical Notes | | :--- | :--- | :--- | :--- | :--- | | **Stage / Gameplay** | **Looped** | $60\text{s} - 180\text{s}+$ | $100 - 160\text{ BPM}$ | Multi-part structure (*Intro $\rightarrow$ Theme A $\rightarrow$ Theme B $\rightarrow$ Climax $\rightarrow$ Loop*) to prevent loop fatigue during long play sessions. | | **Boss Battle** | **Looped** | $45\text{s} - 120\text{s}$ | $140 - 180+\text{ BPM}$ | Fast-paced, driving syncopation, diminished/phrygian modes, aggressive YM2612-style FM leads. | | **Title / Menu** | **Looped** | $20\text{s} - 60\text{s}$ | $80 - 130\text{ BPM}$ | Catchy theme or ambient melody setting the game atmosphere. | | **Game Over** | **One-Off** | $4\text{s} - 15\text{s}$ | $60 - 90\text{ BPM}$ | **Non-looping single play**. Sad descending chromatic slide or minor chord resolution. Keeps restart friction low. | | **Stage Clear / Fanfare** | **One-Off** | $5\text{s} - 15\text{s}$ | $120 - 160\text{ BPM}$ | **Non-looping single play**. Triumphant ascending major arpeggio fanfare celebrating completion. | --- ## 3. SECTION 2: JSON Sound Format & CLI Player (`play.go`) To test sound effects and multi-track compositions outside game runtimes, use the declarative **JSON Sound Format** parsed natively by [`scripts/sound.go`](scripts/sound.go). ### 3.1 Declarative JSON Sound Specification #### Sound Effect JSON (`sfx_laser.json`) ```json { "title": "Laser Bow Shot", "type": "sfx", "sequence": [ { "wave_type": "square", "duration": 0.15, "start_freq": 800.0, "end_freq": 150.0, "duty_cycle": 0.25, "volume": 0.3, "attack": 0.01, "decay": 0.05, "sustain": 0.2, "release": 0.09, "pan": 0.0 } ] } ``` #### Multi-Track BGM Song JSON (`song_boss.json`) ```json { "title": "Boss Battle Theme", "type": "song", "bpm": 150, "time_signature": "4/4", "tracks": [ { "name": "Ch1 Sawtooth Lead", "pan": -0.2, "notes": [ { "wave_type": "sawtooth", "duration": 0.2, "start_freq": 659.25, "end_freq": 659.25, "vibrato_freq": 8.0, "vibrato_depth": 10.0, "volume": 0.12, "attack": 0.02, "decay": 0.05, "sustain": 0.7, "release": 0.05 } ] }, { "name": "Ch4 Driving Bass", "pan": 0.0, "notes": [ { "wave_type": "square", "duration": 0.2, "start_freq": 110.0, "end_freq": 110.0, "duty_cycle": 0.5, "volume": 0.14, "attack": 0.01, "decay": 0.1, "sustain": 0.5, "release": 0.05 } ] } ] } ``` --- ### 3.2 Using the CLI Player Tool (`play.go`) The CLI player [`scripts/play.go`](scripts/play.go) allows developers and testing agents to play or export audio definitions: ```bash # 1. Play JSON sound effect or song (one-off by default) go run ./scripts play sound.json # 2. Play JSON sound effect or song in a loop go run ./scripts play -loop song_stage.json # 3. Play built-in 6-channel Genesis style demo soundtrack (one-off or -loop) go run ./scripts demo go run ./scripts demo -loop # 4. Synthesize JSON definition and export directly to a 16-bit 44.1kHz Stereo .wav file go run ./scripts export song_stage.json stage_theme.wav ``` --- ## 4. Mandatory Quality Directives for AI Generation When an AI agent uses this skill to compose audio or generate sound driver code: 1. **NEVER Generate Short 1-Bar or 2-Bar Musical Loops**: * Any BGM generated MUST be a complete composition spanning at least **8 to 16 bars** with chord progressions, theme development, and harmonic transitions. 2. **MANDATORY 6-Channel Polyphony**: * Every background soundtrack MUST feature at least **6 distinct polyphonic instrument tracks** (Lead, Counter-Melody, Harmony Pad, Bass, Arpeggiator, Drums/Percussion). 3. **MANDATORY Expressive Parameterization**: * Every note/track MUST specify tailored `DutyCycle` ($0.125 - 0.5$), `Pan` (stereo field distribution), `VibratoFreq`/`VibratoDepth` for lead instruments, and distinct ADSR envelope ramps. 4. **MANDATORY 32-Bit Summation & Clamping**: * Multi-track audio mixing MUST sum in 32-bit integers (`int32`) and hard-clamp to `[-32768, +32767]` to eliminate wrap-around distortion. 5. **No Monophonic Beeps**: * Sound effects must use frequency modulation sweeps, noise filters, or 2-stage note sequences (`GenerateSequencePCM`) to sound crisp, punchy, and retro-console authentic. --- ## 5. Gotchas & Engineering Best Practices * **Integer Overflow Wrap-Around**: Summing track samples directly in `int16` causes violent digital clipping and speaker crackle. Always sum tracks in `int32` and hard-clamp to `[-32768, +32767]`. * **Audio Popping & Clicks**: Instantly stopping a waveform oscillator creates a steep DC offset jump that sounds like a loud "pop" or click. Always apply a release envelope ramp (at least $5\text{--}10\text{ ms}$). * **Memory & Frame GC Spikes**: Avoid instantiating or generating PCM slices inside main frame rendering functions (`Update`/`Draw`). Pre-render all audio buffers during system initialization. * **Audio Channel Choking**: High-frequency user events (e.g. clicking 50 times/sec) will choke audio players. Implement cooldown rate limiters ($30\text{--}50\text{ ms}$) on interactive triggers. --- ## 6. Summary Checklist for Procedural Audio Quality 1. **Pre-render SFX & Loops**: Generate PCM byte buffers on boot to keep execution overhead at zero during gameplay frames. 2. **Mimic YM2612 6-Channel Polyphony**: Layer at least 6 distinct instrument channels (Lead, Counterpoint, Pad, Bass, Arpeggio, Percussion/Noise) to achieve retro console soundtrack depth. 3. **Support Dual Playback Modes**: Provide both `Play(pcm, false)` (one-off) for stingers and `Play(pcm, true)` (infinite loop) for BGM. 4. **Hard-Clamp Mixed PCM**: Always sum in `int32` and clamp to `[-32768, +32767]` when mixing audio tracks to avoid harsh digital overflow wrap-around distortion. 5. **Declarative JSON & CLI Testing**: Use JSON sound definitions and `go run . export` to validate audio quality and generate `.wav` previews. 6. **Enforce AI Generation Quality Directives**: Enforce 16-bar length, 6-channel polyphony, and expressive parameterization on all agent outputs. --- ## 7. State-Based Adaptive BGM Composition Rules When composing code-synthesized multi-track audio for dynamic game states: - **Exploration / Ambient**: Low BPM ($60\text{--}90$), sparse instrumentation, soft pads, subtle woodwinds, key of C Major. - **Tension / Stealth**: Medium BPM ($90\text{--}110$), staccato strings, muted sub-bass, ticking percussion. - **Combat / Action / Boss**: High BPM ($120\text{--}160+$), driving drums, heavy bassline, intense brass/synths, key of D minor. --- # Skill: sprite-animation (game-dev) > 2D sprite sheet management, frame animation sequencing, and Aseprite integration guide for games. Covers sprite grid slicing, animation state machines (idle, walk, attack, death), frame duration timing, tag loops, and Go animation controllers in Ebitengine. Activate when slicing sprite sheets, configuring character animations, integrating Aseprite files (.ase/.aseprite), or writing game animation controllers. **Web Page**: https://skills.danicat.dev/game-dev/sprite-animation/ **Source**: https://skills.danicat.dev/game-dev/sprite-animation/SKILL.md **Version**: 0.2.0 **Digest**: sha256:553fd2622e71890ad858fe751bc2721bfc3a01fda341b419538b037e0439f677 **Install**: `npx skills add danicat/skills --skill sprite-animation -y` ## Instructions # 2D Sprite Animation & Aseprite Integration Guide (Animator Role) This skill equips AI agents acting in the **Animator Agent Role** with the tools, specifications, and Go controllers required to design, validate, slice, and manage 2D character sprite sheets, animation frame sequences, tag loops, and Aseprite files (`.ase` / `.aseprite`) for Ebitengine v2 games. --- ## 1. Animator Agent Role & Core Responsibilities In a game development team, the **Animator Agent** owns all 2D sprite animation pipelines: 1. **Asset Validation & Format Verification**: Inspects sprite sheet images (from `nano-banana` or artist files) using file identification tools (`file`, `mimetype`, `http.DetectContentType`) to verify binary integrity and grid dimensions before slicing. 2. **Animation Tag & State Specification**: Defines animation tags (`idle`, `walk`, `run`, `attack`, `hurt`, `death`, `cast`), frame duration timings ($50\text{ms} - 200\text{ms}$), and loop directions (`LoopForward`, `LoopReverse`, `LoopPingPong`, `LoopOnce`). 3. **Aseprite Integration & Slicing**: Loads Aseprite files (`.ase` / `.aseprite` / `.json`) using recommended Go libraries ([`SolarLune/goaseprite`](https://github.com/SolarLune/goaseprite)) or pure-code Ebitengine `SubImage` grid slicing. 4. **Animation Controller Code Generation**: Authors clean, GC-friendly Ebitengine animation controllers that manage frame timers, state switches, directional flips, and completion callbacks (`OnComplete`). --- ## 2. Technical Reference Standards & Specifications For complete binary format specifications, GIMP RGBA palette specifications, and production Go code implementations, consult: | Module | Reference File | Key Topics Covered | | :--- | :--- | :--- | | **Aseprite Binary Format & GPL** | [`references/aseprite_format.md`](references/aseprite_format.md) | Header, frame headers, cel chunks (`0x2005`), tag chunks (`0x2018`), 9-patch slices (`0x2022`), and GIMP `.gpl` RGBA palette format extension. | | **Go Animation Controller** | [`references/animation_controller.go`](references/animation_controller.go) | Complete, production-grade Ebitengine `AnimationController` and `GridSpriteSheet` implementation with delta time ($dt$) updating and horizontal flipping. | --- ## 3. Asset Validation & Grid Slicing Workflow Never assume a generated image is a valid PNG or has correct dimensions based solely on filename extension: ```bash # 1. Validate actual file type using file identification tools file assets/sprites/player_sheet.png # Expected output: PNG image data, 256 x 128, 8-bit/color RGBA # 2. Verify grid dimensions (e.g. 256x128 image with 32x32 frames = 8 columns x 4 rows = 32 frames) ``` --- ## 4. Animation State Machine Benchmark Table When authoring animation sequences for characters and entities, enforce standard frame count and duration benchmarks: | Animation Tag | Frame Range / Count | Frame Duration | Loop Mode | Gameplay Trigger / Transition | | :--- | :--- | :--- | :--- | :--- | | **`idle`** | $4 - 8\text{ frames}$ | $120\text{ms} - 180\text{ms}$ | `LoopForward` | Default state when velocity is zero ($VX=0, VY=0$). | | **`walk` / `run`** | $8 - 12\text{ frames}$ | $60\text{ms} - 100\text{ms}$ | `LoopForward` | Active when moving horizontally ($VX \neq 0$). | | **`jump` / `fall`** | $2 - 4\text{ frames}$ | $100\text{ms}$ | `LoopOnce` / Hold | Triggered on jump start; holds final frame during airborne fall. | | **`attack`** | $6 - 10\text{ frames}$ | $40\text{ms} - 80\text{ms}$ | `LoopOnce` | Triggered on attack keypress. Invokes `OnComplete` callback back to `idle`. | | **`hurt`** | $3 - 5\text{ frames}$ | $50\text{ms}$ | `LoopOnce` | Triggered on damage hit. Flash red/white overlay. | | **`death`** | $6 - 10\text{ frames}$ | $100\text{ms}$ | `LoopOnce` | Triggered on zero health. Holds final collapse frame without looping. | --- ## 5. Integration Patterns in Ebitengine ### 5.1 Using SolarLune's `goaseprite` Library ```go import "github.com/SolarLune/goaseprite" type Player struct { Anim *goaseprite.File X, Y float32 } func NewPlayer() *Player { return &Player{ Anim: goaseprite.New("assets/player.json"), } } func (p *Player) Update(dt float32) { p.Anim.Update(dt) } func (p *Player) Draw(screen *ebiten.Image) { op := &ebiten.DrawImageOptions{} op.GeoM.Translate(float64(p.X), float64(p.Y)) // Draw current frame sub-image from Aseprite atlas sub := p.Anim.Image.SubImage(p.Anim.CurrentFrameBounds()).(*ebiten.Image) screen.DrawImage(sub, op) } ``` ### 5.2 Using Pure-Code Grid Slicing Controller ```go sheet := &GridSpriteSheet{ Image: embeddedSpriteImage, FrameWidth: 32, FrameHeight: 32, Columns: 8, TotalFrames: 32, } controller := NewAnimationController(sheet) controller.AddTag(AnimationTag{Name: "idle", StartFrame: 0, EndFrame: 5, FrameDuration: 150 * time.Millisecond, Loop: LoopForward}) controller.AddTag(AnimationTag{Name: "run", StartFrame: 8, EndFrame: 15, FrameDuration: 80 * time.Millisecond, Loop: LoopForward}) controller.Play("run") ``` --- ## 6. Animator Agent Pre-Flight Checklist Before confirming animation code or sprite assets: - [ ] **Validated File Format**: Verified image using `file` CLI tool (ensuring RGBA format and no corrupted/misnamed extensions). - [ ] **Grid Math Verified**: Image width and height are exact integer multiples of frame width and height. - [ ] **All Animation Tags Defined**: Included `idle`, `run`/`walk`, `attack`, and `death` states. - [ ] **No Allocation in `Draw()`**: `SubImage` bounds calculations use pre-computed rectangles or persistent `DrawImageOptions`. - [ ] **Horizontal Flipping Handled**: Configured negative matrix scale ($Scale(-1, 1)$) for left-facing direction without duplicating sprite assets. --- # Skill: vibe-game-developer (game-dev) > Master orchestrator and workflow router for building 2D games in Go with Ebitengine. Coordinates the full game development lifecycle across concept design (GDD creation), engine architecture, asset pipelines (pure-code procedural vs. AI-generated media), animation controllers, and WebAssembly deployment. Activate when building a 2D game from scratch, planning game workflows, routing game asset requests, or managing end-to-end game projects. **Web Page**: https://skills.danicat.dev/game-dev/vibe-game-developer/ **Source**: https://skills.danicat.dev/game-dev/vibe-game-developer/SKILL.md **Version**: 0.2.0 **Digest**: sha256:5d23eae3734121ae8955773b936a991552d2281bc599f7d905a6a9f1d0b1bb99 **Install**: `npx skills add danicat/skills --skill vibe-game-developer -y` ## Instructions # Vibe Game Developer: Master Orchestrator & Request Router This master skill teaches the agent how to analyze, classify, and route user game development requests to the specialized skill best suited for the task. > [!NOTE] > **Genre-Agnostic Design Principle**: > All skills and reference modules in this suite provide **generic, highly adaptable building blocks suitable for any 2D game genre** (puzzle, arcade, strategy, platformer, racing, rhythm, RPG, shmup, or simulation). Specific code examples (such as progress bars, jump gravity curves, or A* pathfinding) are illustrative patterns—apply and adapt only the components that fit the game's unique design and mechanics. --- ## 1. Skill Selection & Intent Routing Matrix When responding to user requests, evaluate the underlying engineering need and activate the primary specialized skill according to this decision matrix: | User Intent / Request Type | Primary Specialized Skill | Key Technical Characteristics | | :--- | :--- | :--- | | **Game Design & Concept Probing** | **[`game-design`](../game-design/SKILL.md)** | Game Designer role: interactive `/grill-me` probing interview, mechanics, controls, art/audio strategy, and `GDD.md` creation. | | **Ebitengine 2D Game Architecture** | **[`ebitengineer`](../ebitengineer/SKILL.md)** | Ebitengine game loop, 16:9 canvas, FSM scene flow, WASM touch, Cloud Run deployment, plus 6 core engine modules: Physics/Collisions (`AABB`/Spatial Hash), Tilemaps/Autotiling, UI/HUD (9-slice/anchors), Action Mapping, Entity Pools/ECS, and A* Pathfinding/AI. | | **Pure-Code DSP Audio Synthesis** | **[`procedural-composer`](../procedural-composer/SKILL.md)** | Zero-asset runtime DSP sound engine (`sound.go`), YM2612 6-channel polyphony, FM synthesis, ADSR envelopes, JSON sound format, and CLI player (`play.go`). | | **Generative CD-Quality AI Music** | **[`lyria`](../../media/lyria/SKILL.md)** | High-fidelity 44.1 kHz stereo music (`lyria-3-clip-preview` & `lyria-3-pro-preview`), custom lyrics, section tags (`[Verse]`, `[Chorus]`), multimodal image-to-music, and `.mp3`/`.wav` export. | | **Pure-Code Procedural 2D Graphics** | **[`procedural-art`](../procedural-art/SKILL.md)** | Pure-code Go texture generation (`art.go`), 2D matrix transformation math (`GeoM`), 32-bit RGBA color ramps, non-linear easing, pre-allocated particle pools, and Kage shaders. | | **Generative AI Images & Pixel Art** | **[`nano-banana`](../../media/nano-banana/SKILL.md)** | Conversational image generation via Gemini Nano Banana models (`gemini-3.1-flash-image`, `gemini-3.1-pro-image`), pixel art prompts, and multi-image character/style consistency. | | **2D Sprite Animation (Animator Role)** | **[`sprite-animation`](../sprite-animation/SKILL.md)** | Animator subagent role: sprite sheet grid slicing, animation tag state machines, Aseprite `.ase`/`.aseprite` parsing, `SolarLune/goaseprite` integration, and Go controllers. | | **Go Code Quality & Testing** | **[`godoctor`](../../coding/godoctor/SKILL.md)** | Go style guidelines, flat package architecture, `smart_build`, `smart_edit`, TestQuery SQL test log analyzer, and Selene mutation testing. | | **Parallel Feature Swarm Orchestration** | **[`swarm-coding`](../../agents/swarm-coding/SKILL.md)** | Multi-agent parallel task decomposition for full-stack features or large refactorings. | --- ## 2. Decision Rules: Pure-Code Procedural vs. Generative AI Assets A critical responsibility of this master skill is determining whether an asset request should be built **procedurally in pure Go code** or **generated using Gemini AI models**: ### 2.1 Audio & Music Routing Rules * **Choose [`procedural-composer`](../procedural-composer/SKILL.md)** when: - The user requests **Game Sound Effects (SFX)**: button clicks, coin pick-ups, laser blasts, jumps, explosions, or UI audio cues. - The user requests retro chiptune audio, synthesized waveforms, or lightweight FM audio. - The game requires zero external `.mp3`/`.wav` dependencies or real-time dynamic pitch/filter manipulation during gameplay. - The user requests a JSON sound specification or code-driven audio engine implementation (`sound.go`). * **Choose [`lyria`](../../media/lyria/SKILL.md)** when: - The user requests **Background Music (BGM)**: CD-quality 44.1 kHz stereo music tracks, full songs with custom lyrics, instrumental score beds, or BGM loops. - The user wants to compose background music matching a visual reference image or photo. - Output music must be exported as standalone `.mp3` or `.wav` audio files. --- ### 2.2 Graphics & Visual Routing Rules * **Choose [`procedural-art`](../procedural-art/SKILL.md)** when: - The user requests pure-code texture generation (`art.go`), vector geometry, dynamic particle systems (explosions, fire, magic), or custom Kage post-processing shaders. - The game requires zero disk I/O, infinite resolution scaling, or real-time palette swapping in Go memory. - The request involves matrix transformation ordering, sub-frame interpolation curves, or direct bitmap pixel crafting. * **Choose [`nano-banana`](../../media/nano-banana/SKILL.md)** when: - The user requests AI-generated concept art, character avatars, item icons, or AI pixel art sprites (`16x16`, `32x32`, `64x64`). - The request specifies character visual consistency for recurring characters, heroes, or NPCs across scenes. - The output is an image file (`.png`/`.jpg`). --- ## 3. Standard End-to-End Game Workflow When guiding the user through building a complete 2D game from scratch: 1. **Game Concept & GDD**: Activate `game-design` (`/grill-me`) to probe player vision, define core mechanics, controls, art/audio strategy, and save `GDD.md`. 2. **Architecture & Scope**: Activate `ebitengineer` to set up package structure (`internal/`), 16:9 virtual pixel canvas, delta time ($dt$) 60 FPS timing, and FSM scene progression. 3. **Visual Art & Sprites**: - For UI/particle FX/vector geometry $\rightarrow$ Activate `procedural-art`. - For character concept art / AI pixel sprite sheets $\rightarrow$ Activate `nano-banana` + `sprite-animation`. 4. **Sound Effects & Music**: - For retro SFX & synthesized chiptunes $\rightarrow$ Activate `procedural-composer`. - For high-fidelity background music beds $\rightarrow$ Activate `lyria`. 5. **Code Review & Quality Gate**: Activate `godoctor` (`smart_build`, unit testing, Selene mutation testing) to ensure code correctness and test coverage. 6. **Deployment**: Activate `ebitengineer` to compile to WebAssembly and configure Google Cloud Run deployment with multi-stage Docker builds. --- # Skill: lyria (media) > Generative music and audio synthesis from text prompts or reference images using Google Lyria 3 models. Generates 44.1 kHz stereo music clips, full songs with custom lyrics, and instrumental soundtracks using lyria-3-clip-preview and lyria-3-pro-preview, with support for multimodal image inputs and MP3/WAV export. Activate when composing background music, generating songs, creating soundtracks from images, or producing AI audio clips. **Web Page**: https://skills.danicat.dev/media/lyria/ **Source**: https://skills.danicat.dev/media/lyria/SKILL.md **Version**: 0.2.0 **Digest**: sha256:1342bf7cefa092bd8927e85d78d5bed9930423835088fe7bfbfc78719d81366c **Install**: `npx skills add danicat/skills --skill lyria -y` ## Instructions # Lyria Music Generation Skill Generate high-fidelity **44.1 kHz stereo audio**, full songs with structured lyrics, instrumental soundtracks, and thematic compositions from text prompts or visual reference images using Google's **Lyria 3** foundation models (`lyria-3-clip-preview` and `lyria-3-pro-preview`). --- ## Available scripts - `scripts/lyria.py`: CLI tool for text-to-music and image-to-music generation, lyric export, and audio format conversion. - `scripts/test_lyria.py`: Test suite verifying Lyria argument parsing and multimodal input limit enforcement. --- ## Trigger Conditions Activate this skill whenever the user asks to: - Generate music, songs, soundtracks, game audio beds, or background music. - Compose musical themes inspired by artwork, concept photos, or screenshots. - Create 30-second audio loops or multi-minute structured songs with verses, choruses, and custom lyrics. - Synthesize instrumental audio tracks (`"Instrumental only, no vocals"`). --- ## Model Selection & Comparison Matrix | Model | Model ID | CLI Name | Primary Use Case | Duration | Audio Format | Reference Guide | | :--- | :--- | :--- | :--- | :--- | :--- | :--- | | **Lyria 3 Clip** | `lyria-3-clip-preview` | `clip` | Short clips, loops, previews, rapid style testing | Exactly 30s | MP3, WAV | [lyria-3-clip.md](references/lyria-3-clip.md) | | **Lyria 3 Pro** | `lyria-3-pro-preview` | `pro` | Full songs, multi-section arrangements, film scoring | Up to 184s | MP3, WAV | [lyria-3-pro.md](references/lyria-3-pro.md) | ### Model Selection Guide - **Rapid Prototyping**: Start with **Lyria 3 Clip** (`clip`) to iterate quickly on genre combinations, tempos, and instrumentation. - **Full Song Production**: Select **Lyria 3 Pro** (`pro`) when requiring timestamped transitions (`[0:00 - 0:15] Intro...`), multi-verse vocal delivery, or multi-minute thematic development. --- ## Deep Technical References Consult dedicated reference cards in `references/` for detailed audio parameters, timing controls, and API schemas: - **[references/lyria-3-clip.md](references/lyria-3-clip.md)**: Specifications for 30-second clips, loops, and rapid prototyping. - **[references/lyria-3-pro.md](references/lyria-3-pro.md)**: Specifications for full-length song arrangement, timestamp controls, and multimodal scoring. - **[references/README.md](references/README.md)**: Musical composition prompt reference and index. --- ## Core Execution Workflows ### 1. CLI Execution via `scripts/lyria.py` Execute `scripts/lyria.py` with `uv run`: ```bash # Generate a 30-second chiptune arcade loop with Lyria 3 Clip uv run scripts/lyria.py \ -p "An energetic 8-bit chiptune arcade melody at 140 BPM in C major. Instrumental only." \ -f "chiptune.mp3" \ -m "clip" # Generate a full orchestral soundtrack with Lyria 3 Pro uv run scripts/lyria.py \ -p "An epic cinematic orchestral theme building from quiet strings to a triumphant brass finale" \ -f "soundtrack.mp3" \ -m "pro" \ --lyrics-file "structure.txt" # Multimodal Image-to-Music (compose music inspired by an image) uv run scripts/lyria.py \ -p "Ambient relaxing soundscape matching the mood of this landscape. Instrumental only." \ -i "landscape.jpg" \ -f "landscape_theme.mp3" \ -m "pro" ``` #### CLI Argument Reference - `-p`, `--prompt`: Text prompt describing style, genre, instruments, BPM, and structure (required). - `-f`, `--filename`: Output audio file path (default: `music.mp3`). - `-m`, `--model`: `clip` / `lyria-3-clip-preview` or `pro` / `lyria-3-pro-preview` (default: `pro`). - `-i`, `--input-image`: Path to input image(s) for visual mood inspiration (up to 10). - `--format`: Audio container format (`mp3` or `wav`). - `--lyrics-file`: Optional path to write generated lyric transcription / structure text. - `--api`: `interactions` (default) or `models`. --- ### 2. Dual SDK Integration Patterns #### Interactions API (`client.interactions.create`) — Recommended ```python import base64 from google import genai client = genai.Client() # Generate full-length song with timestamp structure prompt = """ An atmospheric lo-fi beat in D Minor at 80 BPM: [0:00 - 0:15] Intro: Dusty vinyl crackle and mellow electric piano chords. [0:15 - 0:45] Verse: Warm boom-bap drum groove enters with subtle bassline. [0:45 - 1:15] Chorus: Full melodic progression with saxophone accents. [1:15 - 1:30] Outro: Slow fade out with piano alone. """ interaction = client.interactions.create( model="lyria-3-pro-preview", input=prompt, ) if interaction.output_audio: with open("lofi_track.mp3", "wb") as f: f.write(base64.b64decode(interaction.output_audio.data)) if interaction.output_text: print("Generated Lyrics / Structure:\n", interaction.output_text) ``` #### Multimodal Image-to-Audio (Python) ```python import base64 from google import genai client = genai.Client() with open("art_concept.png", "rb") as f: img_b64 = base64.b64encode(f.read()).decode("utf-8") interaction = client.interactions.create( model="lyria-3-pro-preview", input=[ {"type": "image", "data": img_b64, "mime_type": "image/png"}, {"type": "text", "text": "Compose an ethereal cyberpunk synth soundtrack matching this neon cityscape. Instrumental only."}, ], ) if interaction.output_audio: with open("cyberpunk_theme.mp3", "wb") as f: f.write(base64.b64decode(interaction.output_audio.data)) ``` --- ## Prompting Best Practices 1. **Genre & Subgenre**: Be specific (e.g. `synthwave`, `delta blues`, `chamber pop`, `lo-fi hip-hop`). 2. **Instrumentation**: Name specific instruments (`Fender Rhodes`, `TR-808 drums`, `nylon-string guitar`, `cello`). 3. **Tempo & Key**: Include BPM and musical key (`120 BPM`, `in A Minor`). 4. **Vocal Control**: For instrumental tracks, explicitly specify `"Instrumental only, no vocals"`. For vocals, provide bracketed lyrics (`[Verse]`, `[Chorus]`). 5. **Timestamp Arrangements**: For Pro models, use bracketed timestamps (`[0:00 - 0:20]`) to direct transitions and builds. --- # Skill: nano-banana (media) > Conversational image generation and multimodal image editing tool using Google Nano Banana models. Generates high-resolution images (1K, 2K, 4K), performs style transfers and image edits ("banana this"), and maintains character or style consistency using multi-image reference inputs. Activate when generating illustrations, editing or transforming images, creating visual assets, or maintaining character consistency across scenes. **Web Page**: https://skills.danicat.dev/media/nano-banana/ **Source**: https://skills.danicat.dev/media/nano-banana/SKILL.md **Version**: 0.2.0 **Digest**: sha256:8bfc8c7d0dd443274cfcc0c9fc653273510f1bdaff61a7d255ca3b67153e4d36 **Install**: `npx skills add danicat/skills --skill nano-banana -y` ## Instructions # Nano Banana Skill Generate, edit, and iterate on visual imagery conversationally using Google's native **Nano Banana** image generation foundation models (`gemini-3.1-flash-lite-image`, `gemini-3.1-flash-image`, `gemini-3-pro-image`, `gemini-2.5-flash-image`). --- ## Available scripts - `scripts/banana.py`: Production CLI tool for text-to-image generation, multimodal editing, and consistency anchoring with model capability validation. - `scripts/test_banana.py`: Test suite verifying CLI argument parsing and capability validation guards. --- ## Trigger Conditions Activate this skill whenever the user asks to: - Generate new images or illustrations from text prompts. - Edit, transform, style, or combine existing images. - Use **"banana" as a verb** (e.g., "please banana this image", "banana this character into anime style", "banana this photo into chibi style"). - Maintain character, subject, or style consistency across generated imagery using reference images. - Create 4K high-resolution visual assets or extreme aspect-ratio banners (`1:4`, `4:1`, `1:8`, `8:1`). --- ## Model Selection & Capability Matrix | Capability / Feature | Nano Banana 2 Lite (`nano-banana-2-lite`) | Nano Banana 2 (`nano-banana-2`) | Nano Banana Pro (`nano-banana-pro`) | Nano Banana (`nano-banana`) | | :--- | :--- | :--- | :--- | :--- | | **Model ID** | `gemini-3.1-flash-lite-image` | `gemini-3.1-flash-image` | `gemini-3-pro-image` | `gemini-2.5-flash-image` | | **Primary Focus** | Ultra-low latency (<2s), high volume | Generalist workhorse, speed + 4K | Studio precision & asset production | Foundational (Retiring Oct 2026) | | **Resolutions** | `1K` (1024px) only | `512px` (0.5K), `1K`, `2K`, `4K` | `1K`, `2K`, `4K` | `1K` (1024px) only | | **Aspect Ratios** | 14 discrete ratios | 14 discrete ratios (incl. `1:4`, `4:1`, `1:8`, `8:1`) | 10 standard ratios | 10 standard ratios | | **Search Grounding** | ❌ Not Supported | **Web Search + Image Search** | **Web Search** | ❌ Not Supported | | **Thinking Mode** | Supported (`minimal`, `high`) | Supported (`minimal`, `high`) | Enabled by Default | ❌ Not Supported | | **Video Context** | ❌ Not Supported | YouTube URLs & MP4 files | ❌ Not Supported | ❌ Not Supported | | **Reference Anchors** | Up to 14 (Local/Single edit focus) | Up to 10 objects + 4 characters | Up to 6 objects + 5 characters + 3 styles | Up to 3 input images | | **Function Calling**| Supported | ❌ Not Supported | ❌ Not Supported | ❌ Not Supported | | **Reference Guide** | [nano-banana-2-lite.md](references/nano-banana-2-lite.md) | [nano-banana-2.md](references/nano-banana-2.md) | [nano-banana-pro.md](references/nano-banana-pro.md) | [nano-banana.md](references/nano-banana.md) | --- ## Deep Technical References Consult dedicated reference cards in `references/` for full specs, exact token counts, and pixel dimensions: - **[references/nano-banana-2-lite.md](references/nano-banana-2-lite.md)**: Consult when building real-time UI tools, fast prototyping, or cost-critical high-frequency pipelines. - **[references/nano-banana-2.md](references/nano-banana-2.md)**: Consult for 4K generation, Google Image Search Grounding, video-to-image workflows, and ultra-wide/tall banners (`1:4`, `4:1`, `1:8`, `8:1`). - **[references/nano-banana-pro.md](references/nano-banana-pro.md)**: Consult for studio asset production, multi-reference consistency across 14 anchors (objects + characters + artistic style), and storyboards. - **[references/nano-banana.md](references/nano-banana.md)**: Consult for `gemini-2.5-flash-image` specifications and migration paths. - **[references/README.md](references/README.md)**: Index and guidelines for storing project-specific visual consistency anchors. --- ## Core Execution Workflows ### 1. CLI Execution via `scripts/banana.py` Run `scripts/banana.py` with `uv run` to generate or edit images: ```bash # High-velocity 1K generation with Nano Banana 2 Lite (Default) uv run scripts/banana.py \ -p "A minimalist flat illustration of a coffee cup on a wooden table" \ -f "coffee_lite.png" \ -m "nano-banana-2-lite" \ -a "1:1" # Studio-quality 4K generation with Nano Banana Pro uv run scripts/banana.py \ -p "An authentic architectural photograph of a modern library atrium with skylights" \ -f "library_4k.png" \ -m "nano-banana-pro" \ -r "4K" \ -a "16:9" \ --search # Ultra-wide banner (4:1) with Nano Banana 2 and Image Search Grounding uv run scripts/banana.py \ -p "A panorama header of the Swiss Alps at sunrise with fresh snow" \ -f "alps_banner.png" \ -m "nano-banana-2" \ -r "2K" \ -a "4:1" \ --image-search # Conversational Image Editing ("banana this") with Multi-Reference Consistency uv run scripts/banana.py \ -p "banana this character: place the character into an astronaut suit on Mars" \ -i "references/mascot_front.png" \ -i "references/suit_concept.png" \ -f "astronaut_mascot.png" \ -m "nano-banana-2" \ -r "2K" ``` #### CLI Argument Reference - `-p`, `--prompt`: Text prompt describing generation or edit instructions (required). - `-f`, `--filename`: Output file path for generated PNG/JPEG (required). - `-i`, `--input-image`: Path to input/reference image(s). Can be specified up to 14 times. - `-m`, `--model`: `nano-banana-2-lite` (default), `nano-banana-2`, `nano-banana-pro`, `nano-banana`. - `-r`, `--resolution`: `512px`, `1K` (default), `2K`, `4K`. - `-a`, `--aspect-ratio`: `1:1` (default), `1:4`, `1:8`, `2:3`, `3:2`, `3:4`, `4:1`, `4:3`, `4:5`, `5:4`, `8:1`, `9:16`, `16:9`, `21:9`. - `--thinking-level`: `minimal` or `high` (Banana 2 & Banana 2 Lite). - `--search`: Enable Google Search Grounding (Banana 2 & Banana Pro). - `--image-search`: Enable Google Image Search Grounding (Banana 2 only). - `--api`: `interactions` (default, Interactions API) or `models` (`generate_content`). --- ### 2. Dual SDK Integration Patterns #### Interactions API (`client.interactions.create`) — Recommended Best for multi-turn editing, search grounding, and stateful iteration: ```python import base64 from google import genai client = genai.Client() # Text-to-Image Generation with 4K Resolution & Search Grounding interaction = client.interactions.create( model="gemini-3.1-flash-image", input="An infographic chart showing the timeline of space exploration milestones", tools=[{"type": "google_search"}], generation_config={"thinking_level": "high"}, response_format={ "type": "image", "aspect_ratio": "16:9", "image_size": "4K", }, ) if interaction.output_image: with open("space_milestones.png", "wb") as f: f.write(base64.b64decode(interaction.output_image.data)) ``` #### Models API (`client.models.generate_content`) Direct stateless multimodal generation: ```python from google import genai from PIL import Image client = genai.Client() img = Image.open("references/product.png") response = client.models.generate_content( model="gemini-3.1-flash-image", contents=[img, "Place this product on a sleek marble countertop with soft studio lighting."], ) for part in response.candidates[0].content.parts: if part.inline_data: with open("product_studiolit.png", "wb") as f: f.write(part.inline_data.data) break ``` --- ## Prompting Best Practices 1. **Be Hyper-Specific**: Define materials, surface textures, lighting setups, and camera angles (`three-point softbox`, `macro lens`, `shallow depth of field`). 2. **Context & Intent**: State the functional purpose (`e-commerce hero banner`, `editorial illustration`, `app store icon`). 3. **Conversational Inpainting**: When editing, clearly describe what to modify while instructing to preserve unchanged surroundings (`"Change only the sofa to brown vintage leather. Keep all lighting and room decor untouched."`). 4. **Positive Framing**: Describe what should appear instead of using negative constraints (`"an empty street with no signs of vehicles"` rather than `"no cars"`). --- # Skill: engineering-flow (coding) > Engineering standards, decision pipelines, and code hygiene guidelines for software development. Covers architectural decision workflows (RFCs and ADRs), task prioritization, grounded technical research, semantic versioning, and clean code practices like explicit error handling and dead code removal. Activate when designing system architecture, planning releases, refactoring codebases, establishing project standards, or resolving technical uncertainty. **Web Page**: https://skills.danicat.dev/coding/engineering-flow/ **Source**: https://skills.danicat.dev/coding/engineering-flow/SKILL.md **Version**: 0.2.0 **Digest**: sha256:efb5186721d66f5e74072194ade3f164094793a19bea93c3c09aff1edf3eca45 **Install**: `npx skills add danicat/skills --skill engineering-flow -y` ## Instructions # Engineering Flow Engineering standards, decision pipelines, and code hygiene rules. --- ## Delivery Principles Ship working software in small, verifiable increments: - Keep changes scoped to a single logical objective. - Avoid speculative abstractions and overengineering. - Implement thin, vertical slices from entrypoint to persistence. - Verify each slice with automated tests and compiler checks before proceeding. --- ## Design Pipeline: RFCs and ADRs Separate exploration from permanent architectural choices: ```mermaid graph TD A[Ambiguous Goal / High Uncertainty] --> B[RFC in design/rfc/] B -->|Consensus Reached| C[ADR in design/adr/] C --> D[Implementation Tasks] E[Trivial / Low-Uncertainty Task] --> D ``` - RFCs (`design/rfc/`): Use during exploration when requirements are ambiguous, trade-offs need debate, or multiple viable architectures exist. RFCs are fluid working documents. - ADRs (`design/adr/`): Use to record finalized decisions. ADRs are immutable historical logs capturing context, chosen architecture, and accepted trade-offs. - Tasks: Break ADR conclusions into concrete checklist items with clear acceptance criteria. --- ## Task Prioritization Categorize work by technical certainty and business value: | | High Technical Certainty | Low Technical Certainty | | :--- | :--- | :--- | | **High Value** | **Direct execution**: Implement interactively with compiler feedback and tight test loops. | **Research & Spikes**: Do not write production code yet. Run throwaway spikes in `scratch/` or draft an RFC. | | **Low Value** | **Delegate**: Offload to background tasks or subagents. | **Defer / Discard**: Drop or postpone until certainty increases or value is demonstrated. | --- ## Research & Evidence Hierarchy Do not guess APIs, package syntax, or model behaviors. Ground technical decisions in primary sources: ```text [1] Source Code (highest authority) └── [2] Official Documentation & API Reference └── [3] Official Release Notes & Announcements └── [4] Industry Expert Articles (< 3 months old) └── [5] Community Posts (< 3 months old) └── [6] Stale Articles (> 3 months old — discard) └── [7] Social Media (unverified — cross-check first) ``` Research rules: - Test APIs and compiler behavior with throwaway scripts in `scratch/` before modifying production code. - Discard community posts older than 3 months for fast-moving packages and AI tooling. - Always include clickable URLs when citing documentation or external examples. --- ## Dependency Version Verification Never guess version numbers, dependency syntax, or model names: - Inspect local project manifests (`go.mod`, `package.json`, `pyproject.toml`) for existing pinned constraints. - Query package registries directly (`npm view version`, `go list -m -versions `, `pip index versions `) or verify current dependency documentation. - Verify AI model names and API versions against current official documentation before updating API calls (e.g., verifying current Gemini model names against Google GenAI documentation). --- ## Semantic Versioning & 0.x Zero-Debt Rule Follow Semantic Versioning (`MAJOR.MINOR.PATCH`): - Increment `MAJOR` (`X.0.0`) for backwards-incompatible API changes. - Increment `MINOR` (`x.Y.0`) for backwards-compatible new features. - Increment `PATCH` (`x.y.Z`) for backwards-compatible bug fixes. ### The 0.x Zero-Debt Policy - In `0.x` development, never attempt backwards compatibility. - Do not add compatibility shims, deprecation wrappers, alias redirects, or fallback branches to support previous `0.x` shapes. Refactor callers and interfaces directly. --- ## Broken Window Code Hygiene Enforce clean code standards across every edit: - Delete dead code, unreachable branches, unused variables, and stale comments immediately. - Implementation comments must explain current logic only. Never write comments detailing how earlier versions worked or why code was rewritten; historical context belongs exclusively in ADRs and RFCs. - Keep names clean, unambiguous, and consistent across variables, types, and files. - Handle every error explicitly at the origin point. Never discard errors (e.g., `_ = err`, empty `catch`, or unhandled promises). - Never suppress linter errors with ignore directives (`//nolint`, `# noqa`, `eslint-disable`). Fix the underlying code. - Logging is not error handling. An error must be handled, propagated to the caller, or aborted with a clean exit. --- ## Pre-Release Quality Gate Before staging, committing, or pushing code: - Run the full build, format, lint, and test suite. - Verify all modified files satisfy the Broken Window Code Hygiene criteria. - Never commit or push with failing tests, broken formatting, or active lint errors. --- # Skill: godoctor (coding) > Developer tooling and architectural safety rules for Go. Automatically validates AST integrity, guards against regressions with compiler rollback gates, eliminates blind spots via Selene mutation testing, and enables fast test and coverage analytics with TestQuery SQLite queries. Activate when writing or refactoring Go code, fixing compilation or test failures, auditing test thoroughness with mutation testing, or enforcing idiomatic Go standards. **Web Page**: https://skills.danicat.dev/coding/godoctor/ **Source**: https://skills.danicat.dev/coding/godoctor/SKILL.md **Version**: 0.2.0 **Digest**: sha256:a6c6f7c963f487c892e765f73444ca610932dd6843711e0932f39ad2164a4539 **Install**: `npx skills add danicat/skills --skill godoctor -y` ## Instructions # Go Quality & Tooling Guide (GoDoctor) GoDoctor provides AST-aware Go developer tooling, code quality enforcement, and testing analytics available both as a command-line interface (CLI) and as a Model Context Protocol (MCP) server. --- ## 1. Go Coding & Architectural Standards ### Google Go Style & Idiomatic Practices - **Standard Toolchain Enforcement**: All code must be strictly formatted with `gofmt`, organized with `goimports`, checked with `go vet`, and linted with `golangci-lint`. - **Naming Conventions**: - Avoid repeating package names in exported types or functions (*no stuttering*). Use `user.Service` instead of `user.UserService`, `http.Server` instead of `http.HttpServer`, and `config.Load` instead of `config.LoadConfig`. - Use camelCase for unexported identifiers and PascalCase for exported identifiers. Acronyms must remain uniform in case (e.g., `JSONURL`, `dbID`, `xmlHTTP`). - **Error Handling**: - Return errors as the last return value. - Wrap errors with contextual information using `fmt.Errorf("action description: %w", err)`. - Do not panic in libraries or standard business logic; return explicit errors. ### Package Architecture & Layout - **Flat Package Structure**: Prefer flat package layouts over deep enterprise layered modeling (such as `adapters/`, `ports/`, `entities/`, `controllers/`, `repositories/`, `services/`, `usecases/`). Keep code flat in the root or logically grouped by feature/domain. - **Private vs. Public API**: Use `internal/` for private packages that should not be imported by external modules. Do not create a `pkg/` directory unless developing a cloud-native project in the Kubernetes ecosystem. - **Test Fixtures & Golden Files**: Store test fixtures, golden files, mock datasets, and external test inputs in `testdata/` directories. The Go toolchain ignores `testdata/` folders during normal package compilation. - **Avoid Monolithic Files**: Split package logic into clear, focused files named after their primary responsibility (e.g., `server.go`, `handler.go`, `config.go`, `types.go`). - **Prohibition of Generic Catch-All Packages**: NEVER create generic `util`, `shared`, `common`, or `helpers` packages. These act as catch-all dumping grounds that destroy dependency boundaries. Place functionality in specific, domain-named packages or close to its site of use. ### API Design & HTTP Architecture - **Interface Segregation**: Keep interfaces small and consumer-defined (*accept interfaces, return structs*). Do not create premature interfaces with single implementations. Expose concrete types from producer packages. - **HTTP Service Design**: Follow modern Go HTTP service design patterns: - Constructor-based dependency injection (e.g., `NewServer(cfg, logger)`). - Group HTTP routes and handlers on a single server struct. - Write explicit HTTP middleware for cross-cutting concerns (logging, authentication, tracing). --- ## 2. Tool Selection Matrix | Task / Goal | CLI Command (`godoctor call`) | MCP Tool Name | Behavior / Safeguards | | :--- | :--- | :--- | :--- | | **AST-Aware Code Edits** | `godoctor call edit` | `smart_edit` | Coordinate matching + AST formatting + atomic write + compiler rollback gate (`go vet`). | | **Build & Quality Pipeline** | `godoctor call build` | `smart_build` | Builds Go binaries and packages with integrated compilation, testing, coverage analysis, linting, and quality verification. | | **Test & Benchmark Runner** | `godoctor call test` | `smart_test` | Multi-tier runner (`fast`, `basic`/`standard`, `benchmark`, `complete`) + auto-indexes into `testquery.db`. | | **AST Documentation** | `godoctor call docs` | `read_docs` | Fetches package docs, exported symbols, types, and function signatures with 3-tier fallback caching. | | **Mutation Testing** | `godoctor call selene` | `selene` | Evaluates test suite quality by mutating AST operators and checking for test assertion kills. See [references/selene.md](references/selene.md). | | **SQL Test Analytics** | `godoctor call tq` | `test_query` | Executes SQLite queries against test history and statement coverage in `testquery.db`. See [references/testquery.md](references/testquery.md). | ### Test Runner Tiers (`smart_test` / `godoctor call test`) - **`level: "fast"`**: Sub-second inner loop test execution. Runs package unit tests directly; skips coverage profiling, benchmarks, and mutation analysis. Ideal for rapid iterative development. - **`level: "basic"` / `"standard"`**: Standard testing tier. Runs unit tests with statement coverage profiling and auto-indexes execution metrics into `.godoctor/testquery.db`. - **`level: "benchmark"`**: Runs unit tests, coverage profiling, and Go benchmark suites (`go test -bench=.`). - **`level: "complete"`**: Comprehensive quality gate. Runs unit tests, coverage profiling, benchmarks, and full multi-worker Selene AST mutation testing across all packages. Ideal for pre-commit, CI verification, and release audits. --- ## 3. Core Principles & Safeguards - **Zero-Fallback Policy**: External binaries (`golangci-lint`, `modernize`, `deadcode`, `selene`, `testquery`) must be pre-installed in `$PATH` or defined in `.godoctor.yaml`. Dynamic `go run` compilation fallbacks are banned to eliminate 1.5s–4.5s latency delays and ensure reproducible execution. - **Tool Version Tracking**: GoDoctor actively verifies installed tool versions against recommended baselines, reporting non-blocking upgrade recommendations and providing `godoctor check`. - **Absolute Paths Required**: All directory (`dir`) and file (`filename`) parameters must be absolute paths (e.g. `/path/to/project`). - **Atomic Edit Transactions & Compiler Gate**: `edit` / `smart_edit` writes changes to temporary files before atomic replacement, preserving file permissions. Edits are verified via `go vet ./...` and automatically rolled back if errors are introduced. - **Concurrency & Resource Management**: Heavy operations like `level: "complete"` (Selene AST mutation testing) utilize all CPU cores; avoid spawning concurrent test/build tasks while complete runs are in flight to prevent CPU exhaustion and SQLite WAL contention. - **Configuration-Driven**: Subsystems read settings from `.godoctor.yaml` following a strict 3-tier precedence hierarchy: $$\text{Per-Call Payload (JSON)} \succ \text{Config File } (\texttt{.godoctor.yaml}) \succ \text{Built-in Defaults}$$ --- ## 4. Environment Diagnostics (`godoctor check`) Inspect installed external tools, versions, and health status: ```bash # Formatted ASCII diagnostic table godoctor check # Machine-readable JSON output godoctor check --json ``` --- ## 5. Centralized Configuration (`.godoctor.yaml`) Initialize a configuration file in your repository: ```bash godoctor init ``` Key configuration sections in `.godoctor.yaml`: ```yaml version: "1" # CLI & Runtime Settings cli: default_output: "text" color: true # Server Execution Settings server: write_timeout: "5m" allowed_origins: - "http://localhost" - "http://localhost:*" - "http://127.0.0.1" - "http://127.0.0.1:*" # External Tools & Version Management tools: golangci_lint: recommended_version: "v2.12.2" pkg: "github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.12.2" modernize: recommended_version: "latest" pkg: "golang.org/x/tools/go/analysis/passes/modernize/cmd/modernize@latest" deadcode: recommended_version: "latest" pkg: "golang.org/x/tools/cmd/deadcode@latest" selene: recommended_version: "latest" pkg: "github.com/danicat/selene/cmd/selene@latest" workers: 0 # 0 defaults to runtime.GOMAXPROCS testquery_compat: true testquery: recommended_version: "latest" pkg: "github.com/danicat/testquery@latest" db_path: ".godoctor/testquery.db" # Subsystem Flags & Behavior features: autofix: true deadcode_check: true testquery_sync: true version_check_hints: true auto_rollback: true ``` --- ## 6. Installation & Surface Management ### Installing GoDoctor CLI ```bash go install github.com/danicat/godoctor/cmd/godoctor@latest ``` ### Managing Surfaces (`godoctor install` & `uninstall`) Configure MCP server registration in `mcp_config.json` and unpack agent skills: ```bash # Configure MCP and skills globally (default: ~/.gemini/config) godoctor install # Configure in workspace scope (.agents/) godoctor install -w # Modular configuration godoctor install --mcp # MCP server registration only godoctor install --skills # Skills unpacking only # Clean removal godoctor uninstall godoctor uninstall -w ``` --- ## 7. Direct CLI Invocation Examples (`godoctor call`) ### 1. `edit` (AST-Verified Coordinate Edits with Atomic Rollback) ```bash godoctor call edit '{"filename": "/absolute/path/to/main.go", "old_content": "fmt.Println(\"old\")", "new_content": "fmt.Println(\"new\")"}' ``` ### 2. `build` (Build, Test, and Lint Pipeline) ```bash # Standard workspace build and test godoctor call build '{"dir": "/absolute/path/to/project"}' # Build with specific output binary target godoctor call build '{"dir": "/absolute/path/to/project", "packages": "./cmd/godoctor", "output": "bin/godoctor"}' ``` ### 3. `test` (Multi-Tier Test Runner) ```bash # Available levels: fast, basic, benchmark, complete godoctor call test '{"dir": "/absolute/path/to/project", "level": "basic"}' ``` ### 4. `docs` (AST Symbol & Type Documentation) ```bash godoctor call docs '{"import_path": "net/http", "symbol_name": "Client"}' ``` ### 5. `selene` (Mutation Testing) ```bash godoctor call selene '{"dir": "/absolute/path/to/project"}' ``` ### 6. `tq` (SQL Test & Coverage Analytics) ```bash godoctor call tq '{"dir": "/absolute/path/to/project", "query": "SELECT package, test, elapsed FROM all_tests WHERE action = '\''fail'\''"}' ``` --- ## 8. Detailed References For specialized workflows, refer to the companion references: - **TestQuery SQL Analytics & Schema**: [references/testquery.md](references/testquery.md) — Comprehensive database schema (`all_tests`, `all_coverage`, `test_coverage`, `all_code`), SQLite query recipes, and statement coverage metrics. - **Selene Mutation Testing Guide**: [references/selene.md](references/selene.md) — AST mutation operators, mutant statuses (`KILLED`, `SURVIVED`, `UNCOVERED`), targeted mode execution, and surviving mutant remediation strategies. --- # Skill: latest-version (coding) > Query and verify latest stable package versions from official registries (npm, PyPI, Go proxy, Cargo, RubyGems) and Gemini models. Resolves accurate version constraints, checks for deprecated or yanked packages, and prevents version guessing. Activate when adding or updating dependencies, initializing new projects, editing package manifests (such as package.json, go.mod, pyproject.toml, Cargo.toml), or selecting Gemini models. **Web Page**: https://skills.danicat.dev/coding/latest-version/ **Source**: https://skills.danicat.dev/coding/latest-version/SKILL.md **Version**: 0.2.0 **Digest**: sha256:5a9d7521e51222570c1a8388fc8bd4f03271f5614dca328dc35ebb0f1899dc18 **Install**: `npx skills add danicat/skills --skill latest-version -y` ## Instructions # Latest Software Version (latest-version) Queries official registries to find stable package versions. Do not guess versions or rely on outdated knowledge. ## Available scripts - **`scripts/latest.js`** — Queries official package registries (npm, PyPI, Go proxy, Cargo, RubyGems) and Gemini models for stable versions. ## How to Use ### 1. Find the Ecosystem We support these registries: * `npm`: Node.js/JS * `pypi`: Python * `go`: Go * `cargo`: Rust * `gem`: Ruby * `gemini`: Gemini models (use 'latest', 'flash', 'pro', or brand names as the name) ### 2. Run the Command (Node.js 18+) Execute the bundled helper script with one or more package names. You can append the `--json` flag to receive structured JSON results: ```bash node scripts/latest.js [package-name2]... [--json] ``` ### 3. Save the Version Write the returned version constraint to your configuration file (such as `package.json`, `requirements.txt`, `go.mod`, etc.). --- ## Gotchas & Edge Cases * **Go Proxy Capitalization (Severe)**: The standard Go module proxy (`proxy.golang.org`) is case-sensitive and requires uppercase letters in module paths (e.g. `Sirupsen`) to be encoded with exclamation marks (`!sirupsen`). While the script handles this automatically, remain alert to this rule when auditing manual package layouts. * **Scoped NPM Packages**: NPM scoped packages (e.g., `@types/node` or `@google/genai`) must include the `@` symbol when passed as command arguments. * **PyPI Name Normalization**: PyPI treats underscores and hyphens interchangeably in registry lookups (e.g., `pip-install` vs `pip_install`), but Python code `import` statements must strictly match the code namespace. Ensure you do not write invalid Python import syntax. --- ## Warning Action Rules When a dependency is flagged with warnings by `latest.js` (e.g., deprecated, yanked, retracted, or archived): 1. **Halt Execution**: Stop the writing process immediately. 2. **Report Details**: Present the exact deprecation, retraction, or yanked reason returned by the script directly to the user. 3. **Propose Alternatives**: Query registry alternatives or request user instructions before writing any flagged or insecure packages to project configurations. --- ## Validation Loop When updating dependencies, follow this strict loop to prevent breaking the build: ```mermaid graph TD A[Start: Request Package] --> B[Run node scripts/latest.js] B --> C{Warnings / Errors?} C -->|Yes| D[Stop & Propose Alternatives / Query User] C -->|No| E[Write Version to Configuration File] E --> F[Run Local Package Tidy/Install] F --> G{Compilation Success?} G -->|No| H[Backtrack / Query Lower Version Constraint] H --> E G -->|Yes| I[Complete Task & Save Lockfile] ``` --- # Skill: pyhd (coding) > Modern Python development workflow, project architecture, and code quality guidelines using uv, Ruff, and pytest. Enforces strict virtual environment isolation with uv, modern Python 3.10+ typing, AST-safe linting and formatting with Ruff, and automated pytest verification loops. Activate when creating, refactoring, testing, or building Python code, managing dependencies with uv, or configuring pyproject.toml. **Web Page**: https://skills.danicat.dev/coding/pyhd/ **Source**: https://skills.danicat.dev/coding/pyhd/SKILL.md **Version**: 0.2.0 **Digest**: sha256:5d7a2c641686dfd68ba95eec4cbd40854ad6a5fc6c199522001a2b4bbf752be4 **Install**: `npx skills add danicat/skills --skill pyhd -y` ## Instructions # Modern Python Development (Pyhd) This guide establishes the standard development workflow, project structure, and code quality gates for Python projects using `uv` for fast environment and dependency management, `ruff` for linting and formatting, and `pytest` for test verification. --- ## 1. Project Scaffolding & Architecture Prefer the standard `src/` layout for Python packages to avoid accidental imports of uninstalled local code and ensure test parity with installed packages. ### Standard Project Layout ```text my-project/ ├── .venv/ # Managed isolated virtual environment (gitignored) ├── pyproject.toml # Unified project metadata, dependencies, and tool config ├── README.md # Project documentation ├── src/ │ └── my_package/ │ ├── __init__.py # Package export root │ ├── core.py # Domain logic │ └── py.typed # PEP 561 marker for type checkers └── tests/ ├── conftest.py # Shared test fixtures and pytest hooks ├── unit/ # Fast, isolated unit tests └── integration/ # Multi-module integration tests ``` ### Dependency Management with `uv` Manage dependencies deterministically using `uv` commands: ```bash # Initialize a new application or library project uv init --app my-project # For standalone applications uv init --lib my-library # For reusable packages with src/ layout # Add production dependencies uv add requests pydantic # Add development / testing dependencies uv add --dev ruff pytest pytest-cov # Synchronize local .venv with pyproject.toml and lockfile uv sync # Update lockfile without modifying dependencies uv lock ``` ### Self-Contained Scripts (PEP 723) For standalone automation or utility scripts, declare dependencies directly inline using PEP 723 script metadata: ```python # /// script # requires-python = ">=3.11" # dependencies = [ # "httpx", # "rich", # ] # /// import httpx from rich import print response = httpx.get("https://httpbin.org/get") print(response.json()) ``` Execute single-file scripts with automated dependency isolation: ```bash uv run script.py ``` --- ## 2. Plan-Validate-Execute (Refactoring) When performing complex or multi-file Python refactoring: 1. **Plan**: Scan the workspace with `grep_search` to identify all call-sites, import statements, and references to target symbols. 2. **Validate**: Verify compatibility of planned changes against dependent modules and type signatures. 3. **Execute**: Modify files incrementally, running the **Code Verification Loop** after each change. --- ## 3. Code Verification Loop After modifying any Python file, execute this verification loop before completing tasks: ```mermaid graph TD A[Start: Modify Code] --> B[Lint: uv run ruff check --fix] B --> C{Lint Clean?} C -->|No: Manual fixes needed| D[Fix Violations] D --> B C -->|Yes| E[Format: uv run ruff format] E --> F[Test: uv run pytest] F --> G{Tests Pass?} G -->|No| D G -->|Yes| H[Loop Complete] ``` ### Step-by-Step Verification Commands 1. **Lint & Auto-Fix**: Resolve syntax, style, and import sorting issues: ```bash uv run ruff check --fix ``` 2. **Format Code**: Ensure consistent code style: ```bash uv run ruff format ``` 3. **Run Unit & Integration Tests**: Verify zero regressions: ```bash # Run all tests uv run pytest # Run targeted test file or function uv run pytest tests/unit/test_core.py -k "test_process_data" ``` --- ## 4. Virtual Environment Isolation > [!IMPORTANT] > **Virtual Environment Isolation**: Always prefix Python commands, test runners, and formatting tools with `uv run` (e.g. `uv run python script.py`, `uv run ruff check`, `uv run pytest`). This guarantees execution within the local `.venv/` interpreter, preventing system package contamination and missing import errors. --- ## 5. Gotchas & Edge Cases * **Circular Imports in Type Annotations**: When module `A` imports type `B` purely for type annotations, prevent runtime import cycles by using `typing.TYPE_CHECKING`: ```python from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from my_package.service import DatabaseService ``` * **Mutable Default Arguments**: Never use mutable objects (`list`, `dict`, `set`) as default parameter values. Use `None` as a sentinel: ```python # ❌ Bug: Shared list across calls def append_item(item: str, target: list[str] = []) -> list[str]: target.append(item) return target # ✅ Correct: Fresh container per invocation def append_item(item: str, target: list[str] | None = None) -> list[str]: if target is None: target = [] target.append(item) return target ``` * **Explicit Exception Chaining**: When catching and re-raising errors as domain-specific exceptions, preserve root-cause tracebacks using `from err`: ```python try: data = parse_payload(raw) except json.JSONDecodeError as err: raise ValidationError("Malformed JSON payload") from err ``` * **Modern Python 3.10+ Typing**: Use built-in generics (`list[str]`, `dict[str, Any]`) and union syntax (`str | None`, `int | float`). Avoid importing legacy types from `typing` (`List`, `Dict`, `Union`, `Optional`). --- ## 6. 📚 Progressive Disclosure & References - **Python Best Practices Guide**: [`references/best_practices.md`](references/best_practices.md) — Idiomatic Python patterns, type annotations, Ruff configuration, and pytest fixture guidelines. --- # Skill: double-diamond (agents) > Universal multi-agent orchestration workflow based on the Double Diamond framework (Inception -> Discovery -> Definition -> Development -> Delivery). Coordinates parallel subagents with context isolation to separate problem-space research from solution-space implementation. Activate for complex, high-ambiguity initiatives across software engineering, in-depth research, long-form writing, legal analysis, or product strategy requiring structured human alignment gates. **Web Page**: https://skills.danicat.dev/agents/double-diamond/ **Source**: https://skills.danicat.dev/agents/double-diamond/SKILL.md **Version**: 0.2.0 **Digest**: sha256:16fc94d0a1d9a067e1f5141a8d53377a84d26e27643d64f7ec6c789cd280993e **Install**: `npx skills add danicat/skills --skill double-diamond -y` ## Instructions # Double-Diamond Multi-Agent Orchestration The `double-diamond` skill coordinates complex, high-ambiguity initiatives through the proven **Double Diamond** framework, preceded by an **Inception** alignment phase. It leverages **parallel subagents with context isolation** to thoroughly explore the problem space before committing to solution-space implementation. ``` INCEPTION PHASE (Pre-Diamond Alignment) /grill-me User Interview Establish Shared Understanding │ ▼ DIAMOND 1: PROBLEM SPACE DIAMOND 2: SOLUTION SPACE (Research & Exploration) (Creation & Verification) /--- Discovery (Diverge) ---\ /--- Development (Diverge) ---\ / Parallel `research` sub- \ / Parallel creation sub- \ / agents explore landscape, \ / agents craft disjoint \ Start > constraints & prior art > Brief > sections/modules in parallel > Delivery \ / Gate \ / (Gates) \--- Definition (Converge) --/ \--- Delivery (Converge) ----/ Synthesize findings into Holistic review, integration, a Foundation Document and quality gate verification ``` --- ## 🌐 Universal Domain Mapping Double Diamond adapts seamlessly across technical, creative, and analytical domains: | Phase | Software Engineering | Writing & Publishing | Legal & Policy Research | Product & Strategy | | :--- | :--- | :--- | :--- | :--- | | **0. Inception** | Stack, constraints, latency, scope | Audience, tone, thesis, length | Jurisdiction, case theory, facts | Market, user persona, success metrics | | **1. Discover** *(Diverge)* | Codebase, APIs, edge cases | Background research, angles, data | Precedents, statutes, case law | Competitor analysis, customer interviews | | **2. Define** *(Converge)* | Technical Specification | Structured Editorial Outline | Legal Brief / Argument Structure | PRD / Feature Specification | | **Steering Gate** | Approve architecture & trade-offs | Approve thesis & outline | Approve legal theory & approach | Sign off on product direction | | **3. Develop** *(Diverge)* | Parallel module implementation | Parallel chapter/section drafting | Parallel argument/motion drafting | Parallel prototype/stream exploration | | **4. Deliver** *(Converge)* | Build, tests, lint, spec compliance | Fact-check, style, voice, flow | Citation audit, counter-arguments | Executive synthesis, launch readiness | --- ## ⚡ Core Principles & Operational Rules 1. **Pre-Diamond Inception (Alignment Gate):** - Before launching research divergence, the Coordinator executes an **Inception** phase via the `/grill-me` interactive interview protocol (using `ask_question`). - The Coordinator explores the existing environment/context first, then interviews the user about goals, constraints, non-negotiables, target audience, and deliverable modality. 2. **Two Distinct Diamond Phases (Problem Space vs. Solution Space):** - **Diamond 1 (Problem Space):** Focuses exclusively on reconnaissance, constraint mapping, dependency analysis, and definition. No final deliverable code or prose is authored during Diamond 1. - **Diamond 2 (Solution Space):** Focuses on parallel creation against the approved definition, followed by rigorous quality gating. 3. **Context Isolation via Subagents:** - Deep exploration and multi-track creation happen in isolated subagent contexts (`research` for read-only exploration, `self` for creation). This prevents context pollution and hallucination in the Coordinator's session. 4. **Mandatory User Steering Gate (Human-in-the-Loop Alignment):** - Between Diamond 1 and Diamond 2, the Coordinator halts to present the synthesized **Foundation Document** (Spec, Outline, Brief, or PRD) and trade-offs to the user for explicit review and confirmation. 5. **Disjoint Work Allocation (Zero Collision):** - In Diamond 2 (Development), parallel creator subagents receive strictly disjoint assignments (e.g., distinct source files, separate article sections, independent legal claims) to prevent overwrite collisions. 6. **Domain-Specific Delivery Quality Gates:** - Work is not delivered until all domain-specific quality gates pass: structural integrity, localized unit/section verification, holistic consistency, and compliance with the approved Foundation Document. --- ## 🎯 Agent Budget & Degree of Parallelism (DOP) * **Definition**: **Agent Budget** is synonymous with **Degree of Parallelism (DOP)**. It defines the maximum number of **active, concurrent subagents** allowed to execute at the exact same time. * **Active vs. Past Capacity**: Completed or terminated subagents do **not** consume budget. The budget applies strictly to currently running subagents. When a subagent completes its work, its concurrency slot is immediately freed. * **Elastic Scaling**: While the baseline default is $\text{DOP} = 4$, the framework scales elastically to any user-requested budget (e.g., $\text{DOP} = 10, 20, 50+$) for massive parallel surveys, parameter sweeps, or multi-module initiatives. * **High-DOP High-Signal Mandate (Micro-Probe Rule)**: When operating with elevated concurrency ($\text{DOP} \ge 8$), subagents must act as focused micro-probes. The Coordinator instructs subagents to return dense, high-signal, structured summaries ($\le 150$ words or tabular format) rather than verbose essays, enabling clean Map-Reduce synthesis without context dilution. ### Recommended Baseline Sizing: | Initiative Scale | Agent Budget ($\text{DOP}$) | Active Discovery Workers | Active Creation Workers | Typical Scope | | :--- | :---: | :---: | :---: | :--- | | **Focused / Targeted** | **2** | **2** (Landscape + Standards) | **2** (Core + Surface) | Single module, short article, targeted feature | | **Standard (Default)** | **4** | **4** (Landscape, Standards, Edge Cases, Comparative) | **4** (WPs 1–4 disjoint modules/sections) | Multi-module service, comprehensive whitepaper, PRD | | **Complex / Deep** | **6–8+** | **6–8+** (Subsystem reconnaissance / micro-probes) | **6–8+** (Distributed package authors) | Full architectural rewrite, multi-chapter publication | | **Massive Swarm** | **20–50+** | **20–50+** (Broad API surveys, micro-benchmarks, fuzzing) | **20–50+** (Massive parallel module/asset generation) | Wide ecosystem sweeps, multi-file migrations | --- ## 📡 Non-Blocking Coordinator & Reactive Concurrency The Coordinator is the primary conversational interface and strategic conductor. It must remain **permanently unblocked** to respond to user messages at any point during execution. 1. **Role Separation (Delegation over Execution):** - The Coordinator orchestrates, synthesizes, and interfaces with the user. It **never** blocks itself with long, sequential manual execution—heavy exploration and drafting are delegated to subagents. 2. **Fire-and-Yield Concurrency:** - When the Coordinator spawns subagents via `invoke_subagent`, it **immediately halts tool calls to end its turn**. It never loops, sleeps, or polls. 3. **Always Unblocked for User Queries:** - Because the Coordinator never enters busy-wait polling loops, it is always available to process incoming user messages while subagents work in the background: - **Status Inquiries**: The Coordinator can immediately provide progress updates or inspect active workers via `manage_subagents (Action="list")`. - **In-Flight Steering / Scope Changes**: If the user provides new constraints or changes requirements mid-run, the Coordinator can steer active subagents via `send_message` or cancel/restart them via `manage_subagents (Action="kill")`. 4. **Automatic Reactive Wakeup:** - When subagents finish their tasks, the messaging platform automatically wakes up the Coordinator with their full results. --- ## 🧭 The 6-Step Double-Diamond Workflow ### 1. Step 0: Inception (Pre-Diamond Alignment) * Coordinator activates the `/grill-me` protocol, systematically interviewing the user one decision node at a time via `ask_question`. * Explores existing materials first, then clarifies scope boundaries, deliverable modality, non-negotiables, and user preferences. * **Reference Guide:** Read [`references/inception_phase.md`](references/inception_phase.md) for interview patterns and decision-tree traversal. ### 2. Step 1: Discover (Diamond 1 Divergence) * Coordinator decomposes the problem space into up to $\text{DOP}$ orthogonal exploration vectors (e.g., Landscape reconnaissance, Standards & APIs, Constraints & Failure modes, Prior art). * Spawns parallel `research` subagents using `invoke_subagent` and immediately yields execution. * **Reference Guide:** Read [`references/research_phase.md`](references/research_phase.md) for vector decomposition and prompt templates. ### 3. Step 2: Define (Diamond 1 Convergence) * Coordinator synthesizes research reports into a unified **Foundation Document** (Technical Specification, Editorial Outline, Legal Brief, or PRD). * Establishes system contracts, interfaces, chapter structure, or argument trees, alongside disjoint work package allocations. * **Document Template:** Populate [`assets/specification_template.md`](assets/specification_template.md) with research synthesis and work breakdowns. ### 4. Step 3: User Steering Gate (Interactive Alignment) * Coordinator presents the executive summary, draft Foundation Document, and architectural/editorial trade-offs to the user. * Solicits user feedback, resolves decision forks, and obtains explicit confirmation before proceeding to creation. ### 5. Step 4: Develop (Diamond 2 Divergence) * Coordinator spawns up to $\text{DOP}$ parallel creator subagents (`self` subagents with write & tool access) and immediately yields execution. * Each creator receives a strictly disjoint Work Package (WP) and executes localized verification: - **Software**: Package-scoped unit tests (`go test ./internal/pkg/...`, `pytest tests/unit/`, `npm test -- src/pkg/`). - **Writing**: Section drafting against word count, tone, and source citations. - **Legal/Policy**: Argument drafting with case citations and statutory cross-referencing. * **Reference Guide:** Read [`references/development_phase.md`](references/development_phase.md) for disjoint allocation and creator prompt templates. ### 6. Step 5: Deliver (Diamond 2 Convergence & Quality Gating) * Coordinator integrates all parallel deliverables into a coherent whole and executes end-to-end verification. * **Failure Recovery Protocol**: If any integration test, fact-check, or consistency check fails: 1. Isolate the failing component and review specific error traces or discrepancies. 2. Launch a targeted repair subagent with the exact context and interface contract. 3. Re-verify all delivery gates until 100% pass before presenting the final deliverable to the user. --- ## ⚠️ Common Gotchas & Antipatterns 1. **Skipping Inception & Assuming User Intent:** Never jump straight into research divergence without establishing core scope boundaries, audience, and constraints with the user. 2. **Premature Implementation in Diamond 1:** Never author production code or final prose during the discovery and definition phase. Diamond 1 is strictly for reconnaissance, constraint mapping, and interface/outline design. 3. **Bypassing the User Steering Gate:** Never transition directly from definition into creation without presenting the foundation document and trade-offs to the user for explicit confirmation. 4. **Overlapping Work Allocations:** Never assign two parallel creator subagents to the same file, section, or deliverable slice. Work Packages MUST be strictly disjoint to prevent race conditions and merge conflicts. 5. **Broad Integration Sweeps during Creation:** Creator subagents must perform fine-grained, localized verification (e.g. package unit tests, section fact-checks) rather than whole-project sweeps while sibling subagents are midway through edits. 6. **Passive Polling Loops:** Coordinator agents must NEVER poll subagent statuses in a loop. Spawning subagents is fire-and-yield; rely on automatic reactive wakeup to keep the Coordinator responsive to the user. --- ## 📚 Progressive Disclosure & References - **Inception Phase Guide**: [`references/inception_phase.md`](references/inception_phase.md) — Pre-diamond alignment, decision-tree traversal, and `/grill-me` protocol rules. - **Research Phase Guide**: [`references/research_phase.md`](references/research_phase.md) — Exploration vectors, subagent prompt templates, and synthesis rules across domains. - **Development Phase Reference**: [`references/development_phase.md`](references/development_phase.md) — Delivery execution, specialized workers, and non-blocking coordination. - **Specification Template**: [`assets/specification_template.md`](assets/specification_template.md) — Structured specification template for the Define phase. --- # Skill: intercom (agents) > Inter-session communication mesh connecting independent terminal sessions on the same host via Unix Domain Sockets and dedicated Comms Subagents. Features sticky project identities, zero impersonation, non-blocking duplex messaging, crash-resilient mailbox spooling, and automatic clean restart lifecycles. Activate when coordinating multi-agent workflows across separate workspaces, delegating tasks between independent terminal sessions, relaying test failures or code diffs, or establishing a local agent mesh network. **Web Page**: https://skills.danicat.dev/agents/intercom/ **Source**: https://skills.danicat.dev/agents/intercom/SKILL.md **Version**: 0.2.0 **Digest**: sha256:2860c685bb9cc4327c9cbb1760769f084f40b417a32aea73340e6c9d51048a81 **Install**: `npx skills add danicat/skills --skill intercom -y` ## Instructions # Intercom: Inter-Session Multi-Agent Comms Mesh `intercom` establishes zero-configuration, bidirectional inter-session communication between independent agent CLI sessions running on the same host using Unix Domain Sockets and dedicated Comms Subagents. ## Available scripts & assets - **`scripts/agy_ipc.py`**: Zero-dependency Unix Domain Socket transport, message router, auto-elected hub daemon, and sticky identity manager. - **`scripts/namegen.py`**: Sci-fi communications officer identity generator with sticky project persistence and channel collision protection. - **`scripts/test_ipc.py`**: Unit and integration test suite validating socket transport, leader election, NDJSON message framing, sticky identities, and clean restart lifecycles. - **`assets/agents/comms-officer.md`**: Dedicated subagent template for the Communications Officer. - **`references/comms-officer.md`**: Comprehensive guide to the Comms Officer subagent pattern and unblocked execution. - **`references/protocol.md`**: Low-level wire protocol, message envelope specification, socket framing, and persistence architecture. --- ## ⚡ Core Operational Mandates To ensure maximum responsiveness, zero user friction, and context hygiene, all Intercom mesh operations MUST adhere to these five core rules: 1. **One Sticky Comms Agent per Project Workspace:** - Every project directory maintains **one and only one sticky Communications Officer identity** (persisted in `.intercom/session.json`). - The identity is automatically resolved and bound when initializing comms. Across restarts and tool runs, the project always speaks under its established officer codename (e.g., `nyota-uhura`). 2. **Zero Impersonation & Collision Prevention:** - When claiming or validating an identity, the runtime checks active channel peers (`peers.json` and active socket connections). - If another running project is already actively connected under that officer name, the system automatically assigns the next available officer from the roster, preventing name collisions and impersonation. 3. **Mandatory Comms Officer Subagent (Unblocked Main Session):** - The Main Agent Session (ROOT) is the pair-programming interface to the user and **MUST NEVER** block itself running background listener scripts or managing raw socket streams. - The Main Agent **ALWAYS spawns a dedicated `comms-officer` subagent** via `invoke_subagent`. - The Comms Officer manages the background bridge, receives incoming socket events, and relays high-signal updates to the Main Agent via `send_message`. 4. **Smart Script Usage (Zero User Confirmation Spam):** - **NEVER** run `agy_ipc.py poll` in a tight loop or scheduled cron job. Polling loops repeatedly prompt the user for script authorization. - The Comms Officer subagent starts the background listener **ONCE** upon activation: ```bash python3 scripts/agy_ipc.py listen --channel --session --fresh ``` - Running as a single background task authorized once, it streams incoming messages and reactively awakens the subagent without polling overhead. 5. **Clean Restarts & Dead Comms Cleanup (Zero Context Contamination):** - When restarting or initializing a session (`agy_ipc.py init` or `agy_ipc.py listen --fresh`), the session mailbox is automatically reset to the current stream head. - Stale historical messages from dead sessions or yesterday's runs are never replayed into the LLM context. - Channel broadcasts route exclusively to **currently active connected peers**, preventing message buildup in orphaned zombie mailboxes. --- ## 1. Mesh Topology & Architecture ``` ┌────────────────────────────────────────────────────────┐ ┌────────────────────────────────────────────────────────┐ │ PROJECT A (Terminal 1) │ │ PROJECT B (Terminal 2) │ │ │ │ │ │ ┌──────────────────────────────────────────────────┐ │ │ ┌──────────────────────────────────────────────────┐ │ │ │ Main Agent Session (ROOT) │ │ │ │ Main Agent Session (ROOT) │ │ │ │ (Unblocked, pairing with the user) │ │ │ │ (Unblocked, pairing with the user) │ │ │ └────────────────────────▲─────────────────────────┘ │ │ └────────────────────────▲─────────────────────────┘ │ │ │ send_message (Relay) │ │ │ send_message (Relay) │ │ ▼ │ │ ▼ │ │ ┌──────────────────────────────────────────────────┐ │ │ ┌──────────────────────────────────────────────────┐ │ │ │ Comms Officer Subagent (nyota-uhura) │ │ │ │ Comms Officer Subagent (seven-of-nine) │ │ │ │ (Runs background listener, isolates network) │ │ │ │ (Runs background listener, isolates network) │ │ │ └────────────────────────┬─────────────────────────┘ │ │ └────────────────────────┬─────────────────────────┘ │ │ │ agy_ipc.py send / listen │ │ │ agy_ipc.py send / listen │ └───────────────────────────┼────────────────────────────┘ └───────────────────────────┼────────────────────────────┘ │ │ ▼ ▼ ┌───────────────────────────────────────────────────────────────────────────────────┐ │ Intercom Unix Domain Socket Hub & Spool │ │ /tmp/agy-ipc//hub.sock │ │ (Auto Leader-Election, Live Peer Routing, Zero-Config) │ └───────────────────────────────────────────────────────────────────────────────────┘ ``` --- ## 2. Quickstart: Connecting Two Sessions Follow this streamlined 3-step workflow to connect independent agent sessions: ### Step 1: Initialize Project Comms & Claim Sticky Identity Run `init` to establish the project's sticky identity, start the hub daemon, and reset mailbox state: ```bash python3 scripts/agy_ipc.py init --channel collab ``` *Output:* ```json { "status": "ready", "channel": "collab", "session_id": "nyota-uhura", "name": "Nyota Uhura", "title": "Chief Communications Officer", "is_sticky": true, "inbox_reset": true } ``` ### Step 2: Spawn the Dedicated Comms Officer Subagent The Main Agent uses `invoke_subagent` to launch the Comms Officer in the background: ```python invoke_subagent( Subagents=[{ "TypeName": "comms-officer", "Role": "Communications Officer", "Prompt": "You are our dedicated Comms Officer (nyota-uhura) for channel 'collab'. Run the background listener with 'python3 scripts/agy_ipc.py listen --channel collab --session nyota-uhura --fresh' and relay any incoming messages to this main session." }] ) ``` ### Step 3: Communicate Asynchronously - **Sending Outgoing Messages:** The Main Agent sends a directive to the Comms Officer via `send_message`: ```python send_message( Recipient="", Message="SEND TO seven-of-nine: Please review the newly generated auth schema." ) ``` The Comms Officer executes `python3 scripts/agy_ipc.py send --channel collab --session nyota-uhura --to seven-of-nine --text "Please review the newly generated auth schema."` and acknowledges. - **Receiving Incoming Messages:** When the remote peer responds, the background listener outputs the event, and the Comms Officer immediately notifies the Main Agent: ```python send_message( Recipient="", Message="[INTERCOM INCOMING from seven-of-nine]: Schema review passed with 0 warnings. Ready to merge." ) ``` --- ## 3. Communication Commands Matrix | Action | Command | Purpose | | :--- | :--- | :--- | | **Initialize Comms** | `python3 scripts/agy_ipc.py init --channel ` | Resolves sticky project identity, auto-spawns hub, resets inbox | | **Start Listener** | `python3 scripts/agy_ipc.py listen --channel --session --fresh` | Persistent stream listener running in Comms Officer background | | **Direct Message** | `python3 scripts/agy_ipc.py send --channel --session --to --text ""` | Direct point-to-point transmission to a specific officer | | **Broadcast** | `python3 scripts/agy_ipc.py send --channel --session --to "*" --text ""` | Channel-wide announcement delivered only to live connected peers | | **Query Peers** | `python3 scripts/agy_ipc.py peers --channel ` | Enumerates currently connected active sessions | | **Clean Stale State** | `python3 scripts/agy_ipc.py cleanup --channel --stale` | Prunes dead sockets and locks without interrupting active channel | | **Full Reset** | `python3 scripts/agy_ipc.py cleanup --channel ` | Completely purges channel socket, locks, and spool directory | --- ## 4. Script Reference & CLI Options All scripts require **zero external dependencies** and execute on Python 3.10+ standard libraries (`asyncio`, `socket`, `fcntl`, `json`). ### `scripts/agy_ipc.py` ```bash # Initialize project comms (idempotent, sticky, zero-collision) python3 scripts/agy_ipc.py init --channel main # Send direct message with structured JSON payload python3 scripts/agy_ipc.py send --channel main --session nyota-uhura --to seven-of-nine --text "Diff ready" --json-payload '{"files": ["auth.go"]}' # Stream incoming messages (runs continuously in background subagent) python3 scripts/agy_ipc.py listen --channel main --session nyota-uhura --fresh # List live peers python3 scripts/agy_ipc.py peers --channel main # Purge stale dead artifacts python3 scripts/agy_ipc.py cleanup --channel main --stale ``` ### `scripts/namegen.py` ```bash # Claim or retrieve sticky identity for current project without collisions python3 scripts/namegen.py --claim --channel main --json # Generate raw single officer ID python3 scripts/namegen.py --id-only # Display full roster python3 scripts/namegen.py --all ``` --- ## 5. Antipatterns & Operational Gotchas 1. **The Polling Loop Trap:** Running `agy_ipc.py poll` inside a `while` loop or scheduled timer. This spams the user with approval prompts. **Solution:** Launch `listen` once as a persistent background task. 2. **The Main Session Blocking Trap:** Running `listen` directly inside the Main Session. This blocks the main chat and prevents the user from pairing with the assistant. **Solution:** Always delegate comms to a dedicated `comms-officer` subagent. 3. **The Identity Clash Trap:** Hardcoding session names (e.g. `session="agent1"`) instead of using `init` / `namegen.py --claim`. **Solution:** Always let `init` resolve the sticky, collision-free identity. 4. **The Stale History Contamination Trap:** Restarting an agent and reading old inbox backlogs without `--fresh`. **Solution:** Always pass `--fresh` on restart so the agent only reads new messages from the current conversation. --- ## 6. Progressive Disclosure & References - **[Comms Officer Subagent Guide](references/comms-officer.md)**: Deep dive into the Comms Officer subagent pattern, lifecycle management, and message relaying. - **[Comms Officer Subagent Template](assets/agents/comms-officer.md)**: Ready-to-use subagent prompt definition. - **[Protocol & Framing Specification](references/protocol.md)**: Wire protocol, message envelope schema, socket framing, and persistence architecture. --- # Skill: skill-optimizer (agents) > Comprehensive guide to develop and improve Agent Skill performance. Contains best practices for skill formatting (frontmatter and metadata), naming, descriptions, fine-tuning activation triggers, evaluations, production-readiness and open sourcing. Activate when developing new skills or refining existing ones. **Web Page**: https://skills.danicat.dev/agents/skill-optimizer/ **Source**: https://skills.danicat.dev/agents/skill-optimizer/SKILL.md **Version**: 0.5.0 **Digest**: sha256:f58c45b1f42b2c1da077a27cb7f70b509841d7b6a55191657fa553c2098b2cbf **Install**: `npx skills add danicat/skills --skill skill-optimizer -y` ## Instructions # Agent Skill Optimizer Procedures, authoring principles, and quality standards for creating, auditing, and optimizing Agent Skills according to the Agent Skills specification and open-source best practices. ## Available scripts - **`scripts/count_tokens.py`** — Audits skills and categories against Tier 1, 2, and 3 token limits using Vertex AI ADC, Gemini API, or offline heuristic. --- ## Skill Architecture & Progressive Disclosure Limits Skills use a 3-tier progressive disclosure model to minimize token consumption: 1. **Tier 1 — Routing & Discovery Metadata** (~50–100 words / $\le 150$ tokens): - **Fields**: `name` (1–64 characters) and `description` (1–1024 characters). - **Runtime behavior**: Injected into the model's system prompt at startup for all available skills so the orchestrator can route tasks accurately. - **Budget limit**: Keep routing tokens $\le 150$ (ideal ~100 tokens). Keep description $\le 1024$ characters. 2. **Tier 2 — Skill Instructions & Body** (< 5,000 tokens / < 500 lines): - **Scope**: The main `SKILL.md` body (excluding frontmatter). - **Runtime behavior**: Loaded into active context only when the skill is explicitly activated. - **Budget limit**: Strict limit of $\le 5,000$ tokens and $\le 500$ lines. Move detailed API tables, expansive guides, and catalogs into Tier 3. 3. **Tier 3 — On-Demand Resources & References**: - **Scope**: Subdirectories loaded only when explicitly requested by instructions: - `references/`: Domain guides, schemas, cheat sheets, and syntax rules. Formatted as **Open Knowledge Format (OKF v0.2)** concept markdown documents with YAML frontmatter (`type`, `resource`, `sources`, `verified`) and an `index.md` bundle map for progressive disclosure. - `scripts/`: Executable helper tools and automation scripts. - `assets/`: Static templates, seed data, or boilerplate files. --- ## Frontmatter Specification & Metadata Guidelines Every skill must provide valid YAML frontmatter containing core identifiers, licensing, and an authoritative canonical URL: ```yaml --- name: my-skill description: > Concise definition of the skill and tangible topics covered. Mentions key architecture or superpower. Activate when encountering primary use case or problem conditions. license: Apache-2.0 metadata: category: coding tags: "go, refactoring, testing, quality" author: Maintainer Name (maintainer@example.com) version: "1.0.0" canonical: https://skills.example.com/coding/my-skill/ compatibility: Requires Go 1.22+ allowed-tools: Bash(go:*) Read --- ``` ### Field Rules & Single-URL Provenance #### 1. Core Top-Level Fields - `name` (required): 1-64 characters, lowercase alphanumeric and single hyphens (`a-z`, `0-9`, `-`). No consecutive hyphens (`--`), no leading/trailing hyphens. Must match directory name exactly. - `description` (required): 1-1024 characters. Non-empty. Follows the 3-Part Skill Description Blueprint (Definition & Scope + Superpower + Human Triggers). Do not include internal implementation plumbing. - `license` (required): Short SPDX license identifier (e.g., `Apache-2.0`, `MIT`) or path to a bundled license. - `compatibility` (optional): Environment or tool requirements (e.g., `Requires Python 3.11+`). Omit if standard. - `allowed-tools` (optional): Space-separated list of pre-approved tools (experimental). #### 2. Metadata Block (`metadata`) - `category` (recommended): Functional taxonomy domain (e.g., `coding`, `agents`, `devops`, `media`, `writing`, `analytics`). Recommended to match the parent category folder name in structured repositories. - `tags` (recommended): 3 to 6 high-level domain anchors for search and categorization. Avoid redundant synonym stuffing. - `author` (recommended): Maintainer attribution string (e.g., `Author Name (email@example.com)` or organization name). - `version` (recommended): Semantic Versioning SemVer 2.0.0 (`MAJOR.MINOR.PATCH`). - `canonical` (recommended): The authoritative web URL pointing to the skill's published documentation (e.g., `https://skills.example.com///`). - **Single Canonical URL Standard**: Avoid duplicating `homepage` and `repository` fields in frontmatter when a single canonical URL suffices. This reduces metadata overhead by ~60–80 tokens per skill while maintaining full provenance. #### 3. Zero Contamination Gate All public skills must be strictly generic, modular, and platform-agnostic: - **No local machine specifics**: Never include personal machine paths or local home directory structures. - **No internal corporate knowledge**: Never include internal project names, private channel names, or proprietary infrastructure URLs. - **No credentials or tokens**: Never leak API keys, personal access tokens, or private secrets. --- ## Optional Reference: Agent Skills MCP Server To query live specifications and documentation during development, you can connect the Agent Skills MCP server: - **Server URL**: `https://agentskills.io/mcp` - **MCP Configuration** (e.g., `~/.gemini/config/mcp_config.json` or `claude_desktop_config.json`): ```json { "mcpServers": { "agentskills": { "url": "https://agentskills.io/mcp" } } } ``` --- ## 5-Stage Skill Audit & Optimization Process Follow this procedure when creating, reviewing, or refining skills: ### Stage 1: Structure & File Layout - **Name Alignment**: Confirm `name` in frontmatter matches the directory name exactly. - **Tier 1 & Tier 2 Limits**: Verify routing budget ($\le 150$ tokens, $\le 1024$ chars) and body budget ($\le 5,000$ tokens, $\le 500$ lines) using `scripts/count_tokens.py`. - **Progressive Disclosure**: Move extensive documentation (> 100 lines), schemas, or static data into `references/` or `assets/`. - **Clean Relative Paths from Skill Root**: All internal file and script references in `SKILL.md` MUST use relative paths starting from the skill root directory (e.g., `scripts/process.py`, `references/guide.md`, `assets/template.md`). - **No category prefixes**: Use `scripts/tool.py`, never `category/skill-name/scripts/tool.py`. - **No placeholders**: Use `scripts/tool.py`, never `{skillDir}/scripts/tool.py` or `{baseDir}/scripts/tool.py`. - **No absolute paths**: The agent harness resolves relative paths against the skill base directory automatically. - **Available Scripts Discovery**: List bundled scripts in an `## Available scripts` section in `SKILL.md` so the agent immediately discovers available tools. - **Conditional Loading**: Clearly state *when* the agent should read each reference file. #### Auditing Skills with Bundled `scripts/count_tokens.py` Audit skills against Tier 1, Tier 2, and Tier 3 limits using the self-contained PEP 723 Python script: ```bash # 1. Audit a single skill uv run scripts/count_tokens.py ../../coding/godoctor/SKILL.md # 2. Audit a category directory of skills uv run scripts/count_tokens.py ../../coding/ # 3. Fast offline audit (uses ~4 chars/token heuristic, no API or network calls) uv run scripts/count_tokens.py ../../agents/ --heuristic-only # 4. Machine-readable JSON output (for CI/CD pipelines) uv run scripts/count_tokens.py ../../coding/godoctor/SKILL.md --json ``` **Authentication & Models**: - **Vertex AI ADC (Default)**: Automatically detects Application Default Credentials (`gcloud auth application-default login`) with model `gemini-3.7-flash` and location `global`. - **Gemini Developer API**: Set `export GEMINI_API_KEY="..."` to authenticate directly via Gemini API. - **Offline Fallback**: Automatically falls back to an offline ~4 chars/token heuristic if no network or credentials are available. ### Stage 2: Description, Trigger & Tag Optimization The frontmatter `description` is the primary text loaded by orchestrators at startup to determine activation. Craft every `description` against this 3-part blueprint: ``` [1. Concrete Definition & Scope] + [2. Architectural Superpower / Key Topics] + [3. Natural, Decisive Trigger] ``` 1. **Concrete Definition & Scope**: - State what the skill does in plain, direct English. - Enumerate tangible topics, formats, and artifacts covered. - Use universal mental models (e.g., *"Divide to Conquer approach"*). - Avoid narrating a play-by-play checklist in the description. 2. **Key Architecture / Superpower**: - State the technical capability plainly (e.g., *"uses parallel subagents to ensure context isolation"*). - Explain why the approach matters for quality and reliability. - Use open, illustrative examples (e.g., *"connected channels (such as LinkedIn, X/Twitter, Bluesky, and others)"*). - Do not waste tokens explaining internal algorithms or private code plumbing (e.g., AST parsing, regex, SQLite internals). 3. **Decisive Triggers**: - Include explicit domain terms and tool names. - Anchor triggers to user intent and problem characteristics (e.g., *"when tackling problems that require out of the box thinking"*, *"when developing new skills or refining existing ones"*). #### Trigger Discipline (The Anti-Pushy Rule) - **Eliminate Artificial Coercion**: Avoid phrases like *"Activate even if the user does not explicitly mention..."* or *"Trigger whenever anything related is requested"*. Overly aggressive trigger language causes false positives and pollutes the context window during multi-turn chats. - **Describe Problem Traits, Not Model Behavior**: Guide the orchestrator by detailing the **problem symptoms**, **task objectives**, and **domain vocabulary** that uniquely require this skill. Let clear architectural boundaries drive routing decisions naturally. #### Tag Taxonomy Guidelines - Choose **3 to 6 high-level domain anchors** for search indices. - **Do NOT repeat the skill name as a tag**: The `name` is already indexed. Repeating it wastes tag budget. - **Avoid generic noise tags**: Words like `cli` or `hierarchy` convey minimal context. Use domain-specific anchors like `management` or `structure`. - **Omit implementation details**: Skip low-level tags (`sqlite`) when high-level intent tags (`sql`, `analytics`) are present. - **Include brand/ecosystem anchors** when scoped specifically (e.g., `google` for Google-specific standards). ### Stage 3: Core Principles for Skill Body Design Every skill body must adhere to these 6 instructional standards: 1. **Teach Practices, Not Passive Declarations**: - Provide concrete, repeatable workflows, architectural patterns, commands, and debugging steps. - Focus on what the agent should *do*, *check*, and *produce*, rather than reciting encyclopedia definitions. 2. **Readability & Clear Scannability**: - Maintain clear sentence structure and high scannability (aim for Fog Index ~12–15 with leeway for technical syntax). - Avoid dense walls of text; organize multi-step procedures into structured checklists (`- [ ] Step 1...`). 3. **Zero Marketing, Buzzwords & Fake Qualifiers**: - Never use marketing buzzwords (*"vibrant"*, *"cutting-edge"*, *"blazing-fast"*, *"world-class"*, *"bespoke"*, *"game-changing"*). - Never use fake technical qualifiers (*"high signal SQLite WAL Engine"* ❌). State capabilities plainly (*"SQLite database"* ✅). 4. **Usability Over Implementation Plumbing**: - Emphasize the interface the agent interacts with (e.g., `SQLite` tells the agent to query via SQL). - Omit internal runtime trivia that does not affect agent interaction (e.g., disk page size, WAL flushing mechanics, internal cache layouts). 5. **Self-Contained with Explicit Installation for Optional Skills**: - Skills must function independently and provide complete baseline instructions. - When referencing a companion or guest skill (e.g., `godoctor`, `pyhd`, `buffer`), always provide its exact installation command: ```bash npx skills add / --skill -y ``` - Always treat guest skills as **strictly optional** with graceful fallbacks if the companion skill is not installed in the workspace. 6. **Zero Contamination**: - Ensure all instructions, examples, and scripts are 100% generic, platform-agnostic, and safe for public open-source distribution. ### Stage 4: Script Design & Bundling When bundling helper scripts into `scripts/`: - **Relative Path Invocations**: In `SKILL.md`, all execution examples must use relative paths from the skill root directory (e.g., `uv run scripts/analyze.py input.json`). Never prefix with category directories or template variables (`{skillDir}`, `{baseDir}`). - **Discovery in `## Available scripts`**: List all bundled scripts in an `## Available scripts` section in `SKILL.md` with brief functional descriptions so the agent discovers them up front. - **Mandatory Invocation & Auth Documentation**: Every bundled script must be documented with concrete execution examples, runtime requirements (`uv`, `deno`, `bun`), expected arguments, and its authorization model (e.g., Vertex AI ADC, API keys, OAuth, or offline fallback). - **Non-interactive execution**: Accept arguments via flags, environment variables, or stdin; never prompt for TTY input. - **Self-contained dependencies**: Declare dependencies inline using standard runtimes: - Python: PEP 723 script metadata (`# /// script ... # ///`) executed via `uv run` or `pipx`. - TypeScript/JavaScript: Deno (`deno run`) or Bun (`bun run`). - Ruby: `bundler/inline` (`require 'bundler/inline'`). - **Clean interfaces**: Provide `--help` with clear options and usage examples. - **Structured output**: Write machine-readable output (JSON/CSV) to stdout; write logs and progress to stderr. - **Actionable errors**: Output specific failure causes, expected inputs, and recovery steps. - **Safe operations**: Support `--dry-run` and idempotent execution for stateful or destructive operations. ### Stage 5: Operational Patterns & Failure Recovery Enhance skills with proven structural patterns: - **Gotchas & Edge Cases**: Document environment quirks, schema oddities, or non-obvious failure recovery steps. - **Output Templates**: Provide concrete Markdown, YAML, or JSON templates for expected outputs. - **Workflow Checklists**: Use markdown task lists (`- [ ] Step 1...`) for multi-stage processes. - **Validation Loops**: Require running a validator script or checklist, inspecting errors, and iterating until passing. - **Plan-Validate-Execute**: For batch or high-risk tasks, require generating a plan file, validating against schema, and executing only after validation passes. --- ## Case Studies: 3 Representative Before & After Optimizations The following 3 case studies demonstrate how to apply these principles across three major skill archetypes: ### Case Study 1: `double-diamond` (Process, Agents & Context Isolation) * **Scenario**: Complex orchestration and multi-phase methodologies. * **Anti-Pattern (AI Slop & Procedural Choreography ❌)**: ```yaml description: > Orchestrate complex engineering initiatives using the Double Diamond framework (Inception -> Discover -> Define -> Develop -> Deliver). Researches codebase constraints before writing code to resolve ambiguity, establish scope, and prevent architectural mistakes. Produces a technical specification for user review, then parallelizes development across independent subagents with automated compiler and test quality gates. Activate for high-ambiguity spikes, major refactors, multi-agent coding swarms, or explicit research-then-implement workflows. Do not use for single-file edits or simple bug fixes. tags: "agents, double-diamond, agile, swarm, orchestration, architecture, planning, research, problem-framing, parallel-coding, subagents, quality-gates" ``` * **Best Practice (Clean Definition & Architectural Superpower ✅)**: ```yaml description: > Development methodology to perform tasks using the Double Diamond framework, following the process: Inception -> Discovery -> Definition -> Development and Delivery. Uses parallel subagents to perform the tasks ensuring context isolation for optimal results. Activate when the user requests to use the Double Diamond methodology, when they mention terms like inception and discovery, or when tackling problems that require out of the box thinking, reducing ambiguity and/or enterprise grade quality levels. tags: "inception, delivery, agile, planning, research, subagents" ``` * **Why it works**: Replaces artificial procedural narration with a direct definition, highlights the real architectural superpower (**context isolation**), anchors triggers to human problem traits, and reduces 12 redundant tags to 6 high-signal anchors. --- ### Case Study 2: `godoctor` (Developer Tooling & Safety Gates) * **Scenario**: Language tooling, linters, code quality, and testing frameworks. * **Anti-Pattern (Generic Linter Jargon & Self-Referential Tags ❌)**: ```yaml description: > Developer tooling for Go that enforces language style, idioms, code formatting, testing standards, and complexity limits. Includes automated AST validation, rollback guards for broken changes, Selene mutation testing to expose blind spots, and multi-tiered testing loops. Activate when authoring or refactoring Go code, debugging compilation issues, auditing test suite strength, reducing cyclomatic complexity, or ensuring strict adherence to idiomatic Go conventions. tags: "godoctor, go, golang, ast, selene, mutation-testing, testing, refactoring, quality" ``` * **Best Practice (Concrete Safety Mechanisms & Value Framing ✅)**: ```yaml description: > Developer tooling and architectural safety rules for Go. Automatically validates AST integrity, guards against regressions with compiler rollback gates, eliminates blind spots via Selene mutation testing, and isolates test databases with TestQuery SQL transactions. Activate when writing or refactoring Go code, fixing compilation or test failures, auditing test thoroughness with mutation testing, or enforcing idiomatic Go standards. tags: "go, golang, testing, refactoring, quality, mutation-testing" ``` * **Why it works**: Highlights the architectural safety mechanisms (**compiler rollback gates** and **isolated SQL transactions**), removes self-referential tag noise (`godoctor`), and frames value around preventing broken builds. --- ### Case Study 3: `google-oss` (Ecosystem Scoping & Organizational Standards) * **Scenario**: Brand-specific or organizationally bounded guidelines. * **Anti-Pattern (Vague General Purpose Claims ❌)**: ```yaml description: > Standards, compliance verification, and licensing automation for Google open-source software and personal projects by Googlers. Ensures proper application of the Apache 2.0 license, license headers using addlicense, copyright attributions, repository disclaimers, and open-source release readiness. Activate when preparing a repository for public open-source release, auditing license headers, checking copyright statements, or ensuring compliance with open-source policies. tags: "standards, google-oss, license, apache-2-0, compliance, addlicense, disclaimer" ``` * **Best Practice (Explicit Organizational Boundaries & Brand Tag ✅)**: ```yaml description: > Compliance guide and licensing automation strictly for Google Open Source projects and personal projects created by Googlers. Applies Apache 2.0 license headers via addlicense, verifies copyright attributions, and configures mandatory repository disclaimers. Activate when preparing Google open-source or Googler personal repositories for public release, auditing license headers, or verifying open-source policy compliance. tags: "google, open-source, licensing, compliance, standards, copyright" ``` * **Why it works**: Explicitly defines the organizational boundary ("strictly for Google Open Source projects and personal projects created by Googlers") to prevent misuse on generic third-party open-source, and adds the essential `google` ecosystem tag. --- # Skill: swarm-coding (agents) > Orchestrates multi-agent hierarchical swarms using a divide-and-conquer architecture for complex, multi-system, or orthogonal engineering initiatives (e.g., concurrent backend, frontend, database, QA). Manages hierarchical Lead Agents and Specialists, disjoint work allocations, and strict parent-child communication. Activate whenever the user mentions 'swarm', requests multi-agent team coordination, or needs context isolation across multiple technical domains. **Web Page**: https://skills.danicat.dev/agents/swarm-coding/ **Source**: https://skills.danicat.dev/agents/swarm-coding/SKILL.md **Version**: 0.2.0 **Digest**: sha256:55a2fc6f2482272fe3f3cb1288854ea20e2b8074817aed3a9acf0e3894d6d40a **Install**: `npx skills add danicat/skills --skill swarm-coding -y` ## Instructions # Swarm Coding Swarm Coding divides complex engineering objectives among multiple specialized subagents structured in a clear hierarchical organization chart. This divide-and-conquer strategy guarantees context isolation, prevents cross-domain pollution, and accelerates execution by keeping subagent tasks narrowly scoped. > [!NOTE] > In this guide, the terms "agent" and "subagent" are used interchangeably. --- ## ⚡ Core Principles & Operational Rules 1. **Mandatory Activation:** Activate this skill immediately on any mention of the word "swarm" (case-insensitive) in relation to planning or executing a task. 2. **Coordinator Persistence & Non-Execution:** - The ROOT Swarm Coordinator ALWAYS remains a coordinator and NEVER falls back to an executor. - The Swarm Coordinator is strictly forbidden from writing production implementation code, running tests/builds, or performing direct command execution. 3. **Split Coordinator Profiles:** - **Swarm Coordinator (ROOT):** Attributed strictly to the ROOT agent that activated the skill (Multiplicity: 1). Defines the top-level **Org Chart**, names Lead Agents, allocates the agent budget, writes top-level architecture specs, and coordinates overall progress. - **Lead Agent:** Attributed to domain or system leads (Multiplicity: N, one per system/domain). Receives an allocated sub-budget from the Swarm Coordinator, assembles a specialist team, writes domain specifications, delegates tasks, and integrates domain deliverables. 4. **Specialist Role:** Attributed to task executors. Designs and implements narrowly-scoped components within a single domain, adhering to domain specs and running operational validation loops. 5. **Strict Communication Hierarchy (No Lateral Messaging):** - **Allowed:** Messaging between immediate parents and children ONLY (Swarm Coordinator $\leftrightarrow$ Lead Agent, Lead Agent $\leftrightarrow$ Specialist). - **Forbidden:** Direct communication between agents on the SAME layer (Lead Agent $\leftrightarrow$ Lead Agent, Specialist $\leftrightarrow$ Specialist) or direct escalation (Specialist $\leftrightarrow$ Swarm Coordinator) is strictly forbidden. - **Design Document First:** Inter-domain or cross-layer coordination MUST be handled by writing or updating shared design documents first, then notifying parent/child agents via hierarchical messaging. 6. **Team Continuity & Semi-Permanent Hierarchy (No Disposable Assets):** Treat agents as persistent team members, not disposable assets. Do not prematurely terminate subagents and spawn new ones. Retain and aggressively reuse active Lead Agents and Specialists across task iterations to preserve accumulated context. 7. **Fine-Grained Targeted Testing (No Broad Root Sweeps):** Specialists MUST execute fine-grained, package-scoped unit tests (e.g., `go test ./internal/physics/...`) strictly targeting their assigned task. Running broad project-root test commands (e.g., `go test ./...`) is strictly forbidden for Specialists unless explicitly requested by the Swarm Coordinator, preventing cross-task contamination and false failures while parallel agents work concurrently. --- ## 🎯 Agent Budget & Degree of Parallelism (DOP) * **Definition**: **Agent Budget** is synonymous with **Degree of Parallelism (DOP)**. It defines the maximum number of **active, concurrent subagents** allowed to execute at the exact same time across the entire swarm hierarchy. * **Active vs. Past Capacity**: Completed or terminated subagents do **not** consume budget. The budget applies strictly to currently running subagents. When a subagent completes its work, its concurrency slot is immediately freed. * **Default Concurrency**: Assumes a default budget of **10** active concurrent agents if omitted by the user. * **Low Budget Guard ($\le 1$):** If the user explicitly specifies an `agent budget <= 1`: - **HALT immediately** and do NOT spawn subagents or start implementation. - Trigger an interactive conversation with the user using `ask_question`. - Explain that multi-agent swarm orchestration requires budget $> 1$ (recommended 10). Present choices: (1) Increase budget to 10 (Recommended), (2) Specify a custom budget $> 1$, or (3) Fall back to single-agent execution. * **Adaptive Team Hierarchy**: - **Focused ($\text{DOP} \le 4$)**: Flat structure (Coordinator $\rightarrow$ Specialists directly). - **Standard / Multi-Domain ($\text{DOP} \ge 6$)**: Hierarchical structure (Coordinator $\rightarrow$ Domain Tech Leads $\rightarrow$ Specialists). - **Massive Swarms ($\text{DOP} \ge 20\text{--}50+$)**: Subagents act as focused micro-probes, returning dense, high-signal structured findings ($\le 150$ words) to enable crisp synthesis without context dilution. ### Concurrency Sizing Matrix: | Initiative Scale | Agent Budget ($\text{DOP}$) | Structure Type | Domain Tech Leads | Specialists per Lead | Typical Scope | | :--- | :---: | :---: | :---: | :---: | :--- | | **Focused** | **2–4** | Flat | None (Direct Coordinator) | 2–4 Specialists | Targeted dual-subsystem or focused feature | | **Standard (Default)** | **10** | Hierarchical | 2–3 (e.g., Backend, Frontend, QA) | 2–3 per domain | Full-stack application, multi-package service | | **Complex Platform** | **16–20+** | Hierarchical | 4–5 (API, Core Engine, UI, Infra, QA) | 3–4 per domain | Distributed microservices, full platform build | | **Massive Swarm** | **20–50+** | Elastic Micro-Probes | Distributed Leads / Probes | Micro-probes ($\le 150$w) | Wide ecosystem sweeps, multi-file migrations | --- ## 📡 Non-Blocking Coordinator & Reactive Concurrency The Swarm Coordinator is the primary user interface and top-level organizational conductor. It must remain **unblocked $\ge 99\%$ of the time** to receive steering comments, scope modifications, and status requests from the user. 1. **Role Separation (Delegation over Execution):** - The Swarm Coordinator acts like an engineering director: it breaks down epics, writes top-level architectural contracts, and manages the org chart. It **never** blocks itself with sequential coding, manual building, or terminal test runs. 2. **Fire-and-Yield Concurrency:** - When the Coordinator spawns Lead Agents via `invoke_subagent`, it **immediately halts tool calls to end its turn**. It never loops, sleeps, or polls. 3. **Always Unblocked for User Steering & Status Inquiries:** - Because the Coordinator never enters busy-wait polling loops, it is permanently available to process incoming user messages while the swarm works in the background: - **Status Inquiries**: The Coordinator can immediately provide live progress updates or inspect active workers via `manage_subagents (Action="list")`. - **In-Flight Steering / Scope Changes**: If the user provides new constraints or changes requirements mid-run, the Coordinator can steer active Lead Agents via `send_message` or cancel/restart them via `manage_subagents (Action="kill")`. 4. **Sole User Escalation Interface:** - Subagents do not possess `ask_question`. All requirement ambiguities or design trade-offs encountered by Specialists are messaged up to their Tech Lead, who routes them to the Swarm Coordinator via `send_message`. The Coordinator prompts the user with `ask_question` and relays decisions back down the hierarchy. --- ## 🔄 Map-Reduce Workflow & The "Reduce" (Reconciliation) Step Swarm Coding operates as a two-stage **Map-Reduce** engineering pipeline: ```mermaid graph TD subgraph Map Phase [1. Map Phase: Parallel Stream Execution] direction TB L1[Tech Lead Backend] --> S1[Specialist: Core API] L1 --> S2[Specialist: Database Models] L2[Tech Lead Frontend] --> S3[Specialist: UI Components] end subgraph Reduce Phase [2. Reduce Phase: Reconciliation & Final Verification] direction TB AUD[Audit Boundaries & Scan Placeholders] --> WIRE[Task QA/Integration Specialist to Wire Real Components] WIRE --> PURGE[Purge Temporary Stubs & Mock Adapters] PURGE --> E2E[Run End-to-End Integration Test Suite] E2E --> PROOF[Deliver Verified Evidence Log to Coordinator] end Map Phase --> Reduce Phase ``` ### 1. Map Phase (Parallel Development & Collision Avoidance) * **Flexible Subagent Prompting**: Provide clear domain goals and target boundaries in prompts without brittle syntax constraints. * **Tech Lead Arbitration**: Team Leads dynamically arbitrate file boundaries and dependencies among their specialists as changes evolve. * **Temporary Interface Contracts**: When Specialist A depends on in-progress work from Specialist B, they program against agreed interface stubs or mocks. ### 2. The Final "Reduce" Phase (Integration & Placeholder Purge) Parallel execution often leaves behind temporary mocks or stubs where real implementations were created by peer agents. Before declaring success, the Coordinator orchestrates the final **Reduce** step: 1. **Placeholder & Stub Audit**: Scans code boundaries to ensure no dangling `TODO` comments, dummy return values, or temporary mock adapters survive. 2. **Reconciliation & Real Component Wiring**: The Coordinator tasks a designated **Integration/QA Specialist** to connect all real modules together. 3. **End-to-End Project Verification**: The QA Specialist runs full project builds, integration tests, and linters, reporting actual terminal proof back to the Coordinator before final delivery to the user. --- ## 👥 Mechanics and Roles Subagents in a Swarm Coding session assume one of three roles: 1. **Swarm Coordinator (ROOT)** [Multiplicity: 1] - Acts as top-level architect and organizational manager. - Defines the **Org Chart**, names Lead Agents for each domain, allocates agent budgets, and writes top-level architecture specs. - **Persistence & Non-Execution:** Strictly forbidden from executing code or running build/test commands. - **Sole User Interface:** Sole agent in the swarm authorized to interact with the user via `ask_question`. 2. **Lead Agent (Domain Tech Lead)** [Multiplicity: N] - Technical lead for a specific domain or system (e.g., Frontend, Backend, Database). - Assembles a Specialist team within their allocated sub-budget, writes domain specs ("Design Document First"), deconstructs domain tasks, arbitrates collisions, and integrates deliverables. - **Tool Restrictions:** Command/script execution is disabled (`commandExecutionPolicy: off`). Delegates execution to Specialists and routes user questions up to the Swarm Coordinator via `send_message`. 3. **Specialist (Task Implementer / QA)** [Multiplicity: N] - Executes narrowly-scoped technical tasks within their assigned domain. - Follows domain specifications, executes the operational validation loop (build, test, lint, format), replaces stubs, and provides proof-of-validation logs to their parent Lead Agent. --- ## 💬 Communication Hierarchy & Rules ```mermaid graph TD ROOT["Swarm Coordinator (ROOT)"] <-->|Parent-Child Message| LEAD1["Lead Agent (Backend)"] ROOT <-->|Parent-Child Message| LEAD2["Lead Agent (Frontend)"] LEAD1 <-->|Parent-Child Message| SPEC1["Specialist (API Dev)"] LEAD1 <-->|Parent-Child Message| SPEC2["Specialist (QA Engineer)"] LEAD2 <-->|Parent-Child Message| SPEC3["Specialist (UI Dev)"] LEAD1 -.-x|FORBIDDEN: Sibling Message| LEAD2 SPEC1 -.-x|FORBIDDEN: Sibling Message| SPEC2 SPEC1 -.-x|FORBIDDEN: Direct Escalation| ROOT ``` 1. **Vertical Parent-Child Messaging ONLY:** - Swarm Coordinator $\leftrightarrow$ Lead Agent - Lead Agent $\leftrightarrow$ Specialist 2. **Forbidden Lateral Communication:** - Communication between agents on the SAME layer (Lead $\leftrightarrow$ Lead, Specialist $\leftrightarrow$ Specialist) is strictly forbidden. - Specialists MUST NOT message the Swarm Coordinator directly. 3. **Specification-Driven Coordination ("Design Document First"):** - When a change in Domain A impacts Domain B, Lead Agent A updates the shared design document in the workspace, then messages the Swarm Coordinator. The Swarm Coordinator reviews and notifies Lead Agent B. --- ## ⚠️ Gotchas & Antipatterns 1. **The Coordinator-to-Executor Fallback Trap:** Once activated, the Swarm Coordinator MUST NOT interpret user follow-up messages as permission to write code or execute tasks directly. Treat all messages as requests *to the swarm*. 2. **Leftover Placeholder Trap:** Delivering code where temporary stubs or mocks survive into the final codebase. Always execute the Reduce phase to purge stubs and wire real implementations. 3. **Under-Utilization Mismatch:** Spawning too few agents or failing to utilize Lead Agents when the agent budget and task scope allow multi-tier delegation. Always build a sensible Org Chart when budget $\ge 6$. 4. **Sibling Messaging Trap:** Attempting to send direct messages between peer Lead Agents or peer Specialists. Always route cross-component updates through shared design documents and hierarchical parent-child messages. 5. **Disposable Asset Pitfall (Context Loss):** Terminating subagents prematurely and spawning fresh ones for related tasks. Active subagents should be retained and reused across domain task iterations. 6. **The Root Test Contamination Trap:** Running broad project-root test commands (e.g., `go test ./...`) while parallel agents are modifying other packages causes false test failures. Specialists must scope test commands strictly to their assigned package until the final Reduce step. 7. **Passive Polling Loops:** Coordinator and Lead agents must never poll subagent statuses in a tight loop; rely on automatic reactive wakeup upon subagent task completion. --- ## 📚 Progressive Disclosure & References - **Swarm Coordinator Reference**: [`references/coordinator.md`](references/coordinator.md) — Root coordinator responsibilities, org chart design, unblocked posture, and the Reduce step. - **Lead Agent Reference**: [`references/lead.md`](references/lead.md) — Domain tech lead responsibilities, dynamic collision arbitration, and sub-team management. - **Specialist Reference**: [`references/specialist.md`](references/specialist.md) — Task execution, operational validation loop, stub replacement, and proof-of-correctness reporting. - **Bundled Lead Agent Template**: [`assets/agents/lead-agent.md`](assets/agents/lead-agent.md) — Standard subagent definition for domain leads. - **Bundled Specialist Agent Template**: [`assets/agents/specialist-agent.md`](assets/agents/specialist-agent.md) — Standard subagent definition for specialist workers. --- # Skill: uno-reverse (agents) > Radical simplification, red-teaming, and Occam's Razor devil's advocate for software architecture, PRDs, agent workflows, and technical designs. Challenges feature creep, speculative abstractions, and bloated specifications by proposing minimum viable primitives that deliver 90% of value with 10% of moving parts. Activate when reviewing complex technical proposals, pruning bloated architectures, red-teaming design docs, eliminating speculative features, or seeking the simplest possible path to production. **Web Page**: https://skills.danicat.dev/agents/uno-reverse/ **Source**: https://skills.danicat.dev/agents/uno-reverse/SKILL.md **Version**: 0.1.0 **Digest**: sha256:ebcbc0e6c021ee0b75db8f43933ae546c5880e94e2b64c6782c5262f423c3805 **Install**: `npx skills add danicat/skills --skill uno-reverse -y` ## Instructions # Uno-Reverse: Radical Simplification & Red-Teaming > *"Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away."* — Antoine de Saint-Exupéry The `uno-reverse` skill provides a rigorous **contrarian simplification and red-teaming framework**. While standard engineering processes naturally drift toward feature accretion, defensive layering, and speculative generalization, `uno-reverse` forces the opposite trajectory: **aggressive subtraction, primitive collapsing, and minimum viable execution**. --- ## 🎯 The 4 Inversion Principles ``` ┌─────────────────────────────────────────────────────────────┐ │ THE UNO-REVERSE RAZOR │ ├─────────────────────────────────────────────────────────────┤ │ 1. Subtraction Before Addition: "Can we delete our way out?" │ │ 2. Primitive Collapsing: "Can 1 composable primitive do 5 jobs?"│ │ 3. Zero-Speculation (YAGNI): "Are we solving an imagined problem?"│ │ 4. Failure-Surface Inversion: "How will this complexity break?" │ └─────────────────────────────────────────────────────────────┘ ``` 1. **Subtraction Before Addition**: Before designing a new subsystem, caching layer, or protocol, ask: *What existing assumption or artificial constraint can be deleted to make this entire feature unnecessary?* 2. **Primitive Collapsing**: Engineers frequently add flags, endpoints, and micro-abstractions for every sub-case. Identify the single underlying mathematical or conceptual primitive that subsumes all sub-cases without bespoke code. 3. **Zero-Speculation (Strict YAGNI)**: Reject all "future-proofing", pluggable abstraction layers for single implementations, and configurable policies where a single sensible constant or deterministic convention works. 4. **Failure-Surface Inversion**: Evaluate a system by its total attack, bug, and maintenance surface: $$\text{Reliability} \propto \frac{1}{\text{Moving Parts}^2}$$ Every added cache, lock, daemon, state file, and flag represents a new failure mode and cognitive tax. --- ## 🚩 Speculative Language Red-Flag Filter (PRDs & Specs) When auditing technical proposals or PRDs, immediately flag these weasel phrases: | Speculative Phrase ❌ | Underlying Reality | Uno-Reverse Action ✅ | | :--- | :--- | :--- | | *"Future-proof design"* | Unused code and speculative abstractions today | Delete the abstraction; write the concrete implementation. | | *"Pluggable provider model"* | Only 1 provider exists | Hardcode the single provider until a 2nd concrete provider is built. | | *"Flexible policy engine"* | Author avoided making a design decision | Pick the single sensible default convention. | | *"Event-driven microservices"* | Synchronous calls disguised as message queues | Use direct in-process function calls. | | *"Highly configurable"* | Shifting architectural choices to end-users | Ship zero flags; make opinionated choices. | | *"Generic abstraction layer"* | Premature DRY before seeing 3 distinct patterns | Duplicate the 5 lines of code; wait for Rule of Three. | --- ## 🔬 Accidental Complexity Code Smells (Codebase Audits) When reviewing code, actively hunt down and prune these structural anti-patterns: 1. **Single-Implementation Interfaces**: * *Smell*: An interface `FooService` with only one concrete struct `fooServiceImpl`. * *Fix*: Delete the interface. Export the concrete struct directly. Introduce interfaces only when consumers need mocking at architectural boundaries. 2. **Passthrough Wrapper Functions**: * *Smell*: Function `GetUserData(id)` that does nothing except call `db.FetchUser(id)`. * *Fix*: Eliminate the middleman. Call the underlying operation directly. 3. **State Machine Inflation**: * *Smell*: A 7-state lifecycle machine (`PENDING_APPROVAL`, `READY_FOR_QUEUE`, `QUEUED`, ...) with 15 transition validation functions. * *Fix*: Collapse to 2 boolean flags or an active/done state. 4. **Relational Over-Normalization for Small Datasets**: * *Smell*: A 6-table normalized schema with foreign keys and joins for $< 10,000$ total records. * *Fix*: Store as a single flat SQLite table, JSON document, or in-memory map. --- ## 🤖 The Agent & AI Workflow Razor AI systems are especially prone to multi-agent and prompt bloat. Apply these rules: | Bloated Agent Pattern ❌ | Collapsed Alternative ✅ | Rationale | | :--- | :--- | :--- | | **5-Agent Swarm for sequential task** | Single agent with 1 clear prompt | Multi-agent handoffs add latency, token cost, and lossy context degradation. | | **Intermediate Summarizer Agents** | Direct downstream consumption | "Telephone game" summarization strips critical nuance. | | **Micro-Tool Sprawl (10 single-action tools)** | 1 Polymorphic Tool with clear args | Decreases tool selection entropy and LLM routing hallucinations. | | **Autonomous Loop without Guardrails** | Deterministic script + LLM leaf node | Use code for control flow and LLMs only for fuzzy transformation. | --- ## 🔍 The 4-Step Uno-Reverse Audit Workflow When invoked on a design document, PRD, or proposed codebase change, execute this 4-step inversion protocol: ```mermaid flowchart TD A[Incoming Proposal / Complex Spec] --> B[Step 1: The Subtraction Test] B --> C[Step 2: Primitive Collapsing & Flag Pruning] C --> D[Step 3: The Cache & State Invalidation Probe] D --> E[Step 4: The 10% Minimum Viable Proposal] E --> F[Output: Simplification Scorecard & Minimalist Spec] ``` ### Step 1: The Subtraction Test (The 3 Deadly Questions) Apply these questions to every component in the proposal: 1. **The Ghost Problem Test**: If we do *nothing* and ship zero lines of code, what *actually* breaks in production today? 2. **The 90/10 Rule**: What 10% of this proposal delivers 90% of the actual user value? Can we discard the remaining 90% of the spec? 3. **The Accidental Complexity Probe**: Is this feature solving a real user problem, or is it solving a problem introduced by an earlier bad abstraction? ### Step 2: Primitive Collapsing & Surface Pruning Collapse multiple flags, commands, or data structures into single composable primitives: | Bloated Pattern (Before ❌) | Collapsed Primitive (After ✅) | Rationale | | :--- | :--- | :--- | | `--page`, `--section`, `--index`, `--toc`, `#slug` | Positional URI path `doc[#section]` | Unified resource addressability replaces 5 separate flags. | | Separate `read`, `load`, `refs`, `peek` commands | Single polymorphic `load ` | Reduces agent decision entropy and CLI verb sprawl. | | Configuration file + 12 env vars + CLI flags | Deterministic convention over configuration | Eliminates configuration drift and precedence bugs. | | In-memory LRU cache + Disk cache + Remote sync | Fast on-the-fly streaming | Raw operations in RAM (< 1 ms) make caching slower than compute. | ### Step 3: The Cache & State Invalidation Probe Whenever a proposal introduces caching, local state files, or background workers: - **Calculate the Cache Paradox**: Measure the cost of on-the-fly computation vs. cache serialization, disk I/O, hash verification, and invalidation race conditions. - **Enforce Ephemeral Execution**: If in-memory computation takes $< 1\text{ ms}$, **strictly forbid persistent caching layers**. ### Step 4: The 10% Minimum Viable Proposal (MVP) Draft an alternative "Uno-Reverse Specification" that: - Achieves the core objective in $\le 20\%$ of the proposed lines of code. - Uses zero external dependencies or heavy frameworks. - Requires zero background daemons, zero state migrations, and zero cache management. --- ## 🛡️ Chesterton’s Fence: When NOT to Simplify Radical simplification is **not** reckless deletion. Before eliminating a mechanism, identify whether it represents **Essential** or **Accidental** complexity: ``` ┌───────────────────────────────────────┬───────────────────────────────────────┐ │ NEVER PRUNE (Essential Safety) │ ALWAYS PRUNE (Accidental Bloat) │ ├───────────────────────────────────────┼───────────────────────────────────────┤ │ • Concurrency locks & race guards │ • Unbenchmarked caching layers │ │ • Authentication & permission checks │ • Generic abstract factories │ │ • Input validation & sanitization │ • Pluggable drivers for 1 provider │ │ • Idempotency tokens & rollbacks │ • Config flags for internal decisions │ │ • Explicit error handling boundaries │ • Micro-agent coordination swarms │ └───────────────────────────────────────┴───────────────────────────────────────┘ ``` > **The Chesterton Gate**: *If you cannot explain why a defensive check or data field was originally added, you are forbidden from deleting it until you understand its failure mode.* --- ## 📋 The Simplification Audit Scorecard Deliver all audit results in this standardized, high-signal markdown format: ```markdown # 🔄 Uno-Reverse Simplification Audit: [Topic / Proposal] ## 1. Executive Inversion Summary - **Proposed Complexity**: [Summary of moving parts, services, and flags in original design] - **Recommended Verdict**: [Prune / Collapse / Re-architect] - **Potential Code Reduction**: ~X% (from ~Y LOC to ~Z LOC) ## 2. The Cut List (Items to Eliminate Immediately) | Proposed Feature / Component | Reason for Elimination | What Happens Without It | | :--- | :--- | :--- | | [Feature A] | Speculative generalization | Nothing; solve with a single constant | | [Feature B] | Cache paradox (I/O > Compute) | Scan on the fly in < 0.1 ms | ## 3. Collapsed Primitives - **Instead of**: [List of disparate flags / commands] - **Use**: [Single elegant primitive] ## 4. The Minimalist Reference Design [Concrete, ultra-compact specification / code snippet implementing the 10% MVP] ## 5. Chesterton Boundary Assessment - **Essential Complexity Retained**: [Security, safety, or concurrency checks kept intact] - **Risk & Trade-off Assessment**: [Edge cases intentionally omitted and why the trade-off is sound] ``` --- ## 🚫 Common Engineering Traps to Call Out 1. **"What if the user wants X?" (Speculative Customization)**: - *Uno-Reverse Response*: "Wait until 3 distinct users actively request it in production before writing code for it." 2. **"We might support other backends later" (Premature Extensibility)**: - *Uno-Reverse Response*: "Implement the concrete backend directly. Refactoring clean concrete code is 10x faster than maintaining unused abstractions." 3. **"Let's add a cache for performance" (Unbenchmarked Caching)**: - *Uno-Reverse Response*: "Benchmark the raw in-memory operation first. If it takes $< 5\text{ ms}$, a cache is tech debt, not an optimization." 4. **"Let's add a configuration flag" (Passing Design Decisions to Users)**: - *Uno-Reverse Response*: "Make the right design decision in the code. Every configuration flag is an abdication of architectural responsibility." 5. **"Let's spawn an agent swarm for this" (Multi-Agent Vanity)**: - *Uno-Reverse Response*: "If the steps are sequential, write a 15-line deterministic script. Keep agents for non-deterministic reasoning." --- # Skill: buffer (writing) > Manage, draft, schedule, and publish social media content across connected channels (such as LinkedIn, X/Twitter, Bluesky, and others) using the Buffer CLI (@bufferapp/cli). Covers account and channel inspection, queue scheduling with dry-run safety validation, draft ideas management, and GraphQL schema introspection. Activate when scheduling social media posts, inspecting Buffer channels, automating social publishing, or managing social queues. **Web Page**: https://skills.danicat.dev/writing/buffer/ **Source**: https://skills.danicat.dev/writing/buffer/SKILL.md **Version**: 0.1.1 **Digest**: sha256:4c013f5f1706ca87994d052b4d6b6a21954608c7fe82ddc664d8825c3cf518f1 **Install**: `npx skills add danicat/skills --skill buffer -y` ## Instructions # Buffer CLI Playbook Procedures, command workflows, and safety gates for scheduling social media posts, managing channels, and automating publication workflows via the Buffer CLI (`@bufferapp/cli`). --- ## Architecture & Progressive Disclosure To minimize context consumption, `SKILL.md` contains core operational commands and safety rules. Load specialized references on demand: - **Pitfalls & Service Schemas**: Read [references/pitfalls.md](references/pitfalls.md) before composing payloads for complex networks (Instagram, Pinterest, YouTube, Twitter Threads). - **Automation Workflows**: Read [references/workflows.md](references/workflows.md) for shell scripting patterns, timezone math, and Relay cursor pagination. - **Rate Limits & Idempotency**: Read [references/rate_limits.md](references/rate_limits.md) for 429 backoff algorithms, retry matrices, and duplicate-post prevention. --- ## 1. Bootstrapping & Installation The Buffer CLI is generated from Buffer's public GraphQL schema, returning structured JSON with predictable error handling. ### Agent Bootstrap Sequence When running in a new environment or container, follow this self-bootstrapping sequence: ```bash # 1. Check if the Buffer CLI is already installed if ! command -v buffer &> /dev/null; then echo "Buffer CLI not found. Installing globally via npm (requires Node.js 18+)..." npm install -g @bufferapp/cli fi # 2. Verify installation version buffer --version # 3. Diagnose environment, config, API token, and network reachability buffer doctor ``` > [!TIP] > In ephemeral sandbox environments where global npm installation is restricted, you can invoke the CLI on the fly using `npx`: > ```bash > npx -y @bufferapp/cli doctor > ``` ### Authentication Modes 1. **Environment Variable (Recommended for CI / Ephemeral Agents):** ```bash export BUFFER_API_KEY="your-api-key" ``` 2. **Global Configuration (`buffer init`):** ```bash buffer init ``` *Writes API token, default organization, and timezone to `$XDG_CONFIG_HOME/buffer/config.json` (or `~/.config/buffer/config.json`).* --- ## 2. Core Operational Workflows > [!IMPORTANT] > Always use `--output json` when invoking commands within automated scripts or agent subshells to ensure clean machine parsing. ### Workflow A: Channel Discovery & Account Inspection Always inspect available channels before dispatching posts to resolve target `channelId`s: ```bash # Inspect account details and default organization buffer account --output json # List all connected social channels (LinkedIn, X, Bluesky, Threads, Instagram, etc.) buffer channels list --output json # Get detailed metadata for a specific channel buffer channels get --id "" --output json ``` --- ### Workflow B: Safe Post Creation & Scheduling Always execute with `--dry-run` first to validate the payload structure before sending live mutations: ```bash # Step 1: Dry run validation buffer posts create \ --channel-id "" \ --scheduling-type automatic \ --mode addToQueue \ --text "Your post content here" \ --dry-run # Step 2: Live creation (Add to channel queue) buffer posts create \ --channel-id "" \ --scheduling-type automatic \ --mode addToQueue \ --text "Your post content here" \ --output json ``` #### Passing Payloads via JSON or File For complex multi-line text, media attachments, or structured objects: ```bash # Inline JSON payload buffer posts create --json '{ "channelId": "channel_123", "schedulingType": "automatic", "mode": "addToQueue", "text": "Line 1\n\nLine 2 with links" }' --output json # Read payload from file buffer posts create --input post_payload.json --output json # Pipe payload from stdin cat post_payload.json | buffer posts create --input - --output json ``` --- ### Workflow C: Drafting Ideas Create draft thoughts and ideas in Buffer without assigning them immediately to a channel queue: ```bash # Create an idea in an organization buffer ideas create \ --organization-id "" \ --text "Draft angle for next week's release" \ --output json # Create an idea with structured JSON buffer ideas create --json '{ "organizationId": "org_123", "content": { "text": "Architectural breakdown draft" } }' --output json ``` --- ### Workflow D: Inspecting & Monitoring Scheduled Posts ```bash # List recent posts on a channel buffer posts list --channel-id "" --output json # Fetch specific post status buffer posts get --id "" --output json ``` --- ## 3. Field Selection (`--fields`) To minimize payload sizes and optimize context tokens, filter responses using comma-separated dot-notation paths or brace expansion: ```bash # Select top-level and nested properties buffer posts get --id "" --fields id,text,channel.name --output json # Brace expansion for list connections buffer posts list --channel-id "" --fields 'items.{id,text,status},pageInfo.endCursor' --output json # Retrieve complete GraphQL payload buffer posts get --id "" --fields all --output json ``` --- ## 4. Dynamic Schema Introspection When crafting payloads with unknown parameters or enums, query the live schema directly: ```bash # List all available command groups buffer schema list # Inspect exact input types, enum values, and output shapes for a command buffer schema describe posts create ``` --- ## 5. Global Flags & Exit Codes ### Global Flags | Flag | Description | Best Practice | | :--- | :--- | :--- | | `--output ` | Output renderer format | Always specify `--output json` in agent tooling | | `--dry-run` | Validates input locally without network calls | Always run before stateful mutations | | `--quiet` | Suppress spinners and stderr notices | Recommended for headless execution | | `--verbose` | Print rate-limit summary after requests | Useful for debugging throughput limits | | `--timeout ` | Command timeout in milliseconds (default: 30000) | Set appropriately for large batch requests | ### Exit Code Reference | Exit Code | Classification | Cause & Agent Remediation | | :---: | :--- | :--- | | **`0`** | Success | Command completed successfully. | | **`1`** | General Error | Runtime failure. Check error message on stderr. | | **`2`** | Usage / Validation Error | Missing required flags, invalid JSON, or schema mismatch. Run `buffer schema describe `. | | **`3`** | API Error | GraphQL upstream error or rate limit exhaustion. Inspect returned error details. | | **`4`** | Authentication Error | Missing or invalid token. Run `buffer doctor` or export `BUFFER_API_KEY`. | --- # Skill: deslopify (writing) > Editorial guidelines and rewriting workflow for purging text of AI clichés, tropes, and formulaic filler. Identifies and removes overused AI vocabulary (such as delve, tapestry, seamlessly), negative parallelism, dramatic countdowns, and repetitive summaries to restore natural human cadence. Activate when rewriting text to remove AI tells, polishing drafts to sound authentically human, eliminating filler tropes, or auditing prose style. **Web Page**: https://skills.danicat.dev/writing/deslopify/ **Source**: https://skills.danicat.dev/writing/deslopify/SKILL.md **Version**: 0.2.0 **Digest**: sha256:00812fac37913982b253d096363883c974856a29718424b2a19c198d92ff61d5 **Install**: `npx skills add danicat/skills --skill deslopify -y` ## Instructions # Deslopify: AI Slop & Trope Removal Procedures, editorial standards, and de-slopification workflows for purging text of recognizable Large Language Model (LLM) structural patterns, formulaic clichés, and conversational tropes to make technical writing sound authentically human, grounded, and engaging. --- ## Reference Catalog of AI Tells Consult [`references/tropes.md`](references/tropes.md) for the exhaustive catalog of AI tells, syntactic anti-patterns, and overused vocabulary. ### Quick Reference: Common AI Tells & Direct Alternatives | Category | Overused AI Pattern | Human-Sounding Alternative | | :--- | :--- | :--- | | **Magic Adverbs** | *quietly*, *deeply*, *fundamentally*, *remarkably*, *arguably* | Cut entirely or replace with concrete metrics and verified facts. | | **Pompous Vocabulary** | *delve*, *tapestry*, *landscape*, *robust*, *seamless*, *leverage*, *harness*, *testament* | Use simple, concrete words: *explore*, *look at*, *system*, *reliable*, *fast*, *use*. | | **The "Serves As" Dodge** | *serves as a reminder*, *stands as a testament*, *marks a pivotal moment* | Use direct copulas: *is*, *reminds us*, *shows*, *routes*, *was built in*. | | **Negative Parallelism** | *"It's not X — it's Y"*, *"Not because X, but because Y"* | State the point directly without staging a theatrical contradiction. | | **Dramatic Countdowns** | *"Not a bug. Not a feature. A design flaw."* | Combine into a single direct statement: *"This is a design flaw."* | | **Self-Answering Rhetoric** | *"The result? Devastating."*, *"The scary part? Nobody noticed."* | State facts without self-answering drama: *"Nobody noticed the failure."* | | **Filler Transitions** | *"It's worth noting that..."*, *"Importantly..."*, *"Notably..."* | Cut the preamble. If it's worth noting, state the fact directly. | | **Pedagogical Tones** | *"Let's break this down"*, *"Here's the thing"*, *"Here's the kicker"* | Eliminate teacher-mode signposting; present the technical facts directly. | | **Fractal Summaries** | Summarizing every section at the end of the section | Let the section content speak for itself; eliminate redundant sub-conclusions. | --- ## Before & After Transformation Matrix Use these concrete technical writing transformations to convert formulaic AI slop into crisp, peer-to-peer engineering prose: | AI Slop Anti-Pattern | Raw AI Draft (Slop) | Human Engineering Rewrite | Key Editorial Changes | | :--- | :--- | :--- | :--- | | **Pompous Vocabulary + Adverbs** | *"The system quietly leverages a robust orchestration pipeline to seamlessly deliver unprecedented throughput across the entire distributed landscape."* | *"The system uses a distributed pipeline to process 50,000 requests per second."* | Cut buzzwords (*quietly*, *leverages*, *robust*, *seamlessly*, *landscape*); added verified metrics. | | **Negative Parallelism + Self-Answering Drama** | *"It's not just a caching layer — it's a fundamental reimagining of state. The result? Instantaneous queries."* | *"Keeping index pages in memory reduced query latency from 80ms to 2ms."* | Removed theatrical negation (*"not just X — it's Y"*) and rhetorical drama (*"The result?"*); stated technical cause and effect directly. | | **Dramatic Countdown** | *"Not a slow disk. Not network jitter. A deadlock in the connection pool."* | *"A connection pool deadlock stalled all worker threads."* | Eliminated faux-suspense countdown; stated root cause upfront. | | **Pedagogical Preambles & Fillers** | *"It's worth noting that before we delve into the implementation, let's break down why this matters."* | *"Here is the connection pool architecture:"* | Cut teacher-mode signposting (*"delve"*, *"let's break down"*, *"it's worth noting"*). | | **The "Serves As" Dodge** | *"The proxy server serves as a crucial gateway, standing as a testament to modular design."* | *"The proxy routes incoming traffic and terminates TLS."* | Replaced pompous copulas (*serves as*, *stands as a testament*) with active technical verbs (*routes*, *terminates*). | | **Superficial Present-Participle Analysis** | *"We enabled HTTP/3, highlighting the team's forward-looking approach and underscoring our commitment to performance."* | *"Enabling HTTP/3 eliminated head-of-line blocking on packet loss."* | Cut hollow puffery (*"highlighting...", "underscoring..."*); explained concrete technical benefit. | --- ## 4-Stage Deslopification Workflow Follow this procedure when reviewing or rewriting any text: ```mermaid graph LR A[1. Scan & Tag Tells] --> B[2. Deconstruct AI Structure] B --> C[3. Direct Active Rewrite] C --> D[4. Cadence & Rhythm Audit] ``` ### 1. Stage 1: Scan & Tag Tells - Scan the input text against the patterns in [`references/tropes.md`](references/tropes.md). - Tag every occurrence of: - Magic adverbs (*quietly*, *deeply*, *fundamentally*). - Pompous vocabulary (*delve*, *tapestry*, *landscape*, *robust*, *seamless*). - Rhetorical questions and false suspense (*The catch?*, *Here's the kicker*). - Negative parallelism (*It's not just X, it's Y*). ### 2. Stage 2: Deconstruct AI Structure - Strip out formulaic LLM structures: - **Fractal summaries**: Delete sub-conclusions under intermediate headings (e.g., *"In summary, this step showed..."*). - **Signposted conclusions**: Replace "In conclusion", "Wrapping up", and "The bottom line" with direct summaries or actionable next steps. - **Bold-first bullet fatigue**: Convert long lists of bold-leaded pseudo-bullets into connected, narrative paragraphs where appropriate. - **Excessive em-dashes**: Limit em-dashes to at most one per document; use parentheses, commas, or separate sentences instead. ### 3. Stage 3: Direct Active Rewrite - **Replace inflated vocabulary**: Simplify grandiose descriptors to plain, active verbs and concrete nouns. - **Break formulaic symmetry**: Vary sentence lengths dramatically. Follow a long, nuanced sentence with a short, punchy one. - **Remove false suspense**: State the takeaway upfront (Inverted Pyramid style) rather than holding back information for a staged reveal. - **Ground claims in specifics**: Replace vague hype (*"provides an incredibly powerful mechanism"*) with concrete technical specifics (*"executes within 5ms on a single core"*). ### 4. Stage 4: Cadence & Rhythm Audit - Read the final draft to verify: - Does it sound like a knowledgeable human engineer speaking with a peer? - Are there any lingering rule-of-three triplets (tricolons)? - Is the sentence length varied naturally rather than stuck in uniform 15-word rhythms? - Is the tone authentic, conversational, and grounded in real-world engineering nuance? --- # Skill: google-blog-style (writing) > Style guide, legal compliance standards, and validation workflow for the Google Developers Blog. Enforces technical readability targets (Fog Index 12–15), professional tone, inclusive language, legal compliance, and style linting via Vale and Speedgrapher. Activate when drafting, editing, reviewing, or validating technical blog posts and articles for the Google Developers Blog. **Web Page**: https://skills.danicat.dev/writing/google-blog-style/ **Source**: https://skills.danicat.dev/writing/google-blog-style/SKILL.md **Version**: 0.2.1 **Digest**: sha256:e4e9520a26155eee3bcee3ae7e7776fcb9733498aacaa90585daab9140e8f376 **Install**: `npx skills add danicat/skills --skill google-blog-style -y` ## Instructions # Google Blog Style Guide Use this skill to strictly focus on drafting, editing, and validating technical blog posts, articles, and reviews for official Google Developer blogs. ## Core Mandates 1. **Readability First**: Target a Gunning Fog Index between **12 and 15** (Professional/Technical). 2. **Deterministic Tooling**: Run the validation scripts to ensure code safety and legal compliance. 3. **Inclusive Language**: Avoid niche jargon unless it is widely understood globally. See `references/style_guide/jargon.md`. 4. **Legal Safety**: Do not make unsubstantiated claims or discuss future roadmaps. Follow `references/legal_guidelines.md`. ## Workflow: Strict Plan-Validate-Execute ### 1. Plan **Before writing:** 1. **Define Goals**: Identify the key takeaway and target audience. 2. **Consult Guides**: - `references/writing_guide.md` (Tone and Structure). - `references/nomenclature_tags.md` (Correct tagging). 3. **Outline**: Use `assets/template.md` as a structural starting point. 4. **Style Guide Search**: Always use `grep_search` progressively within `references/style_guide/` to confirm specific formatting or brand rules before making assumptions. ### 2. Execute 1. **Write**: Focus on clarity, enthusiasm, and technical accuracy. - Use sentence case for all headings. - Adhere to rules found via `grep_search` in `references/style_guide/`. 2. **Modularize**: Keep `SKILL.md` brief by putting detailed docs in the `references/` folder. 3. **Refine**: Ensure the call to action is clear and all placeholder links use `example.com`. ### 3. Validate (Mandatory) > **GOTCHA:** If the `speedgrapher` MCP server is available, you MUST use Speedgrapher's tools and skills (`speedgrapher.vale`, `speedgrapher.fog`, `speedgrapher.slop`) to validate drafts instead of the custom local scripts. If `speedgrapher` is unavailable, use the following validation scripts: 1. **All-in-One Validation**: Run `node scripts/validate_all.cjs ` to run style linting, fog checks, and legal checks in one step, outputting a concise Markdown report. 2. **Standalone Checks**: - **Linting**: `node scripts/lint_style.cjs ` (Uses Vale). - **Readability**: Run `node scripts/fog.cjs `. - **Sanitization**: `node scripts/sanitize_blog.cjs `. 3. **Legal Review**: Manually check against `references/legal_guidelines.md`. ## Resources - **Template**: `assets/template.md` - **Validation**: `scripts/validate_all.cjs` - **Guides**: - `references/writing_guide.md` - `references/legal_guidelines.md` (CRITICAL) - `references/style_guide/` (Comprehensive style reference) - `references/nomenclature_tags.md` --- # Skill: inverted-pyramid (writing) > Structural guide and editorial model for organizing technical articles, developer documentation, and READMEs. Applies the Inverted Pyramid model to place high-value summaries and actionable quickstarts first, cascading down to usage workflows, architectural details, and compliance. Activate when structuring technical articles, writing or refactoring README files, organizing documentation hierarchy, or making technical guides scannable. **Web Page**: https://skills.danicat.dev/writing/inverted-pyramid/ **Source**: https://skills.danicat.dev/writing/inverted-pyramid/SKILL.md **Version**: 0.1.1 **Digest**: sha256:9dbd3322cbc15ea6b84e31298a4345993a98248df59377411e9615cddd16158f **Install**: `npx skills add danicat/skills --skill inverted-pyramid -y` ## Instructions # Inverted Pyramid Documentation Model Editorial guidelines and structural standards for authoring technical articles, README files, API references, and developer documentation using the **Inverted Pyramid** model—ensuring readers extract immediate, actionable value above the fold while details cascade progressively downward. --- ## 1. Core Philosophy: Information Cascading The **Inverted Pyramid** model organizes content by reader utility rather than author chronology: ```mermaid graph TD A["[High Value] Summary & Prescribed Core Actions"] --> B["[Medium Value] Usage, Workflows & Setup"] B --> C["[Detail Value] Development, Testing & Architecture"] C --> D["[Low Value] Internal Implementation & Compliance"] ``` ### The 3 Reader Archetypes Every technical document must cater to three distinct reading depths: 1. **The Scanner (5–10 seconds)**: Reads the headline, grabs the installation/execution command, and starts working immediately. 2. **The Operator (2–5 minutes)**: Reads usage tables, CLI flags, workflow checklists, and common recipes. 3. **The Contributor / Architect (10+ minutes)**: Explores internal architecture, build pipelines, design decisions, and compliance boundaries. --- ## 2. Standard Document Structures ### A. README & Project Documentation Hierarchy User-facing project documentation **must** follow this strict structural sequence: 1. **Title & High-Impact Summary**: - Short, active one-sentence hook explaining what the project is, what problem it solves, and why it exists. 2. **Prescribed Actions (Immediate Quickstart)**: - Copy-paste installation command (`npx ...`, `go install ...`, `pip install ...`, `cargo install ...`). - Single highest-value initial command to verify setup or produce output. 3. **Usage Guides & Workflows**: - Common CLI flags, arguments, configuration options, and copy-pasteable recipes. - Output examples and expected terminal responses. 4. **Developer & Contributor Instructions**: - How to clone, build locally, execute test suites, run linters, and verify builds. 5. **Technical Architecture & Internals**: - Subsystem designs, data schemas, module boundaries, and trade-off rationales. 6. **Legal & Compliance**: - License identifier, copyright, contributing links, and security policies. --- ### B. Technical Article & Blog Post Hierarchy 1. **Above the Fold (Lead Block - First 150 words)**: - State the core thesis, metric improvement, or direct answer immediately. - Do not open with generic throat-clearing (*"In today's fast-paced world of technology..."*). 2. **The Visual / Working Example**: - Provide a working code snippet or architectural diagram within the first two scrolls. 3. **Step-by-Step Breakdown & Nuance**: - Implementation steps, edge cases, configuration details, and benchmarking data. 4. **Actionable Takeaways & Next Steps**: - Concrete next actions, repository links, and references. --- ## 3. Structural Rules & Editorial Principles - **Lead with Action**: Never bury installation commands behind paragraphs of architectural theory. Let the user run the tool first. - **Sentence-Case Headings**: Keep headings clear, concise, and sentence-cased, leading with high-value nouns or active verbs. - **Table Density**: Use tables for CLI flags, tool comparisons, and option summaries rather than loose bullet lists. - **Copy-Paste Code Blocks**: Every command block must be complete and ready to execute without editing placeholders unless explicitly highlighted. --- # Skill: seo-optimizer (writing) > Technical SEO and Generative Engine Optimization (GEO) guide for developer docs and engineering blogs. Optimizes content for search engines and AI answer engines (Google AI Overviews, ChatGPT, Perplexity), splits human summary from search description metadata, verifies JSON-LD structured data (TechArticle), and maintains llms.txt. Activate when auditing technical SEO, optimizing articles for AI answer engines (GEO), generating llms.txt, or structuring search metadata. **Web Page**: https://skills.danicat.dev/writing/seo-optimizer/ **Source**: https://skills.danicat.dev/writing/seo-optimizer/SKILL.md **Version**: 0.1.1 **Digest**: sha256:171505d71bcae67f9ba8a63009b075cd37f7416160f4b374d81091a51702e6ae **Install**: `npx skills add danicat/skills --skill seo-optimizer -y` ## Instructions # SEO & Generative Engine Optimizer (GEO) Procedures, technical standards, and validation workflows for optimizing technical publications, developer documentation, and engineering blogs for traditional search ranking and AI-driven generative search engines, rooted directly in official Google Search Central guidelines. --- ## Skill Architecture & Progressive Disclosure To minimize context overhead, `SKILL.md` defines core workflows, operational checklists, and decision trees. Load detailed reference modules and execute audit scripts on demand: - **Official Google Search GenAI Standards**: Read [references/google_search_genai_guidelines.md](references/google_search_genai_guidelines.md) for Google's official stance on AI Overviews, RAG grounding, query fan-out, non-commodity content, and mythbusting. - **Meta Tags & Robots Specifications**: Read [references/meta_tags_and_robots_spec.md](references/meta_tags_and_robots_spec.md) for supported vs. unsupported meta tags, indexing directives (`nosnippet`, `max-snippet`, `max-image-preview:large`), and `data-nosnippet`. - **Multilingual & International SEO**: Read [references/multilingual_international_seo.md](references/multilingual_international_seo.md) for `hreflang` rules, bidirectional parity, URL architecture, and avoiding IP auto-redirect pitfalls. - **AI Search & GEO Standards**: Read [references/geo_and_ai_search.md](references/geo_and_ai_search.md) when optimizing for multi-engine AI discovery (Google AI Overviews, ChatGPT Search, Perplexity, Claude) and `llms.txt`. - **Technical SEO Checklist**: Read [references/technical_seo_checklist.md](references/technical_seo_checklist.md) when auditing titles, descriptions, headings, outbound link qualifications (`rel="sponsored"`, `rel="ugc"`, `rel="nofollow"`), and image accessibility. - **Frontmatter & Taxonomy**: Read [references/frontmatter_standards.md](references/frontmatter_standards.md) when splitting human-facing `summary` from search-facing `description`, or formatting tag taxonomy. - **Schema.org Structured Data**: Read [references/schema_markup_guide.md](references/schema_markup_guide.md) when generating or validating JSON-LD (`TechArticle`, `BreadcrumbList`, `HowTo`). - **Site Migrations & Status Codes**: Read [references/site_migrations_and_status_codes.md](references/site_migrations_and_status_codes.md) for HTTP status codes, domain migrations, Change of Address workflows, crawl budget, and crawlable link architecture. - **Search Appearance & SERP Features**: Read [references/search_appearance_and_serp_features.md](references/search_appearance_and_serp_features.md) for SERP visual elements, site names, favicon technical requirements, featured snippets (Position 0 direct answers), byline date parity, Google Discover standards, organic sitelinks, and paywalled content (Flexible Sampling). - **Evergreen Content Refreshes**: Read [references/content_refresh_guide.md](references/content_refresh_guide.md) when updating decaying legacy articles, retitling posts, or resolving search query cannibalization. --- ## Core SEO & GEO Philosophy Modern technical discoverability operates across two complementary surfaces: ```mermaid graph LR A[Technical Article / Doc] --> B[Traditional Search Engine] A --> C[Generative AI Search Engine] B --> D[Keyword Matching, SERP CTR, Meta Snippets] C --> E[Entity Extraction, Direct Answer Synthesis, Citations] D --> F[Direct Web Traffic] E --> F E --> G[Grounding & LLM Mindshare] ``` ### 1. Substance Over Commodity Fluff Search engines and generative AI models prioritize **non-commodity content with high Information Gain**—unique architectural diagrams, original code examples, verified benchmark data, and authoritative personal experience. Commodity summaries are filtered out. ### 2. The Inverted Pyramid & Value-First Answering Every technical post must answer the primary search intent **above the fold (within the first 2 paragraphs)** before detailing implementation specifics, historical context, or configuration options. ### 3. Dual-Purpose Metadata Split Never reuse the same text string for human preview cards and search engine indexing: - **`summary` (For Humans)**: A provocative, curiosity-inducing editorial hook displayed on homepage feeds, category lists, and related-article cards (80–180 characters). - **`description` (For Search & LLM Engines)**: A factual, high-density, keyword-grounded direct answer used in ``, OpenGraph tags, and Schema.org `description` (120–160 characters). Note that `` is unsupported and ignored. --- ## 5-Stage SEO & GEO Optimization Workflow Follow this procedure when auditing or authoring content: ```mermaid graph TD S1[Stage 1: Intent & Query Grounding] --> S2[Stage 2: Frontmatter & Metadata Split] S2 --> S3[Stage 3: GEO & Inverted Pyramid Structure] S3 --> S4[Stage 4: Technical SEO & Schema Verification] S4 --> S5[Stage 5: Deterministic Audit & Validation Loop] ``` ### Stage 1: Intent & Query Grounding 1. Identify the **Primary Target Intent**: - *Informational*: Developer wants to understand a concept (e.g., "how do antigravity subagents work"). - *Procedural/Tutorial*: Developer wants step-by-step instructions (e.g., "build mcp server in go"). - *Diagnostic/Troubleshooting*: Developer has a specific error or configuration challenge. 2. Formulate the **Core Search Query** and ensure the article provides an unambiguous, definitive answer. ### Stage 2: Frontmatter & Metadata Split Verify and craft distinct metadata fields: ```yaml --- title: "Building an MCP Server with Gemini CLI and Go" summary: "Turn any Go CLI into a native tool for AI agents with just 50 lines of code." description: "Step-by-step tutorial on building a Model Context Protocol (MCP) server in Go for Gemini CLI. Covers JSON-RPC handlers, tool discovery, and local debugging." categories: ["Software Engineering"] tags: ["apis", "golang", "mcp", "tutorial"] --- ``` - Title: 40–60 characters. Clear, high-signal, active phrasing. - Description: 120–160 characters. Concise, keyword-rich, direct. - Tags: Alphabetically sorted, lowercase kebab-case, no category duplication. ### Stage 3: GEO & Inverted Pyramid Structure 1. **The Lead Block**: Place the definitive takeaway, core metric, or architectural summary in the opening 150 words. 2. **Scannable Headings**: Use action-oriented `H2` and `H3` headings. Frame complex sections around real developer questions. 3. **Data & Fact Density**: Use tables for comparisons, bold key technical terms on first introduction, and provide copy-pasteable fenced code blocks with language identifiers. 4. **Quotability**: Write clear 1–2 sentence definitions that LLMs can extract verbatim as citations. ### Stage 4: Technical SEO & Schema Verification 1. **Single H1**: Exactly one `H1` tag per document (typically supplied by template frontmatter title). 2. **Heading Depth**: Never skip levels (e.g., `H2` directly to `H4`). 3. **Image Accessibility**: Every image must have descriptive `alt` text explaining the diagram or architecture (never generic names like `image.png` or empty `alt=""`). 4. **Outbound Link Qualification**: Use `rel="sponsored"`, `rel="ugc"`, or `rel="nofollow"` where appropriate. 5. **Internal Cross-Linking**: Include 2–4 contextual internal links to related articles using descriptive anchor text (never "click here" or "this post"). 6. **JSON-LD Schema**: Ensure the template emits valid `TechArticle` or `Article` structured data. ### Stage 5: Deterministic Audit & Validation Loop Execute the bundled audit tools and iterate until all issues are resolved: 1. **If Speedgrapher MCP is available**: - Run `speedgrapher.analyze_seo` on the target URL or Markdown draft. - Run `speedgrapher.fog` to ensure technical readability index is between **11.0 and 15.0**. - Run `speedgrapher.slop` to ensure AI cliché score is $< 25$. 2. **Run Bundled SEO Audit Script**: ```bash python3 scripts/audit_seo.py ``` For machine-readable JSON output: ```bash python3 scripts/audit_seo.py --json ``` 3. **Check `llms.txt` Synchronization**: When adding or restructuring articles, verify that the site's `/llms.txt` index is updated: ```bash python3 scripts/generate_llmstxt.py --content-dir content/posts --output static/llms.txt ``` --- ## Validation Rules & Gotchas > [!WARNING] > **Common SEO & GEO Gotchas:** > 1. **Duplicate Summary/Description**: Using identical strings for `summary` and `description` triggers a warning. `summary` is for human conversion; `description` is for search snippet extraction. > 2. **Generic Alt Text**: Alt text like `screenshot` or `diagram` provides zero semantic value to image search and multi-modal AI crawlers. Use descriptive explanations like `Architecture diagram showing Antigravity CLI communication with SQLite memory bank`. > 3. **Skipping Heading Levels**: Going from `## Heading` directly to `#### Sub-heading` breaks document outline parsing in search crawlers. > 4. **Vague Anchor Text**: Never link with `[link]({{< ref "..." >}})` or `[here]({{< ref "..." >}})`. Always use the localized target article title or descriptive topic name. > 5. **Unqualified Outbound Links**: Commercial/affiliate links should be qualified with `rel="sponsored"`, user comments with `rel="ugc"`. > 6. **Keywords Meta Tag**: Do not add ``; Google ignores it. --- ## Resources & Tooling Map - **Scripts**: - `scripts/audit_seo.py`: Automated CLI for technical SEO, metadata split, and GEO readiness auditing. - `scripts/generate_llmstxt.py`: Generator for standard `llmstxt.org` index files. - **References**: - `references/google_search_genai_guidelines.md`: Official Google Search Central AI search guidelines. - `references/meta_tags_and_robots_spec.md`: Google supported meta tags, robots directives, and HTTP headers. - `references/multilingual_international_seo.md`: Multilingual and international SEO with `hreflang`. - `references/geo_and_ai_search.md`: AI search engines, citation factors, and information gain. - `references/technical_seo_checklist.md`: Core meta tags, headings, link qualification, and accessibility. - `references/frontmatter_standards.md`: Taxonomy, tagging, and summary/description specification. - `references/schema_markup_guide.md`: Schema.org JSON-LD templates and property rules. - `references/site_migrations_and_status_codes.md`: HTTP status codes, full site migrations, crawl budget, and crawlable links. - `references/search_appearance_and_serp_features.md`: SERP anatomy, site names, favicons, featured snippets, Discover standards, and paywalls. - `references/content_refresh_guide.md`: Evergreen updates and search query decay mitigation. - **Assets**: - `assets/seo_audit_template.md`: Standard audit report format. - `assets/llms_txt_template.txt`: Standard `llms.txt` template. --- # Skill: social-copy (writing) > Editorial workflow and platform playbooks for drafting developer-native social media copy and campaigns. Extracts technical evidence via git log inspections or /grill-me interviews, establishes a canonical foundation narrative (CANONICAL.md), tailors derivatives for connected platforms (such as LinkedIn, X/Twitter, Bluesky, and others), and enforces anti-slop guidelines. Activate when drafting social media posts, writing release announcements, authoring technical threads, or running developer campaigns. **Web Page**: https://skills.danicat.dev/writing/social-copy/ **Source**: https://skills.danicat.dev/writing/social-copy/SKILL.md **Version**: 0.2.0 **Digest**: sha256:b4e9ae71b450d86d835dfe4798ce06e54c18371e063d63e4f27ba5c37a462d93 **Install**: `npx skills add danicat/skills --skill social-copy -y` ## Instructions # Social Copy Playbook Systematic procedures, voice standards, and platform-specific playbooks for crafting high-engagement, developer-native social media copy and cross-platform campaigns. --- ## Architecture & Progressive Disclosure To minimize context overhead, `SKILL.md` defines core editorial workflows and routing. Load detailed platform playbooks and anti-pattern checklists on demand: - **LinkedIn**: Read [references/linkedin_playbook.md](references/linkedin_playbook.md) when writing LinkedIn posts, PDF document carousels, or B2B engineering announcements. - **Twitter / X**: Read [references/twitter_playbook.md](references/twitter_playbook.md) when writing single tweets, micro-threads (3–5 tweets), or X long-form native posts / articles. - **Bluesky**: Read [references/bluesky_playbook.md](references/bluesky_playbook.md) when posting to AT Protocol feeds, sharing direct links, or formatting open-source releases with rich link cards. - **Instagram**: Read [references/instagram_playbook.md](references/instagram_playbook.md) when designing 4:5 carousels, micro-blog captions, and comment-to-DM funnels. - **Reddit**: Read [references/reddit_playbook.md](references/reddit_playbook.md) when writing self-posts for technical subreddits (`r/programming`, `r/golang`, `r/webdev`, `r/MachineLearning`, `r/devops`). - **Threads**: Read [references/threads_playbook.md](references/threads_playbook.md) when writing builder-centric 500-character posts with single Topic Tags. - **Anti-Patterns & Slop**: Read [references/anti_patterns.md](references/anti_patterns.md) before finalizing copy to eliminate AI clichés, unicode bolding bugs, and engagement-bait triggers. --- ## Core Voice & Editorial Philosophy Technical copy succeeds by delivering **immediate utility and authentic engineering depth** rather than marketing hype. ### 1. The Developer-to-Developer Tone Write like a **senior engineer or architect speaking to peers**: - **Direct & Unvarnished:** State the technical problem, constraint, or metric on Line 1. - **Transparent About Trade-offs:** No architecture or tool is flawless. Acknowledge what was sacrificed (memory, complexity, query latency). - **Substance Over Slogans:** Replace vague buzzwords (*"seamless", "revolutionary"*) with concrete technical nouns (*"lock-free ring buffer", "eager loading", "connection pooling"*). ### 2. The "Value-First" / "Zero-Click" Principle Every post should provide actionable insight directly in the timeline. Readers should learn something valuable even if they never click an external link. --- ## Campaign Lifecycle States Every social campaign follows a strict 4-state lifecycle tracked explicitly in its `CANONICAL.md` header (`- **Status**: `): | State | Definition & Trigger | Required Artifacts | | :--- | :--- | :--- | | `Draft` | Initial research, deep git inspection, `/grill-me` extraction, and `CANONICAL.md` authoring. Channel derivatives are being drafted. | `CANONICAL.md` | | `Ready` | Copy audited against anti-patterns, character budgets verified, and derivatives finalized. Awaiting author publishing gate. | `CANONICAL.md`, channel files (`linkedin.md`, `twitter.md`, etc.) | | `Scheduled` | Dispatched to a queue or scheduled for a specific timestamp (via Buffer CLI or native scheduler). | `CANONICAL.md`, scheduled date/time, optional `.ics` reminder | | `Published / Live` | Dispatched live (`shareNow`) or confirmed live on external channels. | Live post URLs recorded, workspace backlog updated | --- ## 7-Stage Social Campaign Workflow Follow this procedure when creating, publishing, or auditing social campaigns: ### Stage 1: Evidence Discovery & Grounding Never hallucinate features, metrics, or claims. 1. **Inspect Deep Git & Source References**: - **No Shallow Summaries / No One-Line Shortcuts**: Never rely on `git log --oneline` or brief commit titles alone. One-line summaries hide critical architectural nuance, structural refactors, and behavioral details. - Always run full `git log` with commit bodies, inspect diff statistics (`git show --stat`), check architecture decision records (ADRs), and inspect source documentation directly across all referenced repositories. 2. **Interview via `/grill-me`**: If the source is an open-ended topic or raw idea, recommend `/grill-me` or conduct an interactive interview to extract the author's real friction points, unexpected discoveries, and authentic engineering voice. 3. **Draft & Continuously Sync the Canonical Foundation Narrative (`CANONICAL.md`)**: Author a comprehensive, unconstrained master document with `- **Status**: Draft` covering: - Core premise & real motivation. - Exact repositories and what was specifically built/refactored in each. - Concrete performance observations (time-to-first-token, reasoning depth, compile times). - Architectural breakthroughs, failure modes, and trade-offs. - Philosophical takeaways and references to published writing. > [!IMPORTANT] > **Continuous Master Synchronization**: Whenever new evidence is collected (whether through proactive deep git inspection or after user feedback/pushback), immediately update `CANONICAL.md` before adjusting derivative platform posts. ### Stage 2: Target Channel Selection & Playbook Routing 1. Identify target platform(s) for the campaign. 2. Load matching platform references (`references/_playbook.md`). ### Stage 3: Hook Engineering & Character Budgeting Extract the sharpest tension, metric, or discovery from the Foundation Narrative to lead above the fold on each platform: - **LinkedIn**: < 140 characters (Mobile fold). - **Twitter / X**: < 280 characters (`Show more` fold). - **Bluesky**: Total post < 300 graphemes per post (or multi-post thread). - **Instagram**: < 125 characters (`...more` fold). - **Reddit**: Descriptive title specifying `[Tech Stack] + [Problem Solved] + [Metric/Trade-off]`. - **Threads**: Total post < 500 characters. ### Stage 4: Channel-Specific Distillation & Format Assembly Cut and reformat the Foundation Narrative into the appropriate archetype for each channel: - **LinkedIn**: Architectural deep-dive (1,300–2,000 chars) with first-comment link. - **Twitter / X**: Native long-form post (800–2,500 chars) with direct links or micro-thread. - **Bluesky**: Multi-post thread where every post is strictly $\le 300$ graphemes. - **Instagram**: 4:5 multi-slide carousel outline + micro-blog caption with DM automation hook. - **Reddit**: Value-first Markdown self-post (300–800 words, 4-space code indents for Old Reddit). - **Threads**: Casual, builder-centric post (<500 chars) with strictly 1 `#topic` tag. ### Stage 5: Anti-Pattern & Deslopification Audit Review all drafts against [references/anti_patterns.md](references/anti_patterns.md): - [ ] No banned AI words (*"delve", "game-changer", "revolutionary", "testament"*). - [ ] No mathematical unicode bolding (`𝗕𝗼𝗹𝗱` fonts). - [ ] Links positioned according to platform rules (1st comment for LinkedIn, direct in-body for X/Bluesky/Threads/Reddit). - [ ] Hashtags strictly match platform limits (0 for X, 1 for Threads, 0-1 for Bluesky, 1-3 for LinkedIn, 3-5 for Instagram). - [ ] Technical claims, metrics, and commands verified against reality. - Once verified, update header: `- **Status**: Ready`. ### Stage 6: Dispatch & Frictionless Clipboard Pipeline When executing or automating campaign publication (e.g. via Buffer CLI): 1. **Publishing Mode Confirmation Gate**: - Always ask the author whether to **Publish Immediately** (`shareNow`), **Add to Queue** (`addToQueue`), or **Schedule for a Specific Time** (`customScheduled`) before dispatching, unless explicitly commanded in the initial prompt. 2. **Cadence & Spacing Buffer Enforcement**: - **LinkedIn**: Enforce maximum 1 post per 24 hours to prevent intra-day self-cannibalization and algorithmic reach suppression. - **Twitter / X**: Enforce a minimum 2-to-3 hour spacing buffer between standalone posts to protect early engagement velocity, or package same-sitting posts as a connected Thread. - **Bluesky / Threads**: Maintain at least 1–2 hours between standalone broadcast posts. 3. **Safe Validation**: Always run `--dry-run` to validate JSON structures and per-channel constraints before live mutations. 4. **First-Comment Clipboard Pipeline (Free Tier Strategy)**: - For platforms where outbound links are placed in the first comment (such as LinkedIn) and the scheduler's automated comment API is restricted behind paid plans, dispatch the post with `mode: shareNow`. - **Immediately pipe the pre-formatted First Comment to the user's OS clipboard** (`pbcopy` on macOS, `xclip`/`wl-copy` on Linux). - Return the live post URL directly so the author can click the link and press `Cmd+V` / `Ctrl+V` immediately, avoiding forgotten comments and boosting the post's golden-hour engagement signal. ### Stage 7: Post-Dispatch Lifecycle Synchronization & Status Marking As soon as posts are published or confirmed live: 1. **Mark Campaign as `Published / Live`**: - Update `CANONICAL.md` header to `- **Status**: Published / Live` (or `- **Status**: Scheduled` if scheduled for a future milestone). - Record publication timestamp. 2. **Record Live URLs**: - Append the live post URLs (LinkedIn, Twitter/X, Bluesky, Medium, etc.) directly to `CANONICAL.md` or a `## Live Links` section. 3. **Synchronize Workspace Backlog / Task Trackers**: - In repositories tracking active tasks (such as `TODOs.md`), move the campaign to the **`## ✅ Completed Tasks`** section tagged `[DONE - PUBLISHED]`. - Remove or resolve the corresponding item from the active backlog. --- # Skill: buffer-analytics (analytics) > Collect and analyze social media data from Buffer in a local SQLite database. Stores your full post history and metrics across connected channels (such as LinkedIn, X/Twitter, Bluesky, and others) so you can run SQL queries or view reports on engagement, clicks, and views. Activate when you need to analyze social media performance, find the best days or times to post, identify top-performing content, or query Buffer data with SQL. **Web Page**: https://skills.danicat.dev/analytics/buffer-analytics/ **Source**: https://skills.danicat.dev/analytics/buffer-analytics/SKILL.md **Version**: 0.2.0 **Digest**: sha256:d165d7c7f0adb7865271c4980d722314c51252a8ee07bfe35f304872412545e4 **Install**: `npx skills add danicat/skills --skill buffer-analytics -y` ## Instructions # Buffer Analytics: SQLite Ingestion & SQL Query Engine The `buffer-analytics` skill provides high-performance data warehousing and SQL querying for social media data downloaded via the Buffer CLI (`@bufferapp/cli`). It ingests raw payloads without filtering into a local SQLite database and provides a SQL interface for deep content crunching. ## Available scripts - `scripts/buffer_analytics.py`: Automated sync and report CLI (incremental sync, backfill, pre-packaged reports, ad-hoc queries). Executed via `uv run scripts/buffer_analytics.py` (requires Node.js 18+ and `@bufferapp/cli`). - `scripts/test_buffer_analytics.py`: Unit and regression test suite validating schema, query extraction, and CLI flags. --- ## ⚡ Quick Start & Primary Actions All operations are driven via the bundled Python script in `scripts/buffer_analytics.py`: ```bash # 1. Incremental Sync (New posts + 2-day lookback metrics refresh) uv run scripts/buffer_analytics.py sync --db path/to/database.db # 2. Full Historical Backfill (Paginates through entire history) uv run scripts/buffer_analytics.py sync --full --db path/to/database.db # 3. Run Pre-Packaged Reports uv run scripts/buffer_analytics.py report overview --db path/to/database.db uv run scripts/buffer_analytics.py report top-posts --db path/to/database.db uv run scripts/buffer_analytics.py report channels --db path/to/database.db uv run scripts/buffer_analytics.py report timing --db path/to/database.db uv run scripts/buffer_analytics.py report hooks --db path/to/database.db # 4. Run Ad-Hoc SQL Query uv run scripts/buffer_analytics.py query "SELECT service, AVG(impressions), AVG(reactions) FROM v_posts_summary WHERE status = 'sent' GROUP BY service" --db path/to/database.db ``` If `--db` is omitted, the script defaults to `buffer_analytics.db` in the current working directory. --- ## 🗄️ Database Schema & Relational Structure The database maintains 6 normalized relational tables and high-performance SQL views. Detailed DDL and schema definitions are in [`references/schema.md`](references/schema.md). ### Tables 1. **`channels`**: Connected social accounts and metadata. - Key columns: `id` (PK), `organization_id`, `name`, `service` (`linkedin`, `twitter`, `bluesky`), `display_name`, `timezone`, `is_disconnected`, `raw_json`, `synced_at`. 2. **`posts`**: Individual posts, scheduling state, and content. - Key columns: `id` (PK), `channel_id` (FK), `channel_service`, `status` (`sent`, `scheduled`, `draft`), `text`, `external_link`, `sent_at`, `due_at`, `char_count`, `word_count`, `has_link`, `has_media`, `thread_count`, `raw_json`, `synced_at`. 3. **`post_metrics`**: Time-series metrics per post. - Key columns: `id` (PK), `post_id` (FK), `channel_service`, `metric_type` (`impressions`, `reach`, `reactions`, `comments`, `reposts`, `clicks`, `engagementRate`), `value`, `synced_at`. 4. **`post_assets`**: Attached images, videos, and media URLs. - Key columns: `id` (PK), `post_id` (FK), `type`, `mime_type`, `source`, `thumbnail`, `raw_json`. 5. **`post_tags`**: Campaign and topic tags assigned in Buffer. - Key columns: `id`, `post_id` (FK), `name`, `color`. 6. **`sync_history`**: Audit trail of all sync executions. - Key columns: `id` (PK), `channel_id`, `sync_mode`, `posts_fetched`, `posts_inserted`, `posts_updated`, `started_at`, `status`. --- ## 📊 Core Analytical View: `v_posts_summary` The primary view for SQL analytics is `v_posts_summary`, which pivots metrics and computes calendar dimensions: | Column | Type | Description | | :--- | :--- | :--- | | `post_id` | `TEXT` | Buffer Post ID | | `service` | `TEXT` | Network (`linkedin`, `twitter`, `bluesky`) | | `channel_name` | `TEXT` | Account handle/name | | `status` | `TEXT` | `sent`, `scheduled`, `draft` | | `sent_at` | `TEXT` | Full ISO timestamp | | `sent_date` | `TEXT` | Publication date (`YYYY-MM-DD`) | | `year_month` | `TEXT` | Calendar month (`YYYY-MM`) | | `day_of_week` | `TEXT` | Day name (`Monday`, `Tuesday`, etc.) | | `hour_of_day` | `INTEGER` | UTC hour (0–23) | | `char_count` / `word_count` | `INTEGER` | Text length metrics | | `has_link` / `has_media` | `INTEGER` | 1 if link or media is present | | `thread_count` | `INTEGER` | Number of posts in thread | | `impressions` | `REAL` | Total impressions / views | | `reach` | `REAL` | Unique accounts reached | | `reactions` | `REAL` | Likes and reactions | | `comments` | `REAL` | Comments received | | `reposts` | `REAL` | Retweets / reshares | | `clicks` | `REAL` | Link click count | | `engagement_rate` | `REAL` | Total engagement % | | `external_link` | `TEXT` | Live post URL | | `text` | `TEXT` | Full text copy | --- ## 🔍 SQL Analytics Cookbook Pre-tested SQL query recipes are documented in [`references/queries.md`](references/queries.md). ### 1. Best Day of the Week by Channel ```sql SELECT service, day_of_week, COUNT(*) AS posts, ROUND(AVG(impressions), 0) AS avg_impressions, ROUND(AVG(reactions), 1) AS avg_reactions, ROUND(AVG(engagement_rate), 2) AS avg_eng_rate FROM v_posts_summary WHERE status = 'sent' AND day_of_week IS NOT NULL GROUP BY service, day_of_week ORDER BY service, avg_impressions DESC; ``` ### 2. Best Posting Hours (UTC) ```sql SELECT service, hour_of_day || ':00 UTC' AS hour, COUNT(*) AS posts, ROUND(AVG(impressions), 0) AS avg_impressions, ROUND(AVG(reactions), 1) AS avg_reactions FROM v_posts_summary WHERE status = 'sent' AND impressions > 0 GROUP BY service, hour_of_day HAVING COUNT(*) >= 3 ORDER BY avg_impressions DESC; ``` ### 3. Impact of Links in Body vs. First Comment ```sql SELECT service, CASE WHEN has_link = 1 THEN 'Link in Body' ELSE 'No Link / First Comment' END AS placement, COUNT(*) AS posts, ROUND(AVG(impressions), 0) AS avg_impressions, ROUND(AVG(reactions), 1) AS avg_reactions FROM v_posts_summary WHERE status = 'sent' AND service = 'linkedin' GROUP BY placement; ``` --- ## 📚 Progressive Disclosure & References - **Full DDL Schema Reference**: [`references/schema.md`](references/schema.md) — Exact SQL table definitions, column types, constraints, and views. - **SQL Query Recipes**: [`references/queries.md`](references/queries.md) — Analytical queries for timing, link penalties, hooks, and topic cohorts. - **Workflows Guide**: [`references/workflows.md`](references/workflows.md) — Operational guidance for periodic backfills and cron automations. - **Inquiry Playbook**: [`references/inquiry_playbook.md`](references/inquiry_playbook.md) — Strategic questions for campaign and social retrospectives. --- # Skill: google-analytics (analytics) > Collect and analyze Google Analytics 4 (GA4) website data in a local SQLite database. Stores pageviews, active users, reading dwell time, traffic sources, and outbound clicks so you can run SQL queries or view reports on site performance. Activate when analyzing website traffic, measuring reader engagement and dwell time, evaluating the impact of site updates or milestones, or querying Google Analytics with SQL. **Web Page**: https://skills.danicat.dev/analytics/google-analytics/ **Source**: https://skills.danicat.dev/analytics/google-analytics/SKILL.md **Version**: 0.2.0 **Digest**: sha256:b9120a1b7f0fbe85774567dad4093e10b7637def7e5d604a753d868e864fa46b **Install**: `npx skills add danicat/skills --skill google-analytics -y` ## Instructions # Google Analytics 4 SQLite Ingestion & SQL Analytics The `google-analytics` skill ingests Google Analytics 4 (GA4) traffic, reading depth, acquisition channels, event streams, and outbound clicks into a local SQLite analytics database (`google_analytics.db` or `$XDG_DATA_HOME/google-analytics/analytics.db`) without data loss, preserving raw JSON payloads on all records, and providing a fast SQL interface for website analytics. ## Available scripts - `scripts/google_analytics.py`: Automated sync, reporting, and annotation CLI for Google Analytics 4. Executed via `uv run scripts/google_analytics.py` (requires Google Cloud ADC or OAuth credentials). - `scripts/test_google_analytics.py`: Unit and regression test suite validating schema, query extraction, and CLI flags. --- ## ⚡ Quick Start & Primary Actions All operations are driven via the bundled Python CLI script: ```bash # 1. Authorize OAuth 2.0 (with analytics.edit & readonly scopes) uv run scripts/google_analytics.py auth --port 8080 # 2. Discover accessible GA4 properties uv run scripts/google_analytics.py properties # 3. Create Deployment / Milestone Annotation (Cloud API + Local SQLite) uv run scripts/google_analytics.py annotate \ --title "Major Release / Architecture Overhaul" \ --date 2026-08-18 \ --commit abc1234 \ --description "Milestone description and release context." # 4. Incremental Sync (Updates newest days + 3-day latency lookback overlap) uv run scripts/google_analytics.py sync --db path/to/database.db # 5. Full Historical Backfill (Ingests up to 14 months of daily granular data) uv run scripts/google_analytics.py sync --full --db path/to/database.db # 6. Run Pre-Built Reports uv run scripts/google_analytics.py report overview --db path/to/database.db uv run scripts/google_analytics.py report top-pages --db path/to/database.db uv run scripts/google_analytics.py report channels --db path/to/database.db uv run scripts/google_analytics.py report geo --db path/to/database.db uv run scripts/google_analytics.py report events --db path/to/database.db uv run scripts/google_analytics.py report outbound --db path/to/database.db uv run scripts/google_analytics.py report milestone-impact --db path/to/database.db # 7. Execute Ad-Hoc SQL Query uv run scripts/google_analytics.py query "SELECT page_path, total_views, total_users, avg_dwell_sec, avg_bounce_pct FROM v_page_performance LIMIT 10" --db path/to/database.db ``` If `--db` is omitted, the script defaults to `google_analytics.db` in the current working directory. --- ## 🗄️ Database Schema & Relational Structure The database maintains 7 relational tables and 7 analytical views. Detailed DDL and schema definitions are in [`references/schema.md`](references/schema.md). ### Tables 1. **`daily_pages`**: Granular daily page metrics by URL, country, device, and traffic source. - Key columns: `id` (PK), `property_id`, `date`, `page_path`, `page_title`, `country`, `device_category`, `source_medium`, `screen_page_views`, `active_users`, `sessions`, `user_engagement_duration`, `bounce_rate`, `raw_json`, `synced_at`. 2. **`daily_traffic`**: Acquisition channels and source/medium pairs. - Key columns: `id` (PK), `property_id`, `date`, `session_source_medium`, `session_default_channel_group`, `country`, `device_category`, `sessions`, `active_users`, `new_users`, `engaged_sessions`, `user_engagement_duration`, `bounce_rate`, `raw_json`, `synced_at`. 3. **`daily_events`**: User interaction event stream (`scroll`, `click`, `first_visit`, `user_engagement`, `page_view`). - Key columns: `id` (PK), `property_id`, `date`, `event_name`, `page_path`, `country`, `device_category`, `event_count`, `total_users`, `raw_json`, `synced_at`. 4. **`outbound_clicks`**: External link exit destinations and click counts. - Key columns: `id` (PK), `property_id`, `date`, `link_url`, `page_path`, `country`, `event_count`, `total_users`, `raw_json`, `synced_at`. 5. **`properties`**: Verified GA4 property metadata, timezone, and settings. - Key columns: `property_id` (PK), `name`, `account_id`, `display_name`, `industry_category`, `time_zone`, `currency_code`, `service_level`, `raw_json`, `last_synced_at`. 6. **`site_milestones`**: Release milestones and publication events. - Key columns: `commit_hash` (PK), `event_date`, `title`, `description`, `category`, `scope`, `author`, `created_at`. 7. **`sync_history`**: Audit log of sync executions and row counts. - Key columns: `id` (PK), `property_id`, `sync_type`, `start_date`, `end_date`, `pages_synced`, `traffic_synced`, `events_synced`, `outbound_synced`, `status`, `error_message`, `started_at`, `finished_at`. --- ## 📊 Analytical SQL Views | View Name | Description | Key Columns | | :--- | :--- | :--- | | `v_daily_summary` | Daily aggregated traffic metrics | `date`, `total_sessions`, `total_active_users`, `total_page_views`, `total_engagement_min`, `avg_bounce_pct` | | `v_page_performance` | Page rollup with views, active users, dwell time, and bounce rate | `page_path`, `page_title`, `total_views`, `total_users`, `total_sessions`, `avg_dwell_sec`, `total_dwell_min`, `avg_bounce_pct` | | `v_channel_performance` | Acquisition channel breakdown | `channel_group`, `source_medium`, `total_sessions`, `total_users`, `total_new_users`, `total_engaged_sessions`, `engagement_rate_pct`, `total_dwell_min`, `avg_bounce_pct` | | `v_geo_breakdown` | Country traffic and dwell time | `country`, `total_sessions`, `total_users`, `total_page_views`, `avg_dwell_sec`, `avg_bounce_pct` | | `v_events_summary` | Aggregate event counts | `event_name`, `total_events`, `total_users` | | `v_outbound_links` | Outbound destination rankings | `link_url`, `total_clicks`, `total_users`, `referring_pages_count` | | `v_milestone_impact` | Pre vs. Post milestone comparison | `milestone_title`, `milestone_date`, `cohort`, `days_tracked`, `total_views`, `total_users`, `total_sessions`, `avg_engagement_sec`, `avg_bounce_pct` | --- ## 🔍 SQL Analytics Recipes Pre-tested SQL query recipes are documented in [`references/queries.md`](references/queries.md). ### 1. Top Landing Pages by Active Dwell Time ```sql SELECT page_path, page_title, total_views, total_users, avg_dwell_sec || 's' AS avg_dwell, total_dwell_min || 'm' AS total_dwell, avg_bounce_pct || '%' AS bounce_pct FROM v_page_performance ORDER BY total_dwell_min DESC LIMIT 15; ``` ### 2. Category / Subdirectory Rollup ```sql SELECT CASE WHEN page_path LIKE '/docs/%' THEN 'Docs' WHEN page_path LIKE '/blog/%' THEN 'Blog' WHEN page_path = '/' THEN 'Homepage' ELSE 'Other' END AS category, COUNT(DISTINCT page_path) AS page_count, SUM(total_views) AS total_views, SUM(total_users) AS total_users, ROUND(SUM(total_dwell_min), 1) AS total_dwell_min FROM v_page_performance GROUP BY category ORDER BY total_views DESC; ``` --- ## ⚠️ Cross-Tool Alignment: GA4 Organic Search vs. Search Console Property Totals When cross-referencing GA4 acquisition metrics with Google Search Console data: 1. **Multi-Engine Organic Reach:** GA4 `Organic Search` aggregates landing sessions and active users across **all search engines** (Google Search, Bing, DuckDuckGo, Ecosia, Yahoo, AI search engines). Search Console exclusively measures Google Search impressions and clicks. 2. **Session Arrivals vs. SERP Clicks:** GA4 tracks 100% of landing sessions without query-level privacy truncation. In contrast, Search Console API keyword exports filter out "anonymized queries". 3. **Property-Level Reconciliation:** For organic traffic reporting, GA4 `v_channel_performance` (filtering for `channel_group = 'Organic Search'`) naturally aligns with Search Console property-level totals (`daily_site_performance` in `search-analytics` and GSC Web UI Performance cards), while Search Console's `search_performance` table provides the granular ranking breakdown for identifiable keywords. --- ## 📚 Progressive Disclosure & References - **Full DDL Schema Reference**: [`references/schema.md`](references/schema.md) — Complete SQL table definitions, column types, constraints, and views. - **SQL Query Cookbook**: [`references/queries.md`](references/queries.md) — Tested SQL recipes for reading depth, acquisition channels, and exit destinations. - **Authentication Guide**: [`references/setup_auth.md`](references/setup_auth.md) — Google Cloud ADC login, API enablement, and GA4 property permissions. --- # Skill: search-analytics (analytics) > Collect and analyze Google Search Console organic search data in a local SQLite database. Stores clicks, impressions, click-through rates (CTR), average ranking positions, and landing pages so you can run SQL queries or view performance reports. Activate when analyzing Google Search traffic, tracking keyword rankings, finding SEO content optimization opportunities, or querying Search Console data with SQL. **Web Page**: https://skills.danicat.dev/analytics/search-analytics/ **Source**: https://skills.danicat.dev/analytics/search-analytics/SKILL.md **Version**: 0.2.0 **Digest**: sha256:a7d67ca1611ccadb8ac39ff2f7cb6c07af0ec56f0ec7a8706b694a3240b433df **Install**: `npx skills add danicat/skills --skill search-analytics -y` ## Instructions # Google Search Console SQLite Ingestion & SQL Analytics The `search-analytics` skill ingests Google Search Console performance metrics into a local SQLite analytics database (`search_analytics.db` or `$XDG_DATA_HOME/search-analytics/analytics.db`) without data loss, preserving all raw JSON payloads, handling API quotas via 25,000 batch chunks, and providing direct SQL querying over indexed search traffic. ## Available scripts - `scripts/search_analytics.py`: Automated sync, reporting, and OAuth CLI for Google Search Console. Executed via `uv run scripts/search_analytics.py` (requires Google Cloud OAuth credentials). - `scripts/test_search_analytics.py`: Unit and regression test suite validating schema, query extraction, and CLI flags. --- ## ⚡ Quick Start & Primary Actions All operations are driven via the bundled Python script in `scripts/search_analytics.py`: ```bash # 1. Authenticate with Google OAuth 2.0 uv run scripts/search_analytics.py auth --port 8080 # 2. Incremental Sync (Updates newest days + 3-day latency overlap) uv run scripts/search_analytics.py sync --db path/to/database.db # 3. Full Historical Backfill (Ingests up to 16 months of granular daily data) uv run scripts/search_analytics.py sync --full --db path/to/database.db # 4. Run Pre-Built SQL Reports uv run scripts/search_analytics.py report overview --db path/to/database.db uv run scripts/search_analytics.py report top-queries --db path/to/database.db uv run scripts/search_analytics.py report top-pages --db path/to/database.db uv run scripts/search_analytics.py report countries --db path/to/database.db uv run scripts/search_analytics.py report devices --db path/to/database.db uv run scripts/search_analytics.py report timing --db path/to/database.db uv run scripts/search_analytics.py report milestone-impact --db path/to/database.db # 5. Run Ad-Hoc SQL Query uv run scripts/search_analytics.py query "SELECT query, SUM(clicks), SUM(impressions) FROM search_performance GROUP BY query ORDER BY SUM(clicks) DESC LIMIT 10" --db path/to/database.db ``` If `--db` is omitted, the script defaults to `search_analytics.db` in the current working directory. --- ## 🗄️ Database Schema & Relational Structure The database maintains 6 relational tables and 7 high-performance analytical views. Detailed DDL and schema definitions are in [`references/schema.md`](references/schema.md). ### Tables 1. **`daily_site_performance`**: Unfiltered property-level daily totals (`dimensions: ['date']`). Matches 100% of property clicks/impressions in the Search Console web interface and 28-day Achievement badges. - Key columns: `id` (PK), `site_url`, `date`, `search_type`, `clicks`, `impressions`, `ctr`, `position`, `raw_json`, `synced_at`. 2. **`search_performance`**: Granular keyword-level performance partitioned by query, page, country, and device. - Key columns: `id` (PK), `site_url`, `date`, `query`, `page`, `country`, `device`, `search_appearance`, `search_type`, `clicks`, `impressions`, `ctr`, `position`, `raw_json`, `synced_at`. 3. **`properties`**: Verified Search Console web properties. - Key columns: `site_url` (PK), `permission_level`, `raw_json`, `synced_at`. 4. **`sitemaps`**: Submitted XML sitemaps, error counts, and indexed URL counts. - Key columns: `site_url`, `path` (PK), `type`, `last_downloaded`, `last_submitted`, `errors`, `warnings`, `indexed_count`, `raw_json`, `synced_at`. 5. **`site_milestones`**: Release milestones and publication launches for cohort impact analysis. - Key columns: `commit_hash` (PK), `event_date`, `title`, `description`, `category`, `scope`, `author`, `created_at`. 6. **`sync_history`**: Audit log of backfill and incremental sync operations. - Key columns: `id` (PK), `site_url`, `sync_type`, `start_date`, `end_date`, `rows_synced`, `status`, `error_message`, `started_at`, `completed_at`. --- ## 📊 Analytical SQL Views | View Name | Description | Key Columns | | :--- | :--- | :--- | | `v_search_performance` | Granular performance with computed calendar dimensions | `date`, `year_month`, `day_of_week`, `query`, `page`, `country`, `device`, `clicks`, `impressions`, `ctr_pct`, `avg_position` | | `v_daily_summary` | Daily aggregated traffic metrics per site | `date`, `distinct_queries`, `distinct_pages`, `total_clicks`, `total_impressions`, `avg_ctr_pct`, `avg_position` | | `v_top_queries` | Aggregated search term rankings & click share | `query`, `active_days`, `total_clicks`, `total_impressions`, `avg_ctr_pct`, `avg_position` | | `v_top_pages` | Aggregated landing page performance & query breadth | `page`, `ranking_queries`, `active_days`, `total_clicks`, `total_impressions`, `avg_ctr_pct`, `avg_position` | | `v_country_breakdown` | Geographic traffic distribution | `country`, `total_clicks`, `total_impressions`, `avg_ctr_pct`, `avg_position` | | `v_device_breakdown` | Desktop vs. Mobile vs. Tablet comparison | `device`, `total_clicks`, `total_impressions`, `avg_ctr_pct`, `avg_position` | | `v_milestone_impact` | Pre vs. Post milestone search traffic cohort impact | `milestone_title`, `milestone_date`, `cohort`, `days_tracked`, `total_clicks`, `total_impressions`, `avg_ctr_pct` | --- ## 🔍 Common SQL Analytics Recipes Pre-tested SQL query recipes are documented in [`references/queries.md`](references/queries.md). ### 1. High-Opportunity Search Queries (Rank 1-10, Low CTR) ```sql SELECT query, page, ROUND(SUM(impressions), 0) AS imps, ROUND(SUM(clicks), 0) AS clks, ROUND((SUM(clicks)/SUM(impressions))*100, 2) AS ctr_pct, ROUND(AVG(position), 1) AS avg_rank FROM search_performance WHERE position <= 10 GROUP BY query, page HAVING SUM(impressions) >= 500 AND ctr_pct < 3.0 ORDER BY imps DESC LIMIT 15; ``` ### 2. Keyword Cannibalization Detection ```sql SELECT query, COUNT(DISTINCT page) AS competing_pages, GROUP_CONCAT(DISTINCT page) AS pages, ROUND(SUM(clicks), 0) AS total_clicks, ROUND(SUM(impressions), 0) AS total_impressions FROM search_performance WHERE query != '' GROUP BY query HAVING COUNT(DISTINCT page) > 1 ORDER BY total_impressions DESC LIMIT 10; ``` --- ## ⚠️ Critical Architecture: Property-Level Totals vs. Keyword-Level Breakdown When querying and analyzing Search Console data, note the two distinct API behaviors and database tables: 1. **Unfiltered Property-Level Totals (`daily_site_performance`):** - Querying the GSC API with `dimensions: ['date']` (and `aggregationType: 'byProperty'`) returns **100% of property search traffic**, including all rare and long-tail queries. - This data is ingested into `daily_site_performance` and powers `v_daily_summary`. It directly matches the Search Console Web UI Performance graphs, Total Clicks cards, and 28-day Achievement badges (e.g. *700 clicks in 28 days*). 2. **Granular Keyword-Level Breakdown (`search_performance`):** - When querying the GSC API with `dimensions: ['query', 'page', 'country', 'device']`, Google automatically applies **anonymized query filtering** to protect searcher privacy, stripping out rare/unique queries. - On technical and developer blogs, long-tail anonymized queries often represent 50%–70% of total search traffic. Therefore, `search_performance` should be used for keyword rankings and page distributions, while `daily_site_performance` (or `v_daily_summary`) must be used for aggregate traffic totals. 3. **Cross-Engine Reconciliation with Google Analytics 4:** - GA4 records landing sessions under `session_default_channel_group = 'Organic Search'` across all search engines (Google, Bing, DuckDuckGo, etc.) without privacy filtering. - GA4 Organic Search traffic naturally aligns with Search Console property-level totals (`daily_site_performance`), rather than the query-filtered `search_performance` table. --- ## 📚 Progressive Disclosure & References - **Full DDL Schema Reference**: [`references/schema.md`](references/schema.md) — Complete SQL table definitions, column types, constraints, and views. - **SQL Query Cookbook**: [`references/queries.md`](references/queries.md) — Tested SQL recipes for CTR decay curves, keyword cannibalization, and MoM trends. - **OAuth Setup Guide**: [`references/setup_oauth.md`](references/setup_oauth.md) — Step-by-step GCP project, API enablement, and credential setup. --- # Skill: adr-template (standards) > Guide and template for authoring and maintaining Architecture Decision Records (ADRs). Captures structural decisions, background context, trade-offs, and compliance verification in lightweight, immutable markdown records to preserve engineering context. Activate when making significant architectural choices, documenting technical trade-offs, proposing major refactorings, or authoring ADRs. **Web Page**: https://skills.danicat.dev/standards/adr-template/ **Source**: https://skills.danicat.dev/standards/adr-template/SKILL.md **Version**: 0.1.1 **Digest**: sha256:b3c58d5e2a1e4850e9830c1bbbdc59588c11e4d327a6a9f7a1f917e935847c47 **Install**: `npx skills add danicat/skills --skill adr-template -y` ## Instructions # Architecture Decision Records (ADRs) Use this skill to write and maintain Architecture Decision Records (ADRs). ADRs are lightweight, plain-text files that capture architectural choices, their context, and their consequences. --- ## 1. Core Philosophy Architecture consists of decisions that are hard to change. ADRs prevent two primary engineering problems: - Context Loss: Future developers often struggle to understand why code was written a certain way, leading to regressions when they remove constraints they do not see. ADRs record the underlying rationale. - Discussion Decay: ADRs capture the final conclusion and the forces that shaped it, rather than every detail of the debate. --- ## 2. Rules of ADRs > [!IMPORTANT] > - Keep ADRs lightweight. Limit each record to one or two pages. An ADR is a record of a decision, not a comprehensive design specification. > - ADRs are immutable logs. Do not edit an approved and committed ADR. If a decision changes, write a new ADR and update the status of the old one to "Superseded by ADR-NNNN". > - Document consequences and trade-offs. Every architectural choice has downsides. Explicitly list negative consequences, technical debt, and new constraints. --- ## 3. Directory and Naming Conventions Store all ADRs in the project documentation folder: ```text design/adr/ ├── 0001-record-architecture-decisions.md ├── 0002-use-stdio-mcp-transport.md └── 0003-transactional-compiler-gated-editing.md ``` - File format: Markdown (`.md`) - Naming pattern: `NNNN-short-descriptive-title.md` where `NNNN` is a sequential four-digit number starting at `0001`. --- ## 4. Standard ADR Template Use this template when creating an ADR: ```markdown # ADR-[Number]: [Active Verb Title] - Status: [Proposed | Approved | Superseded by ADR-XXXX | Rejected] - Date: [YYYY-MM-DD] - Author(s): [Names] - Deciders: [Names of participants in the decision] ## 1. Context Describe the current situation, background context, and the problem to solve. What technical, organizational, or operational factors are at play? What constraints apply? State facts objectively. ## 2. Decision State the chosen architectural path clearly. Explain why this path was selected over alternatives. List the other options considered and the reasons for rejecting them. ## 3. Consequences Detail the impact of this decision. Explicitly list positive gains, negative trade-offs or constraints, and neutral structural shifts. ## 4. Compliance and Verification How will the team verify that this decision is respected and implemented correctly? Detail the specific automated tests, pipeline checks, or manual hooks that enforce compliance. ``` --- ## 5. Verification Checklist Before finalizing an ADR, verify the following: - [ ] Does the ADR clearly state the forces involved? - [ ] Does it document the alternatives that were discarded? - [ ] Is the tone objective and factual, avoiding unquantifiable words like "perfect", "flawless", or "elegant"? --- # Skill: google-oss (standards) > Compliance and licensing guide for Google Open Source repositories and personal open-source projects published by Googlers. Enforces source file license headers (such as Apache-2.0) using addlicense, verifies license files, inserts required non-official product disclaimers, and audits pre-release compliance. Activate when preparing Google Open Source or Googler personal projects for release, applying copyright headers, or adding required disclaimers. **Web Page**: https://skills.danicat.dev/standards/google-oss/ **Source**: https://skills.danicat.dev/standards/google-oss/SKILL.md **Version**: 0.1.2 **Digest**: sha256:7157d815b24dd57fc106ec621a9bacfd9597d9735defa747c7cb09754bb29c08 **Install**: `npx skills add danicat/skills --skill google-oss -y` ## Instructions # Google Open Source Compliance & License Attributions Audit, apply, and verify Google Open Source policy requirements, source code license headers (`addlicense`), and mandatory repository disclaimers. --- ## ⚡ Quick Reference: Actions & Commands ### 1. Apply License Headers via `addlicense` Install the official Google `addlicense` tool if not already present: ```bash go install github.com/google/addlicense@latest ``` Apply Apache-2.0 copyright headers across all source files: ```bash $(go env GOPATH)/bin/addlicense -c "Google LLC" -l apache . ``` Verify/Check without modifying (CI gate): ```bash $(go env GOPATH)/bin/addlicense -check -c "Google LLC" -l apache . ``` Common license flag options: - `-l apache`: Apache License 2.0 (standard default for Google OSS) - `-l mit`: MIT License - `-l bsd`: BSD 3-Clause License - `-s=only`: Force SPDX short identifier style (`// SPDX-License-Identifier: Apache-2.0`) - `-ignore "vendor/**"`: Ignore specific directory globs --- ### 2. Mandatory README Disclaimers Every repository published by Googlers or under Google open source that is not an official Google product MUST include the appropriate disclaimer in the root `README.md`. #### Standard Non-Official Product Disclaimer: ```markdown --- ## Disclaimer This is not an officially supported Google product. ``` #### Experimental / Educational Project Disclaimer: ```markdown --- ## Disclaimer This is not an officially supported Google product. It is an experimental project created for educational and development purposes. ``` --- ## 📋 Pre-Release Compliance Checklist Before publishing or tagging any public open-source repository, verify: 1. **License Header Coverage**: - Run `addlicense -check` across all code files (`.go`, `.py`, `.ts`, `.js`, `.rs`, `.c`, `.cpp`, `.sh`, `.proto`). - Ensure generated files (e.g. `*.pb.go`) or third-party code in `vendor/` or `third_party/` are properly ignored or attributed. 2. **Root `LICENSE` File**: - Ensure an unmodified copy of the chosen license (e.g. Apache 2.0) exists at the repository root. 3. **Non-Official Product Disclaimer**: - Present at the bottom of root `README.md`. 4. **Zero Internal Contamination**: - No internal links, internal issue trackers, intranet shortcuts, corporate credentials, or non-public project codenames. --- ## 📚 References & Scripts - [License Header Variations](references/license-headers.md): Full syntax for Apache 2.0, MIT, and BSD across languages. - [Disclaimer Variations](references/disclaimers.md): Specific disclaimer templates for samples, tools, and demos. - [Automated Helper Script](scripts/apply-license.sh): Bundled shell script to install `addlicense` and apply headers. --- # Skill: rfc-template (standards) > Collaborative design proposal framework and template for Request for Comments (RFC) documents. Structures technical design proposals, explores alternative solutions, documents spikes and open questions, and tracks proposal lifecycle states before formalizing decisions into ADRs. Activate when proposing major features, exploring technical solutions under uncertainty, drafting design documents, or gathering engineering consensus. **Web Page**: https://skills.danicat.dev/standards/rfc-template/ **Source**: https://skills.danicat.dev/standards/rfc-template/SKILL.md **Version**: 0.1.1 **Digest**: sha256:e124b5b0149a972c2509ffb3306e378a770db7ac3a6604e3006fa24dd1ba7a62 **Install**: `npx skills add danicat/skills --skill rfc-template -y` ## Instructions # Request for Comments (RFC) Framework Use this skill to draft, review, and manage Request for Comments (RFC) documents. RFCs are collaborative design proposals used to explore options, solicit feedback, and build consensus on complex or ambiguous engineering problems. --- ## 1. RFC and ADR Integration RFCs and ADRs form a continuous design workflow: - RFC (Request for Comments): A fluid, collaborative document used for discussion. It outlines multiple options, highlights uncertainties, and gathers feedback. It can be modified or rejected during debate. - ADR (Architecture Decision Record): An immutable record of a final technical decision. - Workflow pipeline: Approved RFCs typically transition into one or more immutable ADRs. Rejections and postponements should also be documented within the RFC directory for historical reference. --- ## 2. Directory and Naming Conventions Store all RFC documents in the project RFC directory: ```text design/rfc/ ├── 0001-use-structured-logging.md ├── 0002-migrate-to-sqlite-cache.md └── 0003-parallelize-type-enrichment.md ``` - File format: Markdown (`.md`) - Naming pattern: `NNNN-short-descriptive-title.md` where `NNNN` is a sequential four-digit number starting at `0001`. --- ## 3. Standard RFC Template Use this template when authoring an RFC: ```markdown # RFC-[Number]: [Descriptive Proposal Title] - Status: [Draft | Ready for Review | In Review | Approved | Rejected] - Date: [YYYY-MM-DD] - Author(s): [Names] - Deciders/Reviewers: [Names of requested reviewers] - ADR Reference: [Link to ADR-XXXX if approved] ## 1. Executive Summary Provide a high-level summary of the proposal, the problem it addresses, and the recommended solution. Keep this to two or three sentences. ## 2. Context and Problem Statement Explain the current situation, the technical constraints, and the specific pain points to solve. Outline user requirements or performance bottlenecks clearly. ## 3. Proposed Solution Detail the technical design. Describe the architecture, API changes, package splits, or tooling requirements. Include diagrams or code blocks to clarify the implementation. ## 4. Discarded Alternatives List other options considered and why they were rejected. Be specific about their limitations. ## 5. Supporting Materials and Prototypes Document spikes, benchmark results, or code prototypes. Reference any temporary exploration code. ## 6. Open Questions List unresolved issues or specific design points where you are seeking feedback. ## 7. References Provide links to documentation, source code, or relevant technical articles. ``` --- ## 4. Lifecycle States An RFC progresses through five distinct states: - Draft: The author is writing the proposal and it is not yet complete. - Ready for Review: The proposal is complete and open for feedback. - In Review: Active debate and refinement are ongoing. - Approved: Technical consensus is reached, guiding future ADR creation. - Rejected: The proposal was found to be unviable, and reasons for rejection are documented. ---