gh-code-search
Search GitHub for real-world code examples and implementation patterns. Use when user wants to find code examples on GitHub, search GitHub repositories, discover how others implement features, learn library usage patterns, or research architectural approaches. Fetches top results with smart ranking (stars, recency, language), extracts factual data (imports, syntax patterns, metrics), and returns clean markdown for analysis and pattern identification.
What this skill does
# GitHub Code Search
Fetch real-world code examples from GitHub through intelligent multi-search orchestration.
## Prerequisites
**Required:**
- gh CLI installed and authenticated (`gh auth login --web`)
- Node.js + pnpm
**Validation:**
```bash
gh auth status # Should show authenticated
```
## Usage
```bash
cd plugins/knowledge-work/skills/gh-code-search
pnpm install # First time only
pnpm search "your query here"
```
## When to Use
**Invoke this skill when user requests:**
- Real-world examples ("how do people implement X?")
- Library usage patterns ("show me examples of workflow.dev usage")
- Implementation approaches ("claude code skills doing github search")
- Architectural patterns ("repository pattern in TypeScript")
- Best practices for specific frameworks/libraries
**Examples requiring nuanced multi-search:**
- "Find React hooks" → Need queries for `useState/useEffect` (imports), `function use` (definitions), `const use =` (arrow functions)
- "Express error handling middleware" → Queries for `(req, res, next) =>` (signatures), `app.use` (registration), `function(err,` (error handlers)
- "How do people use XState?" → Queries for `useMachine`, `createMachine`, `interpret` (actual function names, not "state machine")
- "GitHub Actions for TypeScript projects" → Queries for `.yml` workflow files + `actions/setup-node` + `tsc` or `pnpm build` (actual commands)
## How It Works
**Division of responsibilities:**
### Script Responsibilities (Tool Implementation)
1. Authenticates with GitHub (gh CLI token)
2. Executes single search query (Octokit API, pagination, text-match)
3. Ranks by quality (stars, recency, code structure)
4. Fetches top 10 files in parallel
5. Extracts factual data (imports, syntax patterns, metrics)
6. Returns clean markdown with code + metadata + **GitHub URLs for all files**
**The script is a single-query tool.** Claude orchestrates multiple invocations.
### Claude's Orchestration Responsibilities
**Claude executes a multi-phase workflow:**
1. **Query Strategy Generation:** Craft 3-5 targeted search queries considering:
- Language context (TypeScript vs JavaScript)
- File type nuances (tsx vs ts for React, config files vs implementations)
- Specificity variants (broad → narrow)
- Related terminology expansion
2. **Sequential Search Execution:** Run tool multiple times, adapting queries based on intermediate results
3. **Result Aggregation:** Combine all code files, deduplicate by repo+path, preserve GitHub URLs
4. **Pattern Analysis:** Extract common imports, architectural styles, implementation patterns
5. **Comprehensive Summary:** Synthesize findings with trade-offs, recommendations, key code highlights, and **GitHub URLs for ALL meaningful files**
---
## Claude's Orchestration Workflow
### Step 1: Analyze Request & Generate Queries (BLOCKING)
**Analyze user request to determine:**
- Primary language/framework (TypeScript, Python, Go, etc.)
- Specific patterns sought (hooks, middleware, configs, actions)
- File type variations needed (tsx vs ts, yaml vs json)
**Generate 3-5 targeted queries considering nuances:**
**Example 1: "Find React hooks"**
- Query 1: `useState useEffect language:typescript extension:tsx` (matches import statements, hook usage in components)
- Query 2: `function use language:typescript extension:ts` (matches hook definitions like `function useFetch()`)
- Query 3: `const use = language:typescript` (matches arrow function hooks like `const useAuth = () =>`)
**Example 2: "Express error handling"**
- Query 1: `(req, res, next) => language:javascript` (matches middleware function signatures)
- Query 2: `app.use express` (matches Express middleware registration)
- Query 3: `function(err, req, res, next) language:javascript` (matches error handler signatures with 4 params)
**Example 3: "XState state machines in React"**
- Query 1: `useMachine language:typescript extension:tsx` (matches React hook usage like `const [state, send] = useMachine(machine)`)
- Query 2: `createMachine language:typescript` (matches machine definitions and imports)
- Query 3: `interpret xstate language:typescript` (matches service creation like `const service = interpret(machine)`)
**Rationale for each query:**
- Match actual code patterns (function names, import statements, signatures)
- NOT human-friendly search terms or documentation phrases
- Different file extensions capture different use cases (tsx for components, ts for utilities)
- Specific function/variable names find concrete implementations
- Signature patterns match common code structures (arrow functions, function declarations)
- Language/extension filters prevent noise from unrelated languages
**CHECKPOINT:** Verify 3-5 queries generated before proceeding
---
### Step 2: Execute Searches Sequentially
**For each query (in order):**
```bash
cd plugins/knowledge-work/skills/gh-code-search
pnpm search "query text here"
```
**After each search:**
1. **Note result count** - Too many? Too few?
2. **Check quality indicators** - Stars, recency, code structure scores
3. **Identify patterns** - Are results converging on specific approaches?
4. **Adapt next query if needed:**
- Too many results → Narrow scope (add more filters)
- Too few results → Broaden (remove restrictive filters)
- Found strong pattern → Search for similar variations
**Track which queries succeed** - Note for summary which strategies were effective
**Early stopping:** If first 2-3 queries yield 30+ high-quality results, remaining queries optional
---
### Step 3: Aggregate Results
**Combine all code files from all searches:**
1. **Collect files** from each search output with their GitHub URLs
2. **Deduplicate** by `repository.full_name + file_path`
- Keep highest-scored version if duplicates exist
- Note which queries found the same file (indicates strong relevance)
3. **Maintain diversity** - Ensure multiple repositories represented (avoid 10 files from one repo)
4. **Track provenance** - Remember which query found each file (useful for analysis)
5. **Preserve GitHub URLs** - Maintain full GitHub URLs for every file to include in summary
**Result:** Unified list of 15-30 unique, high-quality code files with GitHub URLs
---
### Step 4: Analyze Patterns
**Extract factual patterns across all code files:**
**Import Analysis:**
- List most common imports (group by library)
- Identify standard library vs third-party dependencies
- Note version-specific patterns (e.g., React 18 hooks)
**Architectural Patterns:**
- Functional vs class-based implementations
- Custom hooks vs inline logic
- Middleware chains vs single-handler
- Configuration patterns (env vars, config files, inline)
**Code Structure:**
- Function signatures (parameters, return types)
- Error handling approaches (try/catch, error middleware, Result types)
- Testing patterns (unit vs integration, mocking strategies)
- Documentation styles (JSDoc, inline comments, README)
**Language Distribution:**
- TypeScript vs JavaScript split
- Strict mode usage
- Type definition patterns
**DO NOT editorialize** - Extract facts, not opinions. Analysis comes in Step 5.
---
### Step 5: Generate Comprehensive Summary
**Output format (exact structure):**
```markdown
# GitHub Code Search: [User Query Topic]
## Search Strategy Executed
Ran [N] targeted queries:
1. `query text` - [brief rationale] → [X results]
2. `query text` - [brief rationale] → [Y results]
3. ...
**Total unique files analyzed:** [N]
---
## Pattern Analysis
### Common Imports
- `library-name` - Used in [N/total] files
- `another-lib` - Used in [M/total] files
### Architectural Styles
- **Functional Programming** - [N] files use pure functions, immutable patterns
- **Object-Oriented** - [M] files use classes, inheritance
- **Hybrid** - [K] files mix both approaches
### Implementation Patterns
- **Pattern 1 Name**: [Description with prevalence]
- **Pattern 2 Name**: [Description with prevalence]
---
## Approaches FoRelated in Writing & Docs
jax-development
IncludedUse this skill when the user is writing, debugging, profiling, refactoring, reviewing, benchmarking, parallelising, exporting, or explaining JAX code, or when they mention JAX, jax.numpy, jit, grad, value_and_grad, vmap, scan, lax, random keys, pytrees, jax.Array, sharding, Mesh, PartitionSpec, NamedSharding, pmap, shard_map, Pallas, XLA, StableHLO, checkify, profiler, or the JAX repo. It helps turn NumPy or PyTorch-style code into pure functional JAX, fix tracer/control-flow/shape/PRNG bugs, remove recompiles and host-device syncs, choose transforms and sharding strategies, inspect jaxpr/lowering/IR, and benchmark compiled code correctly.
nature-article-writer
IncludedDrafts, rewrites, diagnostically critiques, and style-calibrates primary research manuscripts for Nature and Nature Portfolio journals. Use when the user wants a Nature-style title, summary paragraph or abstract, introduction, results, discussion, methods, figure legends, presubmission enquiry, cover letter, reviewer response, or when a scientific draft sounds generic, jargon-heavy, structurally weak, or AI-ish and needs precise, broad-reader-friendly prose without inventing data, analyses, or references. Best for primary research articles and letters rather than reviews or press releases unless explicitly adapting one.
deckrd
IncludedDocument-driven framework that derives requirements, specifications, implementation plans, and executable tasks from goals through structured AI dialogue. Use when user says "write requirements", "create spec", "plan implementation", "derive tasks", "structure this feature", "break down into tasks", or "document this module". Also use for reverse engineering existing code into docs (/deckrd rev). Do NOT use for direct code writing — use /deckrd-coder after tasks are generated. Do NOT use when the user only wants to run or fix existing code without planning.
clinical-decision-support
IncludedGenerate professional clinical decision support (CDS) documents for pharmaceutical and clinical research settings, including patient cohort analyses (biomarker-stratified with outcomes) and treatment recommendation reports (evidence-based guidelines with decision algorithms). Supports GRADE evidence grading, statistical analysis (hazard ratios, survival curves, waterfall plots), biomarker integration, and regulatory compliance. Outputs publication-ready LaTeX/PDF format optimized for drug development, clinical research, and evidence synthesis.
handling-sf-data
IncludedSalesforce data operations with 130-point scoring. Use this skill to create, update, delete, bulk import/export, generate test data, and clean up org records using sf CLI and anonymous Apex. TRIGGER when: user creates test data, performs bulk import/export, uses sf data CLI commands, needs data factory patterns for Apex tests, or needs to seed/clean records in a Salesforce org. DO NOT TRIGGER when: SOQL query writing only (use querying-soql), Apex test execution (use running-apex-tests), or metadata deployment (use deploying-metadata).
accelint-ac-to-playwright
IncludedConvert and validate acceptance criteria for Playwright test automation. Use when user asks to (1) review/evaluate/check if AC are ready for automation, (2) assess if AC can be converted as-is, (3) validate AC quality for Playwright, (4) turn AC into tests, (5) generate tests from acceptance criteria, (6) convert .md bullets or .feature Gherkin files to Playwright specs, (7) create test automation from requirements. Handles both bullet-style markdown and Gherkin syntax with JSON test plan generation and validation.