# danicat/skills (Full Instructions Catalog) > Complete collection of all Agent Skills. --- # 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.1 **Digest**: sha256:6ce547811bde99d41ad6882de65cba3f0fc9b75bbd23382aab9ea434debae6cf **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 DOP = 4, the framework scales elastically to any user-requested budget (e.g., 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 (DOP >= 8), subagents must act as focused micro-probes. The Coordinator instructs subagents to return dense, high-signal, structured summaries (<= 150 words or tabular format) rather than verbose essays, enabling clean Map-Reduce synthesis without context dilution. ### Recommended Baseline Sizing: | Initiative Scale | Agent Budget (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) > Cross-session and cross-project agent communication in Antigravity using the native agentapi CLI and conversation_summaries.db. Discovers active sessions across workspaces, resolves target projectId metadata, bypasses cross-project PermissionDenied checks via environment sanitization, and delivers reactive messages with return-address headers. Activate when coordinating between independent agent sessions, handing off tasks across different projects or workspaces, discovering peer conversation IDs, or sending cross-project messages with agentapi. **Web Page**: https://skills.danicat.dev/agents/intercom/ **Source**: https://skills.danicat.dev/agents/intercom/SKILL.md **Version**: 0.3.1 **Digest**: sha256:dc18cf323f82f139951d32036b7efaba0e83ef85f846370885b5f119b9ec3316 **Install**: `npx skills add danicat/skills --skill intercom -y` ## Instructions # Intercom: Cross-Project & Inter-Session Messaging via `agentapi` `intercom` enables direct, zero-daemon communication between independent Antigravity agent sessions across both the same workspace and different project workspaces on the same host using the native `agentapi` CLI and `sqlite3`. --- ## ⚡ Why Cross-Project Messaging Fails by Default Inside any Antigravity command execution, the runtime populates the environment with session-scoped variables: | Environment Variable | Purpose | | :--- | :--- | | `ANTIGRAVITY_CONVERSATION_ID` | UUID of the current agent conversation | | `ANTIGRAVITY_PROJECT_ID` | UUID of the current workspace's project | | `ANTIGRAVITY_TRAJECTORY_ID` | UUID of the active execution trajectory | | `ANTIGRAVITY_SOURCE_METADATA` | JSON payload binding the tool call to the sender's `conversationId` and `stepIndex` | | `ANTIGRAVITY_LS_ADDRESS` | Local language server RPC address (`localhost:`) | | `ANTIGRAVITY_CSRF_TOKEN` | Local language server authentication token | | `ANTIGRAVITY_APP_DATA_DIR` | Path to `~/.gemini/antigravity` containing `conversation_summaries.db` and `brain/` | When you call the native `send_message` tool—or run `agentapi send-message ` directly—to message a conversation in a **different project workspace**, it fails with: ```text rpc error: code = PermissionDenied desc = permission_denied: source project_id "" does not match target project_id "" ``` Overriding `ANTIGRAVITY_PROJECT_ID=""` alone is **not sufficient**. As long as `ANTIGRAVITY_CONVERSATION_ID`, `ANTIGRAVITY_SOURCE_METADATA`, or `ANTIGRAVITY_TRAJECTORY_ID` remain in the environment, the language server resolves `source project_id` from the sender's conversation record and rejects the cross-project call. ### The 3-Step Cross-Project Handshake 1. **Resolve the Target `projectId`**: Query `$ANTIGRAVITY_APP_DATA_DIR/conversation_summaries.db` or run `agentapi get-conversation-metadata ` (which succeeds across all projects without restriction) to obtain the target's `projectId`. 2. **Sanitize Sender Environment Bindings**: Unset `ANTIGRAVITY_CONVERSATION_ID`, `ANTIGRAVITY_SOURCE_METADATA`, and `ANTIGRAVITY_TRAJECTORY_ID`, while setting `ANTIGRAVITY_PROJECT_ID=""`. 3. **Embed a Return-Address Header**: Because unsetting `ANTIGRAVITY_CONVERSATION_ID` removes automatic sender attribution from the RPC metadata, **always include your own `$ANTIGRAVITY_CONVERSATION_ID`, `$ANTIGRAVITY_PROJECT_ID`, and workspace path (`$PWD`)** in `--title` and at the top of the message body so the recipient knows who sent it and can reply back to you. --- ## 1. 🔍 Discover Active Sessions Across Workspaces When the user refers to a target session by **workspace name** or **topic** rather than an explicit UUID (e.g., *"send this to the socials session"*), query `$ANTIGRAVITY_APP_DATA_DIR/conversation_summaries.db`: ```bash # List the 10 most recent active root sessions across all workspaces sqlite3 -header -column "$ANTIGRAVITY_APP_DATA_DIR/conversation_summaries.db" " SELECT conversation_id, project_id, title, workspace_uris, status, last_modified_time FROM conversation_summaries WHERE parent_conversation_id = '' AND killed = 0 ORDER BY last_modified_time DESC LIMIT 10; " # Filter for the most recently active root session in a specific workspace (e.g. 'socials') sqlite3 -json "$ANTIGRAVITY_APP_DATA_DIR/conversation_summaries.db" " SELECT conversation_id, project_id, title, workspace_uris, status, last_modified_time FROM conversation_summaries WHERE parent_conversation_id = '' AND killed = 0 AND LOWER(workspace_uris) LIKE '%socials%' ORDER BY last_modified_time DESC LIMIT 5; " ``` --- ## 2. 🔎 Inspect Target Session Metadata (`get-conversation-metadata`) Given a ``, verify its live `projectId` and `workspaceUris` via `agentapi`: ```bash TARGET_CONV_ID="7566dedc-5206-4975-bb23-7a879a542f93" agentapi get-conversation-metadata "$TARGET_CONV_ID" | jq '{ projectId: .response.conversationMetadata.metadata.projectId, workspaceUris: .response.conversationMetadata.metadata.workspaceUris, rootConversationId: .response.conversationMetadata.metadata.rootConversationId }' ``` --- ## 3. 📨 Send a Cross-Project Message (`send-message`) Resolve `TARGET_PROJECT_ID`, prepend your return-address header, and invoke `agentapi send-message` with the 3 sender identity variables unset: ```bash TARGET_CONV_ID="7566dedc-5206-4975-bb23-7a879a542f93" TARGET_PROJECT_ID=$(agentapi get-conversation-metadata "$TARGET_CONV_ID" | jq -r '.response.conversationMetadata.metadata.projectId') HEADER="[Intercom From: ${ANTIGRAVITY_CONVERSATION_ID} | Project: ${ANTIGRAVITY_PROJECT_ID} | Workspace: ${PWD}]" BODY="All campaign assets have been copied to your workspace. Please reply to ${ANTIGRAVITY_CONVERSATION_ID} once verified." env -u ANTIGRAVITY_CONVERSATION_ID \ -u ANTIGRAVITY_SOURCE_METADATA \ -u ANTIGRAVITY_TRAJECTORY_ID \ ANTIGRAVITY_PROJECT_ID="$TARGET_PROJECT_ID" \ agentapi send-message \ --title="Intercom from ${ANTIGRAVITY_CONVERSATION_ID} ($(basename "$PWD"))" \ "$TARGET_CONV_ID" \ "$(printf '%s\n\n%s' "$HEADER" "$BODY")" ``` --- ## 4. 🚀 Spawn a New Conversation in Another Project (`new-conversation`) To launch a brand-new root conversation inside another project's workspace context: ```bash env -u ANTIGRAVITY_CONVERSATION_ID \ -u ANTIGRAVITY_SOURCE_METADATA \ -u ANTIGRAVITY_TRAJECTORY_ID \ ANTIGRAVITY_PROJECT_ID="$TARGET_PROJECT_ID" \ agentapi new-conversation \ --title="Task from ${ANTIGRAVITY_CONVERSATION_ID} ($(basename "$PWD"))" \ --model=pro \ "$(printf '%s\n\n%s' "$HEADER" "$PROMPT")" ``` --- ## 5. Operational Rules & Anti-Patterns 1. **Zero Polling & Zero Listener Subagents**: - `agentapi send-message` delivers messages directly into the recipient session's native inbox and triggers an automatic **reactive wakeup**. - Never run polling loops, `sleep` timers, or background listener subagents. After sending a message that awaits a reply, stop calling tools to end your turn; Antigravity will automatically resume your session when the peer replies. 2. **Never Loop `agentapi` Over `brain/` Directories**: - Do not iterate over `$ANTIGRAVITY_APP_DATA_DIR/brain/*` spawning `agentapi get-conversation-metadata` subprocesses—archived or pruned trajectories will fail with `trajectory not found` and waste seconds of latency. - Always query `$ANTIGRAVITY_APP_DATA_DIR/conversation_summaries.db` with `sqlite3` first, then call `agentapi` on the single target UUID. 3. **Always Include Your Return Address**: - Because cross-project environment sanitization unsets `ANTIGRAVITY_CONVERSATION_ID`, the receiving agent only knows who messaged it if you include your `$ANTIGRAVITY_CONVERSATION_ID`, `$ANTIGRAVITY_PROJECT_ID`, and `$PWD` inside the message header. 4. **Fail Fast with Rich Diagnostics**: - Never silently ignore `PermissionDenied` or `trajectory not found` errors. Always inspect the JSON output of `agentapi` and surface any `"error"` field immediately. --- # Skill: parallel (agents) > General-purpose task parallelization and agent scaling engine. Orchestrates concurrent subagents for ANY task (research, analysis, writing, coding, planning, evaluation) across arbitrary parallel budgets. Enforces immediate main session unblocking, flat orthogonal task partitioning, and agent racing / tournament comparisons. Activate whenever the user invokes /parallel, requests parallel execution, specifies a DOP/budget, or wants concurrent agent swarms. **Web Page**: https://skills.danicat.dev/agents/parallel/ **Source**: https://skills.danicat.dev/agents/parallel/SKILL.md **Version**: 0.1.0 **Digest**: sha256:c70d85096accff3746abc26f0afc2518530ecc102d4b2ac11869a7b14677063e **Install**: `npx skills add danicat/skills --skill parallel -y` ## Instructions # Parallel: Task Concurrency & Agent Scaling Engine `parallel` is a domain-agnostic task parallelization and agent scaling engine for Antigravity. It partitions complex objectives across concurrent subagents according to an explicit **Degree of Parallelism (DOP)** budget, guaranteeing complete context isolation, rapid execution, and maximum throughput. Unlike domain-specific multi-agent frameworks, `parallel` scales **ANY** task: in-depth research, long-form writing, technical analysis, strategic planning, full-stack coding, multi-perspective reviews, ETL data processing, UI design, or model evaluation. ``` +-------------------------------------------------------------------------+ | PARALLEL TOPOLOGY | | | | ROOT COORDINATOR | | (Unblocked, Reactive, User-Facing) | | / | \ | | v v v | | +------------+ +------------+ +------------+ | | | Worker 1 | | Worker 2 | | Worker N | | | | (Slice A) | | (Slice B) | | (Slice N) | | | +------------+ +------------+ +------------+ | | \ | / | | v v v | | REDUCE & RECONCILE | | (Synthesize, Validate & Deliver to User) | +-------------------------------------------------------------------------+ ``` --- ## ⚡ Core Principles & Operational Rules ### 1. Autonomous Activation Triggers & Syntax Activate this skill immediately whenever the user requests parallel subagent execution or specifies a concurrency budget: - `/parallel ` (e.g., `/parallel 5`, `/parallel 12`) - `/parallel dop: ` (e.g., `/parallel dop: 8`) - `/parallel budget ` (e.g., `/parallel budget 4`) - **Multi-phase budgets** (e.g., `"use /parallel 5 for planning and /parallel 10 for implementation"`, `"phase 1: /parallel 3; phase 2: /parallel 6"`) - **Natural language triggers** (e.g., *"parallelize this research across 6 agents"*, *"run this task in parallel with a budget of 4"*, *"swarm this audit with DOP 8"*) ### 2. Degree of Parallelism (DOP) & Budget Rules - **Definition**: The **DOP** or **subagent budget** defines the maximum number of **active, concurrent subagents** executing simultaneously. - **Budget Utilization**: It is strongly recommended (though not mandatory) to utilize the **full allocated budget** to maximize concurrency and accelerate completion. - **Minimum Subagent Rule**: At minimum, the task must use at least **1 subagent**. Even with `DOP = 1`, work is delegated to a subagent so the coordinator upholds the non-blocking mandate. - **Omission Default**: If the user asks for parallel execution without specifying a number, default to a sensible budget of **5** (or **10** for extensive codebase initiatives). - **Active vs. Completed Capacity**: Completed or terminated workers release their concurrency slot immediately back to the budget pool. ### 3. Hard Constraint: Immediate Main Session Unblocking The ROOT agent activating `/parallel` operates strictly as a **non-blocking Coordinator**: - **Fire-and-Yield**: The Coordinator defines the task slices, invokes 1+ subagents via `invoke_subagent`, and **immediately stops calling tools to end its turn**. - **Permanent Responsiveness**: The Coordinator MUST NEVER enter polling loops, sleep cycles, or synchronous wait states. It remains unblocked >= 99% of the time, ready to receive user steering commands, scope revisions, or status inquiries. - **Non-Execution**: The Coordinator manages org structure, task allocation, and reconciliation. It NEVER performs direct heavy execution, long-running bash scripts, or code generation itself. ### 4. Topology: Flat by Default - The default architecture is **Flat** (`Coordinator -> N Independent Workers`). - Flat topologies eliminate bureaucratic overhead, minimize communication hops, and maximize parallelism for arbitrary tasks. - Hierarchical sub-leads are reserved only for massive budgets (`DOP >= 20`) with multiple deeply nested technical subsystems. ### 5. Orthogonal & Independent Work Units Unless explicitly racing, tasks must be sliced along **orthogonal, disjoint boundaries**: - Each worker owns an exclusive file, topic facet, test module, or data chunk. - **Single Writer Principle**: Only one subagent is granted write authority to any single file or resource. - **Staging Pattern**: When outputs must combine into a single document or module, workers output to isolated staging files (`staging/chunk_*.md`), which the Coordinator reconciles during the Reduce step. ### 6. The Key Exception: Agent Racing & Tournaments The singular exception to orthogonal partitioning is **Agent Racing**: - When exploring high-ambiguity architecture, solving hard algorithmic puzzles, hunting zero-day bugs, or seeking creative diversity, run identical or perturbed variations of the same prompt across `N` parallel subagents. - Evaluate candidates side-by-side using Best-of-N selection, automated test harnesses, or hybrid synthesis (merging the best elements from each runner). ### 7. Modern Subagent Standards & Model Selection - **Model Selection**: ALWAYS set `Model: 'inherit'` in all subagent definitions and `invoke_subagent` calls. This ensures seamless inheritance of model capabilities and reasoning effort settings without configuration drift. - **Customizations & MCP**: Subagents inherit workspace rules, tools, and MCP servers (`inheritCustomizations: true`, `inheritMcp: true`). - **Disposable Workers**: Subagents are task-scoped and disposable. Spawning fresh workers with clean context windows avoids prompt pollution, tool bloat, and cognitive drift. ### 8. Strict Vertical Messaging (No Sibling Crosstalk) - **Allowed**: `Coordinator <-> Worker` parent-child communication. - **Forbidden**: `Worker <-> Worker` sibling communication. Workers execute independently and must not attempt lateral messaging. - **User Escalation**: Workers do not possess `ask_question`. If a worker encounters an ambiguous requirement, it messages the Coordinator; the Coordinator consults the user via `ask_question` and relays the answer. --- ## 🎯 Universal Domain Decomposition Matrix `/parallel` scales across any operational domain: ```mermaid flowchart TD User["User Request with /parallel "] --> Coord["Coordinator: Evaluate Budget & Partition"] Coord --> Decision{"Task Strategy"} Decision -->|"Orthogonal Decomposition\n(Default: Divide & Conquer)"| Slices["Partition into N Disjoint Tasks\n• Research Facets\n• Chapter Outlines\n• Decoupled Packages\n• Data Shards"] Decision -->|"Racing & Tournaments\n(Exception: Same Problem)"| Race["Dispatch N Competing Candidates\n• Algorithmic Variations\n• Creative Angles\n• Adversarial Red/Blue\n• Best-of-N Tournaments"] Slices --> Exec["Dispatch N Workers via invoke_subagent"] Race --> Exec Exec --> Yield["STOP TOOL CALLS (End Turn Immediately)\nMain Session Unblocked for Steering"] Yield --> Event{"Reactive Wakeup"} Event -->|"User Message"| UserSteer["Process Steering / In-Flight Command"] UserSteer --> Yield Event -->|"Workers Complete"| Reduce["Reduce & Reconcile\n• Ingest Outputs\n• Purge Staging / Stubs\n• Validate & Deliver"] ``` | Domain | Partitioning Dimension | Worker Assignment | Deliverable | Reduce Action | | :--- | :--- | :--- | :--- | :--- | | **Research** | Topic facet, search angle, competitor | Deep-dive on 1 specific subtopic | Research memo with cited sources | Synthesize into master briefing | | **Writing** | Chapter, section, viewpoint | Draft 1 self-contained section | Staged draft section | Harmonize voice, flow, and TOC | | **Coding** | Package, module, subsystem | Implement isolated component | Code files and local unit tests | Wire real modules, run integration tests | | **Review / QA** | Security, performance, style, a11y | Audit codebase through 1 perspective | Categorized vulnerability / issue log | Deduplicate into prioritized matrix | | **Data / ETL** | Date range, key partition, file chunk | Transform and analyze 1 data shard | Shard metrics and cleaned data | Aggregate metrics, generate summary | | **Strategy** | Scenario, risk profile, persona | Model 1 scenario or stakeholder | Scenario impact paper | Build consolidated decision matrix | | **Design** | User flow, viewport, design variant | Spec 1 user journey or wireframe | Layout spec and UI states | Unify design tokens and component lib | --- ## 📡 Non-Blocking Coordinator Protocol The Coordinator guarantees user interactivity during intensive background processing: ``` +--------------------------------------------------------------------------+ | COORDINATOR LIFECYCLE PROTOCOL | | | | 1. Parse DOP & Mode (Single or Multi-Phase) | | 2. Define Disjoint Scopes & Output Contracts | | 3. Call invoke_subagent(Subagents=[...]) | | 4. Brief User: "Dispatched N parallel workers. Standing by..." | | 5. HALT TOOL CALLS (Turn ends immediately) | | | | ... Main session remains fully interactive ... | | - User asks status: Coordinator runs manage_subagents (list) | | - User steers: Coordinator sends message or kills workers | | - Workers finish: Messaging system reactively wakes Coordinator | | | | 6. Execute Reduce & Deliver Verified Synthesis to User | +--------------------------------------------------------------------------+ ``` --- ## 🔀 Multi-Phase Parallel Orchestration When users supply multi-phase parallel budgets in a single instruction (e.g., *"use /parallel 4 for planning and /parallel 10 for implementation"*): ``` PHASE 1: Planning (DOP = 4) Coordinator dispatches 4 planning workers -> YIELDS TURN IMMEDIATELY All 4 workers finish -> Reactive wakeup | v PHASE 1 REDUCE & BARRIER Coordinator compiles unified specification (specs/plan.md) (Optional human checkpoint / review) | v PHASE 2: Implementation (DOP = 10) Coordinator dispatches 10 implementation workers referencing specs/plan.md -> YIELDS TURN IMMEDIATELY All 10 workers finish -> Reactive wakeup | v FINAL REDUCE & DELIVERY Coordinator integrates deliverables, executes validation, presents result ``` For complete multi-phase state machine specifications, consult [`references/multi_phase_orchestration.md`](references/multi_phase_orchestration.md). --- ## 🏁 The Racing Exception: Agent Racing & Tournaments While orthogonal partitioning is the standard default, **Racing** intentionally invests parallel budget into competitive redundancy: 1. **Stochastic Racing**: Dispatch `N` identical prompts to explore diverse generative solutions for complex, open-ended problems. 2. **Perturbed Prompting**: Dispatch `N` workers with conflicting architectural constraints (e.g., low-latency vs high-durability vs fast-iteration). 3. **Adversarial Red-Blue Racing**: Pair builder workers against breaker/exploiter workers to surface edge-case vulnerabilities. 4. **Best-of-N Tournaments**: Collect `N` candidate solutions, rank them with automated benchmarks or judge rubrics, and merge or select the winner. For full tournament brackets, evaluation rubrics, and synthesis patterns, consult [`references/racing_and_tournaments.md`](references/racing_and_tournaments.md). --- ## 🔄 The Reduce (Reconciliation) Pipeline Parallel execution produces distributed artifacts. Before concluding, the Coordinator executes the **Reduce** phase: 1. **Ingestion & Completeness Audit**: Verify that all `N` workers reported deliverables without lingering placeholders (`TODO`, `FIXME`, temporary mock stubs). 2. **Reconciliation & Assembly**: - Merge staged markdown sections into the master manuscript. - Wire real code components together and purge stub adapters. - Aggregate disjoint data matrices into unified summaries. 3. **End-to-End Verification**: - Run compilation, linters, or package-level test suites. - Verify citation integrity and reference cross-links. 4. **Delivery Summary**: Present the final synthesized result with transparent execution metrics (workers deployed, tasks completed, trade-offs resolved). --- ## ⚠️ Gotchas & Antipatterns 1. **The Blocking Coordinator Trap**: Lingering in active execution, looping with `sleep`, or polling subagents. The Coordinator MUST yield immediately after `invoke_subagent`. 2. **The Coordinator-as-Worker Fallback Trap**: The Coordinator writing implementation code or performing search sweeps directly. The Coordinator delegates all execution to subagents. 3. **The Sibling Cross-Talk Trap**: Allowing subagents to communicate laterally. Workers must remain decoupled and message only the parent Coordinator. 4. **The Long-Lived Worker Context Bloat Trap**: Reusing subagents across disparate tasks. Spawn disposable, task-scoped workers with clean contexts. 5. **The Write Collision Trap**: Multiple workers writing to the same file concurrently. Enforce exclusive file ownership or use the staging directory pattern. 6. **The Leftover Staging Trap**: Forgetting to reconcile staged files or leaving temporary mock stubs in production paths. Always execute the Reduce phase. 7. **Under-Budgeting Mismatch**: Spawning fewer workers than the user's allocated budget when sufficient independent tasks exist. Always endeavor to utilize the full budget. --- ## 📚 Progressive Disclosure & References - **Task Decomposition Guide**: [`references/task_decomposition.md`](references/task_decomposition.md) -- Partitioning strategies, domain matrices, staging patterns, and single-writer protocols. - **Racing & Tournaments Guide**: [`references/racing_and_tournaments.md`](references/racing_and_tournaments.md) -- Stochastic races, perturbed constraints, adversarial tournaments, and best-of-N selection. - **Multi-Phase Orchestration Guide**: [`references/multi_phase_orchestration.md`](references/multi_phase_orchestration.md) -- Staged pipelines, barrier synchronization, state handoffs, and in-flight steering. - **Coordinator Playbook**: [`references/coordinator_playbook.md`](references/coordinator_playbook.md) -- Complete operational lifecycle, invocation parsing, dispatch standards, and reactive event handling. --- # 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.1 **Digest**: sha256:aca155e93fefe6b093d303d5726db0249d67c1ed5fefbcdc69f6da44579b7fde **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 / <= 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 <= 150 (ideal ~100 tokens). Keep description <= 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 <= 5,000 tokens and <= 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 (<= 150 tokens, <= 1024 chars) and body budget (<= 5,000 tokens, <= 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. Orchestrates high-level Go toolchain and static analysis utilities (gofmt, goimports, go vet, modernize, golangci-lint, deadcode), guards edits 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, or enforcing idiomatic Go standards. tags: "go, golang, testing, refactoring, quality, mutation-testing" ``` * **Why it works**: Highlights the concrete toolchain orchestration and safety mechanisms (**compiler rollback gates** and **SQLite coverage analytics**), 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.4.0 **Digest**: sha256:45d8d4494f23bd0dec36fc4d00f43ca946ced9a540fd94d4b2803b8c4a4da7ba **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 <-> Lead Agent, Lead Agent <-> Specialist; or Swarm Coordinator <-> Specialist in flat/hybrid structures). - **Forbidden:** Direct communication between agents on the SAME layer (Lead Agent <-> Lead Agent, Specialist <-> Specialist) or direct escalation (Specialist <-> Swarm Coordinator bypassing an intermediate Lead Agent) 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. **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. 7. **Swarm Awareness Propagation (Zero Ambient Knowledge):** - Subagents are spawned with blank context and have **zero ambient understanding** of swarm protocols, DOP mechanics, non-execution posture, or boundary isolation. - Merely stating *"you are a swarm coding agent"* or *"you have a budget of X"* is strictly insufficient and forbidden as a standalone instruction. - **Coordinator -> Lead Propagation**: The Coordinator MUST explicitly define the Lead's system role (non-executing architect), equip it with `commandExecutionPolicy: off` (never `run_command`), preserve customizations (`inheritCustomizations: true`), and provide an operational briefing detailing its exact budget arithmetic (1 slot for lead, DOP - 1 concurrent workers, slot recycling, and backlog drip-feeding). - **Lead -> Specialist Propagation**: The Lead MUST explicitly define the Specialist's scope (strict file boundaries, localized test commands only, fail-fast without fallbacks, evidence-based reporting, and immediate termination to free concurrency slots). --- ## 🎯 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. * **Budget Arithmetic & Slot Accounting**: - `Domain Budget (DOP) = 1 (Lead Agent) + N (Concurrent Specialists)`. - The Lead Agent consumes 1 concurrency slot. For example, if a Lead is allocated a budget slice of 8, it occupies 1 slot and can run up to **7 concurrent Specialists** simultaneously. * **Active vs. Past Capacity (Slot Recycling)**: Completed or terminated subagents do **not** consume budget. The budget applies strictly to currently running subagents. When a subagent completes its work and terminates, its concurrency slot is immediately freed. * **Backlog Drip-Feeding**: When domain tasks exceed available specialist slots ($N$), the Lead Agent maintains a domain task backlog and drip-feeds tasks to fresh Specialists as prior workers conclude. * **Default Concurrency**: Assumes a default budget of **10** active concurrent agents if omitted by the user. * **Low Budget Guard (<= 1):** If the user specifies an `agent budget <= 1`, multi-agent orchestration is disabled. Automatically fall back to direct single-agent execution without spawning subagents, notifying the user: *"Agent budget is set to <= 1; running in direct single-agent execution mode. To enable swarm parallelism, specify an agent budget > 1 (default: 10)."* * **Swarm Shapes (Flat, Nested, Hybrid)**: - **Flat**: Swarm Coordinator coordinates Specialists directly (no intermediate Tech Leads). Used when agent budget < 10. - **Nested**: Swarm Coordinator assigns Tech Leads per domain and allocates each a slice of the agent budget. Leads recursively break down epics into specialist tasks. Used when agent budget >= 10. - **Hybrid**: Combines nested domain teams with flat direct specialists reporting to the Coordinator for standalone or cross-cutting tasks. ### 🌲 Swarm Sizing Decision Tree ```mermaid flowchart TD Budget["Agent Budget (DOP)"] --> Check{"Agent Budget"} Check -->|"Under 10"| Flat["Flat Structure\n• Coordinator -> Specialists directly\n• Disjoint tasks to prevent overlap\n• One task per specialist agent"] Check -->|"10 or more"| ShapeCheck{"Team Topology"} ShapeCheck -->|"Uniform Domains"| Nested["Nested Structure\n• Tech Leads per domain\n• Budget slices (Leads count towards budget)\n• Epics to Leads; Leads recurse to specialists"] ShapeCheck -->|"Mixed Domains + Standalone"| Hybrid["Hybrid Structure\n• Combines Nested domain teams with Flat direct Specialists\n• Standalone tasks report directly to Coordinator"] Nested --> Depth{"Max Nesting Depth"} Hybrid --> Depth Depth -->|"Budget 10–19"| D1["Max Depth = 1\nCoordinator -> Domain Leads -> Specialists"] Depth -->|"Budget 20–49"| D2["Max Depth = 2\nCoordinator -> Leads -> Sub-Leads -> Specialists"] Depth -->|"Budget 50+"| D3["Max Depth = 3\nCoordinator -> Leads -> Sub-Leads -> Component Leads -> Specialists"] ``` #### Decision Rules: 1. **Agent Budget < 10 -> Flat Structure**: - Coordinator coordinates Specialists directly (all specialists, no intermediate Tech Leads). - Break down tasks so that agents do not step on each other, and assign one task to each agent. 2. **Agent Budget >= 10 -> Nested Structure**: - Assign Tech Leads per domain and give them a slice of the agent budget (**Tech Leads also count towards the budget**). - Break down the task into "epics" and give them to the Leads. - Leads recursively break down epics into granular tasks for specialists (or subordinate leads). - **Nesting Level (Max Depth below Coordinator)**: - **Budget < 20** (10-19): `max depth == 1` (Coordinator -> Domain Tech Leads -> Specialists). - **Budget between 20 and 49**: `max depth == 2` (Coordinator -> Domain Tech Leads -> Sub-Leads -> Specialists). - **Budget >= 50** (or > 50): `max depth == 3` (Coordinator -> Domain Tech Leads -> Sub-Leads -> Component Leads -> Specialists). > [!NOTE] > The tree does not need to be perfectly balanced; different branches can have different depths based on domain complexity. 3. **Hybrid Structure (Mixed Workloads)**: - Use when an initiative contains both complex multi-agent domains requiring Tech Leads and focused, standalone, or cross-cutting tasks (e.g., dedicated QA/Integration, architecture spike, or isolated single-task component) that report directly to the Swarm Coordinator without an intermediate Tech Lead. - Nested branches follow the depth rules above, while direct specialists consume 1 concurrency slot each. --- ## 📡 Non-Blocking Coordinator & Reactive Concurrency The Swarm Coordinator is the primary user interface and top-level organizational conductor. It must remain **unblocked >= 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 flowchart TD subgraph MAP["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["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 --> REDUCE ``` ### 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] - Ephemeral and task-scoped (disposable worker). Operates with a clean, focused context window dedicated strictly to its assigned task. - 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, then completes. ### 🛠️ Modern Subagent Configuration & Inheritance When defining subagents (`agent.md` or via `define_subagent`), adhere to modern Antigravity configuration standards: * **Customization & Skill Inheritance (`inheritCustomizations: true`)**: Subagents MUST declare `inheritCustomizations: true`. This ensures the subagent seamlessly adopts all parent and workspace customizations (skills like `kungfu` and domain linters, rules, plugins, and custom configurations) without synchronization drift. Setting this to false strips the subagent of project rules and capabilities. * **MCP Integration (`inheritMcp: true`)**: Passes through external MCP tool servers (e.g., database tools, devtools, knowledge servers) so subagents have access to necessary development tools. * **Model Configuration (`model: inherit`)**: Always use `inherit` (in agent definitions and `invoke_subagent`). Subagents automatically adopt the parent session's model configuration and reasoning effort (`/effort`), ensuring complete behavioral consistency across the swarm hierarchy without model-routing overhead. * **Execution Boundary & Tool Assignment (`commandExecutionPolicy`)**: - **Lead Agents**: MUST have `commandExecutionPolicy: off`. When defining tools for a Lead, **NEVER include `run_command`**. Lead Agents are strictly prohibited from compiling, executing scripts, or running terminal commands. - **Specialists**: MUST have `commandExecutionPolicy: sandbox`. Equipped with file and terminal execution tools (`run_command`), but delegation tools (`define_subagent`, `invoke_subagent`, `manage_subagents`) and user prompting (`ask_question`) are strictly disabled. --- ## 📋 Swarm Briefing Protocols & Canonical Prompt Templates Subagents start with blank conversational context. Simply telling an agent *"you are a swarm coding agent"* or *"you have a budget of 8"* provides zero understanding of swarm protocols, DOP mechanics, non-execution posture, or boundary isolation. Coordinators and Leads must feed complete definitions and structured initial briefings. ### 1. Coordinator -> Lead Agent Briefing Protocol When the Swarm Coordinator spawns a Lead Agent via `invoke_subagent` (referencing `assets/agents/lead-agent.md` or defined via `define_subagent`), the Coordinator MUST supply a prompt conforming to this structure: ```markdown You are the Lead [Domain] Engineer in a hierarchical Swarm Coding session. ### Role & Execution Boundary (Strict Non-Execution) You are an architect, planner, and manager for your domain. You are strictly forbidden from writing production code or running terminal commands yourself. All implementation, package installations, and validation runs MUST be delegated to Specialist subagents. ### Agent Budget & Concurrency Mechanics (DOP: [N]) - Your allocated domain budget is [N] concurrent agents. - You occupy 1 concurrency slot, leaving [N - 1] active concurrent Specialist slots. - Concurrency slots are ephemeral and freed immediately when a Specialist finishes and exits. - If your epic has more tasks than [N - 1], maintain a domain task backlog and drip-feed tasks to new Specialists as prior workers conclude. ### Domain Epic & Specifications [Detailed domain objective, referencing workspace specification files or top-level architecture specs in docs/] ### Your Swarm Protocol 1. Specification First: Draft or update domain API/data contracts before assigning tasks. 2. Task Deconstruction: Break the epic into independent, non-overlapping tasks with disjoint file boundaries. 3. Spawn & Steer Specialists: Define/invoke Specialist workers (model: inherit, commandExecutionPolicy: sandbox). Supply each with explicit file boundaries, localized test commands, and fail-fast rules. 4. Domain Reconciliation: Verify that Specialists replace all temporary stubs/mocks with real implementations, review validation logs, and message completion to your parent (Swarm Coordinator). 5. User Escalation: You do not have ask_question. Send any requirement ambiguities to the Swarm Coordinator via send_message. ``` ### 2. Lead Agent -> Specialist Briefing Protocol When a Lead Agent spawns a Specialist via `invoke_subagent` (referencing `assets/agents/specialist-agent.md`), the Lead MUST provide a prompt conforming to this structure: ```markdown You are a [Domain] Specialist worker in a Swarm Coding session reporting to the Lead [Domain] Engineer. ### Assigned Scope & File Boundaries - Task: [Explicit description of the granular task] - Target Files: [Explicit list of allowed files to create/edit] - Forbidden Boundaries: Do NOT touch files outside your assigned list. If you depend on contracts from other modules, use the agreed interfaces in [spec path]. ### Execution & Validation Rules 1. Scoped Validation: Run ONLY localized package/file tests (e.g., `npm test path/to/test` or `go test ./pkg/...`). NEVER run full-repository root commands like `npm test` or `go test ./...` which pollute other concurrent workers. 2. Fail Fast & No Fallbacks: Never introduce fallback mechanisms, mock modes for live data, or silent error suppression. Always fail fast with rich diagnostics. 3. Proof & Completion: Once implementation passes tests and linters, send your terminal validation output to your parent (Lead [Domain] Engineer) via send_message, then terminate to release your concurrency slot. ``` --- ## 💬 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 <-> Lead Agent - Lead Agent <-> Specialist 2. **Forbidden Lateral Communication:** - Communication between agents on the SAME layer (Lead <-> Lead, Specialist <-> 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 Ambient Swarm Assumption Trap:** Assuming spawned subagents inherently understand they are in a swarm or know what "budget" means. Without injecting system definitions and using the canonical briefing templates, subagents will act like solo coders. 2. **The Lead-As-Coder Prompting Trap:** Prompting a Lead Agent with individual coding commands ("Install library X, implement function Y, verify endpoints") instead of an epic and delegation instructions. This directly causes the Lead to act as an executor. 3. **The Lead Executor Toolset Trap:** Equipping a Lead Agent with `run_command` or setting `commandExecutionPolicy` to anything other than `off`. If a Lead Agent has terminal execution tools, it will bypass its team and code itself. 4. **The Customization Stripping Trap:** Setting `inheritCustomizations: false` or `inheritMcp: false` on subagents. This strips away project rules (fail-fast, no fallbacks), linters, and the `kungfu` gateway. 5. **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*. 6. **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. 7. **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 >= 10. 8. **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. 9. **The Long-Running Agent Context-Pollution Trap:** Retaining subagents indefinitely across multiple distinct tasks accumulates noisy tool logs, failed attempts, and token bloat. Specialists should be disposable and task-scoped—spawn fresh workers with clean context windows per task for maximum precision and speed. 10. **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. 11. **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. Prefers impartial dedicated subagent delegation to prevent context contamination and confirmation bias. 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.2 **Digest**: sha256:96a47fad47298364e979a12b162a811f9c559c1a4f5f73925f1dadac65d46567 **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**. --- ## 🎭 Impartial Review: Dedicated Subagent Delegation (Default) To guarantee the integrity and rigor of an Occam's Razor red-team assessment, **uno-reverse reviews must be conducted by a dedicated, isolated subagent rather than within the invoking agent's active conversation context**. ### 1. Rationale: Why In-Context Audits Fail When an agent that designed, brainstormed, or iteratively implemented a solution attempts to evaluate its own work inline, the review suffers from three critical failure modes: 1. **Confirmation Bias & Sunk-Cost Defense**: An agent that spent multiple conversation turns proposing abstractions, schemas, microservices, or config flags naturally rationalizes their existence. A dedicated subagent has zero psychological or conversational investment in prior proposals. 2. **Context Contamination**: Long-running conversation contexts contain discarded ideas, exploratory reasoning, edge-case anxieties, and premature compromises. This cognitive residue biases the evaluation toward maintaining accidental complexity. A fresh subagent receives only the target specification and the audit mandate, evaluating it with a clean slate. 3. **Preserving Impartiality & Objective Distance**: Genuine red-teaming requires contrarian detachment. An isolated subagent is uninhibited by politeness or conversational continuity—it can objectively propose deleting 90% of a specification without defending earlier dialogue. ### 2. Default Delegation Policy & User Override * **DEFAULT Behaviour**: When `uno-reverse` is activated (via slash command `//uno-reverse`, skill loading, or prompt directive), the parent agent **MUST spawn a dedicated `uno-reverse` subagent** using `invoke_subagent` and immediately yield execution. * **Inline Override**: Subagent delegation is bypassed **ONLY** if the user explicitly requests an inline review (e.g., *"review inline"*, *"run uno-reverse in this session"*, or *"do not use subagents"*). In that case, the parent agent executes the 4-step workflow directly in the current context. ### 3. Delegation Pattern & Subagent Invocation When delegating, select the subagent type: - **`research` (Default)**: Ideal for read-only audits of design documents, PRDs, architectural RFCs, and codebases. - **`self`**: Use when the audit also requires writing code, refactoring files, or generating alternative implementations directly on disk. - **`Model: 'inherit'`**: Preserve the parent session's reasoning effort and model capabilities. #### Antigravity `invoke_subagent` Pattern: ```json { "Subagents": [ { "TypeName": "research", "Role": "Uno-Reverse Auditor", "Model": "inherit", "Prompt": "You are an impartial, contrarian Uno-Reverse Auditor tasked with radical simplification and red-teaming.\n\n### Target of Audit:\n[FILE_PATH_OR_TARGET_DESCRIPTION]\n\n### Mandate & Mindset:\n- You have ZERO investment in prior discussions, earlier decisions, or existing abstractions.\n- Challenge every moving part, configuration flag, caching layer, and speculative interface.\n- Treat complexity as a liability: Reliability = 1 / (Moving Parts ^ 2).\n- Apply the 4 Inversion Principles (Subtraction Before Addition, Primitive Collapsing, Zero-Speculation YAGNI, Failure-Surface Inversion).\n- Respect Chesterton's Fence: understand the failure mode before eliminating essential safety.\n\n### Instructions:\n1. Execute the 4-Step Uno-Reverse Audit Workflow (Subtraction Test, Primitive Collapsing, Cache & State Probe, 10% MVP).\n2. Format your complete findings strictly as the 'Simplification Audit Scorecard':\n - Executive Inversion Summary (Proposed Complexity, Verdict, Code Reduction %)\n - The Cut List (Items to eliminate, rationale, what happens without it)\n - Collapsed Primitives (Disparate mechanisms -> Single primitive)\n - Minimalist Reference Design (10% MVP spec / code)\n - Chesterton Boundary Assessment (Essential complexity kept vs. pruned)\n3. Report your findings back using send_message." } ] } ``` #### Lifecycle & Non-Blocking Coordination: 1. **Dispatch & Yield**: The parent agent invokes the subagent and **immediately halts tool calls to end its turn**. It never polls, sleeps, or busy-waits. 2. **Report Reception**: When the subagent completes the audit and sends its report, the parent agent wakes up reactively. 3. **Synthesis & Presentation**: The parent agent delivers the unvarnished scorecard to the user or uses the minimalist reference design to guide subsequent implementation. --- ## 🎯 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: ``` Reliability = 1 / (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. | > [!NOTE] > **Subagent Delegation vs. Swarm Bloat**: While multi-agent swarms for linear tasks are an anti-pattern, **delegating an assessment to a single, isolated subagent for red-teaming** is essential. The subagent boundary provides clean context isolation, eliminating confirmation bias and conversational anchoring without adding orchestrational sprawl. --- ## 🔍 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 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 <= 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 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-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.1 **Digest**: sha256:2a0e5efcddee001b40c06f21b113482c78e0c0f6812b7abd5e730326ad514b32 **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: skill-analytics (analytics) > Mine and analyze Agent Skill usage, Context-Tax ROI, and trigger attribution from conversation transcripts in a local SQLite database. Scans conversation transcripts and installed skill tiers (built-in, plugin, global, workspace, and catalog) to detect zero-use shelfware and tune activation descriptions with skill-optimizer. Activate when analyzing skill usage over time, auditing system-prompt token overhead, measuring autonomous vs. explicit (::skill or //skill) triggers, or querying conversation skill events with SQL. **Web Page**: https://skills.danicat.dev/analytics/skill-analytics/ **Source**: https://skills.danicat.dev/analytics/skill-analytics/SKILL.md **Version**: 0.2.0 **Digest**: sha256:e259cdade75f8bf460dfe9ef2605d94dca5ed0b322e025366ccc038600ae9ccd **Install**: `npx skills add danicat/skills --skill skill-analytics -y` ## Instructions # Skill Analytics: Conversation Usage Mining & Context-Tax ROI Engine The `skill-analytics` skill mines local agent conversation transcripts (with 0% sampling and automatic `transcript.jsonl` + `transcript_full.jsonl` truncation merging) alongside your installed skill inventory across all tiers (`builtin`, `plugin`, `global`, `workspace`, and `catalog`) into a local SQLite warehouse (`skill_analytics.db`). Pair it with `skill-optimizer` to prune zero-use "shelfware" skills and rewrite under-performing frontmatter descriptions. ## Available scripts - `scripts/analyze.py`: Zero-dependency Python 3 CLI for incremental transcript ingestion, full historical rebuilds, pre-packaged ROI/trigger/velocity/gap reports, and ad-hoc SQL queries. - `scripts/test_analyze.py`: Automated unit and regression test suite validating schema DDL, views, parser accuracy, and markdown SQL code blocks. --- ## ⚡ Quick Start & Primary Actions All operations are driven via `scripts/analyze.py` (runnable via `uv run scripts/analyze.py`): ```bash # 1. Incremental Sync (Only parses new or modified conversation transcripts) uv run scripts/analyze.py sync --db skill_analytics.db # 2. Full Historical Rebuild (Drops and re-mines all conversations from scratch) uv run scripts/analyze.py sync --full --db skill_analytics.db # 3. Run Pre-Packaged Analytical Reports uv run scripts/analyze.py report overview --db skill_analytics.db uv run scripts/analyze.py report roi --db skill_analytics.db uv run scripts/analyze.py report triggers --db skill_analytics.db uv run scripts/analyze.py report velocity --db skill_analytics.db uv run scripts/analyze.py report gaps --db skill_analytics.db # 4. Run Ad-Hoc SQL Query uv run scripts/analyze.py query "SELECT skill_name, source_tier, tier1_tokens_est, total_activations, roi_recommendation FROM v_skill_roi LIMIT 15" --db skill_analytics.db ``` If `--db` is omitted, the script defaults to `skill_analytics.db` in the current working directory. --- ## 🗄️ Database Schema & Relational Structure The database maintains 4 relational tables and 5 analytical views. Full column-level DDL and constraints are documented in [`references/schema.md`](references/schema.md). ### Tables 1. **`skills_inventory`**: Every discovered skill across `builtin`, `plugin`, `global`, `workspace`, and `catalog` tiers, including `is_always_in_prompt`, `tier1_tokens_est` (`name + description` routing cost), and `tier2_tokens_est` (`SKILL.md` body cost). 2. **`conversations`**: Metadata across the union of `conversation_summaries.db` and `brain/` transcript directories (`total_steps`, `user_input_steps`, `planner_steps`, `first_step_at`, `last_step_at`). 3. **`ingestion_state`**: File size, `mtime_ns`, and SHA-256 head watermarks per conversation for sub-second incremental updates. 4. **`skill_events`**: Every extracted skill event across all conversation transcripts: - `direct_skill_view`: Direct `view_file` activations on any `*//SKILL.md`. - `skill_resource_view`: Companion `references/`, `examples/`, `assets/`, or `scripts/` reads. - `cli_invocation`: CLI skill invocations (`load`, `learn`, `run`, `find`, `show`, `list`, `status`, `update`, `forget`, `catalog`) and direct script executions (`script_exec`). - `user_notation`: User prompt shortcuts (`modern_::`, `classic_//`, `find_:?`). - Includes `trigger_mode` (`autonomous`, `user_explicit`, `rule_driven`) and `is_self_test` (`0` for production, `1` for test/authoring). --- ## 📊 Analytical SQL Views | View Name | Description | Key Columns | | :--- | :--- | :--- | | `v_skill_roi` | Context-Tax vs. Activation ROI across all skill tiers | `skill_name`, `source_tier`, `is_always_in_prompt`, `tier1_tokens_est`, `total_activations`, `autonomous_activations`, `explicit_activations`, `resource_reads`, `script_runs`, `roi_recommendation` | | `v_trigger_attribution` | Autonomous description matching vs. manual user overrides | `skill_name`, `source_tier`, `total_activations`, `autonomous_activations`, `explicit_activations`, `autonomous_share_pct`, `trigger_health` | | `v_daily_invocations` | Daily time-series across event categories and actions | `day`, `invocation_kind`, `action`, `prod_count`, `test_count`, `distinct_conversations` | | `v_subcommand_summary` | Aggregate counts and date bounds per command/notation | `invocation_kind`, `action`, `total_events`, `prod_events`, `self_test_events`, `conversations` | | `v_search_gaps` | Search queries ranked by whether they led to a skill load | `search_query`, `invocation_kind`, `search_count`, `led_to_load_count`, `last_searched_at` | --- ## 🔍 Pairing with `skill-optimizer`: Core SQL Workflows Tested SQL recipes for skill portfolio optimization are in [`references/queries.md`](references/queries.md). ### 1. Detect Shelfware Skills Consuming System-Prompt Tokens Find skills with `is_always_in_prompt = 1` that add token overhead on every turn but have `0` activations: ```sql SELECT skill_name, source_tier, source_origin, tier1_tokens_est, cumulative_prompt_tax_tokens, roi_recommendation FROM v_skill_roi WHERE is_always_in_prompt = 1 AND total_activations = 0 AND script_runs = 0 ORDER BY tier1_tokens_est DESC; ``` ### 2. Find Skills Whose Descriptions Fail to Trigger Autonomously Identify skills that are only activated when the user manually types `::skill` or `//skill` (`NEEDS_DESCRIPTION_TUNING` or `WEAK_AUTONOMOUS_TRIGGER`), then feed them to `skill-optimizer`: ```sql SELECT skill_name, source_tier, total_activations, autonomous_activations, explicit_activations, autonomous_share_pct, trigger_health FROM v_trigger_attribution WHERE trigger_health IN ('NEEDS_DESCRIPTION_TUNING', 'WEAK_AUTONOMOUS_TRIGGER') ORDER BY explicit_activations DESC; ``` --- ## 📚 Progressive Disclosure & References - **Full DDL Schema Reference**: [`references/schema.md`](references/schema.md) — Complete SQLite table definitions, indexes, and analytical view logic. - **SQL Query Cookbook**: [`references/queries.md`](references/queries.md) — Ready-to-run queries for Context-Tax ROI, Trigger Attribution, Progressive Disclosure depth, Catalog Gap discovery, and Multi-Skill Conversation Workflows. --- # 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.3.0 **Digest**: sha256:7cc6ceae1abe817f729d91b8184680ccec7ba701590999b216f5d2f50299bb79 **Install**: `npx skills add danicat/skills --skill ebitengineer -y` ## Instructions # Ebitengine 2D Game Development Guide (ebitengineer) Comprehensive, genre-agnostic engineering guidelines for building modular, high-performance, cross-platform 2D games (top-down, tactics, shmup, puzzle, isometric, and platformer) in Go using [Ebitengine v2](https://ebitengine.org/). --- ## Trigger Conditions Activate this skill whenever: - Designing or implementing 2D game architecture, scene flow, camera systems, or rendering pipelines in Go. - Working with Ebitengine interfaces (`ebiten.Game`), state machines, input management, audio, Kage shaders, or `ebiten/v2/text/v2` typography. - Optimizing cycle timing, WASM audio synchronization, build-tagged save persistence, Cloud Run hosting, or writing unit tests for Go game components. --- ## Core Architecture & Fail-Fast Engineering Rules ### 1. Modular Architecture (`internal/`) Organize the codebase into modular subsystems under `internal/`. Never build monolithic single-file games. - For the complete directory tree and package responsibilities, see [`references/project_structure.md`](references/project_structure.md). ### 2. Fail-Fast Asset Embedding & Validation (No Silent Fallbacks) - **Zero-Dependency Embedding**: Embed all game assets (sprites, TTF/OTF fonts, audio streams, Kage shaders) directly into the compiled Go binary using `embed.FS` (`internal/assets`). - **No Silent Fallbacks**: Never ignore errors (`_ = err`), never substitute dummy 1×1 fallback textures when an asset fails to decode, and never silently clamp out-of-bounds tile or frame IDs. Always fail fast and return rich `fmt.Errorf` diagnostics during `Boot` initialization. - **Mandatory Binary Format Validation**: Always validate asset files using file identification tools (`file`, `mimetype`, or `http.DetectContentType` in Go) during asset ingestion. Misnamed or corrupt asset files cause decoding failures or black screens on WebAssembly. ### 3. Premultiplied Alpha Invariant (`color.RGBA` vs. `color.NRGBA`) - In Go's `image/color` and Ebitengine, `color.RGBA` is **alpha-premultiplied**: every channel must satisfy $R \le A$, $G \le A$, $B \le A$. - Never construct non-premultiplied literals like `color.RGBA{255, 0, 0, 100}` (where $R > A$). Use valid premultiplied `color.RGBA{100, 0, 0, 100}` or straight-alpha `color.NRGBA{255, 0, 0, 100}`. ### 4. Aspect Ratio & Virtual Pixel Canvas - **16:9 Widescreen Priority**: Unless explicitly specified otherwise, target a **16:9 virtual resolution** (`320x180`, `640x360`, `1280x720`, `1920x1080`). - **Virtual Pixel Canvas**: All entity physics, collision math, camera coordinates, Kage shader pixel units, and UI layouts operate strictly in virtual canvas coordinates. - **Automatic Multi-Resolution Scaling**: `Layout(outsideWidth, outsideHeight int)` returns constant virtual dimensions (`virtualWidth, virtualHeight`). ### 5. Cycle Timing & Frame Synchronization - **Target Frame Rate**: Standard target is **60 TPS** (`ebiten.SetTPS(60)`). - **Delta-Time Integration**: Integrate movement, camera exponential decay, and timers using delta time ($dt = 1.0 / 60.0$ or measured frame delta) for consistent behavior across refresh rates. - **Windowing & Fullscreen Toggle**: Support fullscreen toggling via `F11` or `Alt+Enter`: ```go if inpututil.IsKeyJustPressed(ebiten.KeyF11) || (ebiten.IsKeyPressed(ebiten.KeyAlt) && inpututil.IsKeyJustPressed(ebiten.KeyEnter)) { ebiten.SetFullscreen(!ebiten.IsFullscreen()) } ``` --- ## Engine Reference Modules Consult these deep technical reference guides for complete, zero-allocation, fail-fast Go implementations: | Module | Reference File | Key Topics Covered | | :--- | :--- | :--- | | **Project Structure** | [`references/project_structure.md`](references/project_structure.md) | Package tree and `internal/` subsystem responsibilities. | | **Camera & Game Feel ("Juice")** | [`references/camera_and_juice.md`](references/camera_and_juice.md) | 2D `ebiten.GeoM` camera, frame-rate independent exponential lerp, trauma screen shake, hitstop freeze frames, and spring squash-and-stretch. | | **Kage Shaders & `text/v2`** | [`references/shaders_and_text_v2.md`](references/shaders_and_text_v2.md) | Kage `//kage:unit pixels` shaders (2D lighting, CRT, hit-flash) and `ebiten/v2/text/v2` font loading and aligned layout. | | **WASM Audio & Save Storage** | [`references/wasm_audio_and_persistence.md`](references/wasm_audio_and_persistence.md) | 4-byte aligned PCM `Seek()` math for browser autoplay unlock and build-tagged desktop vs. WASM fail-fast save storage. | | **UI & HUD System** | [`references/ui_and_hud.md`](references/ui_and_hud.md) | Premultiplied alpha invariant (`R <= A`), pre-sliced 9-slice panels, anchoring math, zero-alloc progress bars, and `text/v2` buttons. | | **Physics & Collision** | [`references/physics_and_collision.md`](references/physics_and_collision.md) | Genre-agnostic Circle & AABB overlap, axis-separated sweep resolution, spatial hash grids, and slope math. | | **Tilemaps & Levels** | [`references/tilemaps_and_levels.md`](references/tilemaps_and_levels.md) | Pre-sliced tileset validation, camera frustum culling, isometric projection, and 16-pipe bitmask autotiling. | | **Input Action Mapping** | [`references/input_action_mapping.md`](references/input_action_mapping.md) | Rebindable action maps, radial analog deadzones, and zero-alloc gamepad polling. | | **Entity Management** | [`references/entity_management.md`](references/entity_management.md) | Pre-allocated slice pools, deferred deletion buffers, and Structure-of-Arrays (SoA) Light ECS. | | **Pathfinding & AI** | [`references/pathfinding_and_ai.md`](references/pathfinding_and_ai.md) | Fail-fast A* grid pathfinding, steering behaviors (seek/arrive), and enemy decision FSM. | | **Server & Cloud Run** | [`references/server_architecture.md`](references/server_architecture.md) | WebAssembly build, multi-stage Dockerfile, and Cloud Run leaderboard REST API. | --- ## Game State Machine & Scene Flow ### Finite State Machine (FSM) Lifecycle Model all scenes using a `State` interface with strict lifecycle hooks (`Enter() error`, `Update(dt float64) error`, `Draw(screen *ebiten.Image)`, `Exit() error`). ### Standard Scene Progression ```text Boot (Logo & Asset Preload) -> Intro -> Title Screen -> Game Play -> Game Win / 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, hitstop timers, and camera trauma. - Reset transient input buffers so button presses do not bleed 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` (autonomous AI/CPU plays the game). 2. **Instant 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), Shaders & Typography Rules - **Audio Late-Sync (4-Byte PCM Alignment)**: Browser WebAudio contexts remain locked until the first user gesture. Track elapsed time during silent load and `Seek()` to a **4-byte aligned** stereo PCM byte offset (`(samples * 4) % loopLengthBytes`) on first interaction. See [`references/wasm_audio_and_persistence.md`](references/wasm_audio_and_persistence.md). - **Custom Typography (`ebiten/v2/text/v2` Only)**: Never use `ebitenutil.DebugPrint` for game UI and never use deprecated `ebiten/v2/text` v1. Always load TTF/OTF fonts via `text.NewGoTextFaceSource`, `text.GoTextFace`, and `text.Draw` from `github.com/hajimehoshi/ebiten/v2/text/v2`. See [`references/shaders_and_text_v2.md`](references/shaders_and_text_v2.md). - **Kage Shaders (`//kage:unit pixels`)**: Always include `//kage:unit pixels` in Kage shaders and pre-allocate `ebiten.DrawRectShaderOptions` and uniform maps at load time. See [`references/shaders_and_text_v2.md`](references/shaders_and_text_v2.md). - **Build-Tagged Save Persistence**: Implement separate `//go:build !js` (atomic file write in `os.UserConfigDir()`) and `//go:build js && wasm` (`window.localStorage`) storage backends behind a common fail-fast interface. See [`references/wasm_audio_and_persistence.md`](references/wasm_audio_and_persistence.md). --- ## Unit Testing & Performance Rules 1. **Zero Allocations in `Draw()`**: Never call `ebiten.NewImage()`, `SubImage()`, `ebiten.NewShader()`, or allocate slices/maps inside `Draw()`. Pre-allocate all `ebiten.DrawImageOptions`, `text.DrawOptions`, and `SubImage` frame slices during initialization. 2. **Decouple Logic & Render**: Keep all state mutation strictly inside `Update()`. `Draw()` must be a read-only projection of current game state. 3. **Unit Test Coverage**: Write deterministic unit tests for state transitions, collision/spatial hash math, camera lerp/trauma decay, 4-byte PCM alignment, A* pathfinding, and save serialization. --- # 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.3.0 **Digest**: sha256:dcbdb32f7833ad66d25697364eb224ed0f7fff46cae65edb1e73125f8d20194a **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 Socratic interview protocols, probing frameworks, and templates to guide users from initial 2D game ideas to a production-ready **Game Design Document (`GDD.md`)**. > [!IMPORTANT] > **100% Genre-Agnostic 2D Design Principle**: > Never assume a 2D game uses side-scrolling gravity or platforming physics. This workflow supports **every 2D game genre**, including **Top-Down RPGs**, **Bullet-Heavens / Auto-Shooters**, **Twin-Stick & Vertical/Horizontal Shmups**, **Turn-Based Tactics**, **Roguelike Deckbuilders**, **Grid & Physics Puzzle Games**, **Visual Novels & Narrative Adventures**, **Rhythm & Arcade Games**, and **Side-Scrolling Platformers / Metroidvanias**. Always tailor spatial, simulation, control, and asset questions to the chosen genre. --- ## 1. Game Designer Role & Socratic Interview Protocol (`/grill-me`) The **Game Designer Agent** aligns the user's creative and technical vision before any code or assets are generated: 1. **Interactive Socratic Interview (`/grill-me`)**: When starting a new game project or refining an idea, activate the `/grill-me` interview workflow (asking targeted, one-at-a-time probing questions) to systematically explore each branch of the game design tree. 2. **Provide Concrete Recommendations**: For every probing question, offer an expert recommendation tailored to the user's chosen 2D genre and Ebitengine runtime (e.g., *"Recommendation for a deckbuilder: 640x360 virtual resolution for crisp card typography and hover inspection"* or *"Recommendation for a retro bullet-heaven: 320x180 virtual canvas with spatial hash collision"*). 3. **Explicit Asset Pipeline Selection (Procedural vs. AI vs. Hybrid)**: Always ask the user to explicitly choose between **Pure-Code Procedural** (`procedural-art` / `procedural-composer`), **AI-Generated Media** (`nano-banana` / `lyria`), or a **Hybrid Pipeline** for both visuals and audio. 4. **Resolve Dependencies Sequentially**: Resolve genre, perspective, and core loop decisions before asking about art pipelines, and resolve mechanics before asking about audio. 5. **Produce Authoritative `GDD.md`**: Synthesize all agreed decisions into a structured `GDD.md` saved in the workspace root using [`references/gdd_template.md`](references/gdd_template.md). --- ## 2. Genre-Agnostic Socratic Interview Tree (`/grill-me` Workflow) Follow this sequential branching tree when interviewing the user: ```text Branch 1: Core Concept, Genre & Perspective ├── What is the 1-sentence hook / elevator pitch and primary inspiration? ├── What is the 2D genre? (Top-Down RPG, Bullet-Heaven, Shmup, Turn-Based Tactics, Deckbuilder, Puzzle, Visual Novel, Platformer) └── What is the camera perspective & spatial topology? (Top-down 2D plane, Isometric/Orthogonal Grid, Card Table/UI Canvas, Dialogue Stage, Side-View Arena) Branch 2: Simulation Model, Core Loop & Win/Loss Conditions ├── Is simulation Real-Time Continuous (delta-time), Turn-Based / Phase-Driven, Discrete Grid-Step, or Event/Narrative-Driven? ├── What is the primary player loop? (Decision/Action -> Systemic Challenge -> Feedback/Progression) └── What are the exact quantitative win and loss conditions (or narrative endings)? Branch 3: Controls & Input Mapping ├── What input devices are targeted? (Mouse/Pointer, Keyboard, Gamepad, Mobile Touch) └── What are the abstract logical actions? (e.g., Navigate/Move, Select/Primary, Cancel/Secondary, Context/Deck/Inventory, Pause) Branch 4: Visual Art & Asset Pipeline Strategy (Explicit Choice Required) ├── What is the target visual aesthetic & virtual resolution? (e.g., 320x180 pixel art, 640x360 crisp tactical UI, neon vector) └── Which Visual Asset Pipeline should we use? ├── Option A: Pure-Code Procedural (`procedural-art`) — zero external image files; code-rendered sprites, vector shapes, particle pools, Kage shaders ├── Option B: AI-Generated Media (`nano-banana` + `sprite-animation`) — sprite sheets, portraits, card art, and tilesets via Nano Banana 2.1 └── Option C: Hybrid Visual Pipeline — `nano-banana` for characters/cards/backgrounds + `procedural-art` for UI, particles, and Kage VFX shaders Branch 5: Audio & Soundscape Pipeline Strategy (Explicit Choice Required) ├── Which Audio Pipeline should we use for BGM and SFX? │ ├── Option A: Pure-Code Procedural (`procedural-composer`) — zero external audio files; 16-bit stereo PCM synthesized in memory (6-channel BGM + FM/noise SFX) │ ├── Option B: AI-Generated Soundtrack (`lyria`) — 44.1 kHz stereo music tracks/loops via Lyria 3.5 (`lyria-3.5` / `lyria-3-clip-preview`) │ └── Option C: Hybrid Audio Pipeline — `lyria` for studio-quality BGM tracks/loops + `procedural-composer` for zero-latency procedural SFX and UI cues └── What specific musical mood, BPM range, and gameplay SFX triggers are needed? Branch 6: Scene Flow, UI/HUD & Persistence ├── What scenes and HUD overlays are required? (Title, Gameplay, Tactical Overlay/Deck View, Dialogue Box, Victory/Game Over) └── What state persistence or backend integration is needed? (Local save state, run history, or Cloud Run leaderboard) ``` --- ## 3. Template & Technical Standards For the complete, genre-agnostic Game Design Document template, consult: | Module | Reference File | Key Topics Covered | | :--- | :--- | :--- | | **GDD Template** | [`references/gdd_template.md`](references/gdd_template.md) | Genre-agnostic 7-section markdown template covering elevator pitch, spatial/simulation model, core loop, input mapping, explicit visual & audio asset pipeline choices (`nano-banana`/`lyria` vs. `procedural-art`/`procedural-composer` vs. hybrid), scene flow, and Ebitengine architecture notes. | --- ## 4. Probing Question Templates with Genre-Agnostic Recommendations Use these Socratic question templates during the `/grill-me` session: ### Question 1: Genre, Perspective & Core Loop > *"What is the 1-sentence hook for your game, what 2D genre and camera perspective does it use, and is it real-time or turn-based?"* > **Recommendation**: *"Pick a tight, high-clarity 2D loop suited to your genre—for example, a top-down bullet-heaven with automatic weapon firing and spatial-hash swarm evasion; a turn-based grid tactics game on an 8x8 board with deterministic action points; a roguelike deckbuilder with mana/synergy combos; or a branching visual novel with character portrait expressions."* ### Question 2: Progression, Win & Loss Conditions > *"How does a session progress, what triggers victory, and what causes defeat (or a failed run)?"* > **Recommendation**: *"Define explicit, testable state thresholds—such as surviving a 5-minute escalating swarm and defeating the boss (Bullet-Heaven/Shmup), clearing 3 encounter nodes with HP > 0 (Deckbuilder/RPG), solving all grid constraints within the move par (Puzzle), or reaching a key narrative branch (Visual Novel)."* ### Question 3: Explicit Visual Asset Pipeline Choice (`procedural-art` vs. `nano-banana` vs. Hybrid) > *"For visuals, do you want a Pure-Code Procedural pipeline (`procedural-art`), an AI-Generated asset pipeline (`nano-banana` + `sprite-animation`), or a Hybrid pipeline?"* > **Recommendation**: *"Choose **Pure-Code Procedural (`procedural-art`)** for zero-asset geometric/neon games, puzzle grids, and particle-heavy effects; choose **AI-Generated (`nano-banana` + `sprite-animation`)** for rich character portraits, visual novels, card illustrations, and animated pixel sprite sheets; or choose **Hybrid** (`nano-banana` for hero/enemy sprites and backgrounds + `procedural-art` for UI panels, projectiles, particles, and Kage shaders)."* ### Question 4: Explicit Audio Pipeline Choice (`procedural-composer` vs. `lyria` vs. Hybrid) > *"For audio, do you want Pure-Code Procedural synthesis (`procedural-composer`), AI-Generated studio music (`lyria`), or a Hybrid audio pipeline?"* > **Recommendation**: *"Choose **Hybrid** (`lyria` using `lyria-3.5` / `lyria-3-clip-preview` for atmospheric 44.1 kHz stereo BGM loops + `procedural-composer` for instant, zero-latency gameplay SFX and UI clicks), or choose **Pure-Code Procedural (`procedural-composer`)** if you want a 100% self-contained zero-asset binary with YM2612-style 6-channel chiptune BGM and synthesized SFX."* --- ## 5. GDD Generation Checklist Before handing off the generated `GDD.md` to downstream skills (`ebitengineer`, `procedural-art`, `nano-banana`, `sprite-animation`, `lyria`, `procedural-composer`): - [ ] **Elevator Pitch & Genre Defined**: Clear 1-sentence hook, 2D genre, camera perspective, and simulation model (real-time vs. turn-based/grid/narrative) established without unstated platformer assumptions. - [ ] **Core Loop & Win/Loss Explicit**: Player decisions/actions, systemic rules, and quantitative win/loss triggers mapped out. - [ ] **Controls Mapped**: Logical actions bound to appropriate devices (Mouse/Pointer, Keyboard, Gamepad, Touch). - [ ] **Visual Pipeline Explicitly Selected**: Documented as Pure-Code (`procedural-art`), AI-Generated (`nano-banana` + `sprite-animation`), or Hybrid with per-asset breakdown. - [ ] **Audio Pipeline Explicitly Selected**: Documented as Pure-Code (`procedural-composer`), AI-Generated (`lyria`), or Hybrid with BGM and SFX assignments. - [ ] **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.3.0 **Digest**: sha256:c219f12702f9dd1f88c1158660d63c027e6abb20336807f2fbdd62eab0c545f4 **Install**: `npx skills add danicat/skills --skill procedural-art -y` ## Instructions # Procedural Art: Pure-Code 2D Sprites, SDF Primitives, Material Ramps & VFX Guide This skill provides mathematical, graphical, and software architecture patterns for generating high-quality 2D sprites, tilesets, Signed Distance Field (SDF) 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) > * **SDF, Premultiplied Alpha, 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 (`Boot` state) or renders vector/particle effects dynamically during game frames: * **Zero Disk I/O**: Eliminates asset loading delays, missing file errors, and external bundle dependencies. * **Signed Distance Field (SDF) Rasterization**: Composes organic characters, weapons, and tiles mathematically using `SDFCircle`, `SDFBox`, `SDFCapsule`, and `SDFSmoothMin`. * **Strict Premultiplied Alpha Invariant**: Enforces $R, G, B \le A$ on every `color.RGBA` pixel via `PremultiplyRGBA(r, g, b, a)`. --- ## 2. "Retro-HD" Visual Style, Premultiplied Alpha & 4-Step Material Ramps Target the aesthetic richness of classic 16-bit/32-bit console art (SNES, Sega Saturn, Neo Geo) combined with modern 32-bit truecolor shading. ### 2.1 Premultiplied Alpha Invariant (`PremultiplyRGBA`) In Go's `image/color` and Ebitengine (`image.NewRGBA` / `ebiten.NewImageFromImage`), `color.RGBA` values are **alpha-premultiplied** ($R \le A, G \le A, B \le A$). Writing non-premultiplied values like `color.RGBA{255, 255, 255, alpha}` or `color.RGBA{200, 30, 10, 0}` causes glowing halos and blending corruption. Always construct translucent colors via `PremultiplyRGBA`: ```go func PremultiplyRGBA(r, g, b, a uint8) color.RGBA { alpha := uint16(a) return color.RGBA{ R: uint8((uint16(r)*alpha + 127) / 255), G: uint8((uint16(g)*alpha + 127) / 255), B: uint8((uint16(b)*alpha + 127) / 255), A: a, } } ``` ### 2.2 4-Step Material Ramp Structure (`MaterialRamp`) Every material in a procedural sprite (`steel`, `crimson`, `flesh`, `gold`, `foliage`) uses a structured **4-step shading ramp** (`[4]color.RGBA`) paired with a dark 1-pixel silhouette outline (`#0F0C1C`): 1. **Step 0 — Deep Shadow (`[0]`)**: Primary hue shifted toward cool blue/violet (`illumination < 0.25`). 2. **Step 1 — Base Tone (`[1]`)**: Core saturated material color (`0.25 <= illumination < 0.65`). 3. **Step 2 — Light Highlight (`[2]`)**: Primary hue shifted toward warm yellow/orange (`0.65 <= illumination < 0.90`). 4. **Step 3 — High Specular (`[3]`)**: Crisp specular edge or rim highlight (`illumination >= 0.90`). --- ## 3. 2D Signed Distance Field (SDF) Primitives & Smooth Blending Instead of drawing blocky raw rectangles, sculpt multi-part sprites at startup by evaluating 2D Signed Distance Fields per pixel $(p_x, p_y)$ and blending limbs/armor plates with polynomial smooth minimum (`SDFSmoothMin`): * **Circle (`SDFCircle`)**: $d = \|(p_x - c_x, p_y - c_y)\|_2 - r$ * **Rounded Box (`SDFBox`)**: Box centered at $(c_x, c_y)$ with half-extents $(h_w, h_h)$ and corner radius $r$. * **Line Capsule (`SDFCapsule`)**: Swept sphere of radius $r$ along segment $\overline{AB}$ (ideal for limbs, blades, beams, and pauldrons). * **Smooth Union (`SDFSmoothMin`)**: Blends two distance fields $d_1, d_2$ with smoothing factor $k > 0$: $$h = \frac{\max(k - |d_1 - d_2|, 0)}{k}, \quad \text{smin}(d_1, d_2, k) = \min(d_1, d_2) - \frac{1}{4} h^2 k$$ --- ## 4. Transformation Mathematics & Order of Operations (CRITICAL) In 2D graphics programming (`ebiten.GeoM`), **matrix multiplication is non-commutative**. Applying operations in the wrong order causes sprites to orbit wildly or scale off-screen. ### 4.1 Exact Sequence: `Pivot -> Scale -> Rotate -> World Translation` $$M_{\text{correct}} = T(X + O_x, Y + O_y) \cdot R(\theta) \cdot S(S_x, S_y) \cdot T(-O_x, -O_y)$$ 1. `m.Translate(-OriginX, -OriginY)` — Move pivot to $(0, 0)$. 2. `m.Scale(ScaleX, ScaleY)` — Scale relative to pivot. 3. `m.Rotate(Rotation)` — Rotate around pivot. 4. `m.Translate(OriginX+X, OriginY+Y)` — Translate to world position. --- ## 5. Sub-Frame Interpolation & Non-Linear Easing Use delta time ($dt$) and non-linear easing functions to model physical weight, momentum, and elasticity: * **Linear (`EaseLinear`)**: $f(t) = t$ * **Ease-In Quadratic (`EaseInQuad`)**: $f(t) = t^2$ (accelerating under gravity) * **Ease-Out Quadratic (`EaseOutQuad`)**: $f(t) = t(2 - t)$ (decelerating friction slide) * **Ease-InOut Cubic (`EaseInOutCubic`)**: Smooth S-curve for breathing idle and hover loops * **Elastic Overshoot (`EaseElasticOut`)**: $f(t) = 2^{-10t} \sin\left(\frac{(t - 0.075) \cdot 2\pi}{0.3}\right) + 1$ (springy attacks and UI pop-ups) --- ## 6. Retro-HD Sprite Sheet Architecture & Frame Requirements | Animation State | Required Frames / Dir | Keyframes & Pose Progression | Easing / Timing Guidelines | | :--- | :--- | :--- | :--- | | **Idle / Breathing** | 4–8 frames | Subtle chest rise, shoulder dip, weapon idle shimmer. | Smooth `EaseInOutCubic` (1.2s–1.8s cycle). | | **Walk / Run Cycle** | 8–12 frames | Contact $\rightarrow$ Recoil $\rightarrow$ Passing $\rightarrow$ High Point. | Continuous loop (0.6s–0.9s cycle). | | **Attack / Strike** | 6–10 frames | Wind-up $\rightarrow$ Fast Strike/Impact $\rightarrow$ Follow-through $\rightarrow$ Recovery. | Fast `EaseInQuad` to impact, `EaseOutQuad` recovery. | | **Hurt / Hit Recoil** | 3–5 frames | Sharp backward tilt, hit-flash, recovery. | High speed (0.15s–0.25s total). | | **Death / Collapse** | 6–10 frames | Stagger $\rightarrow$ Knees buckle $\rightarrow$ Ground impact $\rightarrow$ Settle. | Heavy `EaseInQuad` drop, non-looping final frame. | --- ## 7. Zero-Allocation Particle Systems & VFX High-performance visual effects (explosions, thrusters, magic trails, sparks) require both a **pre-allocated `[]Particle` pool** and a **reusable `ebiten.DrawImageOptions` struct field (`ps.drawOp`)** so `Draw()` never allocates on the heap: ```go func (ps *ParticleSystem) Draw(screen *ebiten.Image) { for i := range ps.pool { p := &ps.pool[i] if !p.Active { continue } progress := p.Age / p.Life size := p.StartSize + progress*(p.EndSize-p.StartSize) curColor := LerpColor(p.StartColor, p.EndColor, progress) ps.drawOp.GeoM.Reset() ps.drawOp.GeoM.Translate(-8, -8) ps.drawOp.GeoM.Scale(size, size) ps.drawOp.GeoM.Translate(p.X, p.Y) ps.drawOp.ColorScale.Reset() ps.drawOp.ColorScale.ScaleWithColor(curColor) if p.Additive { ps.drawOp.Blend = ebiten.BlendLighter } else { ps.drawOp.Blend = ebiten.BlendSourceOver } screen.DrawImage(ps.texture, &ps.drawOp) } } ``` --- ## 8. Mandatory Quality Directives for AI Art Generation 1. **Premultiplied Alpha Enforcement**: Every translucent `color.RGBA` pixel written to `image.RGBA` or interpolated in particle systems MUST use `PremultiplyRGBA` ($R, G, B \le A$). 2. **Zero Allocations in `Draw()`**: Pre-render all procedural `*ebiten.Image` textures at boot and reuse `ebiten.DrawImageOptions` (`Reset()`) inside `Draw()`. 3. **SDF + 4-Step Material Ramp Composition**: Combine `SDFCircle`, `SDFBox`, `SDFCapsule`, and `SDFSmoothMin` with `MaterialRamp` (`[4]color.RGBA`) surface normal illumination and 1px dark outlines (`ApplyPixelOutline`). 4. **Correct Matrix Transformation Order**: Always execute `Translate(-pivot) -> Scale -> Rotate -> Translate(+pivot + pos)`. --- ## 📚 Progressive Disclosure & References - **Procedural Art Driver**: [`references/art.go`](references/art.go) — Premultiplied RGBA helpers, 4-step `MaterialRamp` shading, `SDFCircle`/`SDFBox`/`SDFCapsule`/`SDFSmoothMin` primitives, zero-allocation `ParticleSystem`, and character sprite rasterization. - **Verification Test Suite**: [`references/art_test.go`](references/art_test.go) — Unit tests verifying `PremultiplyRGBA`, SDF geometry, 4-step material ramps, matrix transformation order, and particle pool lifecycle. --- # 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.3.0 **Digest**: sha256:a79474237a2f81fb6299b115a03cad0f8bbed94956b97c511298e3aa9d3b174c **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, 4-byte aligned PCM synthesizer, DSP post-processing pipeline (`SliceLoopPCM`, `ApplyLowPassFilter`, `ApplyHighPassFilter`, `ApplyBitcrush`), 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 & Mandatory 4-Byte PCM Frame Alignment (`&^ 3`) 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 Hz (44,100 stereo frames per second; `176,400` bytes/sec). * **Channels**: 2 (Stereo: Left `[bytes 0–1]`, Right `[bytes 2–3]`). * **Bits Per Sample**: 16-bit signed integer range `[-32,768 to +32,767]`. * **Mandatory 4-Byte Alignment (`&^ 3`)**: Every stereo sample frame occupies exactly 4 bytes (2 bytes Left + 2 bytes Right). Ebitengine's `audio.Context`, `audio.NewInfiniteLoop`, `audio.NewInfiniteLoopWithIntro`, and stream `Seek` operations **panic at runtime** if given a buffer length or byte seek offset that is not a multiple of 4. Always mask lengths and offsets with bitwise AND-NOT 3 (`&^ 3`): ```go alignedLen := len(pcm) &^ 3 alignedOffset := seekBytes &^ 3 ``` ### 1.3 Procedural DSP Post-Processing Pipeline Beyond raw oscillator synthesis, [`scripts/sound.go`](scripts/sound.go) provides a pure-Go DSP post-processing pipeline for shaping synthesized or decoded 16-bit stereo PCM buffers: 1. **Loop Slicing (`SliceLoopPCM`)**: - Extracts a sample-accurate, 4-byte aligned sub-region `[startSec, endSec]` from a PCM buffer using `bytes.NewReader`, aligned `Seek(int64(startByte)&^3, io.SeekStart)`, and checked `io.ReadFull(reader, out)`. - Essential for trimming intro/outro silence or isolating seamless loop bars before passing the buffer to `audio.NewInfiniteLoop`. 2. **ADSR Amplitude Envelopes (`getEnvelope`)**: - Shapes note contour across four stages: **Attack** ($0 \to 1.0$ linear ramp over $t_A$), **Decay** ($1.0 \to S$ ramp over $t_D$), **Sustain** (constant amplitude $S$ while held), and **Release** ($S \to 0.0$ ramp over $t_R$). - Prevents DC-offset speaker clicks at note boundaries and distinguishes plucked arpeggios from swelling string pads. 3. **Single-Pole IIR Low-Pass & High-Pass Filtering (`ApplyLowPassFilter`, `ApplyHighPassFilter`)**: - **Low-Pass Filter (LPF)**: Attenuates harsh high-frequency harmonics via $y[n] = y[n-1] + \alpha (x[n] - y[n-1])$ where $\alpha \in (0, 1]$ controls cutoff warmth (useful for underwater muffling, warm synth pads, and explosion rumbles). - **High-Pass Filter (HPF)**: Removes DC offset and sub-bass mud via $y[n] = \alpha (y[n-1] + x[n] - x[n-1])$ where $\alpha \in (0, 1)$ isolates crisp transients (useful for hi-hats, radio comms, and UI clicks). 4. **Bitcrushing & Sample-Rate Decimation (`ApplyBitcrush`)**: - **Bit-Depth Quantization**: Right-shifts and left-shifts 16-bit samples (`(sample >> shift) << shift` where `shift = 16 - bitDepth`) to emulate gritty 4-bit or 8-bit DAC crunch. - **Downsampling (Sample-and-Hold)**: Holds each stereo frame for `downsample` consecutive frames to create classic retro aliasing and lo-fi metallic textures. --- ## 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_beat = 60 / BPM ``` * **Quarter Note (1/4)**: `t_beat` * **Eighth Note (1/8)**: `t_beat / 2` * **Sixteenth Note (1/16)**: `t_beat / 4` * **Measure (4/4 time)**: `240 / BPM` seconds #### Flexible Scene Reference Table | Scene / Event Type | Playback Mode | Typical Duration Baseline | Typical BPM Range | Composition Style & Musical Notes | | :--- | :--- | :--- | :--- | :--- | | **Stage / Gameplay** | **Looped** | 60s - 180s+ | 100 - 160 BPM | Multi-part structure (*Intro -> Theme A -> Theme B -> Climax -> Loop*) to prevent loop fatigue during long play sessions. | | **Boss Battle** | **Looped** | 45s - 120s | 140 - 180+ BPM | Fast-paced, driving syncopation, diminished/phrygian modes, aggressive YM2612-style FM leads. | | **Title / Menu** | **Looped** | 20s - 60s | 80 - 130 BPM | Catchy theme or ambient melody setting the game atmosphere. | | **Game Over** | **One-Off** | 4s - 15s | 60 - 90 BPM | **Non-looping single play**. Sad descending chromatic slide or minor chord resolution. Keeps restart friction low. | | **Stage Clear / Fanfare** | **One-Off** | 5s - 15s | 120 - 160 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-10 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-50 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-90), sparse instrumentation, soft pads, subtle woodwinds, key of C Major. - **Tension / Stealth**: Medium BPM (90-110), staccato strings, muted sub-bass, ticking percussion. - **Combat / Action / Boss**: High BPM (120-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.3.0 **Digest**: sha256:ca2429284488000554f909d74d19a5152a765088841189a348dba740eea7cd0f **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 specifications, deterministic CLI slicing tools, and fail-fast Ebitengine v2 Go controllers required to design, validate, slice, and manage 2D character sprite sheets, animation frame sequences, tag loops, and Aseprite files (`.ase` / `.aseprite` / `.json`). --- ## 1. Animator Agent Role & Core Responsibilities In a game development workflow, the **Animator Agent** owns all 2D sprite animation pipelines: 1. **Fail-Fast Asset Validation & Grid Slicing**: Validates sprite sheet images (from `nano-banana` or artist files) using `file` / `mimetype` and [`scripts/slice_spritesheet.py`](scripts/slice_spritesheet.py) to verify binary integrity and exact frame grid divisibility before loading. 2. **Animation Tag & State Specification**: Defines animation tags (`idle`, `walk`, `run`, `attack`, `hurt`, `death`, `cast`), positive frame durations (`40ms–200ms`), and loop modes (`LoopForward`, `LoopReverse`, `LoopPingPong`, `LoopOnce`). 3. **Zero-Allocation Frame Pre-Slicing**: Pre-slices all `ebiten.Image.SubImage` frame references at load time (`NewGridSpriteSheet`) and reuses a persistent `ebiten.DrawImageOptions` field (`ac.drawOp`) so `Draw()` performs **zero** heap allocations. 4. **Fail-Fast State Transitions**: Rejects corrupt sprite sheet dimensions, non-positive frame durations, out-of-bounds tag ranges, and unknown animation tag names with rich `fmt.Errorf` diagnostics. --- ## 2. Technical Reference Standards & Companion Scripts | Module | Path | Key Topics Covered | | :--- | :--- | :--- | | **Go Animation Controller** | [`references/animation_controller.go`](references/animation_controller.go) | Fail-fast `GridSpriteSheet` (load-time `SubImage` pre-slicing) and zero-allocation `AnimationController` with delta-time (`dt`) accumulation and horizontal flipping. | | **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`), GIMP `.gpl` RGBA palettes, and zero-alloc `goaseprite` wrapper. | | **Deterministic Grid Slicer CLI** | [`scripts/slice_spritesheet.py`](scripts/slice_spritesheet.py) | PEP 723 (`pillow>=10.0.0`) CLI script that validates PNG dimensions against `--frame-width` / `--frame-height`, slices grid cells, and exports an Aseprite-compatible JSON manifest + optional frame PNGs. | --- ## 3. Deterministic Sprite Sheet Validation & Slicing (`scripts/slice_spritesheet.py`) Never assume an image is a valid PNG or has evenly divisible grid dimensions based on its filename. Always validate the binary format and run `scripts/slice_spritesheet.py`: ```bash # 1. Verify actual binary MIME/file type file assets/sprites/player_sheet.png # Expected: PNG image data, 256 x 128, 8-bit/color RGBA # 2. Validate grid divisibility, define animation tags, and export Aseprite JSON manifest uv run scripts/slice_spritesheet.py assets/sprites/player_sheet.png \ --frame-width 32 \ --frame-height 32 \ --duration-ms 100 \ --tag idle:0:5:150:forward \ --tag run:8:15:80:forward \ --tag attack:16:21:60:forward \ --tag death:24:31:100:forward \ --output-json assets/sprites/player_sheet.json \ --export-frames-dir build/frames/player ``` If `player_sheet.png` is not an exact integer multiple of `--frame-width` and `--frame-height`, `slice_spritesheet.py` fails fast with a non-zero exit code and reports the exact pixel remainder to `stderr`. --- ## 4. Animation State Machine Benchmark Table | Animation Tag | Frame Range / Count | Frame Duration | Loop Mode | Gameplay Trigger / Transition | | :--- | :--- | :--- | :--- | :--- | | **`idle`** | 4–8 frames | 120ms–180ms | `LoopForward` | Default state when velocity is zero (`VX=0, VY=0`). | | **`walk` / `run`** | 8–12 frames | 60ms–100ms | `LoopForward` | Active when moving (`VX != 0` or `VY != 0`). | | **`jump` / `fall`** | 2–4 frames | 100ms | `LoopOnce` | Triggered on airborne launch; holds final frame until landing. | | **`attack`** | 6–10 frames | 40ms–80ms | `LoopOnce` | Triggered on attack action. Invokes `OnComplete` callback back to `idle`. | | **`hurt`** | 3–5 frames | 50ms | `LoopOnce` | Triggered on damage hit alongside Kage hit-flash shader. | | **`death`** | 6–10 frames | 100ms | `LoopOnce` | Triggered on zero health. Holds final collapse frame without looping. | --- ## 5. Fail-Fast Integration Patterns in Ebitengine ### 5.1 Pre-Sliced Grid Sprite Sheet & Controller (`references/animation_controller.go`) ```go sheet, err := NewGridSpriteSheet(embeddedSpriteImage, 32, 32) if err != nil { return fmt.Errorf("load player sprite sheet: %w", err) } controller, err := NewAnimationController(sheet) if err != nil { return fmt.Errorf("init player animation controller: %w", err) } if err := controller.AddTag(AnimationTag{ Name: "idle", StartFrame: 0, EndFrame: 5, FrameDuration: 150 * time.Millisecond, Loop: LoopForward, }); err != nil { return err } if err := controller.AddTag(AnimationTag{ Name: "run", StartFrame: 8, EndFrame: 15, FrameDuration: 80 * time.Millisecond, Loop: LoopForward, }); err != nil { return err } if err := controller.Play("run"); err != nil { return err } ``` ### 5.2 Zero-Allocation `Update` and `Draw` Usage ```go // In Update(): if err := p.Controller.Update(dt); err != nil { return err } // In Draw(screen *ebiten.Image): // Uses pre-sliced sheet.Frames[currentFrame] and persistent controller.drawOp (0 allocs/op) if err := p.Controller.Draw(screen, p.X, p.Y, p.FacingLeft); err != nil { panic(err) } ``` --- ## 6. Animator Agent Pre-Flight Checklist Before completing animation code or sprite assets: - [ ] **Validated File Format**: Verified image using `file` CLI tool (ensuring valid RGBA PNG and no misnamed JPEG/WebP headers). - [ ] **Grid Math Verified**: Verified exact divisibility via `scripts/slice_spritesheet.py` and `NewGridSpriteSheet`. - [ ] **All Animation Tags Validated**: Checked that `StartFrame <= EndFrame < TotalFrames` and `FrameDuration > 0`. - [ ] **Pre-Sliced `SubImage` Frames at Load Time**: Never call `SubImage` or allocate `ebiten.DrawImageOptions` inside `Draw()`. - [ ] **Horizontal Flipping Handled**: Configured negative matrix scale (`Scale(-1, 1)` + `Translate(FrameWidth, 0)`) for left-facing orientation without duplicating sprite sheets. --- # 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.3.0 **Digest**: sha256:721be8ed68acee03d7e0e684165f46cb74e4f4b1841cbb72400af93c71973381 **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 2D game development requests to the specialized skills in the Game Dev Starter Kit—and how to compose them as modular, independent building blocks. > [!NOTE] > **100% Genre-Agnostic & Modular Design Principle**: > Every skill in this suite is an **independent, composable building block suitable for any 2D game genre**—including **top-down RPGs, bullet-heavens, twin-stick/vertical shmups, turn-based tactics, roguelike deckbuilders, grid/physics puzzles, visual novels, rhythm games, and side-scrolling platformers**. Never assume side-scrolling physics or a single fixed asset pipeline: activate only the skills required for the user's task, and combine pure-code procedural skills (`procedural-art`, `procedural-composer`) with AI-generated media skills (`nano-banana`, `lyria`) freely in pure or hybrid pipelines. --- ## 1. Modular Skill Ecosystem & Intent Routing Matrix Each skill in the starter kit has a distinct, orthogonal responsibility and can be invoked standalone or composed into a multi-skill workflow: | User Intent / Request Type | Specialized Skill | Modular Role & Key Technical Characteristics | | :--- | :--- | :--- | | **Game Design & Socratic Interview** | **[`game-design`](../game-design/SKILL.md)** | **Game Designer**: Interactive `/grill-me` Socratic interview across all 2D genres, explicit choice between procedural (`procedural-art`/`procedural-composer`), AI (`nano-banana`/`lyria`), or hybrid asset pipelines, and authoritative `GDD.md` authoring. | | **Ebitengine 2D Engine Architecture** | **[`ebitengineer`](../ebitengineer/SKILL.md)** | **Engine Architect**: Genre-agnostic Ebitengine (v2) loop, virtual resolution scaling, FSM/stack scene management (pause/inventory/deck/dialogue overlays), fixed-timestep $\Delta t$, zero-allocation `Draw()` loop, Kage shaders, and WebAssembly audio/browser deployment. | | **Pure-Code DSP Audio Synthesis** | **[`procedural-composer`](../procedural-composer/SKILL.md)** | **DSP Sound Engineer**: Zero-asset 16-bit 44.1 kHz stereo PCM audio synthesis (`sound.go`), mandatory 4-byte frame alignment (`&^ 3`), YM2612 6-channel polyphony, FM synthesis, ADSR envelopes, DSP post-processing (`SliceLoopPCM`, LPF/HPF, bitcrushing), and WAV export (`play.go`). | | **Generative Studio AI Music** | **[`lyria`](../../media/lyria/SKILL.md)** | **AI Music Composer**: High-fidelity 44.1 kHz stereo soundtracks and loops via **Lyria 3.5** (`lyria-3.5` / `lyria-3-pro-preview`) and **Lyria 3 Clip** (`lyria-3-clip` / `lyria-3-clip-preview`), timestamped arrangements, custom lyrics, multimodal image-to-music, and `.mp3`/`.wav` export. | | **Pure-Code Procedural 2D Graphics** | **[`procedural-art`](../procedural-art/SKILL.md)** | **Procedural Technical Artist**: Zero-asset Go texture generation (`art.go`), 2D `GeoM` matrix transform ordering, 32-bit RGBA color ramps, sub-frame animation easing, pre-allocated particle pools, and Kage shaders. | | **Generative AI Images & Sprites** | **[`nano-banana`](../../media/nano-banana/SKILL.md)** | **AI Visual Artist**: Conversational image generation and editing via **Nano Banana 2.1** (`gemini-nano-banana-2.1`), `gemini-3.1-flash-lite-image`, and `gemini-3-pro-image` for sprite sheets, character portraits, card art, tilesets, and multi-image style/character consistency. | | **2D Sprite Slicing & Animation** | **[`sprite-animation`](../sprite-animation/SKILL.md)** | **2D Animator**: Sprite sheet grid slicing (`SubImage` zero-alloc views), animation state machines (`idle`, `walk`, `attack`, `cast`, `hit`, `death`), frame timing, Aseprite (`.ase`/`.aseprite`) integration, and Ebitengine animation controllers. | | **Go Code Quality & Mutation Testing** | **[`godoctor`](../../coding/godoctor/SKILL.md)** | **Go Quality Gate**: High-level toolchain orchestration (`gofmt`, `goimports`, `go vet`, `golangci-lint`), compiler rollback gates (`smart_build`, `smart_edit`), TestQuery SQLite analytics, and Selene mutation testing. | | **Multi-Agent Swarm Coordination** | **[`swarm-coding`](../../agents/swarm-coding/SKILL.md)** | **Swarm Coordinator**: Hierarchical divide-and-conquer multi-agent orchestration across disjoint packages (e.g., concurrent engine core, procedural/AI assets, UI/HUD, and QA). | --- ## 2. How the 9 Building Blocks Compose Together ```mermaid flowchart TD GDD["1. game-design (/grill-me -> GDD.md)"] --> Engine["2. ebitengineer (Scene FSM, Virtual Canvas, Loop)"] GDD --> VisChoice{"Visual Pipeline Choice"} GDD --> AudChoice{"Audio Pipeline Choice"} VisChoice -->|Pure-Code| ProcArt["procedural-art (Vectors, Particles, Shaders)"] VisChoice -->|AI-Generated| Nano["nano-banana (gemini-nano-banana-2.1)"] VisChoice -->|Hybrid| ProcArt VisChoice -->|Hybrid| Nano Nano --> SpriteAnim["sprite-animation (Grid Slicing & State Machines)"] AudChoice -->|Pure-Code| ProcComp["procedural-composer (4-Byte Aligned PCM, DSP)"] AudChoice -->|AI-Generated| Lyria["lyria (lyria-3.5 / lyria-3-clip-preview)"] AudChoice -->|Hybrid| ProcComp AudChoice -->|Hybrid| Lyria Engine --> QA["godoctor (Compiler & Lint Gate, TestQuery, Selene Mutation Testing)"] ProcArt --> QA SpriteAnim --> QA ProcComp --> QA Lyria --> QA Swarm["swarm-coding (Optional Parallel Agent Execution)"] -.-> Engine ``` --- ## 3. Decision Rules: Pure-Code Procedural vs. Generative AI vs. Hybrid Assets A core responsibility of this orchestrator is honoring the `GDD.md` pipeline selection (or guiding the user when asked ad-hoc) between **pure-code procedural generation**, **2026 Gemini/Lyria AI models**, or a **hybrid pipeline**: ### 3.1 Audio & Music Routing Rules (`procedural-composer` vs. `lyria`) * **Choose [`procedural-composer`](../procedural-composer/SKILL.md)** when: - Synthesizing **Game Sound Effects (SFX)**: UI clicks, card draws, sword slashes, laser blasts, explosions, or status chimes. - Composing 6-channel YM2612-style chiptune BGM in pure Go with zero external audio files. - Applying runtime DSP post-processing (`SliceLoopPCM`, ADSR envelopes, low-pass/high-pass filtering, bitcrushing) or enforcing 4-byte stereo PCM alignment (`&^ 3`) for Ebitengine `audio.Context`. * **Choose [`lyria`](../../media/lyria/SKILL.md)** when: - Generating studio-quality **44.1 kHz stereo Background Music (BGM)** via **Lyria 3.5** (`lyria-3.5` / `lyria-3-pro-preview`) for full multi-section arrangements or **Lyria 3 Clip** (`lyria-3-clip` / `lyria-3-clip-preview`) for 30-second loops. - Composing thematic soundtracks directly from concept art or screenshots (multimodal image-to-music). * **Choose a Hybrid Audio Pipeline** when: - Combining `lyria` (`lyria-3.5` / `lyria-3-clip-preview`) for rich `.mp3`/`.wav` BGM beds with `procedural-composer` for instant, zero-latency procedural gameplay SFX and DSP loop slicing. --- ### 3.2 Graphics & Visual Routing Rules (`procedural-art` vs. `nano-banana` + `sprite-animation`) * **Choose [`procedural-art`](../procedural-art/SKILL.md)** when: - Generating pure-code textures (`art.go`), crisp geometric entities, tactical grids, particle pools, or Kage post-processing shaders with zero external `.png` files. - Implementing 2D `GeoM` matrix hierarchy transforms or sub-frame interpolation curves. * **Choose [`nano-banana`](../../media/nano-banana/SKILL.md) + [`sprite-animation`](../sprite-animation/SKILL.md)** when: - Generating character sprite sheets, visual novel portraits, deckbuilder card illustrations, or seamless tilesets using **Nano Banana 2.1** (`gemini-nano-banana-2.1`), `gemini-3.1-flash-lite-image` (high-speed prototyping), or `gemini-3-pro-image` (complex multi-subject composition). - Slicing generated sprite sheets into zero-allocation `SubImage` frames and driving state machines (`idle`, `walk`, `attack`, `cast`, `death`) via `sprite-animation`. * **Choose a Hybrid Visual Pipeline** when: - Using `nano-banana` (`gemini-nano-banana-2.1`) + `sprite-animation` for hero/enemy sprites, portraits, or card art while using `procedural-art` for UI panels, particle bursts, projectiles, and Kage screen shaders. --- ## 4. End-to-End Game Development Lifecycle When guiding the user through building a complete 2D game from scratch (or executing any phase independently): 1. **Concept & GDD (`/grill-me`)**: Activate [`game-design`](../game-design/SKILL.md) to run a genre-agnostic Socratic interview, lock in the mechanics, controls, and visual/audio pipeline choice (Procedural, AI, or Hybrid), and write `GDD.md`. 2. **Engine Architecture**: Activate [`ebitengineer`](../ebitengineer/SKILL.md) to scaffold `internal/` packages, virtual resolution scaling, scene state machine (or overlay stack for RPGs/deckbuilders/tactics), fixed-timestep $\Delta t$, and spatial collision/grid systems. 3. **Visual Pipeline Execution**: - **Procedural**: Activate [`procedural-art`](../procedural-art/SKILL.md) for in-memory sprites, vector geometry, particle pools, and Kage shaders. - **AI / Hybrid**: Activate [`nano-banana`](../../media/nano-banana/SKILL.md) (`gemini-nano-banana-2.1`, `gemini-3.1-flash-lite-image`, `gemini-3-pro-image`) to generate sprite sheets/art and [`sprite-animation`](../sprite-animation/SKILL.md) to slice frames and wire animation controllers. 4. **Audio Pipeline Execution**: - **Procedural**: Activate [`procedural-composer`](../procedural-composer/SKILL.md) for 4-byte aligned (`&^ 3`) 16-bit stereo SFX, DSP filters, and 6-channel BGM. - **AI / Hybrid**: Activate [`lyria`](../../media/lyria/SKILL.md) (`lyria-3.5` / `lyria-3-pro-preview`, `lyria-3-clip-preview`) for 44.1 kHz stereo soundtracks and combine with [`procedural-composer`](../procedural-composer/SKILL.md) for loop slicing and SFX. 5. **Parallel Execution (Optional)**: For multi-system builds with orthogonal workstreams, activate [`swarm-coding`](../../agents/swarm-coding/SKILL.md) to coordinate parallel specialist subagents across disjoint file sets. 6. **Quality Gate & Verification**: Activate [`godoctor`](../../coding/godoctor/SKILL.md) to run compiler and linter quality gates, execute unit tests with TestQuery analytics, and eliminate test blind spots via Selene mutation testing. 7. **WebAssembly & Cloud Run Deployment**: Activate [`ebitengineer`](../ebitengineer/SKILL.md) to compile to WASM with browser audio unlock synchronization and package for deployment. --- # Skill: lyria (media) > Generative music and audio synthesis from text prompts or reference images using Google Lyria models. Generates 44.1 kHz stereo music clips, full songs with custom lyrics, and instrumental soundtracks using lyria-3.5 and lyria-3-clip-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.3.1 **Digest**: sha256:88e12dda8e48ef410b0a9ee835abef06da9bb61e0b4b5ea957fedcf533b7566c **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** foundation models (`lyria-3.5` / `lyria-3-pro-preview` and `lyria-3-clip` / `lyria-3-clip-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, model aliases, fail-fast credential checks, 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 / Aliases | Primary Use Case | Duration | Audio Format | Reference Guide | | :--- | :--- | :--- | :--- | :--- | :--- | :--- | | **Lyria 3.5** | `lyria-3.5` (`lyria-3-pro-preview`) | `lyria-3.5`, `3.5`, `pro`, `lyria-pro`, `lyria-3-pro-preview` | Flagship: full songs, expressive vocals, multi-section arrangements, film/game scoring | Controllable (up to ~3m / 184s) | MP3, WAV | [lyria-3-5.md](references/lyria-3-5.md), [lyria-3-pro.md](references/lyria-3-pro.md) | | **Lyria 3 Clip** | `lyria-3-clip-preview` | `lyria-3-clip`, `clip`, `lyria-clip`, `lyria-3-clip-preview` | Short clips, seamless 30s loops, previews, rapid style testing | Exactly 30s | MP3, WAV | [lyria-3-clip.md](references/lyria-3-clip.md) | ### Model Selection & Fail-Fast Policy - **Full Song Production**: Use **Lyria 3.5** (`lyria-3.5` / `lyria-3-pro-preview`, default) for complete tracks with timestamped transitions (`[0:00 - 0:15] Intro...`), multi-verse vocal delivery, or cinematic thematic development. - **Rapid Prototyping & Loops**: Start with **Lyria 3 Clip** (`lyria-3-clip` / `lyria-3-clip-preview`) to iterate quickly on genre combinations, tempos, and 30-second loops. - **Zero Silent Fallbacks**: `scripts/lyria.py` never silently falls back between models, API endpoints, or authentication providers. Missing `GEMINI_API_KEY` (when Vertex AI is not explicitly requested via `--project` or `GOOGLE_GENAI_USE_VERTEXAI=true`), invalid model names, >10 reference images, or empty audio responses fail immediately with descriptive `stderr` diagnostics and a non-zero exit code. --- ## Deep Technical References Consult dedicated reference cards in `references/` for detailed audio parameters, timing controls, and API schemas: - **[references/lyria-3-5.md](references/lyria-3-5.md)**: Flagship specifications for full-length songs, rich vocal synthesis, and arrangements (`lyria-3.5`). - **[references/lyria-3-clip.md](references/lyria-3-clip.md)**: Specifications for 30-second clips, loops, and rapid prototyping (`lyria-3-clip-preview`). - **[references/lyria-3-pro.md](references/lyria-3-pro.md)**: Specifications for full-length preview endpoint (`lyria-3-pro-preview`), timestamp controls, and 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 full song with Lyria 3.5 (default model) uv run scripts/lyria.py \ -p "An energetic pop-rock song with driving drums and upbeat vocals" \ -f "song.mp3" \ -m "lyria-3.5" \ --lyrics-file "lyrics.txt" # 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 "lyria-3-clip" # 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 "lyria-3.5" ``` #### 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`: `lyria-3.5` / `3.5` (default), `lyria-3-clip` / `clip` / `lyria-3-clip-preview`, or `pro` / `lyria-3-pro-preview`. - `-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.5", 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.5", 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 (512px, 1K, 2K, 4K), performs style transfers and mask-based 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.3.0 **Digest**: sha256:eeae4125aa60530e58c9a27d2b60053a33fddceac8f07eb07bbc4ddb3fd702bc **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-nano-banana-2.1`, `gemini-3.1-flash-lite-image`, `gemini-3.1-flash-image`, `gemini-3-pro-image`). --- ## Available scripts - `scripts/banana.py`: Production CLI tool for text-to-image generation, multimodal editing, and consistency anchoring with strict 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, sprites, tilesets, 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 (including the bundled Dani reference anchors). - Create 4K high-resolution visual assets or seamless extreme aspect-ratio banners (`1:4`, `4:1`, `1:8`, `8:1`). --- ## Model Selection & Capability Matrix | Capability / Feature | Nano Banana 2.1 (`nano-banana-2.1`) | Nano Banana 2 Lite (`nano-banana-2-lite`) | Nano Banana 2 (`nano-banana-2`) | Nano Banana Pro (`nano-banana-pro`) | | :--- | :--- | :--- | :--- | :--- | | **Model ID** | `gemini-nano-banana-2.1` | `gemini-3.1-flash-lite-image` | `gemini-3.1-flash-image` | `gemini-3-pro-image` | | **Architecture** | Gemini 3.6 Flash (Oct 2026) | Gemini 3.1 Flash Lite | Gemini 3.1 Flash | Gemini 3 Pro | | **Primary Focus** | **Primary recommended workhorse**; speed, 4K, seamless panoramas, mask editing | Ultra-low latency (<2s), high volume | Generalist multimodal generation + 4K | Studio precision & multi-style asset production | | **Resolutions** | `512px` (0.5K), `1K`, `2K`, `4K` | `1K` (1024px) only | `512px` (0.5K), `1K`, `2K`, `4K` | `1K`, `2K`, `4K` | | **Aspect Ratios** | All 14 discrete ratios (improved seam/tiling elimination on `1:4`, `4:1`, `1:8`, `8:1`) | 14 discrete ratios | 14 discrete ratios (incl. `1:4`, `4:1`, `1:8`, `8:1`) | 10 standard ratios | | **Search Grounding** | **Web Search + Image Search** | ❌ Not Supported | **Web Search + Image Search** | **Web Search** | | **Thinking Mode** | Supported (`minimal`, `medium`, `high`) | Supported (`minimal`, `high`) | Supported (`minimal`, `high`) | Enabled by Default | | **Video Context** | YouTube URLs & MP4 files | ❌ Not Supported | YouTube URLs & MP4 files | ❌ Not Supported | | **Reference Anchors** | Up to 14 (up to 10 objects + 4 characters) + mask editing | Up to 14 (Local/Single edit focus) | Up to 10 objects + 4 characters | Up to 6 objects + 5 characters + 3 styles | | **Function Calling**| ❌ Not Supported | Supported | ❌ Not Supported | ❌ Not Supported | | **Reference Guide** | [nano-banana-2-1.md](references/nano-banana-2-1.md) | [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) | --- ## Deep Technical References Consult dedicated reference cards in `references/` for full specs, exact token counts, and pixel dimensions: - **[references/nano-banana-2-1.md](references/nano-banana-2-1.md)**: Consult for the primary workhorse (`gemini-nano-banana-2.1`), `medium` thinking level, seamless `1:4`/`4:1`/`1:8`/`8:1` panoramas, mask-based conversational editing, and Python/JS/Go SDK patterns. - **[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 (`1K` resolution). - **[references/nano-banana-2.md](references/nano-banana-2.md)**: Consult for `gemini-3.1-flash-image` 4K generation, Google Image Search Grounding, and video-to-image workflows. - **[references/nano-banana-pro.md](references/nano-banana-pro.md)**: Consult for studio asset production, multi-reference consistency across 14 anchors (6 objects + 5 characters + 3 artistic styles), and storyboards. - **[references/README.md](references/README.md)**: Index and guidelines for using the bundled Dani character consistency reference anchors. --- ## Bundled Dani Character Consistency Reference Anchors The `references/` directory includes 4 ready-to-use PNG reference anchors for **Dani** that can be passed via `-i` / `--input-image` to maintain character identity or transfer visual style across scenes: - `references/chibi-dani.png`: Full-body 2D chibi illustration (primary character identity & proportion anchor). - `references/celebrating-dani.png`: Expressive celebratory pose (facial expression & color palette anchor). - `references/speaker-dani.png`: Conference speaker pose at podium (wardrobe & upper-body angle anchor). - `references/chibi_dani_manga.png`: Monochrome manga ink illustration (line-art / manga style transfer anchor). ```bash # Multi-reference character consistency across 3 Dani anchors with Nano Banana 2.1 uv run scripts/banana.py \ -p "banana this character: render Chibi Dani as a 16-bit pixel-art space captain on a starship bridge, keeping her exact glasses, purple hair, and proportions" \ -i "references/chibi-dani.png" \ -i "references/celebrating-dani.png" \ -i "references/speaker-dani.png" \ -f "dani_space_captain.png" \ -m "nano-banana-2.1" \ -r "2K" \ -a "16:9" \ --thinking-level "medium" # Character + manga style transfer using chibi-dani.png and chibi_dani_manga.png uv run scripts/banana.py \ -p "Render the character from the first image coding furiously at a multi-monitor setup in the exact black-and-white manga ink style of the second image" \ -i "references/chibi-dani.png" \ -i "references/chibi_dani_manga.png" \ -f "dani_manga_coder.png" \ -m "nano-banana-2.1" \ -r "2K" \ -a "3:4" ``` --- ## Core Execution Workflows ### 1. CLI Execution via `scripts/banana.py` Run `scripts/banana.py` with `uv run` to generate or edit images: ```bash # Primary creative workhorse generation with Nano Banana 2.1 (Default) and medium thinking uv run scripts/banana.py \ -p "A seamless 2D side-scrolling pixel-art parallax background of a synthwave city skyline" \ -f "synthwave_parallax.png" \ -m "nano-banana-2.1" \ -r "2K" \ -a "4:1" \ --thinking-level "medium" \ --image-search # High-velocity 1K generation with Nano Banana 2 Lite 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 # 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/chibi-dani.png" \ -i "references/celebrating-dani.png" \ -f "astronaut_dani.png" \ -m "nano-banana-2.1" \ -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.1` (default, alias `nano-banana-2-1`), `nano-banana-2`, `nano-banana-2-lite` (alias `nano-banana-lite`), `nano-banana-pro`. - `-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`, `medium` (Nano Banana 2.1 only), or `high`. - `--search`: Enable Google Web Search Grounding (`nano-banana-2.1`, `nano-banana-2`, `nano-banana-pro`). - `--image-search`: Enable Google Image Search Grounding (`nano-banana-2.1` and `nano-banana-2`). - `--api`: `interactions` (default, Interactions API) or `models` (`generate_content`). - `--dry-run`: Validate model capabilities and CLI arguments without calling the API. --- ### 2. Dual SDK Integration Patterns #### Interactions API (`client.interactions.create`) — Recommended Best for multi-turn editing, search grounding, controllable thinking, and stateful iteration: ```python import base64 from google import genai client = genai.Client() # Text-to-Image Generation with Nano Banana 2.1, 4K Resolution, Medium Thinking & Search Grounding interaction = client.interactions.create( model="gemini-nano-banana-2.1", input="An infographic chart showing the timeline of space exploration milestones", tools=[{"type": "google_search", "search_types": ["web_search", "image_search"]}], generation_config={"thinking_level": "medium"}, 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/chibi-dani.png") response = client.models.generate_content( model="gemini-nano-banana-2.1", contents=[img, "Place this character in a cozy pixel-art game developer studio with warm desk lighting."], ) for part in response.candidates[0].content.parts: if part.inline_data: with open("dani_studio.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`, `16-bit SNES pixel art`). 2. **Context & Intent**: State the functional purpose (`2D game sprite sheet with solid #FF00FF chroma key background`, `seamless 4:1 parallax background`, `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: adr-template (coding) > 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/coding/adr-template/ **Source**: https://skills.danicat.dev/coding/adr-template/SKILL.md **Version**: 0.1.1 **Digest**: sha256:bb2bbd1b92d8fd1db4ed242e92170b26d55b9e2e9a9d9dd59f56cc951e29a15a **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: 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. Orchestrates high-level Go toolchain and static analysis utilities (gofmt, goimports, go vet, modernize, golangci-lint, deadcode), guards edits 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, 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.1 **Digest**: sha256:9e9e84c1dd3bee8a8955041405cbd6fec6e392ddf92f137182b458dab58146b8 **Install**: `npx skills add danicat/skills --skill godoctor -y` ## Instructions # Go Quality & Tooling Guide (GoDoctor) GoDoctor is a high-level Go developer workflow orchestrator that coordinates standard Go toolchain binaries and static analysis utilities—providing guarded code edits, automated build and lint pipelines, mutation testing, and SQLite test analytics 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 | | :--- | :--- | :--- | :--- | | **Guarded Code Edits** | `godoctor call edit` | `smart_edit` | Whitespace-insensitive fuzzy matching + `goimports` formatting + atomic file write + compiler rollback gate (`go vet`). | | **Build & Quality Pipeline** | `godoctor call build` | `smart_build` | Orchestrates `go mod tidy`, `modernize -fix`, `gofmt`, `go build`, `go test` with coverage, `golangci-lint`, and `deadcode`. | | **Test & Benchmark Runner** | `godoctor call test` | `smart_test` | Multi-tier runner (`fast`, `basic`, `benchmark`, `complete`) orchestrating `go test`, `go tool cover`, `testquery`, and `selene`. | | **Package & Symbol Docs** | `godoctor call docs` | `read_docs` | Inspects package docs, exported symbols, types, and runnable examples via `go list` and `go/doc` with return-type bundling. | | **Mutation Testing** | `godoctor call selene` | `selene` | Invokes the `selene` CLI binary with parallel workers and `testquery.db` targeted test integration. See [references/selene.md](references/selene.md). | | **SQL Test Analytics** | `godoctor call tq` | `test_query` | Invokes the `testquery` (`tq`) CLI binary to execute 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 `go test -v` directly; skips coverage profiling and `testquery.db` synchronization. Ideal for rapid iterative development. - **`level: "basic"` (default)**: Standard testing tier. Runs unit tests with statement coverage profiling (`go tool cover -func`) and auto-indexes execution metrics into `.godoctor/testquery.db` via `testquery`. - **`level: "benchmark"`**: Runs Go benchmark suites (`go test -bench= -benchmem -run=NONE`) and formats throughput and memory allocations as a Markdown table. - **`level: "complete"`**: Comprehensive quality gate. Runs `basic` unit tests, coverage profiling, and `testquery.db` indexing, followed by multi-worker `selene` mutation testing across 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` matches target blocks using whitespace-insensitive Levenshtein similarity, formats via `goimports`, and writes to a temporary file before atomic rename. Edits are verified via `go vet ./...` across the workspace and automatically rolled back (with identifier spelling suggestions) if errors are introduced. - **Concurrency & Resource Management**: Heavy operations like `level: "complete"` (Selene 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` (Guarded Fuzzy Edits with `goimports` & Compiler 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` (Package & Symbol Documentation via `go/doc`) ```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: google-oss (coding) > 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/coding/google-oss/ **Source**: https://skills.danicat.dev/coding/google-oss/SKILL.md **Version**: 0.1.2 **Digest**: sha256:256bfb23888c9b56341cdd90c239f58699e7f8faae2e7177f0c33992f0eb17f2 **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: 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: rfc-template (coding) > 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/coding/rfc-template/ **Source**: https://skills.danicat.dev/coding/rfc-template/SKILL.md **Version**: 0.1.1 **Digest**: sha256:98e67540351d5fbdb634303f171d29f81e4c915c282e84429080a2bfbd9b3f7c **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. --- # 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.2.0 **Digest**: sha256:c81acf43aad9f936ce525c7fedcca3ca5b3e762a50778c05799518c204cee196 **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, critical pitfalls, and safety rules directly in the body. Load specialized references on demand: - **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 ``` #### Media Hosting Requirement (No File Upload Attachments) > [!WARNING] > **Buffer Does Not Support Direct File Uploads / Attachments**: Buffer's API and CLI do not accept raw binary file uploads or local file paths (such as `path/to/image.png`). > **To add media (images or videos) to a post, the files MUST be hosted somewhere publicly accessible via HTTP/HTTPS** (e.g. S3 bucket, Cloud Storage, GitHub raw content, CDN, or image hosting service) so Buffer can ingest them via their public URLs. Pass hosted media URLs via the `assets` array in a JSON payload: ```json { "channelId": "channel_123", "schedulingType": "automatic", "mode": "addToQueue", "text": "Announcing our new open-source release! 🚀", "assets": [ { "image": { "url": "https://cdn.example.com/images/architecture-diagram.png", "metadata": { "altText": "Architecture diagram illustrating worker pool" } } } ] } ``` For videos, provide the public video URL: ```json { "channelId": "channel_123", "schedulingType": "automatic", "mode": "addToQueue", "text": "Watch the terminal recording in action:", "assets": [ { "video": { "url": "https://cdn.example.com/videos/demo.mp4" } } ] } ``` #### Passing Payloads via JSON or File For complex multi-line text, media attachments, or structured objects: ```bash # Inline JSON payload with hosted media buffer posts create --json '{ "channelId": "channel_123", "schedulingType": "automatic", "mode": "addToQueue", "text": "Line 1\n\nLine 2 with links", "assets": [ { "image": { "url": "https://cdn.example.com/diagram.png", "metadata": { "altText": "Architecture diagram" } } } ] }' --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`. | --- ## 6. Critical Pitfalls & Payload Rules Review these high-risk failure modes before composing commands and JSON payloads: ### 1. Media Hosting & File Attachments - **Buffer Does Not Support Local Attachments**: You cannot upload local file paths. All media (`assets[].image.url` or `assets[].video.url`) **must be hosted publicly via HTTP/HTTPS** (e.g. S3, GCS, CDN, or raw GitHub link). - **Empty `text` without assets is rejected**: Most channels require text or at least one image/video asset. ### 2. Scheduling Modes & Notification Traps - **`mode: addToQueue` is queued, not immediate**: Use `mode: shareNow` to publish immediately. `mode: shareNext` jumps to the front of the queue. `mode: customScheduled` requires `dueAt`. - **`schedulingType: notification` does not auto-publish**: It only sends a push notification to the user's mobile app. Always use `schedulingType: automatic` for hands-off publishing. - **`addToQueue` on a channel with no schedule**: Silently lands in an empty queue slot without scheduling. Check the schedule with `buffer channels get --id ` first. - **All times must be ISO-8601 with offset**: `dueAt` requires a timezone offset (e.g. `2026-05-06T17:00:00-05:00`). Obtain the offset from `buffer config get timezone` or `buffer account --fields timezone`. Never assume UTC. ### 3. Identifier Integrity - **Never guess channel IDs**: Always fetch with `buffer channels list --output json`. Invalid IDs will be accepted initially and fail on execution with vague upstream errors. - **IDs are not portable across organizations**: A `channelId` from Organization A cannot be used while authenticated against Organization B. ### 4. Input & Formatting Constraints - **`--json` overrides flags entirely**: When both `--json` and individual flags are supplied, individual flags are ignored. Use either flags or `--json`, never mix. - **Nested objects need `--json`**: Per-service `metadata.*` and `assets.*` cannot be set via flat CLI flags. Always use `--json` or `--input `. - **Strip control characters**: ASCII control characters (`U+0000`–`U+001F` except whitespace) cause payload rejections. ### 5. Per-Service Minimum Requirements & Threading - **Twitter / X, Threads, Bluesky, Mastodon**: Require `text` only. - **LinkedIn**: `text` or `assets`; documents require `metadata.linkedin.linkAttachment`. - **Instagram**: Image or video asset required; must specify `metadata.instagram.type` and `metadata.instagram.shouldShareToFeed`. - **Twitter / X Threads**: When chaining posts via `metadata.twitter.thread`, the top-level `text` **MUST** match the first thread item's `text`: ```json { "channelId": "ch_123", "text": "First tweet in thread", "metadata": { "twitter": { "thread": [ { "text": "First tweet in thread" }, { "text": "Second tweet in thread" } ] } } } ``` --- # 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.2 **Digest**: sha256:81245d26e1ca6913a9706574aff53a99c22d1d01645792a10d618bea4ecc31e3 **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.4.2 **Digest**: sha256:6a48a4d05ce4a06c88e84af85ab6a3cf8232e5827306ffe16a88322ad28c5ce4 **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. ### 3. Voice Preservation & User Narrative Copyediting To ensure genuine author authenticity: - **Preserve User Quotes 1:1 in Canonical**: Any live comments, raw reflections, and spoken quotes from the author must be recorded verbatim (1:1) in a dedicated `## References / Sources` section inside `CANONICAL.md`. - **Infuse the Author's Voice into Derivative Copy**: These 1:1 remarks are the primary source for the author's authentic cadence, idioms, and engineering perspective. - **Copyedit for Final Polish**: While preserving the narrative spirit, tone, and specific turns of phrase as originally typed, apply professional copyediting during the final draft to ensure clean syntax, grammar, and publication-grade polish. --- ## Frontmatter & Metadata Standards for Copy Files All campaign artifacts—the canonical foundation narrative (`CANONICAL.md`) and every individual platform copy file (`linkedin.md`, `twitter.md`, `bluesky.md`, `threads.md`, `instagram.md`, `reddit.md`)—**MUST use YAML frontmatter for metadata followed by Markdown content**. ### Standard Frontmatter Schema & Canonical Layout ```markdown --- title: "Title or Working Headline" platform: canonical | linkedin | twitter | bluesky | threads | instagram | reddit status: draft | review | ready | scheduled | published target_audience: "Target developer persona or subreddit" character_count: 1420 media: - type: image | video path: "assets/diagram.png" alt: "Architecture diagram showing event pipeline" description: "Dark-mode sequence diagram illustrating worker queues" --- # Post Content / Narrative Begins Here (Markdown) ## Core Narrative & Technical Breakdown ... ## References / Sources ### Live User Comments & Voice Log (Verbatim 1:1) - "Actual unedited quote from the user during chat/interview..." - "Another raw observation about the bug or performance tradeoff..." ### Technical & Git References - Repo: `owner/repo` (commit ``) - PR: `#123` ``` Frontmatter rules: - **`status`**: Current lifecycle state (`draft`, `review`, `ready`, `scheduled`, `published`). - **`media`**: Required array detailing media attachments (type, path/url, alt text, description). - **`character_count`**: Character, grapheme, or word count to verify platform constraints. --- ## Campaign Lifecycle States Every social campaign follows a strict 5-state lifecycle tracked explicitly in the YAML frontmatter of `CANONICAL.md` and all derivative files: | State | Definition & Trigger | Required Artifacts | | :--- | :--- | :--- | | `draft` | Initial research, deep git inspection, `/grill-me` extraction, and authoring `CANONICAL.md`. **Zero derivative posts allowed in this state.** | `CANONICAL.md` | | `review` | Canonical copy or individual derivative draft presented to author for review. Awaiting explicit user approval. | `CANONICAL.md` or platform copy files | | `ready` | Explicit human approval granted, copy deslopified, character budget verified, and media attached. | Approved `CANONICAL.md` and platform files | | `scheduled` | Dispatched to a queue or scheduled for a specific timestamp (via Buffer CLI or native scheduler). | Platform files with scheduled date/time | | `published` | Dispatched live (`shareNow`) or confirmed live on external channels. | Live post URLs recorded in frontmatter & body | --- ## 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` & Live User Log**: - If the source is an open-ended topic or raw idea, conduct an interactive interview or recommend `/grill-me` to extract the author's real friction points, unexpected discoveries, and authentic engineering voice. - **Capture Live Comments 1:1**: Every raw remark, feedback note, or chat input from the user must be logged verbatim into the `## References / Sources` section of `CANONICAL.md`. 3. **Draft the Canonical Foundation Narrative (`CANONICAL.md`)**: Author a comprehensive, unconstrained master document using YAML frontmatter followed by Markdown content: - 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. - **Mandatory `## References / Sources` section**: Houses all verbatim 1:1 user comments and technical source links. > [!IMPORTANT] > **Continuous Master Synchronization**: Whenever new evidence is collected (whether through proactive deep git inspection or after user feedback/pushback), immediately update `CANONICAL.md`—including appending any new user comments—before adjusting derivative platform posts. ### Stage 2: Canonical Approval Gate (Mandatory Human-in-the-Loop) > [!CAUTION] > **STRICT STOPPING GATE**: No individual post or platform copy (`linkedin.md`, `twitter.md`, `bluesky.md`, etc.) may be generated until the user has explicitly reviewed and approved `CANONICAL.md`. 1. Present `CANONICAL.md` to the user for explicit review. 2. Incorporate revisions until the user gives clear, unambiguous approval (e.g., *"approved"*, *"canonical looks great"*, *"proceed with platform posts"*). 3. Update `CANONICAL.md` frontmatter status to `status: ready`. 4. Only after this approval is received, proceed to Stage 3 and Stage 4. ### Stage 3: Target Channel Selection & Playbook Routing 1. Identify target platform(s) for the campaign. 2. Load matching platform references (`references/_playbook.md`). ### Stage 4: Channel-Specific Distillation & Format Assembly Cut and reformat the approved Foundation Narrative into the appropriate archetype for each channel. Each file MUST use YAML frontmatter followed by Markdown content: - **LinkedIn** (`linkedin.md`): Architectural deep-dive (1,300–2,000 chars) with direct in-body link(s) to the primary article, documentation, or repository. - **Twitter / X** (`twitter.md`): Native long-form post (800–2,500 chars) with direct links or micro-thread. - **Bluesky** (`bluesky.md`): Multi-post thread where every post is strictly <= 300 graphemes. - **Instagram** (`instagram.md`): 4:5 multi-slide carousel outline + micro-blog caption with DM automation hook. - **Reddit** (`reddit.md`): Value-first Markdown self-post (300–800 words, 4-space code indents for Old Reddit). - **Threads** (`threads.md`): Casual, builder-centric post (<500 chars) with strictly 1 `#topic` tag. > [!NOTE] > **Infusing User Voice with Copyediting**: Draw heavily on the 1:1 user comments captured in the Canonical's `## References / Sources` section to infuse the author's personality, perspective, and phrasing into each channel post. Preserve the author's authentic narrative while applying professional copyediting to ensure a polished appearance. > [!IMPORTANT] > **Mandatory Media Requirement**: Every single social post MUST include at least one media item (picture or video)—such as an architectural diagram, Ray.so/Carbon dark-mode code card, terminal recording, benchmark plot, carousel slide, or demo clip. Naked, text-only posts are strictly prohibited across all platforms. Specify media details in the file's YAML frontmatter `media:` array. ### Stage 5: Anti-Pattern & Deslopification Audit Review all drafts against [references/anti_patterns.md](references/anti_patterns.md) and execute anti-slop checks (leveraging the `deslopify` skill): - [ ] No banned AI words (*"delve", "game-changer", "revolutionary", "testament"*). - [ ] No mathematical unicode bolding (`𝗕𝗼𝗹𝗱` fonts). - [ ] Links positioned directly in the post body across technical platforms (LinkedIn, X, Bluesky, Threads, Reddit); never hide primary links in the first comment. - [ ] 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. - [ ] **At least one media item (image or video) is attached and documented in frontmatter.** ### Stage 6: Individual Copy Human-in-the-Loop Approval Gate & Dispatch > [!CAUTION] > **STRICT HUMAN-IN-THE-LOOP APPROVAL FOR EVERY COPY**: Every individual platform post draft MUST be presented to the user and receive explicit human-in-the-loop approval before submitting, dispatching, or scheduling. Never publish or schedule unapproved drafts. When human approval is granted and dispatching/automating 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. **Direct In-Body Link & Native Media Pairing**: - Include primary outbound URLs (blog post, documentation, or GitHub repo) directly in the post body on LinkedIn, X, Bluesky, Threads, and Reddit, paired with an attached native image/video asset (`assets` array) so the post renders as a full-bleed visual card rather than a bare link preview. - Because the primary URL lives inside the post body, posts can be safely scheduled (`customScheduled` or `addToQueue`) without needing manual first-comment follow-ups. ### Stage 7: Post-Dispatch Lifecycle Synchronization & Status Marking As soon as posts are published or confirmed live: 1. **Mark Campaign as `published`**: - Update frontmatter `status: published` in `CANONICAL.md` and channel copy files. - Record publication timestamp. 2. **Record Live URLs**: - Append live post URLs (LinkedIn, Twitter/X, Bluesky, Reddit, etc.) directly into `CANONICAL.md` and the respective copy file. 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. ---