Regex-based context injection. Type SKILL or SNIPPET keywords to load context.

version
3.1.0
GitHub stars
7

Install

/plugin install claude-context-orchestrator@warren-claude-code-plugin-marketplace

Run it inside Claude Code after adding the marketplace with /plugin marketplace add WarrenZhu050413/Warren-Claude-Code-Plugin-Marketplace.

Contents

Discovered from source

Skills 53

Google Calendar Management

Three access methods, in order of preference:

1. gcallm CLI (Creating Events)

Best for creating events from natural language or file input.

# Direct text
gcallm "Meeting with Sarah tomorrow at 3pm"

# From file (preferred for multi-event)
cat /tmp/gcal/events.txt | gcallm

# From clipboard
gcallm

# From screenshot
gcallm -s "Add events from this screenshot"

# Ask questions
gcallm ask "What's on my calendar today?"
gcallm ask "Am I free Thursday afternoon?"

2. MCP Tools (Full CRUD When Available)

When the google-calendar MCP server is connected, these tools are available:

mcp__google-calendar__list-events    # List events in a time range
mcp__google-calendar__search-events  # Search by query string
mcp__google-calendar__create-event   # Create event
mcp__google-calendar__update-event   # Update event (supports recurring with modificationScope)
mcp__google-calendar__delete-event   # Delete event

Updating Recurring Events

Use modificationScope to control which instances are affected:

  • all — update/delete the entire series
  • this — only this instance
  • thisAndFollowing — this and all future instances

Color IDs

IDColor
1Lavender
2Sage
3Grape
4Flamingo
5Banana
6Tangerine
7Peacock
8Graphite
9Blueberry
10Basil
11Tomato (Red)

3. Direct Google Calendar API (Fallback)

When MCP tools are unavailable, use the REST API with stored OAuth tokens.

Token Location

/Users/wz/.config/google-calendar-mcp/tokens.json

Read Token

TOKEN=$(python3 -c "import json; print(json.load(open('/Users/wz/.config/google-calendar-mcp/tokens.json'))['normal']['access_token'])")

Common API Calls

# List events
curl -s -H "Authorization: Bearer $TOKEN" \
  "https://www.googleapis.com/calendar/v3/calendars/primary/events?timeMin=2026-01-01T00:00:00Z&timeMax=2026-12-31T23:59:59Z&singleEvents=true"

# Search events
curl -s -H "Authorization: Bearer $TOKEN" \
  "https://www.googleapis.com/calendar/v3/calendars/primary/events?q=SEARCH_TERM&timeMin=...&timeMax=...&singleEvents=true"

# Create event
curl -s -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  "https://www.googleapis.com/calendar/v3/calendars/primary/events" \
  -d '{"summary":"Event Title","location":"Place","colorId":"11","start":{"dateTime":"2026-02-03T09:00:00","timeZone":"America/New_York"},"end":{"dateTime":"2026-02-03T10:00:00","timeZone":"America/New_York"},"recurrence":["RRULE:FREQ=WEEKLY;COUNT=16;BYDAY=TU"]}'

# Update event (single instance)
curl -s -X PATCH -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  "https://www.googleapis.com/calendar/v3/calendars/primary/events/EVENT_ID" \
  -d '{"colorId":"11"}'

# Delete event (entire recurring series — use base recurring event ID, no instance suffix)
curl -s -X DELETE -H "Authorization: Bearer $TOKEN" \
  "https://www.googleapis.com/calendar/v3/calendars/primary/events/RECURRING_EVENT_ID"

# Delete single instance
curl -s -X DELETE -H "Authorization: Bearer $TOKEN" \
  "https://www.googleapis.com/calendar/v3/calendars/primary/events/EVENT_ID_WITH_INSTANCE_SUFFIX"

Recurring Event IDs

  • Base ID: abc123 — represents the series
  • Instance ID: abc123_20260203T140000Z — represents one occurrence
  • Deleting/updating the base ID affects all instances
  • Each instance has recurringEventId pointing back to the base

RRULE Examples

RRULE:FREQ=WEEKLY;COUNT=16;BYDAY=TU          # Every Tuesday for 16 weeks
RRULE:FREQ=WEEKLY;COUNT=16;BYDAY=MO,WE       # Mon & Wed for 16 weeks
RRULE:FREQ=WEEKLY;COUNT=16;BYDAY=TU,TH       # Tue & Thu for 16 weeks
RRULE:FREQ=DAILY;COUNT=5                      # Daily for 5 days
RRULE:FREQ=WEEKLY;UNTIL=20260530T000000Z      # Weekly until date

HTTP Status Codes

CodeMeaning
200Success (GET/PATCH)
204Success (DELETE)
401Token expired — need to refresh or re-auth via MCP server
404Event not found
409Conflict (duplicate)

Warren's Calendar

  • Account: wzhu@college.harvard.edu
  • Timezone: America/New_York
  • Calendar ID: primary

Principles

  • Type Safety: Use LuaCATS annotations everywhere
  • Modular Architecture: Single Responsibility Principle - one module, one purpose
  • Thin Orchestration: Keep init.lua under 400 lines - it coordinates, doesn't implement
  • Lazy Loading: Minimize startup impact
  • User Choice: Provide <Plug> mappings, not forced keymaps
  • 0-indexed Internally: LSP-style coordinates, convert to 1-indexed only for storage
  • Test-Driven: Write tests using Plenary

Module Organization

Extract when:

  • Code block > 150 lines with distinct purpose
  • 3+ similar/duplicate functions
  • Complex logic needing isolated testing

Target structure:

lua/plugin-name/
├── init.lua          -- ~300 lines: setup, coordination, public API
├── operations.lua    -- Core business logic
├── display.lua       -- UI/rendering
├── config.lua        -- Configuration
└── utils.lua         -- Shared utilities

What Belongs in init.lua: ✅ Module requires, setup(), autocommands, keymap/command registration, public API (thin wrappers)

What Does NOT Belong: ❌ Complex logic (>10 lines/function), helper functions, data transformations, duplicate patterns

Refactoring Patterns

Extract Module

-- Before: Mixed concerns in init.lua (170 lines)
local function normalize_range() end
local function compute_visual_range() end
function M.add_annotation_from_visual()
  local range = compute_visual_range(...)
end

-- After: Extracted to visual.lua
-- lua/plugin-name/visual.lua
local M = {}
function M.normalize_range(bufnr, range) end
function M.compute_visual_range(bufnr, opts) end
return M

-- init.lua becomes thin
local visual = require('plugin-name.visual')
function M.add_annotation_from_visual()
  local range = visual.compute_visual_range(...)
  require('plugin-name.operations').add_annotation(range)
end

Consolidate Duplicates

-- Bad: 4 nearly identical functions
function M.show_tldr() ... popup.show_tldr(anno) end
function M.show_vsplit() ... popup.open_vsplit(anno) end
function M.show_hsplit() ... popup.open_hsplit(anno) end
function M.show_large() ... popup.open_large(anno) end

-- Good: Single dispatcher
---@param view_mode "tldr"|"vsplit"|"hsplit"|"large"
function M.show_annotation(view_mode)
  local anno = get_annotation_at_cursor()
  local handlers = {
    tldr = function() popup.show_tldr(anno) end,
    vsplit = function() popup.open_vsplit(anno) end,
    hsplit = function() popup.open_hsplit(anno) end,
    large = function() popup.open_large(anno) end,
  }
  handlers[view_mode]()
end

Type Annotations

---@class Range
---@field start {line: integer, column: integer}
---@field ["end"] {line: integer, column: integer}

---@param opts PluginConfig?
---@return PluginConfig
local function setup(opts)
  return vim.tbl_deep_extend("force", default_config, opts or {})
end

Configuration

local M = {}
local default_config = { enabled = true, timeout = 5000 }
M.config = vim.deepcopy(default_config)

function M.setup(opts)
  M.config = vim.tbl_deep_extend("force", M.config, opts or {})
end

Lazy Loading

local heavy
local function get_heavy()
  if not heavy then heavy = require("heavy.module") end
  return heavy
end

function M.action()
  get_heavy().do_something()
end

Keymaps

vim.keymap.set("n", "<Plug>(plugin-action)", function()
  require("plugin").action()
end, { desc = "Plugin action" })

Commands

local function dispatcher(opts)
  local cmds = { enable = enable, disable = disable, status = status }
  (cmds[opts.fargs[1]] or function()
    vim.notify("Unknown: " .. opts.fargs[1], vim.log.levels.ERROR)
  end)()
end

vim.api.nvim_create_user_command("Plugin", dispatcher, {
  nargs = "+",
  complete = function() return { "enable", "disable", "status" } end,
})

Coordinates

-- 0-indexed internally (LSP-style)
local range = {
  start = { line = 0, column = 5 },
  ["end"] = { line = 0, column = 10 }
}

-- Convert to 1-indexed for storage
local function to_storage(range)
  return {
    start_line = range.start.line + 1,
    start_col = range.start.column,
    end_line = range["end"].line + 1,
    end_col = range["end"].column
  }
end

Testing

describe("plugin", function()
  it("handles normal case", function()
    assert.are.equal("expected", plugin.function("input"))
  end)
end)

-- Dependency injection
M._http_get = function(url) return vim.fn.system("curl " .. url) end
function M.fetch() return M._http_get("https://api.example.com") end

Error Handling

local function read_file(path)
  local ok, result = pcall(vim.fn.readfile, path)
  if not ok then return nil, "Failed to read: " .. path end
  return result, nil
end

local lines, err = read_file("config.json")
if err then
  vim.notify(err, vim.log.levels.ERROR)
  return
end

Extmarks

local ns_id = vim.api.nvim_create_namespace("plugin-name")

function add_highlight(bufnr, line, col_start, col_end)
  return vim.api.nvim_buf_set_extmark(bufnr, ns_id, line, col_start, {
    end_col = col_end,
    hl_group = "PluginHighlight",
    right_gravity = true,
    end_right_gravity = false
  })
end

vim.api.nvim_set_hl(0, "PluginHighlight", { fg = "#FFD700", underline = true })

Autocommands

local augroup = vim.api.nvim_create_augroup("PluginName", { clear = true })

vim.api.nvim_create_autocmd({ "BufReadPost", "BufNewFile" }, {
  group = augroup,
  callback = function(args) end,
  desc = "Initialize plugin"
})

Performance

-- Cache expensive operations
local cache = {}
function M.get(key)
  if not cache[key] then cache[key] = expensive_op(key) end
  return cache[key]
end

-- Async with vim.schedule
vim.schedule(function() slow_computation() end)

-- Debounce
local timer
vim.api.nvim_create_autocmd("TextChanged", {
  callback = function()
    if timer then vim.fn.timer_stop(timer) end
    timer = vim.fn.timer_start(500, on_change)
  end
})

Pitfalls

  • Monolithic init.lua: Extract modules at 400-500 lines
  • Mark indexing: Marks use 1-indexed lines, API uses 0-indexed
  • Buffer validity: Always check vim.api.nvim_buf_is_valid(buf)
  • Global state: Use module-local state
  • Blocking UI: Never block main thread
  • Duplicate code: Consolidate 3+ similar functions

Checklist

  • LuaCATS annotations on public functions
  • init.lua < 400 lines
  • No functions > 100 lines
  • No duplicate patterns
  • Modules follow SRP
  • Deep merge for config
  • Lazy loading for heavy deps
  • Error handling (pcall or nil, err)
  • 0-indexed internally, 1-indexed for storage
  • Autocommands use groups
  • Tests for core functionality
  • <Plug> mappings

Developing Essays

When to Load Which File

Essay TypeFile to Load
College application, PhD statement, "Why X", mentor essay, personal narrativepersonal-essays.md
Literary analysis, historical analysis, argumentative essay on external topicanalytical-essays.md

Rule: If essay answers "who am I / what will I do?" → personal. If essay answers "what does this text/event mean?" → analytical.

Analytical Essays Quick Reference

analytical-essays.md now includes:

  • Phased Framework Methodology: Organize arguments into temporal/thematic phases (Revolution → Reaction → Reform)
  • Critical Argument Linkage: Every paragraph must explicitly connect to thesis
  • Paragraph Planning Tables: Map paragraphs to phases, claims, evidence, and thesis linkage
  • Primary Source Requirements: Rules for evidence inventory and citation practices
  • Expanded Self-Check Checklist: Structure, evidence, and completeness checks

Universal Principles

These apply to ALL essay types. Check before any specific rules.

U1: Factual Accuracy

Rule: Every factual claim must be verifiable.

Elaboration: Don't invent dates, statistics, or events. If uncertain, mark for verification. Applicants lose credibility from a single factual error.

Example:

  • BAD: "Professor Smith's 2019 paper on graph algorithms..."
  • CHECK: Verify paper exists, verify year, verify it's about graph algorithms
  • GOOD: [After verification] "Professor Smith's 2021 paper on shortest-path algorithms..."

U2: Quote Verification

Rule: Every quote must be checked against the original source.

Elaboration: Misquoted professors, misattributed ideas, or paraphrased-as-quoted text damages trust. When in doubt, paraphrase instead of quote.

Example:

  • BAD: Professor Wong said, "Talk to people more." [Did they say exactly this?]
  • CHECK: Find original source, verify exact wording
  • GOOD: Professor Wong emphasized the value of conversation over formal interviews.

U3: No Invented Content

Rule: Never fabricate experiences, achievements, or reflections the writer hasn't expressed.

Elaboration: When writer input is needed, use placeholders. The writer must provide: specific research interests, personal reflections, lessons learned, connections between experiences.

Example:

[WRITER: What specific lesson did you take from this experience?

Example style: "I learned to survey literature first—we could have saved weeks"

Your version: _______________]

U4: Sentence-Level Clarity

Rule: Every sentence must relate explicitly to adjacent sentences.

Elaboration: If the connection isn't clear, add transitional language. Readers shouldn't have to infer how ideas connect.

Example:

  • BAD: "I studied algorithms. Cambridge has a strong theory group."
  • GOOD: "I studied algorithms. This interest drew me to Cambridge's theory group."

U5: Remove Filler Phrases

Rule: Cut phrases that add no meaning.

Elaboration: These phrases signal weak writing and waste word count.

Remove:

  • "I hope to..." → "I aim to" / "I intend to"
  • "more importantly" → [delete]
  • "In particular" → [delete or be specific]
  • "which I took the summer after my second year" → [resume has dates]
  • "incredibly exciting" → [be specific about what excites]

U6: Active Over Passive

Rule: Use active voice unless passive is specifically justified.

Elaboration: Passive voice obscures agency and weakens impact.

Example:

  • BAD: "It was learned that research requires persistence"
  • GOOD: "I learned that research requires persistence"

U7: Compression Test

Rule: If a paragraph can become one sentence without losing meaning, compress it.

Elaboration: Verbosity buries ideas. Force radical reduction to find the core.

Example:

  • BEFORE (3 paragraphs): Discussion of dopamine, YouTube, vlogs, why vlogging works
  • AFTER (2 sentences): "Laptop open, I resisted YouTube, the vlogs and dopamine. Yet my mind wondered—vloggers record unpolished moments for the public, yes, but for themselves too."

Output Format for Feedback

When providing essay feedback:

Structure:

  • One focused paragraph per issue
  • Quote problematic text, then commentary
  • Maximum 3-4 issues per session

Format:

[Issue name]: "[quoted essay text]"

[Single paragraph: problem + suggested fix, 3-5 sentences max]

Priority order:

  1. Missing forward projection
  2. Circular narrative gaps
  3. Weak openings
  4. Weak/multiple throughlines
  5. Abstract language without concrete moments
  6. Structural problems

Red Flag Phrases

These signal weak throughlines in ANY essay type:

  • "I learned a lot"
  • "This experience shaped me"
  • "I'm passionate about"
  • "This taught me the importance of"
  • "I've always been deeply interested"

Response: Push for specificity. What exactly? How specifically?

Managing Skills

Attribution: This skill is based on Anthropic's skill-creator from the anthropic-agent-skills repository, licensed under Apache License 2.0. This derivative work includes modifications for Warren's plugin system and snippet integration.

Copyright: Original work Copyright Anthropic. Modifications Copyright 2025 Warren Zhu.

License: Apache License 2.0 (see LICENSE.txt for complete terms)


Warren's System Configuration

Default Skill Location:

All new skills for Warren's system should be created in:

~/.claude/plugins/marketplaces/warren-claude-code-plugin-marketplace/claude-context-orchestrator/skills/

Other Skill Locations:

  • Personal: ~/.claude/skills/ (individual workflows)
  • Project: .claude/skills/ (team workflows, commit to git)
  • Plugin: Plugin's skills/ directory (distributable)

About Skills

Skills are modular, self-contained packages that extend Claude's capabilities by providing specialized knowledge, workflows, and tools. Think of them as "onboarding guides" for specific domains or tasks—they transform Claude from a general-purpose agent into a specialized agent equipped with procedural knowledge that no model can fully possess.

What Skills Provide

  1. Specialized workflows - Multi-step procedures for specific domains
  2. Tool integrations - Instructions for working with specific file formats or APIs
  3. Domain expertise - Company-specific knowledge, schemas, business logic
  4. Bundled resources - Scripts, references, and assets for complex and repetitive tasks

Anatomy of a Skill

Every skill consists of a required SKILL.md file and optional bundled resources:

skill-name/
├── SKILL.md (required)
│   ├── YAML frontmatter metadata (required)
│   │   ├── name: (required)
│   │   └── description: (required)
│   └── Markdown instructions (required)
└── Bundled Resources (optional)
    ├── scripts/          - Executable code (Python/Bash/etc.)
    ├── references/       - Documentation intended to be loaded into context as needed
    └── assets/           - Files used in output (templates, icons, fonts, etc.)
SKILL.md (required)

Metadata Quality: The name and description in YAML frontmatter determine when Claude will use the skill. Be specific about what the skill does and when to use it. Use the third-person (e.g. "This skill should be used when..." instead of "Use this skill when...").

Critical Format Rule: Do NOT include overview sections or "When to Use This Skill" sections in the SKILL.md body. This information belongs ONLY in the YAML frontmatter description. The body should contain ONLY procedural instructions on how to use the skill.

Incorrect format:

---
name: example
description: Brief description
---

# Example Skill Title

Overview paragraph explaining what the skill does.

## When to Use This Skill
- Use case 1
- Use case 2

## How to Use
Instructions here...

Correct format:

---
name: example
description: Detailed description including what the skill does, when to use it (use case 1, use case 2, etc.), and what it provides. Use when working with X, Y, and Z operations.
---

## How to Use
Instructions here (no overview, no "when to use" section)...
Bundled Resources (optional)
Scripts (scripts/)

Executable code (Python/Bash/etc.) for tasks that require deterministic reliability or are repeatedly rewritten.

  • When to include: When the same code is being rewritten repeatedly or deterministic reliability is needed
  • Example: scripts/rotate_pdf.py for PDF rotation tasks
  • Benefits: Token efficient, deterministic, may be executed without loading into context
  • Note: Scripts may still need to be read by Claude for patching or environment-specific adjustments
References (references/)

Documentation and reference material intended to be loaded as needed into context to inform Claude's process and thinking.

  • When to include: For documentation that Claude should reference while working
  • Examples: references/finance.md for financial schemas, references/mnda.md for company NDA template, references/policies.md for company policies, references/api_docs.md for API specifications
  • Use cases: Database schemas, API documentation, domain knowledge, company policies, detailed workflow guides
  • Benefits: Keeps SKILL.md lean, loaded only when Claude determines it's needed
  • Best practice: If files are large (>10k words), include grep search patterns in SKILL.md
  • Avoid duplication: Information should live in either SKILL.md or references files, not both. Prefer references files for detailed information unless it's truly core to the skill—this keeps SKILL.md lean while making information discoverable without hogging the context window. Keep only essential procedural instructions and workflow guidance in SKILL.md; move detailed reference material, schemas, and examples to references files.
Assets (assets/)

Files not intended to be loaded into context, but rather used within the output Claude produces.

  • When to include: When the skill needs files that will be used in the final output
  • Examples: assets/logo.png for brand assets, assets/slides.pptx for PowerPoint templates, assets/frontend-template/ for HTML/React boilerplate, assets/font.ttf for typography
  • Use cases: Templates, images, icons, boilerplate code, fonts, sample documents that get copied or modified
  • Benefits: Separates output resources from documentation, enables Claude to use files without loading them into context

Progressive Disclosure Design Principle

Skills use a three-level loading system to manage context efficiently:

  1. Metadata (name + description) - Always in context (~100 words)
  2. SKILL.md body - When skill triggers (<5k words)
  3. Bundled resources - As needed by Claude (Unlimited*)

*Unlimited because scripts can be executed without reading into context window.

Skill Creation Process

To create a skill, follow the "Skill Creation Process" in order, skipping steps only if there is a clear reason why they are not applicable.

Step 1: Understanding the Skill with Concrete Examples

Skip this step only when the skill's usage patterns are already clearly understood. It remains valuable even when working with an existing skill.

To create an effective skill, clearly understand concrete examples of how the skill will be used. This understanding can come from either direct user examples or generated examples that are validated with user feedback.

For example, when building an image-editor skill, relevant questions include:

  • "What functionality should the image-editor skill support? Editing, rotating, anything else?"
  • "Can you give some examples of how this skill would be used?"
  • "I can imagine users asking for things like 'Remove the red-eye from this image' or 'Rotate this image'. Are there other ways you imagine this skill being used?"
  • "What would a user say that should trigger this skill?"

To avoid overwhelming users, avoid asking too many questions in a single message. Start with the most important questions and follow up as needed for better effectiveness.

Conclude this step when there is a clear sense of the functionality the skill should support.

Step 2: Planning the Reusable Skill Contents

To turn concrete examples into an effective skill, analyze each example by:

  1. Considering how to execute on the example from scratch
  2. Identifying what scripts, references, and assets would be helpful when executing these workflows repeatedly

Example: When building a pdf-editor skill to handle queries like "Help me rotate this PDF," the analysis shows:

  1. Rotating a PDF requires re-writing the same code each time
  2. A scripts/rotate_pdf.py script would be helpful to store in the skill

Example: When designing a frontend-webapp-builder skill for queries like "Build me a todo app" or "Build me a dashboard to track my steps," the analysis shows:

  1. Writing a frontend webapp requires the same boilerplate HTML/React each time
  2. An assets/hello-world/ template containing the boilerplate HTML/React project files would be helpful to store in the skill

Example: When building a big-query skill to handle queries like "How many users have logged in today?" the analysis shows:

  1. Querying BigQuery requires re-discovering the table schemas and relationships each time
  2. A references/schema.md file documenting the table schemas would be helpful to store in the skill

To establish the skill's contents, analyze each concrete example to create a list of the reusable resources to include: scripts, references, and assets.

Step 3: Initializing the Skill

At this point, it is time to actually create the skill.

Skip this step only if the skill being developed already exists, and iteration or packaging is needed. In this case, continue to the next step.

For Warren's system, create the skill directory manually in the default location:

# Create skill directory in Warren's plugin
mkdir -p ~/.claude/plugins/marketplaces/warren-claude-code-plugin-marketplace/claude-context-orchestrator/skills/my-skill

# Create subdirectories as needed
mkdir -p ~/.claude/plugins/marketplaces/warren-claude-code-plugin-marketplace/claude-context-orchestrator/skills/my-skill/scripts
mkdir -p ~/.claude/plugins/marketplaces/warren-claude-code-plugin-marketplace/claude-context-orchestrator/skills/my-skill/references
mkdir -p ~/.claude/plugins/marketplaces/warren-claude-code-plugin-marketplace/claude-context-orchestrator/skills/my-skill/assets

If using Anthropic's init_skill.py script (for other systems):

scripts/init_skill.py <skill-name> --path <output-directory>

The script creates a template with proper frontmatter and example directories.

After initialization, customize or remove the generated SKILL.md and example files as needed.

Step 4: Edit the Skill

When editing the (newly-generated or existing) skill, remember that the skill is being created for another instance of Claude to use. Focus on including information that would be beneficial and non-obvious to Claude. Consider what procedural knowledge, domain-specific details, or reusable assets would help another Claude instance execute these tasks more effectively.

Start with Reusable Skill Contents

To begin implementation, start with the reusable resources identified above: scripts/, references/, and assets/ files. Note that this step may require user input. For example, when implementing a brand-guidelines skill, the user may need to provide brand assets or templates to store in assets/, or documentation to store in references/.

Also, delete any example files and directories not needed for the skill. The initialization script creates example files in scripts/, references/, and assets/ to demonstrate structure, but most skills won't need all of them.

Update SKILL.md

Writing Style: Write the entire skill using imperative/infinitive form (verb-first instructions), not second person. Use objective, instructional language (e.g., "To accomplish X, do Y" rather than "You should do X" or "If you need to do X"). This maintains consistency and clarity for AI consumption.

Content Organization:

  1. YAML Frontmatter (required):

    • name: Skill identifier
    • description: Comprehensive description that includes:
      • What the skill does
      • When to use it (all use cases)
      • What it provides (features, capabilities)
      • Any pre-configured elements
  2. Markdown Body (required):

    • Start directly with procedural sections (e.g., "## Environment Setup", "## Helper Script Usage")
    • Do NOT include:
      • Title headers repeating the skill name
      • Overview/introduction paragraphs
      • "When to Use This Skill" sections
      • "What This Skill Provides" sections
    • DO include:
      • Setup instructions
      • Usage examples
      • Common operations
      • Workflow guidelines
      • References to bundled resources

Example structure:

---
name: my-skill
description: [Complete description with all use cases and features]
---

## Environment Setup
[Setup instructions]

## Using the Helper Script
[How to use scripts/]

## Common Operations
[Examples and patterns]

All reusable skill contents (scripts, references, assets) should be referenced in the body so Claude knows how to use them.

Step 5: Packaging a Skill

Once the skill is ready, it should be packaged into a distributable zip file that gets shared with the user. The packaging process automatically validates the skill first to ensure it meets all requirements:

scripts/package_skill.py <path/to/skill-folder>

Optional output directory specification:

scripts/package_skill.py <path/to/skill-folder> ./dist

The packaging script will:

  1. Validate the skill automatically, checking:

    • YAML frontmatter format and required fields
    • Skill naming conventions and directory structure
    • Description completeness and quality
    • File organization and resource references
  2. Package the skill if validation passes, creating a zip file named after the skill (e.g., my-skill.zip) that includes all files and maintains the proper directory structure for distribution.

If validation fails, the script will report the errors and exit without creating a package. Fix any validation errors and run the packaging command again.

Note: For Warren's system, skills are typically not packaged as zip files but remain in place within the plugin directory structure.

Step 6: Iterate

After testing the skill, users may request improvements. Often this happens right after using the skill, with fresh context of how the skill performed.

Iteration workflow:

  1. Use the skill on real tasks
  2. Notice struggles or inefficiencies
  3. Identify how SKILL.md or bundled resources should be updated
  4. Implement changes and test again

Snippet Integration (Warren's System)

Skills in Warren's system can be enhanced with snippet integration for instant keyword activation. This allows skills to be triggered by specific keywords in user prompts, providing explicit control over when a skill loads.

When to Add Snippet Integration

Add snippet integration when:

  • Skill needs instant activation by specific keyword (e.g., "USE SKILL_NAME")
  • Skill is used frequently in specific contexts
  • Want to bypass automatic skill discovery and ensure deterministic loading

How to Add Snippet Integration

  1. Read the managing-snippets skill for detailed instructions on snippet management

  2. Add entry to config.local.json at:

    ~/.claude/plugins/marketplaces/warren-claude-code-plugin-marketplace/claude-context-orchestrator/config.local.json
    
  3. Example snippet pattern:

    {
      "hooks": {
        "user-prompt-submit": {
          "enabled": true,
          "order": 0,
          "patterns": [
            {
              "regex": "\\bUSE MY-SKILL\\b",
              "command": "~/.claude/plugins/marketplaces/warren-claude-code-plugin-marketplace/claude-context-orchestrator/scripts/read-skill.sh 'my-skill'"
            }
          ]
        }
      }
    }
    
  4. Test the snippet:

    • Type "USE MY-SKILL" in a prompt
    • Verify the skill content loads
  5. Restart Claude Code to activate the snippet

Snippet vs. Automatic Discovery

Automatic Discovery:

  • Claude decides when to load skill based on description
  • More flexible, adapts to varied user phrasings
  • Relies on good description metadata

Snippet Activation:

  • User explicitly triggers skill with keyword
  • Deterministic loading every time
  • Useful for workflows where skill should always be active

Recommendation: Use both approaches together. Let automatic discovery handle most cases, and provide snippet keywords for power users who want explicit control.


CHANGELOG

Modified 2025-10-26 by Warren Zhu

Changes made to derivative work:

  1. Added Warren's system configuration (Section: "Warren's System Configuration")

    • Specified default skill location for Warren's plugin
    • Listed alternative skill locations
  2. Modified Step 3: Initializing the Skill

    • Added Warren-specific manual directory creation commands
    • Noted that Anthropic's init_skill.py is for other systems
  3. Modified Step 5: Packaging a Skill

    • Added note that Warren's system doesn't typically use zip packaging
    • Skills remain in place within plugin directory
  4. Added Section: "Snippet Integration (Warren's System)"

    • Explained when to add snippet integration
    • Provided instructions for adding snippets
    • Documented snippet vs. automatic discovery tradeoffs
    • Referenced managing-snippets skill for details
  5. Updated YAML frontmatter

    • Modified description to mention Warren's system and snippet integration
    • Renamed skill from "skill-creator" to "Managing Skills"
  6. Added attribution, copyright, and license notices

    • Acknowledged Anthropic as original author
    • Included Apache License 2.0 reference

Original work attribution:

All other content remains unchanged from the original Anthropic skill-creator.

Managing Snippets (v2.0)

Snippets auto-inject context when regex patterns match user messages. This skill provides a streamlined workflow for discovering snippet locations, creating snippets, searching configurations, and direct file editing.

About Snippets

Snippets are pattern-triggered context injection files that enhance Claude's capabilities by automatically loading relevant information when specific keywords appear in user prompts. Think of them as "smart bookmarks" that activate based on what you're working on.

What Snippets Provide

  1. Automatic context loading - Inject relevant documentation when keywords match
  2. Workflow enhancement - Load domain-specific guidance without manual selection
  3. Consistency - Ensure same context is available across sessions
  4. Efficiency - Skip manual skill invocation for frequently-used contexts

When to Use Snippets

  • Frequently-used skills that should activate on keywords (e.g., "DOCKER", "TERRAFORM")
  • Domain-specific documentation that's needed for specific topics
  • Quick-reference material that should load automatically
  • Workflow guides tied to specific technologies or tasks

Anatomy of a Snippet

Every snippet consists of two components:

1. config.local.json Entry (Required)

Located at:

/Users/wz/.claude/plugins/marketplaces/warren-claude-code-plugin-marketplace/claude-context-orchestrator/scripts/config.local.json

Structure:

{
  "name": "snippet-identifier",
  "pattern": "\\b(PATTERN)\\b[.,;:!?]?",
  "snippet": ["../snippets/local/category/name/SNIPPET.md"],
  "separator": "\n",
  "enabled": true
}

Key fields:

  • name: Unique identifier for the snippet
  • pattern: Regex pattern that triggers the snippet (MUST follow standard format)
  • snippet: Array of file paths to inject (relative to config file)
  • separator: How to join multiple files (usually "\n")
  • enabled: Whether snippet is active (true/false)

2. SNIPPET.md File (Required)

Located in subdirectory under:

/Users/wz/.claude/plugins/marketplaces/warren-claude-code-plugin-marketplace/claude-context-orchestrator/snippets/local/

Structure:

---
name: "Descriptive Name"
description: "When to use this snippet and what it provides"
---

[Content to be injected into context]

Organization: Snippets are organized by category:

  • snippets/local/communication/ - Email, reports, writing templates
  • snippets/local/documentation/ - Guides, references, how-tos
  • snippets/local/development/ - Code patterns, debugging workflows
  • snippets/local/productivity/ - Workflow automation, task management
  • snippets/local/output-formats/ - Formatting styles, templates

CLI v2.0 Overview

The snippets CLI provides four focused commands:

  1. paths - Discover available snippet categories and locations
  2. create - Create snippets from source files with validation
  3. list / search - Search snippets by name, pattern, or description
  4. validate - Verify configuration integrity

Installation:

cd /Users/wz/.claude/plugins/.../scripts
make install  # Global: uv tool install
# OR
make dev      # Local dev: uv run snippets

Auto-detect modes:

  • TTY (terminal): Interactive selection interface
  • Non-TTY (piped): JSON output for scripting

Snippet Management Process

Follow these steps in order to effectively manage snippets.

Step 1: Discover Available Locations

Before creating a snippet, explore where snippets can be placed using the paths command.

List all categories:

snippets paths
# OR with JSON output
snippets paths --output json

Filter by keyword:

snippets paths dev        # Shows categories matching "dev"
snippets paths email      # Shows categories matching "email"

Output:

  • Base directory path
  • Category names (communication, documentation, development, productivity, output-formats)
  • Category descriptions
  • Full paths to each category

Step 2: Planning the Pattern

Determine the regex pattern that will trigger your snippet. Patterns must follow the standard format (see Regex Protocol below).

Pattern planning:

  1. Choose ONE distinctive keyword for the snippet (e.g., "DOCKER")
  2. Convert to ALL CAPS (e.g., "docker" → "DOCKER")
  3. Handle multi-word patterns (use _, -, or no separator)
  4. Apply standard format: \b(PATTERN)\b[.,;:!?]?

Examples:

  • Single keyword: \b(DOCKER)\b[.,;:!?]?
  • Multi-word: \b(BUILD_ARTIFACT)\b[.,;:!?]?
  • Compound: \b(SNIPPETMGMT)\b[.,;:!?]?

Step 3: Creating a Snippet

Create snippets using the create command, which validates and registers the snippet automatically.

Creation workflow:

  1. Create source SKILL.md file with frontmatter:

    ---
    name: "Docker Best Practices"
    description: "Use when working with Docker containers, images, and containerization"
    pattern: "\\b(DOCKER)\\b[.,;:!?]?"
    ---
    
    # Docker Best Practices
    [Content here...]
    
  2. Run create command:

    snippets create source.md snippets/local/development/docker/SKILL.md
    
    # With pattern override
    snippets create source.md snippets/local/development/docker/SKILL.md \
      --pattern "\\b(NEW_PATTERN)\\b[.,;:!?]?"
    
    # Force overwrite existing
    snippets create source.md snippets/local/development/docker/SKILL.md --force
    

What create does:

  1. ✅ Validates source file exists
  2. ✅ Parses YAML frontmatter (name, description, pattern)
  3. ✅ Validates pattern format (ALL CAPS, proper structure)
  4. ✅ Validates destination is within snippets/local/
  5. ✅ Extracts snippet name from destination path
  6. ✅ Checks destination doesn't already exist (unless --force)
  7. ✅ Creates destination directory
  8. ✅ Copies file to destination
  9. ✅ Registers in config.local.json automatically

Helpful error messages:

  • Missing frontmatter → Shows required YAML structure
  • Invalid pattern → Explains pattern requirements with examples
  • Invalid destination → Shows expected path format
  • Missing pattern → Reminds to add --pattern flag or pattern field

Common mistakes to avoid:

  • ❌ Using lowercase in pattern
  • ❌ Missing \\b word boundaries (requires double backslash)
  • ❌ Destination outside snippets/local/ directory
  • ❌ Forgetting YAML frontmatter

Step 4: Searching and Inspecting Snippets

Search snippets using enhanced multi-level matching (name → pattern → description).

List all snippets:

snippets                    # Default: list all (TTY: interactive, piped: JSON)
snippets list               # Explicit list command
snippets --output json      # Force JSON output

Search by keyword:

snippets docker             # Searches name, pattern, and description
snippets kubernetes         # Priority: exact name > name contains > pattern > description

Interactive mode (TTY):

  • Shows formatted list with match indicators
  • Navigate with arrow keys
  • Select to open in $EDITOR
  • ESC to cancel

Non-interactive mode (piped/JSON):

  • JSON output with match_type and match_priority
  • Can pipe to jq for filtering
  • Suitable for scripting

Match priority ranking:

  1. Exact name match (priority 1) - snippets mail finds snippet named "mail"
  2. Name contains (priority 2) - snippets dock finds "docker"
  3. Pattern content (priority 3) - snippets KUBECTL finds patterns with KUBECTL
  4. Description match (priority 4) - snippets "email templates" finds description matches

What to check:

  • Enabled status (✓ or ✗)
  • Pattern alternatives (does it cover all intended keywords?)
  • File paths (do they point to correct locations?)
  • Content (read SKILL.md to verify)

Regular audits:

  • Review snippets monthly
  • Disable unused snippets (edit config.local.json)
  • Update patterns based on usage
  • Remove outdated content

Step 5: Updating Snippets (Direct File Editing)

Philosophy: v2.0 CLI focuses on search and creation. Updates are done by editing files directly.

Modify existing snippets when:

  • Pattern doesn't match expected keywords
  • Content is outdated
  • Need to enable/disable temporarily
  • Want to rename for clarity

Update workflow:

  1. Find the snippet:

    snippets docker          # Search to locate snippet
    # OR in interactive mode: select snippet → opens in $EDITOR
    
  2. Determine what needs updating:

    • Pattern expansion → Edit config.local.json
    • Content modification → Edit SKILL.md directly
    • Status change → Edit config.local.json (enabled field)
    • Rename → Edit config.local.json (name field)
  3. For pattern updates:

    # Edit config.local.json directly
    vim ~/.claude/plugins/.../scripts/config.local.json
    
    # Modify the pattern field
    {
      "name": "docker",
      "pattern": "\\b(DOCKER|CONTAINER|DOCKERFILE|KUBECTL)\\b[.,;:!?]?",  # Added KUBECTL
      ...
    }
    
  4. For content updates:

    # Edit SKILL.md directly
    vim ~/.claude/plugins/.../snippets/local/development/docker/SKILL.md
    
    # Update content while maintaining YAML frontmatter
    
  5. Validate changes:

    snippets validate        # Check for errors
    snippets validate --output json  # JSON output for scripting
    
  6. Test:

    • Type trigger keyword in new prompt
    • Confirm content loads correctly

Context-aware updating: If a snippet failed to load during a session, analyze why:

  • Did the pattern not match? → Edit config.local.json to expand pattern
  • Was it disabled? → Change "enabled": false to true
  • Missing keywords? → Add alternatives to pattern

Step 6: Deleting Snippets (Direct File Editing)

Remove snippets that are:

  • No longer needed
  • Superseded by other snippets or skills
  • Creating conflicts with other patterns

Deletion workflow:

  1. Backup first:

    # Create backup of config
    cp ~/.claude/plugins/.../scripts/config.local.json \
       ~/.claude/plugins/.../scripts/config.local.json.backup.$(date +%Y%m%d_%H%M%S)
    
    # Backup snippet file
    cp -r ~/.claude/plugins/.../snippets/local/category/snippet-name \
          ~/.claude/plugins/.../backups/snippet-name_$(date +%Y%m%d_%H%M%S)
    
  2. Remove from config.local.json:

    vim ~/.claude/plugins/.../scripts/config.local.json
    
    # Delete the entire mapping object
    # Ensure JSON remains valid (check commas)
    
  3. Optionally delete SKILL.md:

    rm -rf ~/.claude/plugins/.../snippets/local/category/snippet-name
    
  4. Validate and verify:

    snippets validate              # Check JSON is valid
    snippets                       # Confirm snippet is gone
    # Type trigger keyword → should not load
    

Restoration: If you need to restore:

  1. cp backup/config.local.json.backup.TIMESTAMP config.local.json
  2. cp -r backup/snippet-name_TIMESTAMP snippets/local/category/snippet-name
  3. snippets validate and test trigger keyword

Regex Protocol (Standard Format)

CRITICAL: All snippet patterns MUST follow this format.

Standard Format

\b(PATTERN)\b[.,;:!?]?

Rules:

  1. Single keyword per snippet: Each snippet should have exactly ONE trigger keyword (e.g., DOCKER, not DOCKER|CONTAINER|DOCKERFILE). This ensures predictable activation and avoids confusion about which keyword triggered what.
  2. Word boundaries: \b at start and end
  3. Parentheses: Pattern wrapped in ()
  4. ALL CAPS: Uppercase only (A-Z, 0-9)
  5. Multi-word: Use _, -, or no separator (never spaces)
  6. No mixed separators: Can't mix _ and - in same pattern
  7. Optional punctuation: [.,;:!?]? at end
  8. Alternation discouraged: Avoid | for multiple keywords—create separate snippets if needed

Why Full Punctuation Matters

Users naturally add punctuation when typing. Excluding punctuation causes mismatches:

  • ❌ Pattern [.,;:]? does NOT match "ARTIFACT!"
  • ✅ Pattern [.,;:!?]? matches "ARTIFACT!", "ARTIFACT?", "ARTIFACT."

Always use the full set: [.,;:!?]?

Valid Examples

\b(DOCKER)\b[.,;:!?]?                      # Single keyword (preferred)
\b(BUILD_ARTIFACT)\b[.,;:!?]?              # Underscore separator
\b(BUILD-ARTIFACT)\b[.,;:!?]?              # Hyphen separator
\b(BUILDARTIFACT)\b[.,;:!?]?               # No separator

Invalid/Discouraged Examples

\b(docker)\b[.,;:!?]?              # ❌ Lowercase
\b(BUILD ARTIFACT)\b[.,;:!?]?      # ❌ Space separator
\b(BUILD_ART-IFACT)\b[.,;:!?]?     # ❌ Mixed separators
\bDOCKER\b                         # ❌ Missing parens and punctuation
\b(DOCKER)\b[.,;:]?                # ❌ Incomplete punctuation
\b(DOCKER|CONTAINER|DOCKERFILE)\b[.,;:!?]? # ⚠️ Multiple keywords—avoid

Pattern Transformation

User input → Standard format:

  1. Choose ONE keyword:

    • Pick the most distinctive/memorable keyword
    • "docker, container, dockerfile" → Choose DOCKER (most distinctive)
  2. Convert to ALL CAPS:

    • "docker" → "DOCKER"
    • "build artifact" → "BUILD_ARTIFACT"
  3. Handle multi-word:

    • Choose one separator: _ (preferred), -, or none
    • Apply consistently throughout pattern
  4. Apply standard format:

    • Wrap in \b boundaries
    • Add parentheses
    • Add [.,;:!?]? for punctuation

JSON Escaping

IMPORTANT: In config.local.json, backslashes must be doubled:

{
  "pattern": "\\b(DOCKER)\\b[.,;:!?]?"
}

Single \b becomes \\b in JSON.

Complete Examples

Example 1: Create Docker Snippet

Step 1: Understand needs

  • Trigger: "DOCKER" (single distinctive keyword)
  • Provides: Docker best practices and commands
  • Frequent use: Yes

Step 2: Plan pattern

  • Keyword: DOCKER
  • Pattern: \b(DOCKER)\b[.,;:!?]?

Step 3: Create snippet

  1. Create directory:

    mkdir -p ~/.claude/plugins/.../snippets/local/development/docker
    
  2. Create SNIPPET.md:

    ---
    name: "Docker Best Practices"
    description: "Use when working with Docker containers, images, and containerization"
    ---
    
    # Docker Best Practices
    [Content here...]
    
  3. Add to config.local.json:

    {
      "name": "docker",
      "pattern": "\\b(DOCKER)\\b[.,;:!?]?",
      "snippet": ["../snippets/local/development/docker/SNIPPET.md"],
      "separator": "\n",
      "enabled": true
    }
    

Step 4: Test

  • Type "DOCKER" → snippet loads

Example 2: Create a Related Snippet for Different Keyword

Scenario: User wants "kubectl" to also load kubernetes-related content

Solution: Create a separate snippet (single-keyword rule)

  1. Original snippet: kubernetes with pattern \b(K8S)\b[.,;:!?]?
  2. Create new snippet: kubectl-guide with pattern \b(KUBECTL)\b[.,;:!?]?
  3. Both can reference the same content files if needed

Alternative: If content is truly identical, consider renaming the keyword to something more general (e.g., K8S)

Example 3: Delete Unused Snippet

Backup → Remove from config.local.json → Delete SNIPPET.md → Verify

File Locations

  • Config: ~/.claude/plugins/.../scripts/config.local.json
  • Snippets: ~/.claude/plugins/.../snippets/local/{category}/{name}/SNIPPET.md
  • Categories: communication/, documentation/, development/, productivity/, output-formats/

Best Practices

  • Check architecture first (read config.local.json before creating)
  • Pattern in config.local.json, NOT YAML frontmatter
  • Use ALL CAPS in patterns with full punctuation: [.,;:!?]?
  • Double-escape in JSON: \\b not \b
  • Test after changes
  • Backup before deletion

Quick Reference (v2.0)

TaskCommand / Action
Discover categoriessnippets paths or snippets paths <filter>
Create snippetsnippets create source.md snippets/local/category/name/SKILL.md
List all snippetssnippets or snippets list
Search snippetssnippets <keyword> (searches name/pattern/description)
Update patternEdit pattern field in config.local.json directly
Update contentEdit SKILL.md file directly (or use snippets <name> in TTY → opens $EDITOR)
Enable/disableChange enabled field in config.local.json
Delete snippet1. Backup files
2. Remove from config.local.json
3. Delete SKILL.md directory
Validate configsnippets validate or snippets validate --output json
Test patternType trigger keyword in new prompt

Troubleshooting

IssueFix
Not loadingCheck enabled: true, pattern matches (ALL CAPS), file path correct
Pattern not matchingVerify standard format, use [.,;:!?]?, test with ALL CAPS
Too many loadingCheck overlapping patterns, disable conflicts
JSON errorsValidate syntax, use \\b not \b

Critical Reminders

Architecture:

  • Pattern goes in config.local.json (NOT YAML frontmatter)
  • Always read config.local.json before creating snippets
  • Double-escape in JSON: \\b

When User Corrects You: Stop → Read actual files → Understand architecture → Fix all related mistakes → Verify

Apache License 2.0 Compliance

Guide for ensuring derivative works comply with Apache License 2.0 requirements.

When to Use This Skill

Use this skill when:

  • Creating derivative works from Apache-licensed code
  • Modifying files from Apache-licensed projects
  • Redistributing Apache-licensed software
  • Checking if attribution is correct
  • Validating NOTICE and LICENSE files
  • Ensuring change documentation meets Apache requirements
  • Reviewing code for license compliance before release

Apache License 2.0 Overview

The Apache License 2.0 is a permissive license that allows:

  • Commercial use
  • Modification
  • Distribution
  • Patent use (with grant)
  • Private use

Key requirement: Derivative works must comply with Section 4 redistribution requirements.

Compliance Workflow

Follow this 4-step workflow to ensure Apache 2.0 compliance:

Step 1: Attribution Requirements (Section 4c)

Requirement: Retain copyright, patent, trademark, and attribution notices from the source.

Checklist:

- [ ] Retained all copyright notices from original files
- [ ] Retained all patent notices from original files
- [ ] Retained all trademark notices from original files
- [ ] Retained all attribution notices from original files
- [ ] Did NOT remove or modify existing attribution

Example - Proper Attribution:

# Copyright 2024 Original Author
# Copyright 2025 Your Name (modifications)
#
# Licensed under the Apache License, Version 2.0...

Example - WRONG (missing original copyright):

# Copyright 2025 Your Name
# Licensed under the Apache License, Version 2.0...

Step 2: NOTICE and LICENSE Files (Section 4d)

Requirement: Include LICENSE and NOTICE files (if present in original) with redistribution.

LICENSE File Checklist:

- [ ] LICENSE.txt or LICENSE file exists in distribution
- [ ] Contains complete Apache License 2.0 text
- [ ] File is in root directory or documented location

NOTICE File Checklist (if original work has NOTICE):

- [ ] NOTICE.txt or NOTICE file exists in distribution
- [ ] Includes attribution notices from original NOTICE
- [ ] Added your own attribution notices if applicable
- [ ] NOTICE is in root directory or same location as LICENSE

Example NOTICE File Content:

Project Name
Copyright [year] [Original Copyright Owner]

This product includes software developed by [Original Author/Organization].

[If you made modifications:]
Modifications Copyright 2025 Your Name
- Modified: [brief description]
- Modified: [brief description]

Step 3: Change Documentation (Section 4b)

Requirement: Cause modified files to carry prominent notices stating that you changed the files.

Checklist:

- [ ] All modified files have change notices
- [ ] Change notices are "prominent" (easy to find)
- [ ] Change notices state WHAT was modified
- [ ] Change notices state WHO made modifications
- [ ] Change notices optionally include WHEN

Best Practice - In-File Notice:

# Modified 2025-10-26 by Your Name
# Changes: Added error handling for edge case X

Best Practice - CHANGELOG/CHANGES File:

## Modified 2025-10-26 by Your Name

**Changes made to derivative work:**

1. **Modified file.py** - Added error handling for edge case X
2. **Modified config.py** - Updated default configuration values
3. **Added new_feature.py** - New module for feature Y

**Original work attribution:**
- Source: [original repository URL]
- License: Apache License 2.0
- Copyright: [Original Copyright Owner]

Where to Document:

  • Option 1: Direct in modified files (preferred for few changes)
  • Option 2: CHANGELOG.md or CHANGES.md file (preferred for many changes)
  • Option 3: Both (most comprehensive)

Step 4: Redistribution Compliance (Section 4a)

Requirement: Provide copy of Apache License 2.0 with redistributions.

Checklist:

- [ ] LICENSE file included in source distributions
- [ ] LICENSE file included in binary distributions
- [ ] License reference in file headers (optional but recommended)
- [ ] Documentation mentions Apache License 2.0

Recommended File Header:

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Quick Compliance Check

Run through this quick checklist before releasing derivative work:

Attribution:
- [ ] Original copyright notices retained
- [ ] Original attribution notices retained

Files:
- [ ] LICENSE file present
- [ ] NOTICE file present (if original had one)

Changes:
- [ ] Modified files have change notices
- [ ] CHANGELOG or in-file documentation of changes

Distribution:
- [ ] License included with source distribution
- [ ] License included with binary distribution (if applicable)

Common Scenarios

Scenario 1: Modified a Few Files

  1. Add change notice to each modified file
  2. Retain original copyright in files
  3. Add your copyright for modifications
  4. Ensure LICENSE file is in distribution
  5. Update NOTICE if original had one

Scenario 2: Created Derivative Work (Fork)

  1. Keep original LICENSE file
  2. Keep original NOTICE file
  3. Create CHANGELOG documenting all modifications
  4. Add your copyright for new files
  5. Update README with attribution to original

Scenario 3: Incorporated Apache Code into Your Project

  1. Copy LICENSE file (or merge into yours)
  2. Copy NOTICE file (or merge into yours)
  3. Add attribution to your documentation
  4. Document which parts came from Apache project
  5. Note modifications you made

Validation Commands

# Check LICENSE file exists
test -f LICENSE.txt && echo "✓ LICENSE found" || echo "✗ LICENSE missing"

# Check NOTICE file exists (if applicable)
test -f NOTICE.txt && echo "✓ NOTICE found" || echo "✗ NOTICE missing"

# Check for copyright notices in files
grep -r "Copyright" --include="*.py" --include="*.js" .

# Check for Apache License references
grep -r "Apache License" --include="*.py" --include="*.js" .

Reference Materials

For detailed requirements and examples:

External Resources

Notes

This skill provides guidance only. For legal advice about license compliance, consult a lawyer. When in doubt about compliance, err on the side of over-attribution rather than under-attribution.

Claude SDK Debugging Guide

When to Use This

  • SDK-related errors (Claude Agent SDK, MCP servers)
  • JSON serialization errors involving SDK objects
  • TypedDict mismatch errors
  • SDK internal processing failures
  • MCP server configuration errors

Debugging Strategy

1. Get Full Error Traceback

CRITICAL: User-facing errors don't show root cause. Always check log files.

# Check error logs
tail -50 logs/errors.log

# Grep for specific error
grep "JSON serializable" logs/errors.log | tail -5

# Check recent errors
tail -100 logs/errors.log | grep -A 20 "ERROR"

Why: SDK errors surface deep in internal code. Full tracebacks show:

  • Exact SDK file and line number where error occurred
  • Complete call stack leading to the error
  • Actual vs expected data structures

2. Locate SDK Source Code

Once you have the traceback, find the SDK source file:

# Find SDK files in virtual environment
find .venv/lib -name "subprocess_cli.py" -path "*/claude_agent_sdk/*"

# Or in global Python packages
find /Users/$USER/.local/lib -name "*sdk*"

Read the SDK code at the failure point to understand:

  • What the SDK expects
  • How it processes the data
  • What checks it performs

3. Understand SDK Internal Processing

Example: McpSdkServerConfig Serialization

Error: Object of type Server is not JSON serializable

Traceback shows: subprocess_cli.py:169 - json.dumps({"mcpServers": servers_for_cli})

Read SDK source at line 154-169:

if isinstance(config, dict) and config.get("type") == "sdk":
    # For SDK servers, pass everything except the instance field
    sdk_config = {k: v for k, v in config.items() if k != "instance"}
    servers_for_cli[name] = sdk_config
else:
    servers_for_cli[name] = config

# Line 169: JSON serialization
json.dumps({"mcpServers": servers_for_cli})

Root cause: SDK strips instance field but only if:

  1. config.get("type") == "sdk" (must have type key)
  2. Checking k != "instance" (must use instance key, not server)

4. Common SDK Contracts

McpSdkServerConfig TypedDict
# Correct structure
McpSdkServerConfig(
    type="sdk",        # SDK checks: config.get("type") == "sdk"
    name="server_name", # Server identifier
    instance=server     # SDK strips before JSON: k != "instance"
)

# Wrong - causes JSON serialization error
McpSdkServerConfig(
    server=server,  # Wrong key! SDK can't strip this
    name="name"      # Missing type="sdk"
)

Why it matters:

  • TypedDict is just a dict at runtime - wrong keys don't error immediately
  • Error surfaces later when SDK tries to process it
  • SDK's internal logic depends on exact key names
ClaudeAgentOptions.mcp_servers
# SDK expects dict[str, McpSdkServerConfig | McpStdioServerConfig | ...]
options = ClaudeAgentOptions(
    mcp_servers={
        "server_name": create_sdk_mcp_server(
            name="server_name",
            version="1.0.0",
            tools=[tool1, tool2]
        )
    }
)

5. SDK Bug Fix Checklist

When patching SDK bugs:

  • Fix original bug (e.g., wrong parameter)
  • Match SDK contracts (correct TypedDict keys)
  • Read SDK internal processing (how SDK uses the return value)
  • Test downstream behavior (not just immediate return)
  • Verify no new errors (check logs after fix)
  • Document why (comment referencing SDK source location)
Example: Patching create_sdk_mcp_server
def patched_create_sdk_mcp_server(
    name: str,
    version: str = "1.0.0",  # Bug: SDK passes this to Server() which doesn't accept it
    tools: list[SdkMcpTool] | None = None,
) -> McpSdkServerConfig:
    """Patched version fixing bug #323."""
    from mcp.server import Server

    # FIX 1: Don't pass version to Server.__init__()
    # Original SDK bug: Server(name, version=version)
    server = Server(name)  # Correct: Server only accepts name

    # ... tool registration ...

    # FIX 2: Return with correct TypedDict keys
    # SDK subprocess_cli.py:154-159 expects these exact keys:
    # - type="sdk" for identification
    # - name for server name
    # - instance for Server object (stripped before JSON serialization)
    return McpSdkServerConfig(
        type="sdk",      # SDK checks config.get("type") == "sdk"
        name=name,       # Identifier
        instance=server  # SDK strips: k != "instance"
    )

6. Verification Strategy

After fixing SDK bugs:

# 1. Verify immediate return
result = create_sdk_mcp_server(name="test", tools=[tool1])
assert result["type"] == "sdk"
assert result["name"] == "test"
assert "instance" in result

# 2. Verify SDK processing (simulate SDK's internal logic)
sdk_config = {k: v for k, v in result.items() if k != "instance"}
import json
json.dumps({"mcpServers": {"test": sdk_config}})  # Should not error

# 3. Test full workflow
options = ClaudeAgentOptions(mcp_servers={"test": result})
async with ClaudeSDKClient(options=options) as client:
    # Should successfully connect without JSON serialization errors
    pass

Common Patterns

Pattern 1: TypedDict Mismatch

Symptom: Error occurs in SDK internal code, not at return statement

Cause: Wrong TypedDict keys - runtime doesn't validate, fails downstream

Solution: Read SDK source to find exact keys it expects

Pattern 2: JSON Serialization Errors

Symptom: Object of type X is not JSON serializable

Cause: SDK failed to strip non-serializable fields

Solution:

  1. Check if SDK has stripping logic (like k != "instance")
  2. Verify your keys match SDK's strip conditions
  3. Ensure identification keys are present (like type="sdk")

Pattern 3: SDK Parameter Bugs

Symptom: TypeError: __init__() got unexpected keyword argument

Cause: SDK passes parameters that underlying library doesn't accept

Solution:

  1. Patch to remove unsupported parameters
  2. But also verify SDK's processing still works
  3. Match SDK's expected return structure

Key Takeaways

  1. Always check full tracebacks - User errors hide root cause
  2. Read SDK source - Internal processing reveals requirements
  3. Match exact TypedDict keys - Runtime doesn't validate structure
  4. Test downstream - Fix original bug AND SDK's usage
  5. Document SDK source refs - Future debugging and maintenance

Quick Reference

# Find error in logs
tail -50 logs/errors.log

# Find SDK source
find .venv/lib -name "*subprocess_cli*"

# Verify TypedDict structure
python -c "from claude_agent_sdk import McpSdkServerConfig; print(McpSdkServerConfig.__required_keys__)"

Related

Follow Test-Driven Development (TDD): write tests before code for high-quality, reliable, maintainable software.

The Red-Green-Refactor-Commit Cycle

TDD follows a repetitive four-phase cycle:

1. RED Phase - Writing a Failing Test

  • Write a test for the next bit of functionality you want to add
  • The test should define a specific behavior or functionality that doesn't exist yet
  • The test MUST fail initially - this confirms the test is actually checking something
  • Keep tests simple and focused on a single aspect
  • Think about edge cases and potential bugs before writing code

Guidelines:

  • Each test should focus on ONE specific behavior
  • Use descriptive test names that explain what behavior is being tested
  • Avoid overly intricate tests - start with the simplest test possible
  • Pick tests that are easy to implement and move you closer to your goal

2. GREEN Phase - Making It Pass

  • Write the minimum amount of code necessary to make the test pass
  • Focus solely on functionality, not perfection
  • Don't worry about code quality yet - just make it work
  • Be disciplined: write ONLY enough code to pass the current test

Guidelines:

  • Resist the urge to implement extra features not covered by the test
  • Keep moving forward and gaining confidence
  • If you find yourself writing complex code, your test might be too ambitious

3. REFACTOR Phase - Cleaning It Up

  • Refactor both new and old code to make it well-structured
  • Improve code quality, remove duplication, apply best practices
  • Run linter to catch style issues and maintain code standards
  • CRITICAL: Ensure all tests still pass after refactoring
  • Do NOT change functionality or introduce breaking changes

Guidelines:

  • Apply SOLID principles and design patterns where appropriate
  • Eliminate code duplication (DRY principle)
  • Improve naming, structure, and readability
  • Run make lint or equivalent to fix formatting and style issues
  • NEVER skip this step - it's the most commonly neglected but crucial phase

4. COMMIT Phase - Saving Your Progress

  • MANDATORY: Commit your working code after completing each Red-Green-Refactor cycle
  • Commit messages should describe the behavior you just implemented
  • Keep commits atomic and focused on one feature/behavior
  • All tests MUST be passing before committing

Commit Message Format:

Add: <brief description of new behavior>

- RED: <what test was added>
- GREEN: <what code was implemented>
- REFACTOR: <what improvements were made>

Tests: <number> passing

Example:

Add: configurable default explain query

- RED: Added tests for custom query from config
- GREEN: Implemented get_default_explain_query with config support
- REFACTOR: Added config validation and fallback logic

Tests: 30 passing

Why Commit After Each Cycle:

  • Creates a detailed history of your development process
  • Makes it easy to revert if a future change breaks something
  • Provides checkpoints you can return to
  • Documents your TDD journey for code reviews
  • Prevents losing work if something goes wrong

Core TDD Principles

1. Writing Tests First

Always write the test before the implementation code.

Benefits:

  • Ensures the application is written for testability
  • Guarantees every feature has tests
  • Leads to deeper understanding of requirements early
  • Forces you to think about the API and design before implementation

2. Testing Behavior, Not Implementation

  • Focus on what the code should do, not how it does it
  • Tests should verify observable behavior and outcomes
  • Avoid testing internal implementation details
  • This allows safe refactoring without breaking tests

3. Keeping Tests Small and Focused

  • One test per behavior/requirement
  • Tests should be independent of each other
  • Improves readability, maintainability, and debugging
  • Makes it clear what broke when a test fails

4. Incremental Development

  • Take small steps - one test at a time
  • Build up functionality gradually
  • Each cycle should take minutes, not hours
  • Commit working code after each complete cycle

Best Practices for Modern TDD (2024-2025)

Testing Strategy

  1. Starting with the Simplest Test

    • Begin with basic happy path scenarios
    • Gradually add edge cases and error conditions
    • Build complexity incrementally
  2. Using Meaningful Test Names

    // Bad
    test('test1', ...)
    
    // Good
    test('should return 401 when JWT token is expired', ...)
    test('should calculate total price including tax for multiple items', ...)
    
  3. Avoiding Over-Mocking

    • When every collaborator is mocked, refactors become painful
    • Prefer narrow integration points (seams)
    • Use contract tests that exercise real integrations where practical
    • Mock only external dependencies (APIs, databases, file systems)
  4. Integrating with CI/CD

    • Integrate test suite with development environment
    • Set up continuous integration pipelines to run tests automatically
    • Tests should run on every code change
    • Catch regressions early
  5. Treating Test Coverage as a Guide, Not a Goal

    • High coverage is a side effect of good TDD, not the objective
    • Focus on testing important behaviors
    • 100% coverage doesn't guarantee bug-free code

Code Organization

  1. Separation of Concerns

    • TDD naturally promotes modular, testable code
    • Keep business logic separate from infrastructure
    • Use dependency injection for better testability
  2. Following SOLID Principles

    • Single Responsibility: Each class/function has one reason to change
    • Open/Closed: Open for extension, closed for modification
    • Liskov Substitution: Subtypes must be substitutable
    • Interface Segregation: Many specific interfaces over one general
    • Dependency Inversion: Depend on abstractions, not concretions

Team Collaboration

  1. Reviewing Tests Together

    • Share effective testing techniques
    • Catch bad testing habits early
    • Ensure consistent testing standards across the team
  2. Pair Programming on Complex Features

    • One person writes the test, other writes the code
    • Rotate roles frequently
    • Improves code quality and knowledge sharing

Common Pitfalls to Avoid

Skipping the Refactor Step

The most common TDD mistake. Never neglect refactoring - it keeps code clean and maintainable.

Skipping the Commit Step

Don't forget to commit! Each complete cycle should be saved. Missing commits means losing valuable checkpoints and history.

Writing Tests After Code

This defeats the purpose of TDD. Tests written after are often biased toward the implementation and miss edge cases.

Testing Implementation Details

Tests should verify behavior, not how it's implemented. Implementation-focused tests break during refactoring even when behavior hasn't changed.

Writing Overly Complex Tests

If a test is hard to write, the design might be wrong. Simplify your approach or break down the functionality.

Not Running Tests Frequently

Run tests after every small change. Fast feedback is essential to TDD's effectiveness.

Ignoring Failing Tests

Never commit code with failing tests. Either fix the code or fix the test - don't leave it broken.

Writing Too Much Code at Once

Resist the urge to implement multiple features. Stay disciplined: one test, one minimal implementation, then refactor, then commit.

Practical Implementation Guidelines

When Starting a New Feature

  1. Understanding Requirements Thoroughly

    • Clarify acceptance criteria
    • Identify edge cases
    • Define expected behaviors
  2. Writing Your First Test

    Describe what you're testing
    → Write test that fails
    → Verify it fails for the right reason
    → Implement minimal code
    → Watch test pass
    → Refactor
    → Commit with descriptive message
    
  3. Building Incrementally

    • Add one test at a time
    • Keep all tests passing
    • Commit after each complete Red-Green-Refactor cycle

Test Organization

tests/
├── unit/           # Fast, isolated tests
├── integration/    # Tests with real dependencies
└── e2e/           # End-to-end user scenarios
  • Unit tests: Fast, test single units in isolation
  • Integration tests: Test multiple units working together
  • E2E tests: Test complete user workflows

TDD with Different Approaches

Modern software development often combines methodologies:

  • TDD + BDD: Combine technical tests (TDD) with behavior specifications (BDD)
  • TDD + DDD: Use TDD to implement domain-driven designs
  • TDD + Agile: TDD fits naturally into agile sprints and iterations

Benefits

  • Quality: Bugs caught early, testable code, comprehensive coverage
  • Design: Modular architecture, clear separation, maintainable
  • Confidence: Refactor fearlessly, instant feedback, regression prevention
  • Documentation: Tests document behavior, always up-to-date
  • Git History: Atomic commits, easy tracing, simple reverts
  • Speed (long-term): Less debugging, fewer bugs, easier features

Challenges

  • Learning Curve: Requires discipline, practice, patience
  • More Code: Tests need maintenance too
  • Mindset Shift: Different from traditional development, needs team buy-in
  • Committing: Easy to forget after each cycle, build the habit

Your TDD Workflow Checklist

For every new feature or bug fix:

  • Write a failing test that describes the desired behavior (RED)
  • Run the test and confirm it fails for the right reason
  • Write the minimum code to make the test pass (GREEN)
  • Run the test and confirm it passes
  • Refactor the code while keeping all tests passing (REFACTOR)
  • Run all tests to ensure no regressions
  • Commit your changes with descriptive message (COMMIT)
  • Repeat for the next behavior

Remember

"The act of writing a unit test is more an act of design than verification. It is also more an act of documentation than verification." - Robert C. Martin

TDD is not just about testing - it's a design and development methodology that leads to better software through disciplined practice.

When in doubt: Red → Green → Refactor → Commit → Repeat

Iterating Code

Use for complex, multi-faceted topics requiring deep understanding, abstract/theoretical concepts, historical/academic subjects, or progressive knowledge building where synthesis is the goal.

3-Round Pattern

Round 1: Foundation

  • Goal: Establish baseline understanding
  • Explore: Core concepts, historical context, key figures
  • Focus: Breadth over depth
  • Output: Mental map

Round 2: Deep Dive

  • Goal: Understand relationships and nuances
  • Explore: How concepts relate, perspectives, debates
  • Focus: Connections between Round 1 findings
  • Output: Integrated understanding

Round 3: Synthesis

  • Goal: Advanced understanding, critical evaluation
  • Explore: Implications, contradictions, scholarly debates
  • Focus: Evaluate competing interpretations
  • Output: Sophisticated, multi-layered comprehension

Subagent Coordination

Parallel within rounds:

Round Goal
    ├─→ Agent 1: Aspect A
    ├─→ Agent 2: Aspect B
    └─→ Agent 3: Aspect C
    └─→ Synthesis

Sequential between rounds:

Round 1: Foundation
    ↓ (synthesize)
Round 2: Connections
    ↓ (synthesize)
Round 3: Analysis
    ↓ (final synthesis)
Final Understanding

Example: Chinese Women's History

Round 1 - Foundation:

  • Agent 1: Historical context (Ming-Qing)
  • Agent 2: Confucian patriarchy framework
  • Agent 3: Women's educational access

Round 2 - Connections:

  • Agent 1: Revisionist vs modernization narrative
  • Agent 2: Ko's footbinding & agency reinterpretation
  • Agent 3: Mann's "moral wives" & state ideology

Round 3 - Synthesis:

  • Agent 1: Modernization vs revisionist debate
  • Agent 2: Why "tradition" doesn't explain China's path
  • Agent 3: Implications for patriarchy and agency

Implementation Steps

  1. Define topic and angles

    • Round 1: 3 foundational aspects
    • Round 2: 3 connection/debate aspects
    • Round 3: 3 analytical/critical aspects
  2. Launch Round 1 (parallel agents)

  3. Synthesize Round 1 (patterns, connections)

  4. Launch Round 2 (refined by Round 1)

  5. Synthesize Round 2 (identify gaps)

  6. Launch Round 3 (critical analysis)

  7. Final synthesis (integrate all rounds)

Benefits

  • Progressive complexity (Foundation → Connections → Analysis)
  • Reduced cognitive load (focused rounds)
  • Better retention (step-by-step mental models)
  • Identifies gaps (each round reveals next steps)
  • Parallel efficiency (simultaneous investigation)
  • Synthesis moments (deliberate integration)

Key Principles

  1. Clear round objectives (one goal per round)
  2. Parallel within, sequential between
  3. Synthesize after each round
  4. Refine based on findings
  5. Document connections (Round 1 → 2 → 3)

Tech Stack

Frontend

  • React + TypeScript + Vite
  • Tailwind CSS preferred over plain CSS files
  • Text editor: CodeMirror or TipTap recommended over plain textarea
  • react-markdown for LLM response rendering
  • vitest + @testing-library/react for testing

Backend

  • FastAPI + uv + sse-starlette (for real-time streaming)
  • Use pyproject.toml (modern, consolidates config)
  • CORS: Include all potential dev ports (5173, 5174, 3000) - Vite bounces to alternate ports
  • pytest + pytest-asyncio for testing
  • Ruff for linting

LLM Integration

  • claude-agent-sdk (Anthropic's official agent SDK)
  • Simple HTTP request/response preferred over WebSocket streaming
  • Client-side history management - frontend stores conversation, sends full history, backend stays stateless
  • Models: haiku (speed), opus (quality)

Makefile Conventions

Provide a Makefile with standardized commands:

.PHONY: help serve kill restart test lint

help:  ## Show this help message
	@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-15s\033[0m %s\n", $$1, $$2}'

serve:  ## Start both frontend and backend
	@echo "Starting backend..."
	cd backend && uv run uvicorn main:app --port 8000 &
	@echo "Starting frontend..."
	cd frontend && npm run dev &
	@echo "Services started. Use 'make kill' to stop."

kill:  ## Stop all services
	@pkill -f "uvicorn main:app" 2>/dev/null || true
	@pkill -f "vite" 2>/dev/null || true
	@echo "Services stopped."

restart: kill serve  ## Restart all services

test:  ## Run all tests
	cd backend && uv run pytest
	cd frontend && npm test

lint:  ## Run linters
	cd backend && uv run ruff check .
	cd frontend && npm run lint

Key principles:

  • make help as the default/documented entry point - shows all available commands
  • make serve starts full stack with single command
  • make kill cleanly stops services - no orphan processes
  • Disable hot reload during development - prevents test flakiness
  • Health endpoints return service identification for debugging:
@router.get("/health")
async def health():
    return {"status": "healthy", "service": "your-service-name"}

SDK Gotchas (claude-agent-sdk)

Authentication

  • Local auth works automatically - no API key needed when running locally
  • Don't use raw anthropic.Anthropic() - it requires explicit API key
  • Import: from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage

Two Usage Patterns

Pattern 1: Text-Only Mode (for simple completions)

options = ClaudeAgentOptions(
    model="claude-sonnet-4-20250514",
    system_prompt=system_prompt,
    max_turns=1,
    allowed_tools=[],  # Disables tools, forces text output
)

result_text = ""
async for message in query(prompt=prompt, options=options):
    if isinstance(message, ResultMessage):
        result_text = message.result or ""

Pattern 2: Agent Mode (for file operations, testing, iteration)

options = ClaudeAgentOptions(
    model="claude-sonnet-4-20250514",
    system_prompt=system_prompt,
    max_turns=None,  # Unlimited turns
    cwd=str(working_dir),
    permission_mode="acceptEdits",
    allowed_tools=["Read", "Glob", "Grep", "Write", "Edit", "WebFetch", "Bash"],
    add_dirs=[str(working_dir)],
)

Tool Behavior (CRITICAL)

  • Tools enabled = different output: When tools are available, Claude may USE them rather than OUTPUT text
  • Example: "Create index.html" → Claude writes the file via Write tool, ResultMessage.result is empty
  • To get text output, use allowed_tools=[]
  • To let Claude create files, enable tools + set cwd and permission_mode

Message Type Checking

from claude_agent_sdk import (
    AssistantMessage, ResultMessage,
    TextBlock, ToolUseBlock, ToolResultBlock
)

async for message in query(prompt=prompt, options=options):
    if isinstance(message, AssistantMessage):
        for block in message.content:
            if isinstance(block, ToolUseBlock):
                tool_name = block.name
                tool_input = block.input or {}
            elif isinstance(block, TextBlock):
                text = block.text
    elif isinstance(message, ResultMessage):
        result = message.result

NEVER use attribute-based type checking like block.type == 'tool_use' - fails silently.

General Gotchas

  1. Never break early from async generator - causes cancel scope errors
  2. Consume entire generator even if you have the result
  3. Empty result with tools - If ResultMessage.result is empty, Claude likely completed an action via tools

LLM Output Validation (Early Return Pattern)

When LLM output requires parsing, validate before proceeding:

# Parse structured output from LLM
analysis = await self._analyze_codebase(session_id, path, question)

# Log raw output for debugging
logger.info(
    "Analysis complete",
    session_id=session_id,
    analysis_length=len(analysis),
    analysis_preview=analysis[:500] if analysis else "EMPTY",
)

# Parse and validate
variants = parse_xml_tags(analysis, "variant")

logger.info("Parsed results", num_variants=len(variants))

# CRITICAL: Early return on validation failure
if len(variants) == 0:
    logger.error("No variants found", analysis_output=analysis[:1000])
    await activity_stream.emit(session_id, "session_error",
        "Analysis failed to produce results. Check logs.")
    return LaunchResponse(session_id=session_id, variants=[],
        error="Analysis produced no results")

# Only proceed if validation passed
await activity_stream.emit(session_id, "analysis_complete",
    f"Found {len(variants)} variants")

Key principle: Emit error event, then return early. Never continue a workflow with empty/invalid LLM output.


Parsing Structured LLM Output

When LLMs output structured formats (XML, JSON), use proper parsing libraries:

XML Output - Use ElementTree

DON'T use regex for XML parsing:

# Fragile - breaks on whitespace, special chars, nested tags
for match in re.finditer(r'<(\w+)>(.*?)</\1>', response):
    axis = match.group(1)
    content = match.group(2)

DO use xml.etree.ElementTree:

import xml.etree.ElementTree as ET

# Extract XML block from LLM response (may have surrounding text)
xml_match = re.search(r'<root>(.*?)</root>', response, re.DOTALL)
if not xml_match:
    logger.warning("No XML block found")
    return []

try:
    root = ET.fromstring(f"<wrapper>{xml_match.group(1)}</wrapper>")

    for item in root.findall('item'):
        data = {
            "id": item.get('id'),  # Attributes
            "name": item.findtext('name'),  # Child element text
        }
        # Dynamic child parsing
        for child in item:
            if child.text:
                data[child.tag] = child.text

except ET.ParseError as e:
    logger.warning(f"XML parse error: {e}")
    # Fallback to basic regex if needed

Benefits:

  • Proper tree traversal for nested structures
  • Automatic whitespace handling
  • Clear errors on malformed XML
  • Dynamic element discovery (no hardcoded tag names)

JSON Output

import json

# Clean markdown code blocks if present
clean = response.strip()
if clean.startswith("```"):
    clean = re.sub(r"^```(?:json)?\n?", "", clean)
    clean = re.sub(r"\n?```$", "", clean)

try:
    data = json.loads(clean)
except json.JSONDecodeError as e:
    logger.error(f"JSON parse error: {e}", raw_response=response[:500])
    return None

Key principle: LLMs produce text, not data structures. Always parse with proper libraries, log raw output on failure.


Parallel Agent Operations

When running multiple agents in parallel with asyncio.gather:

results = await asyncio.gather(*build_tasks, return_exceptions=True)

successful = 0
failed = 0
for i, result in enumerate(results):
    if isinstance(result, Exception):
        failed += 1
        logger.error("Build failed", variant_id=variants[i].id,
            error=str(result), error_type=type(result).__name__)
        variants[i].status = "error"
        # CRITICAL: Emit to activity stream so errors are visible
        await activity_stream.emit(session_id, "builder_error",
            f"[{variants[i].id}] Build failed: {str(result)[:200]}",
            details={"error": str(result)})
    else:
        successful += 1
        variants[i] = result

logger.info("All builds completed", successful=successful, failed=failed)

Key principle: Errors in return_exceptions=True are silent by default. Emit them to SSE stream for visibility.


Structured Logging

Use structlog for LLM pipelines:

import structlog

structlog.configure(
    processors=[
        structlog.stdlib.filter_by_level,
        structlog.stdlib.add_log_level,
        structlog.processors.TimeStamper(fmt="iso"),
        structlog.processors.format_exc_info,
        structlog.dev.ConsoleRenderer() if sys.stdout.isatty()
            else structlog.processors.JSONRenderer(),
    ],
    wrapper_class=structlog.stdlib.BoundLogger,
    logger_factory=structlog.stdlib.LoggerFactory(),
)

logger = structlog.get_logger()

What to log:

# Before LLM call
logger.info("Starting analysis", session_id=session_id, question=question[:100])

# After LLM call
logger.info("Analysis complete", result_length=len(result), has_expected_tags="<variant" in result)

# After parsing
logger.info("Parsed results", num_variants=len(variants))

# After parallel operations
logger.info("All builds completed", successful=successful_count, failed=failed_count)

# On errors
logger.error("Build failed", variant_id=variant.id, error=str(e), error_type=type(e).__name__)

Always include context IDs (session_id, variant_id, etc.) for log correlation.


Prompt Management

Store prompts as composable .txt files:

prompts/
├── system.txt          # Base system prompt
├── format.txt          # Output format instructions
├── examples.txt        # Few-shot examples
└── shared/
    └── json-output.txt # Reusable JSON formatting

Principles:

  • Load and compose at request time, not startup - allows changes without restart
  • Wrap chunks in XML tags when composing: <system>...</system>, <format>...</format>
  • Support template variables: {user_input}, {history}
  • Name files by API route where used

Testing Philosophy

  • Test LLM apps end-to-end, not just frontend
  • Verify responses are correct, not just that requests succeed
  • Save logs to ./logs folder for debugging test failures
  • For agent testing: choose 2-3 typical scenarios initially (tokens cost money)
  • Exclude long-running agent tests from normal pytest runs
  • Use Playwright for E2E with network/console capture

Sample .gitignore

# Dependencies
node_modules/
.pnpm-store/

# Build output
dist/
build/
.vite/

# IDE
.idea/
*.swp
.vscode/

# Environment (NEVER commit API keys)
.env
.env.local
.anthropic_key
*.key

# Logs
logs/
*.log

# Testing
coverage/
.pytest_cache/
__pycache__/

# Cache
.eslintcache
.ruff_cache/

# Python
.venv/
venv/
.uv/

# Generated
*.tmp
.annotations/

References

Load these as needed:

  • references/chat-interface.md - Message handling, input behavior, UI/UX patterns for chat applications
  • references/realtime-streaming.md - SSE patterns, early connection, phase-based activity UI
  • references/storage-patterns.md - File-based vs SQL, JSONL for logs, JSON for config
prompt-engineeringprototyperapid-fullstacktesting-webappsuv-debugwriting-scriptsdeveloping-essaysdocumentation-tutorialfetching-imagesiterm-neovim-launcherpedagogical-journeyusing-claudeusing-clisusing-codexusing-github-cliusing-linearusing-nvimusing-screenshotsapplying-stylebuilding-artifactsclearing-outputgenerating-htmloutputting-textplanning-htmlspanish-learningtheming-artifactsvisualizing-subagentswriting-paperswarren-stylecanvas-lmsgenerating-ttsgmail-assistantgoogle-drivemaking-cleareropen-sourcepdftextreflecting-learningssearching-deeplysending-notificationssession-handofftracking-todostranscribe-assemblyaicreating-issues

Agents 105

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

⚠️ CRITICAL: Apache 2.0 License Compliance - READ BEFORE ANY COMMIT

MANDATORY PRE-COMMIT WORKFLOW for ANY modifications to Anthropic-derived skills:

Step 1: Identify if Your Changes Affect Apache 2.0 Licensed Skills

Anthropic-derived skills (Apache 2.0 licensed):

  • skills/building-artifacts/
  • skills/building-mcp/
  • skills/testing-webapps/
  • skills/theming-artifacts/
  • skills/managing-skills/ (derived from Anthropic documentation)

If you modified ANY of these, proceed to Step 2. Otherwise, standard MIT license applies.

Step 2: Update the NOTICE File

BEFORE committing, edit skills/ANTHROPIC_SKILLS_NOTICE:

  1. Locate the "MODIFICATIONS:" section (around line 43)
  2. Add your modification following this format:
MODIFICATIONS:

[Previous modifications...]

Modified by: Fucheng Warren Zhu
Date: [YYYY-MM-DD]

Changes made to [skill-name]:
- [Specific change 1]
- [Specific change 2]
- [Brief description of why the change was needed]

---

Example entry:

Modified by: Fucheng Warren Zhu
Date: 2025-10-21

Changes made to building-artifacts:
- Updated React version in examples from 18.2 to 18.3
- Added TypeScript strict mode examples
- Enhanced template to include Vite configuration

Reason: Updated to current React best practices and added type safety guidance

---

Step 3: Verify License Files Are Present

Ensure these files exist and are unmodified:

  • skills/ANTHROPIC_SKILLS_LICENSE - Full Apache 2.0 license text
  • skills/ANTHROPIC_SKILLS_NOTICE - Attribution and modifications tracking
  • LICENSE - Main MIT license with Apache 2.0 notice

Step 4: Commit with Proper Attribution

Use commit messages that reference the license:

git commit -m "Update building-artifacts skill with React 18.3 examples

Modified Apache 2.0 licensed skill from Anthropic example-skills.
See skills/ANTHROPIC_SKILLS_NOTICE for modification details.
"

Quick Reference: What Requires NOTICE Updates?

✅ YES - Update NOTICE:

  • Modifying skill instructions or content
  • Adding/removing examples in Anthropic skills
  • Changing skill structure or organization
  • Updating references or documentation
  • Any functional changes to skill behavior

❌ NO - No NOTICE update needed:

  • Changes to MIT-licensed skills (using-codex, using-claude, etc.)
  • Changes to snippets system (scripts/, snippets/, hooks/)
  • Changes to templates (unless in Anthropic skills)
  • Documentation updates outside skills directory
  • Test file modifications

Project Overview

Plugin Name: claude-context-orchestrator (formerly claude-code-skills-manager, originally claude-code-snippets-plugin) Version: 3.0.0 Type: Claude Code plugin with hybrid context management (Agent Skills + deterministic snippets) License: Dual-licensed (MIT + Apache 2.0 for Anthropic skills)

This plugin orchestrates two complementary context injection systems:

  1. Agent Skills - Model-invoked capabilities including:

    • Anthropic example-skills (Apache 2.0): building-artifacts, building-mcp, testing-webapps, theming-artifacts, managing-skills
    • Warren's custom skills (MIT): using-codex, using-claude, searching-deeply, making-clearer, managing-snippets
  2. Deterministic Snippets (MIT) - Hook-based pattern matching for reliable, always-on context injection via UserPromptSubmit hook

This hybrid architecture provides both intelligent, on-demand context (skills) and predictable, rule-based context (snippets) working seamlessly together.

Architecture

Core Components

  1. Agent Skills (skills/) - Model-invoked capabilities

    • managing-skills/ - Overall skill management guidance
    • creating-skills/ - Instructions for creating new skills
    • updating-skills/ - Guide for modifying existing skills
    • deleting-skills/ - Safe deletion procedures
    • reading-skills/ - Listing and viewing skills
    • Additional skills: mcp-builder/, theme-factory/, webapp-testing/, artifacts-builder/
  2. Legacy Snippet System (scripts/, hooks/)

    • snippet_injector.py - UserPromptSubmit hook for pattern-based injection
    • snippets_cli.py - CLI for CRUD operations on snippet configs
    • config.json - Base snippet configuration (committed)
    • config.local.json - User-specific overrides (gitignored)
  3. Commands (commands/)

    • Slash commands for snippet management (legacy v1.0 compatibility)
    • Local commands in commands/local/ (user-specific, not in marketplace)
  4. Templates (templates/)

    • Reusable templates for skills (e.g., html/base-template.html)
    • Examples and reference documentation

Configuration System

Layered Configuration:

  • config.json: Base configuration (committed to git)
  • config.local.json: User-specific overrides (gitignored, takes precedence)
  • Config merging priority: base → local → project-specific

Snippet Injection Hook (hooks/hooks.json):

  • Listens to UserPromptSubmit events
  • Matches patterns against user prompts using regex
  • Injects snippet content via additionalContext
  • Supports multi-file snippets with custom separators

Common Development Commands

Testing the Plugin Locally

# Install plugin locally for testing
/plugin marketplace add file:///Users/wz/.claude/plugins/marketplaces/warren-claude-code-plugin-marketplace
/plugin install claude-context-orchestrator@warren-claude-code-plugin-marketplace

# Verify installation
/help | grep -A5 "claude-context-orchestrator"

Managing Snippets via CLI

# Navigate to plugin directory
cd /Users/wz/.claude/plugins/marketplaces/warren-claude-code-plugin-marketplace/claude-context-orchestrator

# List all snippets with statistics
python3 scripts/snippets_cli.py --config scripts/config.json list --show-stats

# Create a new snippet
python3 scripts/snippets_cli.py --config scripts/config.json create my-snippet \
  --pattern "pattern-regex" --content "snippet content"

# Update a snippet
python3 scripts/snippets_cli.py --config scripts/config.json update my-snippet \
  --pattern "new-pattern-regex"

# Delete a snippet (with backup)
python3 scripts/snippets_cli.py --config scripts/config.json delete my-snippet --backup

# Validate snippet configurations
python3 scripts/snippets_cli.py --config scripts/config.json validate

Working with Skills

List all skills:

find skills -name "SKILL.md" | sort

View a skill:

cat skills/managing-skills/SKILL.md

Create a new skill:

mkdir -p skills/my-skill
cat > skills/my-skill/SKILL.md << 'EOF'
---
name: My Skill Name
description: What it does and when to use it (include trigger keywords)
---

# My Skill Name

[Instructions for Claude]
EOF

Test skill activation: Ask Claude a question that matches the skill's description keywords

Running Tests

# Run all tests
python3 -m pytest tests/

# Run unit tests only
python3 -m pytest tests/unit/

# Run integration tests
python3 -m pytest tests/integration/

# Run validation tests
python3 -m pytest tests/validation/

# Run specific test file
python3 -m pytest tests/unit/test_snippet_injector.py -v

Git Workflow with Apache 2.0 Compliance

Standard workflow (for MIT-licensed code):

git add .
git commit -m "Your commit message"
git push

Apache 2.0 workflow (for Anthropic-derived skills):

# 1. Make your changes to an Anthropic skill
vim skills/building-artifacts/SKILL.md

# 2. Update the NOTICE file (CRITICAL!)
vim skills/ANTHROPIC_SKILLS_NOTICE
# Add your modification entry in the MODIFICATIONS section

# 3. Verify license files are present
ls -la skills/ANTHROPIC_SKILLS_LICENSE skills/ANTHROPIC_SKILLS_NOTICE

# 4. Commit with proper attribution
git add skills/building-artifacts/SKILL.md skills/ANTHROPIC_SKILLS_NOTICE
git commit -m "Update building-artifacts skill with [description]

Modified Apache 2.0 licensed skill from Anthropic example-skills.
See skills/ANTHROPIC_SKILLS_NOTICE for modification details.
"
git push

Version Management

# Update plugin version in manifest
vim .claude-plugin/plugin.json
# Change "version" field

# Update marketplace version
cd ..
vim .claude-plugin/marketplace.json
# Change "version" field for claude-context-orchestrator entry

# Update CHANGELOG
vim CHANGELOG.md
# Add new version entry

# Commit version bump
git add .claude-plugin/plugin.json ../.claude-plugin/marketplace.json CHANGELOG.md
git commit -m "Bump version to X.Y.Z"
git tag vX.Y.Z
git push && git push --tags

Development Workflows

Working with Skills

Creating a new skill:

mkdir -p skills/my-skill
cat > skills/my-skill/SKILL.md << 'EOF'
---
name: My Skill Name
description: What it does and when to use it (include trigger keywords)
---

# My Skill Name

[Instructions for Claude]
EOF

Testing a skill: Ask Claude a relevant question that matches the skill's description trigger terms.

Updating a skill: Edit the SKILL.md file directly. No restart needed—skills reload automatically.

Working with Legacy Snippets

Using the CLI directly:

# List all snippets
python3 scripts/snippets_cli.py --config scripts/config.json list --show-stats

# Create a snippet
python3 scripts/snippets_cli.py --config scripts/config.json create my-snippet \
  --pattern "pattern" --content "content"

# Update a snippet
python3 scripts/snippets_cli.py --config scripts/config.json update my-snippet \
  --pattern "new-pattern"

# Delete a snippet
python3 scripts/snippets_cli.py --config scripts/config.json delete my-snippet --backup

Config file locations:

  • Base: scripts/config.json
  • Local: scripts/config.local.json
  • Use --use-base-config flag to modify base config instead of local

Testing the Plugin

Install locally for testing:

# From marketplace root directory
/plugin marketplace add file:///Users/wz/.claude/plugins/marketplaces/warren-claude-code-plugin-marketplace

# Install plugin
/plugin install claude-code-skills-manager@warren-claude-code-plugin-marketplace

# Verify installation
/help | grep -A5 "claude-code-skills-manager"

Important Patterns

Template Pattern for Complex Skills

Skills that need external files (templates, examples) use this pattern:

skills/
└── my-skill/
    ├── SKILL.md                    # Main skill with instructions
    └── reference/
        ├── template.html           # Reusable template
        └── examples.md             # Usage patterns

In SKILL.md, reference files with ${CLAUDE_PLUGIN_ROOT}:

**Template**: `${CLAUDE_PLUGIN_ROOT}/skills/my-skill/reference/template.html`

Verification Hash System

Snippets use verification hashes to track content integrity:

**VERIFICATION_HASH:** `9f2e4a8c6d1b5730`

Hashes are auto-generated and updated by snippets_cli.py when content changes.

Announcement System

Snippets can announce themselves when active:

---
SNIPPET_NAME: my-snippet
ANNOUNCE_USAGE: true
---

The injector adds a meta-instruction that tells Claude to announce active contexts at the start of responses.

Key Files

  • Plugin manifest: .claude-plugin/plugin.json - Defines skills directory
  • Marketplace manifest: ../.claude-plugin/marketplace.json - Lists all plugins
  • Migration guide: MIGRATION_GUIDE.md - v1→v2 upgrade instructions
  • Documentation: docs/ - Comprehensive guides and references

Version Migration (v1.0 → v2.0)

v1.0 (Snippets):

  • Hook-based injection with regex patterns
  • Always-on context loading
  • CLI management tools

v2.0 (Skills):

  • Model-invoked via descriptions
  • Progressive disclosure
  • Native Claude Code integration

Both systems coexist for backward compatibility. The hook system still works for users who need it.

Best Practices

  1. Skills over snippets - Prefer Agent Skills for new functionality
  2. Use ${CLAUDE_PLUGIN_ROOT} - Never hardcode absolute paths
  3. Local config for personal overrides - Don't commit config.local.json
  4. Test before committing - Install locally and verify functionality
  5. Follow template pattern - Separate instructions from reusable templates
  6. Write clear descriptions - Include what, when, and trigger keywords

Common Tasks

Add a new meta-skill to the plugin:

  1. Create skills/new-skill/SKILL.md with YAML frontmatter
  2. Write description with clear trigger terms
  3. Test with relevant queries
  4. Update version in .claude-plugin/plugin.json

Update existing documentation:

  1. Edit CLAUDE.md in the parent directory
  2. Update the modification log at the bottom
  3. Commit with descriptive message

Add a new plugin to the marketplace:

  1. Create plugin directory with .claude-plugin/plugin.json
  2. Add entry to ../.claude-plugin/marketplace.json
  3. Update marketplace version
  4. Test local installation

Resources

Claude Context Orchestrator

Regex-based context injection for Claude Code. Type keywords like SKILL or SNIPPET to automatically load relevant context.

How It Works

When you type a message containing a trigger keyword (e.g., LATEX, ARTIFACT, GMAIL), the hook injects matching content into Claude's context via regex pattern matching on the UserPromptSubmit event.

Two injection types:

  • Skills (skills/) - Procedural guides Claude loads when relevant (model-invoked)
  • Snippets (snippets/) - Pattern-triggered context (hook-based)

Installation

Add Marketplace

/plugin marketplace add file:///path/to/warren-claude-code-plugin-marketplace

Install Marketplace

/plugin install claude-context-orchestrator@warren-claude-code-plugin-marketplace

Browse and Install

Quick Start

Using Keywords

Type trigger words in ALL CAPS to load context:

Help me with GMAIL             → loads gmail-assistant skill
I need to LATEX this document  → loads latex snippet
Build an ARTIFACT for me       → loads artifact builder skill

HTML Test

When a snippet is active, you'll see it in the context:

Active Context

Snippets CLI

The snippets CLI is the key tool for managing pattern-triggered context.

Installation

cd scripts/snippets
make install

Core Commands

snippets                # List all snippets with status
snippets paths          # Show snippet locations
snippets validate       # Check config for errors

Search (Most Important!)

The search command is your primary way to find snippets:

# Search by name, pattern, or description
snippets search gmail           # Find gmail-related snippets
snippets search "output"        # Find output format snippets
snippets search latex           # Find latex snippets

# Search with fuzzy matching (default)
snippets search latx            # Still finds "latex" snippets

# Interactive search
snippets search -i              # Opens interactive picker

Search tips:

  • Searches across name, pattern, description, and file paths
  • Case-insensitive by default
  • Use quotes for multi-word searches: snippets search "code style"

Creating Snippets

# Create from existing markdown file
snippets create my-guide.md snippets/local/category/

# Interactive creation
snippets create -i

Updating Snippets

# Update pattern
snippets update my-snippet --pattern "\\b(NEW|PATTERN)\\b[.,;:!?]?"

# Enable/disable
snippets update my-snippet --enabled false
snippets update my-snippet --enabled true

Listing with Filters

snippets list                   # All snippets
snippets list --enabled         # Only enabled
snippets list --disabled        # Only disabled
snippets list --show-stats      # With statistics

Snippet Creation

Creating a Snippet Manually

  1. Create the content file with YAML frontmatter:

    ---
    name: "My Snippet"
    description: "When to use this"
    ---
    
    Content here...
    
  2. Add pattern to config.local.json:

    {
      "name": "my-snippet",
      "pattern": "\\b(MYSNIPPET|MY_SNIPPET)\\b[.,;:!?]?",
      "snippet": ["snippets/local/category/my-snippet/SNIPPET.md"],
      "enabled": true
    }
    
  3. Test: Type MYSNIPPET in a prompt.

Pattern Format

All patterns follow this format:

\b(PATTERN)\b[.,;:!?]?

Rules:

  • ALL CAPS keywords
  • Word boundaries (\b)
  • Optional punctuation ([.,;:!?]?)
  • Double-escape in JSON: \\b

Examples:

\\b(GMAIL|EMAIL)\\b[.,;:!?]?
\\b(LATEX|LATEXSTYLE)\\b[.,;:!?]?
\\b(BUILD_ARTIFACT|ARTIFACT)\\b[.,;:!?]?

Structure

claude-context-orchestrator/
├── skills/                    # Model-invoked capabilities
│   ├── gmail-assistant/       # Email workflows
│   ├── google-drive/          # Drive file operations
│   ├── building-artifacts/    # HTML artifact builder
│   └── ...
├── snippets/                  # Pattern-triggered context
│   └── local/                 # Personal snippets
│       ├── output-formats/    # Formatting guides
│       ├── documentation/     # Reference material
│       └── ...
├── scripts/
│   └── snippets/              # Snippets CLI
│       ├── config.json        # Base config (committed)
│       └── config.local.json  # Personal config (gitignored)
└── hooks/
    └── hooks.json             # UserPromptSubmit hook

Available Keywords

Here are some commonly used keywords:

KeywordLoadsDescription
GMAILgmail-assistantEmail workflows
GDRIVEgoogle-driveDrive file operations
ARTIFACTbuilding-artifactsHTML artifact creation
LATEXlatex-styleLaTeX document formatting
TDDfollowing-tddTest-driven development
SKILLmanaging-skillsSkill management
SNIPPETmanaging-snippetsSnippet management

Run snippets list for the full list.

License

MIT (Apache 2.0 for Anthropic-derived skills in skills/)

Hope you enjoy!

Snippet Keyword Reference

Auto-generated keyword reference for snippet injection system.

Total Snippets: 51

Quick Reference

KeywordSnippet NameCategory
BUILDART, ARTIFACTbuilding-artifactsSkills
BUILDMCP, MCPbuilding-mcpSkills
CHECK_APACHE, APACHE_COMPLIANCE, APACHEapache-complianceDevelopment
CLEAR, CLEARERclear-outputOutput Formats
CLI, USECLIusing-clisDocumentation
CONDENSEcondenseCommunication
DEEPSEARCHsearching-deeplySkills
DOWNLOADdownload-pdfDocumentation
EDPOST, EDed-postCommunication
ESSAYdeveloping-essaysSkills
FAITHFUL, FAITHFULLYfaithfulOther
GCAL, CALENDARgcalOther
GDRIVE, DRIVEgoogle-driveSkills
GHusing-github-cliDocumentation
GMAIL, MAIL, EMAILgmail-assistantSkills
HTMLGEN, HTMLgenerating-htmlOutput Formats
HTMLPLAN, PLANplan-htmlOutput Formats
IMAGESimagesDocumentation
ISSUEcreate-issueOther
ITER, ITERATEiterate-codeDevelopment
JOURNEYjourneySkills
LATEXSTYLE, LATEXlatex-styleOutput Formats
LINEARlinearDocumentation
LUAluaOther
MANAGESKILL, SKILLmanaging-skillsSkills
MANAGESNIP, SNIPPETmanaging-snippetsSkills
MP, MDPREVIEWmarkdown-previewOutput Formats
NOTIFY, NOTIFnotifyProductivity
NVIM, NEOVIMnvimDocumentation
PAPERpaperOutput Formats
PARAGRAPH, PARAGRAPHS, DENSEparagraphOther
POSTpostCommunication
PROMPT, PROMPTINGprompt-engineeringDevelopment
PROTOTYPE, WEBAPPrapid-fullstackSkills
REFLECTreflecting-learningsSkills
SCREENSHOT, SCREENscreenshot-workflowDocumentation
SCRIPT, SCRIPTSwriting-scriptsSkills
SEARCHCLI, SEARCHsearch-cliOther
SPANISH, ESPANOLspanish-learningOutput Formats
STYLEstyleOutput Formats
SUBAGENT, AGENTSsubagent-vizOutput Formats
TDDtddDevelopment
TEACHREPORTtutoring-reportCommunication
TESTWEB, WEBTESTtesting-webappsSkills
TEXT, TXTtext-outputOutput Formats
THEMEART, THEMEtheming-artifactsSkills
TODO, TASKadd-todoProductivity
TTSgenerating-ttsProductivity
TUTORIALdocumentation-tutorialSkills
USECLAUDE, CLAUDEusing-claudeDocumentation
USECODEX, CODEXusing-codexDocumentation

By Category

Communication

  • CONDENSE: condense
  • EDPOST, ED: ed-post
  • POST: post
  • TEACHREPORT: tutoring-report

Development

  • CHECK_APACHE, APACHE_COMPLIANCE, APACHE: apache-compliance
  • ITER, ITERATE: iterate-code
  • PROMPT, PROMPTING: prompt-engineering
  • TDD: tdd

Documentation

  • DOWNLOAD: download-pdf
  • IMAGES: images
  • LINEAR: linear
  • NVIM, NEOVIM: nvim
  • SCREENSHOT, SCREEN: screenshot-workflow
  • USECLAUDE, CLAUDE: using-claude
  • CLI, USECLI: using-clis
  • USECODEX, CODEX: using-codex
  • GH: using-github-cli

Other

  • ISSUE: create-issue
  • FAITHFUL, FAITHFULLY: faithful
  • GCAL, CALENDAR: gcal
  • LUA: lua
  • PARAGRAPH, PARAGRAPHS, DENSE: paragraph
  • SEARCHCLI, SEARCH: search-cli

Output Formats

  • CLEAR, CLEARER: clear-output
  • HTMLGEN, HTML: generating-html
  • LATEXSTYLE, LATEX: latex-style
  • MP, MDPREVIEW: markdown-preview
  • PAPER: paper
  • HTMLPLAN, PLAN: plan-html
  • SPANISH, ESPANOL: spanish-learning
  • STYLE: style
  • SUBAGENT, AGENTS: subagent-viz
  • TEXT, TXT: text-output

Productivity

  • TODO, TASK: add-todo
  • TTS: generating-tts
  • NOTIFY, NOTIF: notify

Skills

  • BUILDART, ARTIFACT: building-artifacts
  • BUILDMCP, MCP: building-mcp
  • ESSAY: developing-essays
  • TUTORIAL: documentation-tutorial
  • GMAIL, MAIL, EMAIL: gmail-assistant
  • GDRIVE, DRIVE: google-drive
  • JOURNEY: journey
  • MANAGESKILL, SKILL: managing-skills
  • MANAGESNIP, SNIPPET: managing-snippets
  • PROTOTYPE, WEBAPP: rapid-fullstack
  • REFLECT: reflecting-learnings
  • DEEPSEARCH: searching-deeply
  • TESTWEB, WEBTEST: testing-webapps
  • THEMEART, THEME: theming-artifacts
  • SCRIPT, SCRIPTS: writing-scripts

Snippet Injection System Testing

Overview

The snippet injection system automatically injects contextual snippets into Claude's prompts based on keyword matching. This test suite validates the entire system.

Running Tests

cd /Users/wz/.claude/plugins/marketplaces/warren-claude-code-plugin-marketplace/claude-context-orchestrator/scripts/snippets
python3 test_snippets.py

Test Coverage

The test suite runs 5 comprehensive tests:

Test 1: File Existence

  • ✓ Validates all snippet files referenced in config exist
  • ✓ Checks both enabled and disabled snippets
  • ✓ Reports missing files with full paths

Test 2: Regex Pattern Validation

  • ✓ Verifies all regex patterns compile correctly
  • ✓ Tests pattern matching against sample keywords
  • ✓ Validates expected matches for common keywords:
    • SCREENSHOT → screenshot-workflow
    • HTML → generating-html
    • SEARCH → search-cli
    • NVIM → nvim
    • SNIPPET → managing-snippets
    • TODO → add-todo

Test 3: Full Injection Flow

  • ✓ Runs snippet_injector.py with test prompts
  • ✓ Validates JSON output structure
  • ✓ Confirms content injection when keywords present
  • ✓ Confirms no injection when no keywords match

Test 4: Config Merging

  • ✓ Tests multi-config priority system
  • ✓ Validates config.json (priority 0) and config.local.json (priority 100)
  • ✓ Confirms higher priority configs override lower ones

Test 5: Content Loading

  • ✓ Loads actual snippet file content
  • ✓ Validates files are readable and not empty
  • ✓ Reports file sizes for verification
  • ✓ Detects encoding issues

Expected Results

All tests should pass:

Overall: 5/5 tests passed
All tests passed! ✓

Current status:

  • 51 enabled snippets (all working)
  • 3 disabled snippets (test-snippet, override-test, pbcopy)
  • 0 encoding errors

Common Issues

Encoding Errors

If you see UTF-8 codec errors, fix with:

iconv -f ISO-8859-1 -t UTF-8 file.md > file_fixed.md
mv file_fixed.md file.md

Path Resolution Errors

Ensure paths in config are relative to claude-context-orchestrator/:

  • ✓ Correct: snippets/local/... or skills/...
  • ✗ Wrong: ../../snippets/local/...

Pattern Not Matching

Check regex escaping in config.local.json:

  • Use \\b for word boundaries (not \b)
  • Test patterns: python3 -c "import re; print(re.search(r'\\bKEYWORD\\b', 'test KEYWORD here'))"

Configuration Files

  • config.json: Base configuration (priority 0, currently empty)
  • config.local.json: Local overrides (priority 100, active config)
  • snippet_injector.py: Main injection script
  • test_snippets.py: This test suite

Adding New Snippets

  1. Create snippet file in appropriate location:

    mkdir -p snippets/local/category/my-snippet
    vim snippets/local/category/my-snippet/SKILL.md
    
  2. Add mapping to config.local.json:

    {
      "name": "my-snippet",
      "pattern": "\\b(KEYWORD)\\b[.,;:!?]?",
      "snippet": ["snippets/local/category/my-snippet/SKILL.md"],
      "separator": "\n",
      "enabled": true
    }
    
  3. Run tests to validate:

    python3 test_snippets.py
    
  4. Test keyword in actual prompt:

    echo '{"prompt": "KEYWORD test"}' | python3 snippet_injector.py
    

Debugging

Enable verbose output:

# Test specific snippet
echo '{"prompt": "SCREENSHOT test"}' | python3 snippet_injector.py 2>&1 | jq

# Check which snippets match
python3 <<'EOF'
import json, re
from pathlib import Path

config_path = Path("config.local.json")
with open(config_path) as f:
    config = json.load(f)

prompt = "YOUR TEST PROMPT HERE"
for mapping in config["mappings"]:
    if re.search(mapping["pattern"], prompt):
        print(f"Matched: {mapping['name']}")
EOF

Maintenance

Run tests after:

  • Modifying snippet_injector.py
  • Adding/removing snippets
  • Changing regex patterns
  • Moving snippet files
  • Updating config files

CI/CD Integration

To integrate into CI/CD:

# Run tests and exit with proper code
python3 test_snippets.py
if [ $? -eq 0 ]; then
    echo "✓ All snippet tests passed"
else
    echo "✗ Snippet tests failed"
    exit 1
fi

Copy to Clipboard

When user requests copying content to clipboard:

  1. Use pbcopy command - Pipe content directly to clipboard
  2. No confirmation needed - Just execute the command
  3. Format properly - Use heredoc for multi-line content

Pattern

cat << 'EOF' | pbcopy
[content here]
EOF

Examples

Single line:

echo "content" | pbcopy

Multi-line:

cat << 'EOF' | pbcopy
Line 1
Line 2
Line 3
EOF

From variable:

printf "%s" "$content" | pbcopy

Rules

  • Execute immediately without asking
  • Confirm after with brief message: "Copied to clipboard"
  • Use heredoc with 'EOF' to preserve formatting
  • Don't add extra newlines unless requested

REF--- name: GCLOUD description: Google Cloud credentials setup and management for Google Drive/Gmail integration keywords: google, gcloud, credentials, oauth, drive, gmail, api location: /Users/wz/.claude/plugins/marketplaces/warren-claude-code-plugin-marketplace/claude-context-orchestrator/skills/GCLOUD.md

Google Cloud Credentials Setup

How Credentials Were Located

Discovery Process

  1. User mentioned Gmail MCP was already configured

    • Checked Claude Desktop config at /Users/wz/.claude.json
    • Found Gmail MCP server configuration:
    "@gongrzhe/server-gmail-autoauth-mcp": {
      "env": {
        "GMAIL_OAUTH_PATH": "/Users/wz/Desktop/OAuth2/gcp-oauth.keys.json",
        "GMAIL_CREDENTIALS_PATH": "/Users/wz/.gmail-mcp/credentials.json"
      }
    }
    
  2. Located OAuth Credentials

    • Path: /Users/wz/Desktop/OAuth2/gcp-oauth.keys.json
    • Size: 412 bytes
    • Created: Sep 24 16:12
    • Contains: OAuth 2.0 client credentials from Google Cloud Console
  3. Located Stored Token

    • Path: /Users/wz/.gmail-mcp/credentials.json
    • Size: 552 bytes
    • Created: Sep 26 03:44
    • Contains: Authenticated user token (access + refresh tokens)

File Locations

# OAuth Client Credentials (from Google Cloud Console)
/Users/wz/Desktop/OAuth2/gcp-oauth.keys.json

# Authenticated User Token (after OAuth flow)
/Users/wz/.gmail-mcp/credentials.json

# Token for Drive API (auto-created by gdrive_sync.py)
/tmp/token.pickle

Using Credentials for Google Drive

Setup Script

# /tmp/gdrive_sync.py uses these credentials

# 1. Looks for credentials.json (OAuth client config)
CREDENTIALS_FILE = '/tmp/credentials.json'  # Copy of gcp-oauth.keys.json

# 2. Creates/uses token.pickle (authenticated session)
TOKEN_FILE = 'token.pickle'  # Created after first auth

Integration Steps

  1. Copy OAuth credentials to working directory:

    cp /Users/wz/Desktop/OAuth2/gcp-oauth.keys.json /tmp/credentials.json
    
  2. First-time authentication (creates token.pickle):

    cd /tmp
    python3 gdrive_sync.py /path/to/file.md
    # Opens browser → Login to Google → Grant permissions
    # Creates token.pickle for future use
    
  3. Subsequent uses (automatic):

    python3 gdrive_sync.py /path/to/file.md
    # Uses existing token.pickle, no browser needed
    

API Scopes

Gmail MCP Scopes

https://www.googleapis.com/auth/gmail.readonly
https://www.googleapis.com/auth/gmail.send
https://www.googleapis.com/auth/gmail.compose

Drive API Scopes (used by gdrive_sync.py)

https://www.googleapis.com/auth/drive.file

Note: Different scopes = Different tokens needed

  • Gmail token: /Users/wz/.gmail-mcp/credentials.json
  • Drive token: /tmp/token.pickle

Quick Commands

Sync file to Google Drive

python3 /tmp/gdrive_sync.py /path/to/file.md

List files in Google Drive

python3 /tmp/gdrive_sync.py list

Via Flask Server (from browser)

// Click "📤 Sync to Drive" button in editor
// Calls: POST http://localhost:8765/sync-gdrive

Troubleshooting

"credentials.json not found"

cp /Users/wz/Desktop/OAuth2/gcp-oauth.keys.json /tmp/credentials.json

"Token expired"

rm /tmp/token.pickle
python3 /tmp/gdrive_sync.py /path/to/file.md
# Re-authenticates via browser

"Insufficient permissions"

# Token might have wrong scopes
rm /tmp/token.pickle
# Re-auth will request correct scopes

Architecture

User edits in Browser
    ↓
Flask Server (/tmp/skill-server.py)
    ↓
Saves to local file (/tmp/skills/SKILL.md)
    ↓
Calls gdrive_sync.py
    ↓
Uses OAuth credentials (gcp-oauth.keys.json)
    ↓
Google Drive API
    ↓
Uploads to Google Drive (Skills folder)

Files Created

/tmp/
├── credentials.json          # OAuth client config (copied)
├── token.pickle             # Authenticated session
├── gdrive_sync.py           # Sync script
├── skill-server.py          # Flask server with /sync-gdrive endpoint
└── skill-editor-server.html # Editor with "Sync to Drive" button

Success Confirmation

When working correctly, you'll see:

✓ Folder 'Skills' created: <folder_id>
✓ Uploaded: SKILL.md (ID: <file_id>)

Check Google Drive: https://drive.google.com/drive/my-drive

  • Should see "Skills" folder
  • Should see uploaded .md files

References

Skills Directory

This directory contains Agent Skills for Claude Code, organized into two categories:

1. Custom Skills

Custom skills created for this project:

Content Creation

  • documentation-tutorial - Systematically analyze technical documentation and create interactive tutorials with exact quotes, code snippets, and feature demonstrations. Use when developing educational content from API docs, platform guides, or software documentation.

Educational Tools

  • pedagogical-journey - Create structured learning paths and educational progressions
  • using-claude - Guide for using Claude effectively in various contexts

Development & Scripting

  • writing-scripts - Best practices for creating Python and Bash scripts
  • using-clis - Guide for working with command-line interfaces

Media & Content

  • generating-tts - Guide for text-to-speech generation
  • fetching-images - Tools and patterns for retrieving and processing images

Analysis & Research

  • searching-deeply - Deep web search and research methodology
  • reflecting-learnings - Reflection and knowledge synthesis tools
  • using-codex - Advanced code analysis and documentation tools

Artifact Building

  • building-artifacts - Create complex interactive artifacts (React, Vue, etc.)
  • building-mcp - Build Model Context Protocol servers
  • theming-artifacts - Professional theming and styling for artifacts

Management Tools

  • managing-skills - Comprehensive skill management guide
  • managing-snippets - Snippet management and organization

2. Anthropic Example Skills

The following skills are from Anthropic's example-skills repository and are licensed under the Apache License 2.0:

  • testing-webapps - Test local web applications using Playwright

License Attribution

All Anthropic skills are licensed under the Apache License 2.0. See:

  • ANTHROPIC_SKILLS_LICENSE - Full Apache 2.0 license text
  • ANTHROPIC_SKILLS_NOTICE - Attribution and modification details

Usage

These skills are automatically loaded when the claude-code-skills-manager plugin is installed. You can use any skill by mentioning it in your request to Claude Code.

Example:

Use the mcp-builder skill to help me create an MCP server for GitHub API integration

Original Source

Anthropic skills copied from: https://github.com/anthropics/skills

Modifications

Skills have been integrated into this plugin structure without modifications to their functionality. The only changes are organizational (directory structure) to fit the Claude Code plugin system.

Codex Subagent

Use OpenAI Codex (gpt-5.3-codex) as a subagent for hard infrastructure bugs and complex debugging tasks.

When to Use

  • Hard infrastructure bugs Opus isn't solving
  • Complex multi-file debugging
  • When you need a second opinion from a different model
  • Robust backend/infra code that needs extra reasoning

Configuration

MCP servers configured in ~/.mcp.json:

  • codex — gpt-5.3-codex with high reasoning effort
  • codex-xhigh — gpt-5.3-codex with xhigh reasoning effort (more thorough)

Async Pattern

For long-running Codex tasks, use the async wrapper:

# Start a task in background
~/.claude/scripts/codex-async.sh start <task_id> "<prompt>" [high|xhigh]

# Check if done
~/.claude/scripts/codex-async.sh check <task_id>

# Wait for result (blocking)
~/.claude/scripts/codex-async.sh wait <task_id> [timeout_seconds]

# Get output
~/.claude/scripts/codex-async.sh output <task_id>

# List all tasks
~/.claude/scripts/codex-async.sh list

# Clean up
~/.claude/scripts/codex-async.sh clean

Example Usage

Via MCP (if available)

When MCP is connected, Codex tools will appear. Use them for:

  • File editing
  • Code generation
  • Debugging

Via Async Script (recommended for long tasks)

# Start Codex investigating a bug
~/.claude/scripts/codex-async.sh start bug-123 "Investigate why the MySQL connection pool is exhausting. Check src/sql/executor.ts and related files. The error is: Connection timeout after 30s" xhigh

# Meanwhile, do other work...

# Check status
~/.claude/scripts/codex-async.sh check bug-123

# Get result when done
~/.claude/scripts/codex-async.sh output bug-123

Codex vs Opus

AspectCodex 5.3Opus 4.5
Best forRobust infra code, hard bugsSmooth UX, taste, creativity
Reasoningxhigh = very thoroughExtended thinking
VerbosityLess verboseMore verbose
SpeedSlower at xhighFaster

Tips

  1. Use xhigh for hard bugs — worth the extra time
  2. Provide context — include file paths and error messages
  3. Let it work — Codex benefits from longer reasoning time
  4. Check periodically — use async pattern for long tasks

Codex CLI

Automate code, bash scripting, web research with clean output.

Install

npm install -g @openai/codex
codex --version

Config

~/.codex/config.toml:

model = "gpt-5-codex"
model_reasoning_effort = "high"
approval_policy = "never"
sandbox_mode = "workspace-write"
web_search = true

Commands

Interactive: Real-time development

codex "Create a Python REST API"

Exec: Automation

codex exec "Task" --full-auto

Bash Scripting

Basic

#!/bin/bash
set -euo pipefail

cd /tmp/project
git init && git config user.email "bot@example.com" && git config user.name "Bot"

codex exec "Your task" --full-auto

With Clean Output

codex exec "Your task" --full-auto --output-last-message /tmp/result.txt
cat /tmp/result.txt

Idempotent

#!/bin/bash
set -euo pipefail

log() { printf '[%s] %s\n' "$(date +%H:%M:%S)" "$*"; }
ensure_tool() { command -v "$1" >/dev/null || { log "install $1"; exit 1; }; }

case "${1:-help}" in
  bootstrap)
    ensure_tool jq
    [[ -f .ready ]] || { ./setup.sh && touch .ready; }
    ;;
  ci)
    for step in lint test build; do
      log "running $step"
      ./scripts/$step.sh || exit 1
    done
    ;;
  watch)
    ensure_tool entr
    find src -type f | entr -r bash -lc './scripts/test.sh'
    ;;
  *)
    printf 'usage: %s {bootstrap|ci|watch}\n' "$0" >&2; exit 64
    ;;
esac

Git Checkpoint

#!/bin/bash
set -euo pipefail

git add . && git commit -m "Before Codex" || true

codex exec "Run tests and fix failures" --full-auto || {
  git reset --hard HEAD~1
  exit 1
}

git add . && git commit -m "Codex: Fixed" || true

Batch

#!/bin/bash
for project in project1 project2 project3; do
  (
    cd "$project"
    git init && git config user.email "bot@example.com" && git config user.name "Bot" || true

    if codex exec "Update dependencies" --full-auto; then
      git add . && git commit -m "Updated" --allow-empty || true
      echo "✓ $project"
    else
      git reset --hard HEAD~1
      echo "✗ $project"
    fi
  )
done

Web Search

Enable with -c web_search=true.

Research with JSON

#!/bin/bash
cd /tmp/research
git init && git config user.email "bot@example.com"

task="Find top 3 bash patterns. Return ONLY valid JSON with: pattern, description, code_example."

codex exec "$task" \
  -c web_search=true \
  --full-auto \
  --output-last-message /tmp/result.json

cat /tmp/result.json | jq .

View Searches

codex exec "Research bash best practices" \
  -c web_search=true \
  --full-auto \
  --json 2>/dev/null | \
  jq -r 'select(.type=="web_search") | .item.query'

View Reasoning

codex exec "Research X" \
  -c web_search=true \
  --full-auto \
  --json 2>/dev/null | \
  jq -r 'select(.type=="reasoning") | .item.text'

Output Control

--output-last-message FILE - Writes final answer to FILE only.

codex exec "Task" --full-auto --output-last-message /tmp/answer.txt
cat /tmp/answer.txt

Result:

  • FILE: Clean plaintext answer
  • STDOUT: 5 lines metadata
  • STDERR: Empty

--json - JSONL events: thread.started, turn.started, reasoning, web_search, agent_message, turn.completed.

codex exec "Task" --full-auto --json 2>/dev/null | jq '.type' | sort | uniq -c

Suppress console: Redirect to /dev/null

codex exec "Task" --full-auto --output-last-message /tmp/answer.txt >/dev/null 2>&1
cat /tmp/answer.txt

Save audit log + clean output:

codex exec "Task" --full-auto \
  --output-last-message /tmp/answer.txt \
  --json >/tmp/audit.jsonl 2>&1
cat /tmp/answer.txt

Python

Simple

import subprocess

result = subprocess.run(
    ['codex', 'exec', 'Create test module', '--full-auto'],
    cwd='/tmp/project',
    capture_output=True,
    text=True
)

print(result.stdout)

Wrapper

from dataclasses import dataclass
from typing import Optional
import subprocess
import os

@dataclass
class CodexResult:
    returncode: int
    stdout: str
    stderr: str
    task: str

    @property
    def success(self) -> bool:
        return self.returncode == 0

class CodexCLI:
    def __init__(self, model="gpt-5-codex", web_search=False):
        self.model = model
        self.web_search = web_search

    def execute(self, task: str, cwd: Optional[str] = None) -> CodexResult:
        output_file = f"/tmp/codex-{os.urandom(4).hex()}.txt"

        cmd = [
            'codex', 'exec', task,
            '--full-auto',
            '-m', self.model,
            '--output-last-message', output_file
        ]

        if self.web_search:
            cmd.extend(['-c', 'web_search=true'])

        result = subprocess.run(
            cmd,
            cwd=cwd or os.getcwd(),
            capture_output=True,
            text=True
        )

        try:
            with open(output_file) as f:
                output = f.read()
            os.unlink(output_file)
        except:
            output = result.stdout

        return CodexResult(
            returncode=result.returncode,
            stdout=output,
            stderr=result.stderr,
            task=task
        )

# Usage
codex = CodexCLI(web_search=True)
result = codex.execute("Research X")
print(result.stdout)

Flags

FlagPurpose
--full-autoAuto-approve, workspace-write sandbox
-c web_search=trueEnable web search
--output-last-message FILEWrite final answer to FILE
--jsonStream JSONL events
-m, --modelgpt-5 (fast), gpt-5-codex (code), o3 (powerful)
-C, --cdWorking directory

Patterns

Research + JSON

codex exec "Find X. Return JSON with: pattern, description, code." \
  -c web_search=true --full-auto --output-last-message /tmp/result.json

Batch docs

for module in auth utils data; do
  codex exec "Generate API docs for $module.py" \
    --full-auto --output-last-message "/tmp/${module}_docs.md"
done

Research → Generate → Commit

codex exec "Research Python testing best practices 2025" \
  -c web_search=true --full-auto --output-last-message /tmp/research.txt

codex exec "Using this research, generate test suite for module.py" --full-auto

git add . && git commit -m "Generated tests from latest best practices"

Performance

TaskTimeSuccess
Simple30-60s99%+
Web search60-120s95%+
Complex120+s90%+

Models:

  • gpt-5: Fast, cheap
  • gpt-5-codex: Default, code-optimized
  • o3: Powerful, slow

Security

Safe:

  • workspace-write sandbox (default)
  • Git checkpoints before Codex
  • Validate generated code

Avoid:

  • danger-full-access without external sandboxing
  • Running without git checkpoints
  • Web search on untrusted domains

Troubleshooting

ProblemSolution
codex not foundnpm install -g @openai/codex
Not in trusted directorygit init in working directory
Web search returns nothingRephrase as task ("Find X"), not question
Too much outputUse --output-last-message FILE
Can't parse outputUse --json with jq
Auth failedcodex login or set OPENAI_API_KEY

Quick Reference

# Basic
codex exec "Task" --full-auto

# Web search
codex exec "Research X" -c web_search=true --full-auto

# Clean output
codex exec "Task" --full-auto --output-last-message /tmp/out.txt

# View searches
codex exec "Task" -c web_search=true --full-auto --json 2>/dev/null | \
  jq -r 'select(.type=="web_search") | .item.query'

# Token usage
codex exec "Task" --full-auto --json 2>/dev/null | \
  jq 'select(.type=="turn.completed") | .usage'

# Different model
codex exec "Task" -m o3 --full-auto

# Specific directory
codex exec "Task" -C /path/to/project --full-auto

ASCII Diagram Best Practices

Essential principles for effective ASCII diagrams based on 2024 research analyzing 507 real-world diagrams.

Core Requirements

Monospace font mandatory - 2:1 aspect ratio ensures vertical/horizontal alignment <72 character width - Prevents cutoff in plaintext rendering (emails, terminals, code comments) Grid-based alignment - Each character occupies same space

Character Selection

Maximum Compatibility (Basic ASCII)

Borders:       | - +
Corners:       + (sharp)  / \ (round)
Arrows:        < > ^ v
Connections:   + (junction)
Dashed:        : (vertical)  = (horizontal)

Enhanced (Unicode Box Drawing)

Borders:       ┌ ┐ └ ┘ ─ │
Junctions:     ├ ┤ ┬ ┴ ┼
Double:        ═ ║ ╔ ╗ ╚ ╝
Arrows:        ← ↑ → ↓ ↔

Rule: Use basic ASCII for maximum compatibility (code comments, email). Use Unicode for modern documentation.

Common Patterns

Box Structures

Simple:           Rounded:          Double:
+-------+         /-------\         ╔═══════╗
| Title |         | Title |         ║ Title ║
+-------+         \-------/         ╚═══════╝

Connections

Arrows:           Trees:            Flow:
A ---> B          root              Start
                  ├── child1          ↓
A <--- B          └── child2        Process
                                      ↓
A <--> B                            End

Tables

+------+--------+----------+
| Col1 | Col2   | Col3     |
+------+--------+----------+
| A    | Data   | Value    |
| B    | More   | Another  |
+------+--------+----------+

Nested/Hierarchical

+-------------------------+
| Container               |
| +-----+    +----------+ |
| | Box |    | Another  | |
| +-----+    +----------+ |
+-------------------------+

Flowchart Example

    Start
      |
      v
+----------+
| Process  |
+----------+
      |
      v
   <Decision>  --No--> End
      |
     Yes
      |
      v
   Action

DITAA Enhancements

When using DITAA (DIagrams Through Ascii Art):

Shape tags (inside boxes):

  • {d} - Document shape
  • {s} - Storage/cylinder
  • {io} - Input/output parallelogram

Special features:

  • Use / and \ for round corners
  • Bullet points: o Item name (space before o)
  • Color codes: cRGB hex notation (e.g., cF00 for red)
/---------\
| cGRE    |
| Success |
\---------/

Layout Principles

Spacing:

  • One space padding inside boxes
  • Two spaces between adjacent elements
  • Align vertically using columns

Alignment:

Good:                Bad:
+---+  +---+        +---+  +---+
| A |  | B |        |A|  |B|
+---+  +---+        +---+  +---+

Line connections:

Sharp turns:         Smooth transitions:
A ---+               A ---\
     |                    |
     +---> B               \---> B

Common Mistakes

❌ Using proportional fonts (renders misaligned) ❌ Exceeding 72 characters (breaks in plaintext) ❌ Inconsistent spacing (hard to read) ❌ Missing alignment (looks unprofessional) ❌ Over-complexity (defeats purpose)

✅ Test in actual rendering environment ✅ Keep simple and focused ✅ Use consistent character styles ✅ Add labels/legend when needed ✅ Align elements on grid

Tools

Online editors:

  • ASCIIFlow - Interactive web-based editor
  • Textik - Quick ASCII charts
  • Markdeep - Render ASCII as SVG

Command-line:

  • DITAA - Convert ASCII to PNG/SVG
  • Graph-Easy - Generate from descriptions
  • PlantUML - UML to ASCII

Workflow: Generate with tools → Hand-tune alignment → Version control with code

Example: System Architecture

+------------+         +-------------+
| Frontend   |-------->| API Gateway |
| (React)    |<--------| (Node.js)   |
+------------+         +-------------+
                              |
                              v
                     +----------------+
                     | Database       |
                     | (PostgreSQL)   |
                     +----------------+

Quick Reference

ElementASCIIUnicodeUse Case
Horizontal-─Borders, connections
Vertical|│Borders, connections
Corner+┌┐└┘Box corners
Junction+├┤┬┴┼Line intersections
Arrow right>→Directional flow
Arrow downv↓Vertical flow
Dashed horiz=┄Optional/weak connection
Dashed vert:┊Optional/weak connection

Context-Specific Tips

In code comments: Use basic ASCII, keep <70 chars, test in actual IDE In Markdown: Can use Unicode, consider code fences with syntax highlighting In emails: Basic ASCII only, assume 72-char width limit In documentation: Use DITAA or similar tools for professional rendering

Condensing Content

Apply these principles when asked to CONDENSE information.

Core Condensing Principles

  1. Many examples ’ Fewer representative examples

    • Keep 1-2 illustrative examples instead of 5-10
    • Choose examples that demonstrate key concepts
    • Remove redundant or similar examples
  2. Elaborate workflows ’ General principles

    • Extract the underlying principles from step-by-step instructions
    • Keep detailed workflows only when steps are absolutely necessary
    • Convert "how to do X" into "key things to know about X"
  3. Remove redundancy

    • Eliminate repetitive explanations
    • Merge similar sections
    • Say things once, clearly
  4. Focus on essential information

    • Preserve critical details and requirements
    • Remove verbose explanations and qualifiers
    • Keep the "what" and "why", reduce the "how" (unless necessary)
  5. Command reference over tutorials

    • List commands with brief inline comments
    • Group related commands together
    • Remove lengthy setup/context sections

When to Condense

Apply condensing to:

  • Long documentation with many examples
  • Verbose workflow specifications
  • Skills/snippets with excessive detail
  • Tutorial-style content that should be reference-style
  • Repeated explanations across sections

What to Preserve

DO NOT condense:

  • Critical warnings or safety information
  • Unique examples that demonstrate different concepts
  • Essential steps in sequential workflows
  • Configuration requirements or syntax rules
  • Error messages and troubleshooting info

Before/After Example

Before (verbose):

### Step 1: Search for Past Emails

Before drafting ANY email, search past correspondence:

```bash
# Search emails to a specific person
gmail search "to:recipient@example.com" --max 10

# Search emails from a specific person
gmail search "from:recipient@example.com" --max 10

# Search recent thread about a topic
gmail search "subject:project-name after:2024/10/01"

When to use each search:

  • Before replying: Use gmail search "from:sender@example.com" to understand their style
  • Before composing: Use gmail search "to:recipient@example.com" to match Warren's past style with them
  • For context: Use gmail search "subject:keyword" to find related emails

**After (condensed):**
```markdown
### Search Commands
```bash
gmail search "to:person@example.com" --max 10      # Emails to someone
gmail search "from:person@example.com" --max 10    # Emails from someone
gmail search "subject:keyword after:2024/10/01"    # By subject + date

Before composing: Search past emails to extract patterns (greeting, tone, sign-off)


## Quick Checklist

When condensing, ask:
- [ ] Can multiple examples be reduced to one representative example?
- [ ] Can step-by-step workflows become general principles?
- [ ] Are there repeated explanations that can be merged?
- [ ] Can commands be listed with inline comments instead of lengthy descriptions?
- [ ] Are there sections that explain "how" when only "what" is needed?
- [ ] Have I preserved all critical warnings and requirements?

## Output Format

After condensing:
- Commands grouped by category with inline comments
- Principles stated clearly and concisely
- 1-2 examples maximum (only if needed for clarity)
- "Key things to know" section instead of extensive workflows
- References to detailed docs when available

Analytical Essays

Rules for essays analyzing external topics: literary analysis, historical analysis, argumentative essays, research papers.

Core principle: Analytical essays answer "what does this mean?" Every claim requires evidence and interpretation.


Phased Framework Methodology

Why Use Phases

Complex analytical essays benefit from organizing arguments into temporal or thematic phases. This prevents chronological dump and forces causal connections between sections.

Common phase structures:

  • Historical: Revolution → Reaction → Reform
  • Literary: Setup → Complication → Resolution
  • Argumentative: Problem → Analysis → Implications
  • Biographical: Conditions → Actions → Consequences

Phase Planning Process

Step 1: Identify the core thesis as a transformation or explanation

  • BAD: "Jiang Qing was vilified after Mao's death"
  • GOOD: "Jiang Qing's vilification functioned as a political mechanism enabling the CCP's post-Mao transition"

Step 2: Map phases to thesis components

PhaseThesis ComponentGuiding Question
Phase 1 (e.g., Revolution)ConditionsWhat created the situation?
Phase 2 (e.g., Reaction)MechanismHow did the transformation occur?
Phase 3 (e.g., Reform)OutcomeWhat did this enable?

Step 3: Assign paragraphs to phases with specific claims

Example (Jiang Qing essay):

PhaseParagraphsContent
REVOLUTIONP1-P3Conditions creating outsider status (actress background, Confucian gender norms, early isolation)
REVOLUTIONP4-P5Mao's strategic deployment (feminized cultural work, personal backing, dependent power)
REACTIONP6-P7Post-1976 scapegoating (swift arrest, gender stereotypes, trial as symbolic cleansing)
REFORMP8Enabling ideological shift (political space for pragmatism, dismantling class-struggle politics)

Critical Argument Linkage

The Linkage Rule

Rule: Each paragraph must explicitly answer: How does this detail explain the thesis specifically?

Elaboration: Every piece of evidence should connect back to your central claim. If a detail is interesting but doesn't explain your thesis, cut it or make the connection explicit.

Test: After each paragraph, ask: "How does this explain why [X]—specifically—became [Y]?" If you can't answer, the paragraph lacks linkage.

Example (Jiang Qing essay):

  • WITHOUT LINKAGE: "Her actress background conflicted with CCP discipline norms."
  • WITH LINKAGE: "Her actress background conflicted with CCP discipline norms, marking her as an outsider whose power could later be revoked without threatening party legitimacy—precisely what made her available as scapegoat."

Linkage Templates

Use these patterns to ensure each paragraph connects to thesis:

  1. Condition → Consequence: "[Detail] created conditions that later enabled [thesis element]"
  2. Evidence → Interpretation: "[Fact] reveals [thesis-relevant insight]"
  3. Counterpoint → Resolution: "Although [apparent contradiction], this actually supports [thesis] because..."

Core Rules

A1: Background vs. Analysis Distinction

Rule: Distinguish between background (established facts) and analysis (your interpretation). Test: "Is this my argument or common knowledge?"

Elaboration: Background provides context; analysis provides insight. An essay that's all background fails to argue anything. An essay that's all analysis lacks grounding.

Example:

  • BACKGROUND: "The An Lushan Rebellion occurred in 755-763 CE and devastated Tang Dynasty society"
  • ANALYSIS: "The Snail Girl story reflects post-rebellion anxiety about domestic stability—the fantasy of a self-sufficient household responds to real fears of economic collapse"

A2: Evidence Triple

Rule: Every claim needs three components: (1) textual evidence, (2) contextual support, (3) logical connection.

Elaboration:

  • Textual evidence = what the text says
  • Contextual support = historical/cultural framework
  • Logical connection = how evidence supports claim

Example:

  • CLAIM WITHOUT EVIDENCE: "Snail Girl served a purpose after the An Lushan rebellion"
  • CLAIM WITH TRIPLE:
    • TEXTUAL: "The story emphasizes the Snail Girl's domestic labor—cooking, cleaning, weaving"
    • CONTEXTUAL: "Post-rebellion Tang society saw increased anxiety about household stability, evidenced by [source]"
    • CONNECTION: "The Snail Girl fantasy addresses this anxiety by imagining a wife who requires no resources but produces abundance"

A3: Interpretation Before Evidence

Rule: State your interpretation, then provide evidence. Don't bury your argument after lengthy quotations.

Elaboration: Lead with what you're arguing, then show why. Readers need the interpretive frame before the evidence makes sense.

Example:

  • WEAK: "[Long quotation from text]... This shows that the author was concerned with X"
  • STRONG: "The author's central concern is X. This emerges in [specific passage], where [brief quotation] demonstrates [connection to claim]"

A4: Quotation Integration

Rule: Quotations must be integrated into your sentences, not dropped in isolation.

Elaboration: A quotation without framing forces readers to interpret it themselves. Your job is to tell them what to see.

Example:

  • DROPPED: The text says, "She vanished into the shell." This is important.
  • INTEGRATED: When the Snail Girl "vanished into the shell," she enacts the very disappearance that defines her value—present only as labor, never as person.

A5: Counterargument Engagement

Rule: Address the strongest objection to your argument. Ignoring counterarguments weakens your position.

Elaboration: Acknowledge what might challenge your reading, then explain why your interpretation holds despite it.

Example:

  • NO COUNTERARGUMENT: "The Snail Girl represents domestic fantasy"
  • WITH COUNTERARGUMENT: "One might argue the Snail Girl represents divine reward for virtue rather than domestic fantasy. However, the story's emphasis on her labor—not her divinity—and the protagonist's attempt to trap her suggest the fantasy is economic, not spiritual"

A6: Thesis Specificity

Rule: Thesis must be arguable and specific. If no reasonable person would disagree, it's not a thesis.

Elaboration: "X is important" is not a thesis. "X reveals Y about Z" is a thesis.

Example:

  • NOT ARGUABLE: "Food plays a role in the Snail Girl story"
  • ARGUABLE: "Food in the Snail Girl story functions as currency for emotional labor—the protagonist's attempt to trap the Snail Girl is an attempt to convert infinite domestic production into permanent possession"

A7: Paragraph Unity

Rule: Each paragraph argues ONE point. Topic sentence states the point; everything else supports it.

Elaboration: If a paragraph makes multiple points, split it. If a sentence doesn't support the topic sentence, move or cut it.

Example:

  • UNFOCUSED: [Paragraph discusses both the Snail Girl's labor AND the protagonist's loneliness AND the story's ending]
  • FOCUSED: [Paragraph 1: The Snail Girl's labor represents impossible abundance] [Paragraph 2: The protagonist's loneliness motivates his transgression] [Paragraph 3: The ending's ambiguity reflects...]

A8: So What? Test

Rule: After every analytical point, answer: "So what? Why does this matter for the text's meaning?"

Elaboration: Observations without significance are just description. Analysis requires connecting observation to meaning.

Example:

  • OBSERVATION: "The Snail Girl is described as beautiful"
  • SO WHAT?: "Her beauty combined with her labor marks her as fantasy object rather than realistic character—she exists to fulfill, not to want"

Structure Rules

AS1: Introduction Pattern

Rule: Introduction moves from context → puzzle → thesis → roadmap.

Elaboration:

  • Context: What does reader need to know?
  • Puzzle: What's surprising, contradictory, or unexplained?
  • Thesis: Your answer to the puzzle
  • Roadmap: How you'll argue it (optional for short essays)

Example:

  • CONTEXT: "The Snail Girl story appears in multiple Tang Dynasty collections"
  • PUZZLE: "Despite its fairy-tale structure, the story centers on labor rather than love—the Snail Girl never speaks, only works"
  • THESIS: "This silence reveals the story's true subject: the fantasy of inexhaustible domestic production"
  • ROADMAP: "I argue this through analysis of the labor descriptions, the protagonist's transgression, and the story's unresolved ending"

AS2: Body Paragraph Pattern

Rule: Each body paragraph follows: claim → evidence → analysis → connection to thesis.

Elaboration: Don't end paragraphs with quotations or evidence. End with analysis that links back to your main argument.

Example:

  • CLAIM: "The Snail Girl's labor is described in terms of abundance, not effort"
  • EVIDENCE: "The text lists 'rice, fish, meat, vegetables' appearing without any description of cooking"
  • ANALYSIS: "This erasure of process—food appears, fully prepared—transforms labor into magic, effort into gift"
  • CONNECTION: "This magical labor is precisely what makes the Snail Girl a fantasy object: she produces without cost"

AS3: Conclusion Pattern

Rule: Conclusion moves from summary → implications → broader significance.

Elaboration: Don't just repeat thesis. Show what follows from your argument—what does this tell us about the genre, period, or larger question?

Example:

  • SUMMARY: "The Snail Girl story is not a love story but a labor fantasy"
  • IMPLICATIONS: "This reading explains the story's anxious ending—once labor is revealed as person, the fantasy collapses"
  • BROADER SIGNIFICANCE: "Tang Dynasty domestic fantasies may tell us more about economic anxiety than romantic ideals"

Common Problems

Problem: Summary Instead of Analysis

Symptom: Essay retells plot or describes what happens without interpreting meaning.

Fix: After every descriptive sentence, add: "This suggests..." or "This reveals..."

Example:

  • SUMMARY: "The protagonist discovers the Snail Girl cooking. He hides and watches her. She transforms into a woman."
  • ANALYSIS: "The protagonist's surveillance—hiding to watch—establishes the power dynamic that defines their relationship: she is object of his gaze before she is person"

Problem: Floating Quotations

Symptom: Quotations appear without introduction or integration.

Fix: Use signal phrases and explain relevance.

Example:

  • FLOATING: "She vanished into the shell." This is significant.
  • INTEGRATED: The Snail Girl's disappearance—"she vanished into the shell"—literalizes her function: she exists only when producing, invisible otherwise.

Problem: Claim Without Stakes

Symptom: Argument is technically correct but reader wonders "so what?"

Fix: Explicitly state why this matters for understanding the text/period/question.

Example:

  • NO STAKES: "The story uses food imagery"
  • WITH STAKES: "The story's food imagery is not decorative but structural—it defines the Snail Girl's value and the protagonist's transgression"

Paragraph-by-Paragraph Planning

Planning Table Method

Before drafting, create a planning table mapping each paragraph to your argument structure:

P#PhaseClaimEvidence NeededThesis Linkage
1Setup[Specific claim][Source/quote][How this explains thesis]
2Setup[Specific claim][Source/quote][How this explains thesis]
...............

Paragraph Independence Test

Each paragraph should:

  1. Make ONE clear claim (stated in topic sentence)
  2. Provide evidence for that claim
  3. Analyze the evidence (not just present it)
  4. Connect explicitly to thesis
  5. Transition to next paragraph's claim

Test: Can someone read just your topic sentences and understand your argument's structure?


Primary Sources and Citations

A11: Primary Source Requirement

Rule: Every analytical essay needs primary source engagement—direct evidence from the object of analysis.

Elaboration: Secondary sources provide context and scholarly conversation. Primary sources provide the actual evidence for your claims. An essay without primary sources is speculation.

For historical essays: Government documents, speeches, contemporary accounts, visual sources For literary essays: Direct quotations from the text being analyzed For social analysis: Interviews, survey data, firsthand observations

A12: Annotated Evidence

Rule: When revising, maintain an evidence inventory—a list of all primary sources cited and where they appear.

Elaboration: This helps identify:

  • Paragraphs lacking primary evidence
  • Over-reliance on single sources
  • Gaps in your evidential foundation

Example:

EvidenceLocationParagraphFunction
Deng speech on "settling accounts"[Source]P8Shows explicit linkage to reform agenda
Trial footage description[Source]P7Demonstrates gendered vilification

Self-Check Checklist

Before submitting any analytical essay:

Structure & Argument

  • Is thesis arguable (would someone disagree)?
  • Are paragraphs organized into clear phases?
  • Does each paragraph link explicitly to thesis?
  • Does each paragraph argue ONE point?

Evidence & Analysis

  • Does each claim have textual evidence + contextual support + logical connection?
  • Are primary sources cited in every analytical section?
  • Are quotations integrated into sentences?
  • Does each analytical point answer "so what?"

Completeness

  • Is strongest counterargument addressed?
  • Does conclusion show implications beyond summary?
  • Is background distinguished from analysis?
  • Have you verified all factual claims and quotations?

Analytical Essay Rules

Rules specific to academic papers, case studies, literary analysis, and analytical writing.

Prerequisites: Read SKILL.md universal rules first.


Rule A1: Background vs Analysis Distinction

Description: Clearly separate established facts from your interpretation.

Elaboration: Background = established facts needed to understand. Analysis = your interpretation using those facts. Test each sentence: "Is this my argument or common knowledge?" If it's common knowledge, it's background. If it's your claim, it needs evidence.

Example:

  • ❌ "The Snail Girl story served a purpose after the An Lushan rebellion." (Claim presented as fact)
  • ✅ "The Snail Girl story reflects post-rebellion anxiety, as evidenced by [textual detail] and the increased presence of courtesan figures in [source]." (Claim + evidence)

Rule A2: Evidence Triangle

Description: Every claim needs three types of support: textual, contextual, and logical.

Elaboration: Textual evidence: quote or detail from the source. Contextual support: historical or cultural information that makes the interpretation plausible. Logical connection: explicit explanation of how evidence supports claim. Missing any leg weakens the argument.

Example:

  • ❌ "The protagonist's journey represents the immigrant experience." (claim only)
  • ✅ "The protagonist's journey represents the immigrant experience: her repeated phrase 'I don't belong here' [textual] echoes the language of displacement common in 1920s diaspora literature [contextual], suggesting the author used her character to voice collective alienation [logical]."

Rule A3: Precision Over Drama

Description: Academic credibility comes from understatement, not emphatic language.

Elaboration: Remove intensifiers that add rhetorical force without increasing precision: "any", "every", "definitive", "clear", "obvious". Let facts do the work. The subtle version is more damning because it's credible.

Example:

  • ❌ "The regime's actions represent a definitive end to any hope of democracy."
  • ✅ "The regime's actions ended democratic participation." (Let the reader feel the weight)

Rule A4: No Melodrama

Description: Avoid dystopian or sensationalist phrasing that triggers skepticism.

Elaboration: Readers dismiss writing that feels like propaganda. The more damning a fact, the more flatly it should be stated. Melodrama invites dismissal; clinical precision invites belief.

Example:

  • ❌ "Every name has been vetted for patriotism by national security police in a chilling display of authoritarianism."
  • ✅ "No opposition candidates appear on the ballot; all have been screened by a vetting committee advised by national security police."

Rule A5: Complete Phrases Over Fragments

Description: Use complete sentences rather than punchy fragments.

Elaboration: Fragment style ("Most striking:") feels journalistic and breathless. Complete phrases ("What is most striking is that...") feel authoritative. Reserve fragments for deliberate rhetorical effect, not as default.

Example:

  • ❌ "Pro-democracy seats: zero. Independent voices: silenced."
  • ✅ "The legislature now contains zero pro-democracy seats, and independent voices have been systematically excluded."

Rule A6: Substantiate Empirical Claims

Description: Every factual assertion needs a source or qualification.

Elaboration: If you claim "emigrants faced hardship," find the source: report, statistic, interview. If you can't cite it, qualify it ("reportedly", "according to interviews") or remove it. Unsubstantiated empirical claims undermine the entire argument.

Example:

  • ❌ "Emigrants have struggled to find work matching their qualifications."
  • ✅ "According to a 2023 British Future report, trained accountants among Hong Kong emigrants are now working in kitchens."

Rule A7: Context Before Events

Description: Establish context before narrating what happened.

Elaboration: The reader needs to understand 2019 before you discuss the 2020 National Security Law. Structural logic means related content stays proximate, and setup precedes action. Don't make readers backtrack.

Example:

  • ❌ "The National Security Law was implemented in 2020. This followed the 2019 protests."
  • ✅ "The 2019 protests—which brought millions to the streets—set the stage for Beijing's response. In 2020, the National Security Law was implemented."

Rule A8: Explain Symbolic Dimensions

Description: When terms have significance beyond literal meaning, make it explicit.

Elaboration: Readers need to understand why actors care. "Hong Kong poses no physical threat to Beijing" might seem obvious—but then why the crackdown? Add: "The threat Hong Kong represents is symbolic and psychological." The symbolic layer isn't obvious; state it.

Example:

  • ❌ "Beijing views Hong Kong's resistance as a threat."
  • ✅ "Hong Kong poses no physical threat to Beijing—the city has no army, no nuclear weapons. The threat is symbolic: a successful example of Chinese people living under rule of law would undermine the Party's claim that authoritarianism is necessary for Chinese prosperity."

Rule A9: No Staccato Sequences

Description: Combine series of short declarative sentences into flowing prose.

Elaboration: "Seventy percent held degrees. Sixty percent had children. Ninety-nine percent planned to stay." feels choppy. Combine into one sentence with natural rhythm. Reserve staccato for deliberate rhetorical effect.

Example:

  • ❌ "Seventy percent held university degrees. Sixty percent had children under 18. Ninety-nine percent planned to stay permanently."
  • ✅ "Seventy percent held university degrees, sixty percent had children under 18, and ninety-nine percent planned to stay permanently."

Rule A10: Specific Conclusions

Description: Conclusions must name implications, not gesture at them.

Elaboration: "...and a warning that extends far beyond Hong Kong's borders" is lazy. What warning? To whom? Name it: "...and a warning to Taiwan, where 'one country, two systems' was once a viable proposal."

Example:

  • ❌ "These events carry implications for the entire region."
  • ✅ "These events demonstrate that Beijing will sacrifice economic interests—Hong Kong's value as a financial hub—to maintain political control, suggesting similar calculus may apply to Taiwan."

Quick Checklist

  • A1: Background and analysis clearly distinguished?
  • A2: Every claim has textual + contextual + logical support?
  • A3: Removed emphatic intensifiers ("any", "every", "clear")?
  • A4: No melodramatic or sensationalist phrasing?
  • A5: Complete sentences, not journalistic fragments?
  • A6: Every empirical claim sourced or qualified?
  • A7: Context established before events narrated?
  • A8: Symbolic dimensions made explicit?
  • A9: No choppy staccato sentence sequences?
  • A10: Conclusion names specific implications?

College Essay Rules

Rules specific to undergraduate personal statements, Common App essays, and college admission essays.

Prerequisites: Read SKILL.md universal rules first.


Rule C1: Values in Opening

Description: State your throughline/values explicitly in the opening paragraph.

Elaboration: Don't bury your thesis in abstractions or save it for the end. Lead with clear personal values, then show how experiences align with those values. The reader should know what the essay is about within the first few sentences.

Example:

  • ❌ "Growing up a member of Gen Z, I'm invested in learning how people negotiate power in digital spaces..."
  • ✅ "I want to understand how policy can empower people, not just regulate them. This matters to me because..."

Rule C2: Uncomfortable Truth

Description: The best throughline makes the writer slightly uncomfortable.

Elaboration: If your essay feels safe and comfortable, you haven't found the real throughline yet. Ask: "What am I afraid to say?" That discomfort often signals authenticity. Essays that take no emotional risk feel generic.

Example:

  • ❌ "I learned that teamwork is important" (safe, generic)
  • ✅ "I realized I'd been performing competence rather than admitting confusion—and that performance was isolating me from the collaboration I claimed to value" (uncomfortable but authentic)

Rule C3: Emotional Climax Development

Description: The turning point deserves full development, not a passing mention.

Elaboration: If the emotional climax gets 3 sentences while setup gets 3 paragraphs, the balance is wrong. The moment of transformation—where understanding shifts—should be the essay's center of gravity. Expand it.

Example:

  • ❌ Setup (3 paragraphs) → "Then I realized I had been wrong" (1 sentence) → Reflection (2 paragraphs)
  • ✅ Setup (1 paragraph) → Moment of realization fully developed with sensory detail, internal conflict, specific thoughts (2 paragraphs) → Forward projection (1 paragraph)

Rule C4: So What Chain

Description: Push every insight through three levels of "So what?"

Elaboration: Surface insights need excavation. First "so what" reveals implication; second "so what" reveals behavior; third "so what" reveals actionable commitment. Stop at the third level—that's what belongs in the essay.

Example:

  • Level 0: "I embrace imperfection"
  • Level 1 (so what?): "I'm willing to be vulnerable"
  • Level 2 (so what?): "I take intellectual risks"
  • Level 3 (so what?): "I contribute bold hypotheses, even if wrong—and invite others to challenge them"
  • ✅ Use Level 3 in the essay

Rule C5: Hook Engagement Test

Description: The opening must do work to engage the reader.

Elaboration: Test: could the essay start at paragraph 2 instead? If yes, paragraph 1 is weak—it's decoration, not engagement. Strong hooks create immediate stakes: surprise, tension, vivid scene, or confession.

Example:

  • ❌ "From a young age, I have always been interested in science..." (could start at paragraph 2)
  • ✅ "The cricket died. I had held the pipette too long, and the specimen I'd spent three weeks preparing was ruined." (cannot skip—reader needs to know what happens next)

Rule C6: No Generation Statements

Description: Don't open with claims about your generation or society.

Elaboration: "As a member of Gen Z..." or "In today's society..." are padding. They're generic, impersonal, and could appear in any applicant's essay. Start with YOU—a specific moment, question, or realization.

Example:

  • ❌ "Growing up in an increasingly connected world, I've witnessed the transformative power of technology..."
  • ✅ "When my grandmother's FaceTime froze mid-sentence, I watched her tap the screen like it was broken. I realized the 'connected world' assumed a fluency she never had."

Rule C7: One Sentence Test

Description: Complete the sentence: "This essay is about how [experience] taught me [insight], which means I will [action]."

Elaboration: If you cannot complete this sentence, the essay isn't ready. The sentence forces you to identify experience, insight, AND forward action. Missing any element signals a gap in the essay's logic.

Example:

  • ❌ "This essay is about how I learned to appreciate diversity." (missing specific experience and action)
  • ✅ "This essay is about how failing my first research project taught me that documenting failure is more valuable than hiding it, which means I will share my mistakes openly to help others learn."

Rule C8: Sensory Specificity

Description: Include at least one moment with sensory detail.

Elaboration: The reader should be able to see, hear, or feel at least one scene. Sensory detail creates presence. "The lab was quiet" vs "The only sound was the ventilation hum and my own breathing as I realized what I'd done."

Example:

  • ❌ "I felt nervous before the performance."
  • ✅ "My hands were damp on the bow. The concert hall smelled like old wood and the collective breath of five hundred people waiting."

Quick Checklist

  • C1: Values/throughline stated clearly in opening?
  • C2: Essay takes emotional risk (uncomfortable truth)?
  • C3: Emotional climax fully developed, not rushed?
  • C4: Insights pushed through "so what" chain to actionable level?
  • C5: Opening does real work (can't skip to paragraph 2)?
  • C6: No generic generation/society statements?
  • C7: Can complete the one-sentence test?
  • C8: At least one moment with sensory detail?

Mentor Essay Rules

Rules specific to "person who influenced you" essays, thank-you notes, and relationship-focused prompts.

Prerequisites: Read SKILL.md universal rules first.


Rule M1: Relationship Over Achievement

Description: Focus on what the person taught you, not what you accomplished.

Elaboration: These essays are about the relationship, not your resume. "I led 493 members" centers you. "You taught me that persistence matters more than perfection" centers the relationship and what you learned from it.

Example:

  • ❌ "Under their mentorship, I led 493 members, organized weekly games, and created three new mentorship programs."
  • ✅ "You taught me that access defines opportunity. When I saw hierarchy forming in our group, I remembered your words and introduced rotating moderators—your lesson applied in practice."

Rule M2: Specific Lesson Attribution

Description: Name the specific lesson you learned from this person.

Elaboration: Generic influence ("they inspired me") is weak. What exactly did they teach you? Quote their words if possible. Show how a specific thing they said or did changed your thinking or behavior.

Example:

  • ❌ "My coach inspired me to be a better person and work harder."
  • ✅ "When you accepted me despite my 33% win rate, you taught me that potential matters more than current performance. I've applied this when recruiting new players—looking for enthusiasm over skill."

Rule M3: Seven-Part Structure

Description: Follow this structure for comprehensive mentor essays.

Elaboration:

  1. Setting: Where/how you met
  2. Relationship: Who they are to you
  3. Transition: How they empowered you
  4. Problems: Challenges in the space
  5. Your actions: What you did, influenced by them
  6. Growth: What you learned from the process
  7. Thank you: Connect back to their specific impact

Example:

  • ❌ [Unstructured narrative jumping between memories]
  • ✅ "We met at the informatics olympiad training camp [setting]. You became my first real mentor in competitive programming [relationship]. When you showed me how to analyze problems systematically [transition], I began to see past the immediate challenge [empowerment]..."

Rule M4: Their Voice Present

Description: Include at least one direct quote or paraphrase of their words.

Elaboration: The mentor's voice should appear in the essay. What did they actually say? If you can't remember exact words, paraphrase: "You told me something like..." or "Your advice was essentially..." This makes the relationship concrete.

Example:

  • ❌ "They gave me good advice about research."
  • ✅ "You said: 'The fieldwork I'm proudest of came from conversations I almost didn't have.' I think of this every time I hesitate to approach someone."

Rule M5: Observable Change

Description: Show observable behavior change, not just internal shift.

Elaboration: "I now think differently" is invisible. "I now do X when Y happens" is observable. The reader should be able to verify the change if they watched you. What would they see you doing differently?

Example:

  • ❌ "After learning from them, I came to appreciate the value of patience."
  • ✅ "After learning from you, I changed how I coach beginners. Instead of correcting immediately, I now ask 'What did you notice?' and let them discover the problem themselves."

Rule M6: Observations as Relationship Lens

Description: Frame intellectual observations through the relationship.

Elaboration: You can include sociological or intellectual insights, but frame them as things the mentor helped you discover. Use observations to explain what the person taught you, not to showcase your own knowledge.

Example:

  • ❌ "I observed that in-game economies create social hierarchies. I implemented rotating moderators to address this."
  • ✅ "You taught me that access defines opportunity. When I saw the in-game economy creating hierarchy, I remembered your lesson and introduced rotating moderators."

Rule M7: Gratitude Specificity

Description: Thank them for something specific, not general influence.

Elaboration: "Thank you for everything" is weak. "Thank you for telling me to talk to people more—that single piece of advice changed how I approach fieldwork" is specific. The thank-you should mirror the specific lesson.

Example:

  • ❌ "I'm grateful for all you've done for me."
  • ✅ "Thank you for accepting me when others wouldn't. That act of belief taught me to offer the same to others."

Rule M8: No Hero Worship

Description: Present the mentor as human, not idealized.

Elaboration: Perfect mentors feel fictional. Acknowledge complexity: maybe they were demanding, or you disagreed at first, or their advice didn't make sense until later. Realistic portrayal is more credible than hagiography.

Example:

  • ❌ "They were the perfect mentor who always knew exactly what to say."
  • ✅ "At first, your advice frustrated me. 'Talk to people more' seemed too simple. It took a year before I understood what you meant—not more conversations, but different ones."

Quick Checklist

  • M1: Essay centers the relationship, not your achievements?
  • M2: Specific lesson clearly attributed to this person?
  • M3: All seven structural elements present?
  • M4: At least one quote or paraphrase of their words?
  • M5: Observable behavior change described?
  • M6: Observations framed through relationship lens?
  • M7: Thank-you is specific, not generic?
  • M8: Mentor portrayed as human, not idealized?

Personal Essays

Rules for essays about yourself: college applications, PhD statements, "Why X" essays, mentor essays, personal narratives.

Core principle: Personal essays answer "what will you do?" not "who are you?" Every theme must translate to future behavior.


Core Rules

P1: One Throughline

Rule: An essay has exactly one throughline. If you have multiple themes, subtract until one remains.

Elaboration: List all themes, write "This essay is about [theme]" for each, identify which feels most urgent, cut everything else. Multiple themes create unfocused essays that readers forget.

Example:

  • MULTIPLE THEMES: Leadership, resilience, intellectual curiosity, community building
  • TEST: "This essay is about leadership" / "This essay is about resilience" / etc.
  • DECISION: "Resilience" feels most urgent → cut the others
  • RESULT: Every paragraph now serves the resilience throughline

P2: Actionability Test

Rule: Every theme must predict specific future behavior. If you can't name 3 concrete behaviors, the theme is too abstract.

Elaboration: Ask "What does this predict about future behavior?" Strong themes generate specific actions; weak themes generate vague intentions.

Example:

  • WEAK: "I learned resilience" → (What specifically will you DO?)
  • STRONG: "I embrace imperfection" →
    1. "I will take intellectual risks in seminars"
    2. "I will share preliminary research ideas before they're polished"
    3. "I will publish null results when experiments fail"

P3: Forward Projection

Rule: Transform past experiences into future capabilities using the template: "Because [experience], I am now capable of [specific action]."

Elaboration: Past-focused essays describe; future-focused essays predict. Admissions wants to know what you'll do, not just what you did.

Example:

  • PAST-FOCUSED: "I had to reinvent myself after injury"
  • FUTURE-FOCUSED: "I reinvented myself once; I can do it again. When research hits dead ends, I will pivot rather than persist blindly."

P4: Realization → Action

Rule: Every realization must include a behavior change. Use the pattern: "I realized [insight]. Now when [situation], I [specific behavior]."

Elaboration: Essays often end with insights but no behavior change. The insight alone is incomplete—show how it changed your actions.

Example:

  • WEAK: "I realized food negotiates belonging"
  • STRONG: "I realized food negotiates belonging. Now when roommates mention what they eat, I ask about the story behind it—not just the cuisine, but who taught them to cook it."

P5: Circular Narrative

Rule: If opening establishes a theme, conclusion must show how that theme manifests in future action.

Elaboration: The opening and conclusion must connect. Test: Replace conclusion with opening theme phrase—does it connect naturally? If not, revise conclusion to explicitly callback.

Example:

  • OPENING: "I'd grown through the words of others"
  • WEAK CONCLUSION: "Bridge-building is carried in everyday objects" (insight, no callback)
  • STRONG CONCLUSION: "At NYU, I'll grow others through my questions—not just learning from their words, but helping them discover meaning in their stories" (callbacks to "words of others" + shows future behavior)

P6: Concrete Translation

Rule: Replace every abstraction with a concrete moment. If you can't name the moment, the concept isn't earned.

Elaboration: Abstract themes need grounding in specific experiences across multiple contexts.

Example:

  • ABSTRACT: "I embrace imperfection"
  • CONCRETE MOMENT: "In the lab, when I killed the cricket, I documented the failure and adjusted technique"
  • THREE CONTEXTS:
    • Academic: "I share preliminary ideas in class before they're polished"
    • Research: "I publish null results when experiments fail"
    • Collaborative: "I admit when I don't know rather than bluffing"

P7: Strong Opening Hook

Rule: Openings must establish stakes before delivering insights. Could the essay start at paragraph 2? If yes, paragraph 1 is weak.

Elaboration: Generic statements about generation, society, or abstract concepts feel like padding. Start with tension, surprise, or vivid scene.

Example:

  • WEAK: "Growing up a member of Gen Z, I'm invested in learning how people negotiate power..."
  • STRONG (tension): "The village preserved matriarchal tradition. Yet every woman I met had left to work in coastal cities."
  • STRONG (surprise): "I expected to learn interviewing tactics. Instead, he told me to stop taking notes."
  • STRONG (scene): "The boy approached singing. His mother, 2,000 miles away, had taught him the melody over FaceTime."

P8: So What? Chain

Rule: Ask "So what?" three times to reach actionable insight. Stop at the third level.

Elaboration: Surface insights are rarely actionable. Dig deeper until you reach specific behaviors.

Example:

  • LEVEL 1: "I embrace imperfection"
  • SO WHAT? → "I'm willing to be vulnerable"
  • SO WHAT? → "I take intellectual risks"
  • SO WHAT? → "I contribute bold hypotheses in seminars, even if wrong"
  • STOP: Third level is the actionable insight

P9: One Sentence Test

Rule: The writer must complete: "This essay is about how [experience] taught me [insight], which means I will [action]."

Elaboration: If they can't complete this sentence, the essay isn't ready. All three parts—experience, insight, action—must be present.

Example:

  • INCOMPLETE: "This essay is about how competitive programming taught me perseverance"
  • COMPLETE: "This essay is about how losing IOI Bronze taught me that structural barriers require self-direction, which means I will build resources for others facing the same obstacles"

PhD Research Statement Rules

Additional rules for PhD research statements. Apply Core Rules first.

PhD1: Specific Research Interest by Paragraph 3

Rule: Reader must grasp your SPECIFIC research interest by the end of paragraph 3.

Elaboration: Vague interest ("I'm interested in algorithms") fails. Specific interest ("I want to understand what graph structures enable efficient algorithms, and where limits arise") succeeds.

Example:

  • VAGUE: "I'm interested in theoretical computer science"
  • SPECIFIC: "I want to design fast algorithms by understanding the combinatorial structures that make them possible—and prove where those structures reach their limits"

PhD2: Opening Hook as Thread

Rule: Start with a compelling question, develop it throughout, circle back in conclusion. Don't abandon hook after paragraph 1.

Elaboration: The opening question should be the essay's spine. Every section should connect back to it.

Example:

  • OPENING: "How can I compute the shortest path efficiently?"
  • BODY: Each paragraph shows how this question evolved (IOI → Cambridge → research → faculty fit)
  • CONCLUSION: "The question that started my journey—how to compute the shortest path—has become a question about the nature of efficient computation itself."

PhD3: Capability Development, Not Event Listing

Rule: Each paragraph develops a CAPABILITY, not just lists an event. Show what you became able to do.

Elaboration: "I did X" is weak. "Doing X made me capable of Y" is strong.

Example:

  • EVENT LISTING: "I attended lectures, won Bronze at ICPC, did an internship"
  • CAPABILITY: "The Tripos gave me a systematic approach to proof. ICPC Bronze taught me to optimize under pressure. The internship showed me I prefer discovering algorithms to deploying them."

PhD4: Transition Logic

Rule: Every paragraph must answer: "Why does this follow from the previous one?"

Elaboration: Map explicit transitions:

  • IOI → University: What was LACKING in self-study?
  • University → Internship: What did structured learning clarify?
  • Internship → Research: How did industry confirm you want academia?
  • Research → Next Project: How does this EXPAND your toolkit?

Example:

  • WEAK: "I then did a summer internship at Hudson River Trading."
  • STRONG: "Self-study built intuition, but I needed rigorous mathematical training. The Tripos provided this—and clarified that my interest was theoretical, not applied."

PhD5: Authentic Research Reflection

Rule: Reflections must be specific to YOUR experience, not generic wisdom ("research requires perseverance").

Elaboration: What did YOU specifically learn that someone else might not have? What would you do differently?

Example:

  • GENERIC: "Research taught me that perseverance is important"
  • SPECIFIC: "I learned to survey literature first—we could have saved weeks knowing the original author was also stuck. I also learned that self-doubt during genuine uncertainty is normal, not a sign of inadequacy."

PhD6: Faculty Fit with Intellectual Engagement

Rule: Connect SPECIFIC faculty work to YOUR specific interest. Show engagement with their IDEAS, not just name-dropping.

Elaboration: Don't say "aligns with my interests." Show how their work connects to your questions.

Example:

  • WEAK: "Professor Williams' research aligns with my interests in algorithms"
  • STRONG: "Professor Williams' work on shortest-path algorithms—the very question that first captivated me at that IOI workshop—has developed into research on graph pattern detection that directly informs my interest in understanding exploitable graph structures"

PhD7: No Weakness Admissions

Rule: Never admit weakness ("Although I lack training in..."). Reframe as growth opportunity.

Elaboration: Weakness admissions invite doubt. Show self-directed interest instead.

Example:

  • WEAK: "Although I lack formal training in parallel computing..."
  • STRONG: "My interest in distributed algorithms has been self-directed; Professor Ghaffari's work offers structured depth in this frontier"

PhD8: Center Target School, Not Current Institution

Rule: Don't praise your current institution. Center the target school.

Elaboration: "Cambridge taught me that..." centers Cambridge. "Through my research, I've learned that..." centers your growth and the target school.

Example:

  • WEAK: "My years at Cambridge have shown me the value of intellectual community"
  • STRONG: "MIT's theory community offers the concentration of researchers and ideas I need to develop as a scholar"

PhD9: Post-PhD Goals

Rule: Mention what you'll do after the PhD. Forward projection extends beyond graduation.

Elaboration: Show you've thought beyond the program itself.

Example:

  • MISSING: [Essay ends with "I look forward to joining MIT"]
  • PRESENT: "After my PhD, I aim to continue closing gaps between upper and lower bounds, developing faster algorithms, and making fundamental discoveries about the limits of efficient computation."

PhD Personal Statement Rules

For the "personal" essay when application has two essays. Apply Core Rules first.

PPS1: Different Angle from Research Statement

Rule: If both essays mention the same experience, use different angles.

Elaboration: Research statement → intellectual curiosity angle. Personal statement → perseverance/community angle.

Example:

  • EXPERIENCE: IOI journey
  • RESEARCH STATEMENT ANGLE: "The question of computing shortest paths efficiently captivated me"
  • PERSONAL STATEMENT ANGLE: "Switzerland lacked coaches who could guide students beyond Bronze. Rather than accepting this, I taught myself—and now ensure future students won't face the same barriers"

PPS2: Meaning Beyond Self

Rule: Show that what you do has meaning beyond your own achievement.

Elaboration: Good throughlines: "What I do should have meaning beyond myself" / "I thrive when lowering barriers for others"

Example:

  • SELF-FOCUSED: "I won Gold at IOI through determination"
  • BEYOND SELF: "Winning Gold mattered less than what came after: I became what I lacked. Since 2021, I've volunteered as coach and mentor for the Swiss IOI team"

"Why This College/Program" Rules

Apply Core Rules first.

WTC1: Specificity Over Name-Dropping

Rule: Show what you'd actually DO, not just list programs. Test: Could another applicant copy-paste this sentence? If yes, add specificity.

Elaboration: Generic references to programs fail. Specific projects/questions succeed.

Example:

  • GENERIC: "I'm excited to join debates at the Philomathean Society"
  • SPECIFIC: "At Philomathean Society, I want to bring debates on digital policy—how do we regulate platforms that shape identity formation?"

WTC2: Program → Question → Values

Rule: Every program mention follows: Program/opportunity → specific question/project you'd pursue → why this connects to your values.

Elaboration: Don't just say you'll use a resource. Say what question you'll investigate with it.

Example:

  • WEAK: "I'll use the Data Driven Discovery Initiative"
  • STRONG: "Through DDDI, I plan to analyze social media discourse patterns using NLP to understand how marginalized communities build counter-narratives—extending my undergraduate work on digital belonging"

Mentor/Thank-You Essay Rules

Apply Core Rules first.

MTE1: Relationship Focus Over Achievement Focus

Rule: Frame achievements through what the mentor taught you, not as standalone accomplishments.

Elaboration: The essay is about the relationship and what you learned from them, not a resume of what you did.

Example:

  • ACHIEVEMENT-FOCUSED: "I led 493 members, organized games, created mentorship programs..."
  • RELATIONSHIP-FOCUSED: "You taught me that persistence matters more than perfection. When you accepted me despite my 33% win rate, I learned that potential matters more than track record."

MTE2: Seven-Part Structure

Rule: Follow this structure for mentor essays:

  1. Introduce setting (where/how you met)
  2. Establish mentor relationship (who they are to you)
  3. Show transition (how they empowered you)
  4. Present problems (challenges in the space)
  5. Detail your actions (influenced by them)
  6. Reflect on growth (what you learned)
  7. Final thank you (connect back to their specific impact)

Elaboration: This structure ensures you cover the relationship arc, not just list accomplishments.

Example:

  • WEAK: Jumping straight to "I implemented rotating moderators..."
  • STRONG: "You taught me that access defines opportunity. When I saw the PeiWan economy create hierarchy in our group, I remembered your words and introduced rotating moderators..."

Self-Check Checklist

Before submitting any personal essay:

  • Can I state the ONE throughline in one sentence?
  • Does throughline predict 3+ specific future behaviors?
  • Does conclusion callback to opening theme?
  • Are all reflections specific (not "perseverance")?
  • Is every abstraction grounded in a concrete moment?
  • Does opening establish stakes (not generic statements)?
  • Are all factual claims verified?
  • Are all quotes checked against source?
  • No weakness admissions?
  • Would I not cringe reading this aloud?

For PhD essays, also check:

  • Specific research interest clear by paragraph 3?
  • Each paragraph develops capability, not just lists event?
  • Faculty connections show intellectual engagement?
  • Post-PhD goals mentioned?
  • Target school centered (not current institution)?

PhD Personal Statement Rules

Rules specific to PhD personal statements—the "tell us about yourself" essay that complements the research statement.

Prerequisites: Read SKILL.md universal rules first.


Rule PS1: Distinct from Research Statement

Description: Personal statement must add new information, not repeat the research statement.

Elaboration: If both essays mention the same experience (e.g., IOI), use different angles. Research statement: intellectual curiosity angle. Personal statement: perseverance/community angle. Read both essays together and ask: "Does each add something new?"

Example:

  • ❌ Research statement: "Winning Gold at IOI showed me I wanted to do research." Personal statement: "My IOI journey taught me about algorithms."
  • ✅ Research statement: "The path to Gold revealed my interest in understanding why algorithms work." Personal statement: "After winning Gold, I became what I had lacked—a coach ensuring future students wouldn't face the same isolation I did."

Rule PS2: Meaning-Beyond-Self Throughline

Description: Show that your work has purpose beyond personal achievement.

Elaboration: "I thrive when what I do has meaning beyond myself" is a strong throughline for personal statements. Every experience should demonstrate this: coaching wasn't just teaching—it was ensuring others wouldn't face your barriers. Rebuilding the team wasn't just playing—it was giving the community a team.

Example:

  • ❌ "I coached the Swiss IOI team and served as scientific director."
  • ✅ "Coaching wasn't just about teaching algorithms—it was about ensuring the next generation wouldn't face the isolation I did. Seeing students I mentored reach IOI proved that what I do can have meaning beyond my own achievements."

Rule PS3: Community Building Evidence

Description: Provide concrete evidence of building communities.

Elaboration: Claims about community require specifics: what was the state before, what did you do, what was the result? "I strengthened communities" is empty. "When I became captain, the team had lost most of its players to graduation; over two years, I rebuilt it from scratch" is concrete.

Example:

  • ❌ "I've always sought opportunities to strengthen the communities around me."
  • ✅ "When I became captain of the Cambridge Handball Club, the team had just lost most of its players and committee to graduation. Over two years, I rebuilt it: recruiting players, designing sessions for all experience levels, and leading us to the Varsity match against Oxford."

Rule PS4: International Perspective Specificity

Description: Make claims about international exposure concrete.

Elaboration: "I've formed friendships with people from all over the world" is vague. Name the countries, the topic discussed, and the insight gained. "Discussing [topic] with friends from [countries] showed me [specific insight]."

Example:

  • ❌ "Cambridge immersed me in a truly international community where I've learned that diverse perspectives lead to better solutions."
  • ✅ "Discussing national service policy with friends from Singapore, Israel, and Switzerland showed me how differently societies balance individual freedom and collective obligation—a tension I now see in debates about research funding priorities."

Rule PS5: Why PhD, Not Just Why Research

Description: Explain why you want a PhD specifically, not just why you like research.

Elaboration: The personal statement should address why you've chosen the PhD path—years of structured training, building expertise, contributing to human knowledge—rather than just expressing love of research. Connect your personal journey to the specific nature of doctoral work.

Example:

  • ❌ "I love research because it lets me explore interesting questions."
  • ✅ "Research, for me, is not just about my own understanding, but about expanding what humanity knows. The PhD represents the training I need to make contributions that others can build on."

Rule PS6: Leadership as Empowerment

Description: Frame leadership as empowering others, not commanding them.

Elaboration: Don't list what you organized or directed. Show how you helped others grow or removed barriers for them. "Building something new requires both vision and attention to where each individual is."

Example:

  • ❌ "As captain, I organized training sessions, scheduled matches, and led team meetings."
  • ✅ "As co-coach, I designed sessions tailored to players at all levels—helping beginners learn fundamentals while challenging experienced players. Building a team requires knowing where each person is."

Rule PS7: Challenges Overcome Without Victimhood

Description: Present challenges as obstacles you overcame, not as claims for sympathy.

Elaboration: "I faced hardship" invites skepticism. "Rather than accepting this limitation, I..." shows agency. The challenge should demonstrate a capability you developed, not explain why you deserve accommodation.

Example:

  • ❌ "Switzerland lacked the coaching infrastructure that other countries have, which made my journey very difficult."
  • ✅ "Switzerland lacked coaches who could guide students beyond Bronze. Rather than accepting this, I spent two years teaching myself through online resources—progressing through Silver to Gold in 2021."

Rule PS8: No Redundancy with Research Statement

Description: Actively audit for repetition between the two essays.

Elaboration: Read both essays back-to-back. Any paragraph that could appear in either essay needs revision. The personal statement reveals character and values; the research statement reveals intellectual trajectory. They should feel like different windows into the same person.

Example:

  • ❌ Both essays describe the summer research project in detail
  • ✅ Research statement: details the technical work and what you learned about research methodology. Personal statement: mentions research only to note that the experience confirmed your commitment to academic life.

Quick Checklist

  • PS1: Personal statement adds new info, not redundant with research?
  • PS2: Clear throughline about meaning beyond self?
  • PS3: Community building claims have concrete evidence?
  • PS4: International experience includes specific topics and insights?
  • PS5: Explains why PhD path specifically, not just "love research"?
  • PS6: Leadership framed as empowering others?
  • PS7: Challenges show agency, not victimhood?
  • PS8: No repetition between essays?

PhD Research Statement Rules

Rules specific to PhD research statements, SOPs, and "describe your research interests" essays.

Prerequisites: Read SKILL.md universal rules first.


Rule P1: Specific Interest by Paragraph 3

Description: Reader must grasp your specific research interest within the first three paragraphs.

Elaboration: Don't make readers wait until the middle to understand what you want to study. By the end of paragraph 3, a faculty member should be able to summarize your research interest in one sentence. Vague interests ("I'm interested in algorithms") fail this test.

Example:

  • ❌ Paragraphs 1-3 discuss: IOI journey, Cambridge experience, internship → reader still doesn't know specific interest
  • ✅ Paragraph 2: "I want to understand what graph structures enable efficient algorithms, and where the limits of efficiency lie"

Rule P2: Opening Hook as Thread

Description: Start with a compelling question and develop it as a thread through the entire essay.

Elaboration: The opening hook should not be abandoned after paragraph 1. It should reappear—explicitly or implicitly—in the research description, faculty fit section, and conclusion. The hook transforms from question to journey to destination.

Example:

  • ❌ Opens with "How can I compute the shortest path?" → never mentioned again after paragraph 1
  • ✅ Opens with shortest path question → mentions it when describing research → connects to Professor Williams' work on shortest paths → conclusion circles back to "the question that started my journey"

Rule P3: Combine Journey and Realization

Description: Merge "what happened" and "what I learned" into one narrative arc.

Elaboration: Don't separate competition journey from realization about deeper interests into different paragraphs. Weave the realization INTO the narrative as it unfolds. "I won Gold, and then I realized I wanted to understand why" becomes "The path to Gold revealed something deeper: I cared less about winning than about understanding why certain structures make solutions possible."

Example:

  • ❌ Paragraph 1: "I competed in IOI and won Gold." Paragraph 2: "After winning, I realized I wanted to do research."
  • ✅ "The path from Bronze to Gold took two years of self-study—but the destination mattered less than what I discovered along the way: my real interest was not in winning, but in understanding why certain structures make efficient computation possible."

Rule P4: Transition Logic

Description: Every paragraph must answer "Why does this follow?"

Elaboration: The reader should never wonder why you're telling them something. Each transition should be motivated: IOI → University (what was lacking in self-study?), University → Internship (what did structured learning clarify?), Internship → Research (how did industry confirm you want academia?), Research → Next Project (how does this expand your toolkit?).

Example:

  • ❌ "After Cambridge, I did an internship at HRT. The following summer, I did research with Prof. Dawar."
  • ✅ "The internship clarified my direction: while industry applies algorithms, I want to discover why they work. This led me to seek research experience with Prof. Dawar."

Rule P5: No Achievement Lists

Description: Don't list accomplishments without showing what they developed.

Elaboration: "I attended lectures, won Bronze, did an internship" is a resume, not a narrative. Each experience should demonstrate a capability you developed. Transform lists into development arcs.

Example:

  • ❌ "I regularly attended algorithm lectures, represented Cambridge at ICPC World Finals, did an internship at HRT, and undertook research with Prof. Dawar."
  • ✅ "The Tripos gave me systematic proof techniques that proved essential in research; ICPC World Finals showed me the gap between solving problems and understanding why solutions work."

Rule P6: Faculty Fit Specificity

Description: Connect specific faculty work to your specific interest.

Elaboration: Don't just name-drop professors with "aligns with my interests." Show intellectual engagement with their actual research. Cite specific papers or results. If your opening hook connects to faculty work, make it explicit.

Example:

  • ❌ "Professor Williams' research aligns well with my interests in graph algorithms."
  • ✅ "Professor Williams' work on shortest path algorithms—the very question that first captivated me at that workshop—represents exactly the kind of fundamental inquiry I want to pursue. Her recent results on graph pattern detection connect to my interest in understanding what structures make efficient search possible."

Rule P7: No "I Hope To"

Description: Replace tentative language with confident intention.

Elaboration: "I hope to" signals uncertainty. Use "I aim to", "I intend to", "I will pursue." You're not hoping for permission—you're stating what you will do if admitted.

Example:

  • ❌ "I hope to contribute to the field of theoretical computer science."
  • ✅ "I aim to close gaps between upper and lower bounds for graph algorithms."

Rule P8: Cut Resume Redundancy

Description: Don't repeat information that appears in your CV.

Elaboration: "Which I took the summer after my second year" adds nothing—the resume has dates. Focus on what the experience taught you or developed, not when it happened.

Example:

  • ❌ "The internship at Hudson River Trading, which I undertook in the summer following my second year of the Mathematical Tripos..."
  • ✅ "The HRT internship gave me a quantitative approach to optimization that I hadn't encountered in pure mathematics."

Rule P9: Side Projects as Toolkit Expansion

Description: Frame non-central work as expanding your methodological toolkit.

Elaboration: Don't say "I enjoy areas outside my main focus"—this suggests scattered attention. Instead, frame side projects as deliberate expansion. "Seeking to expand my methodological toolkit, I joined..."

Example:

  • ❌ "I've always enjoyed exploring different areas of mathematics outside my main focus."
  • ✅ "Working with Prof. Gowers on automated theorem proving introduced me to techniques quite different from algorithm design—methodologies I expect will inform how I approach proofs in my primary research."

Rule P10: Center Target School

Description: Make the target program the focus, not your current institution.

Elaboration: "Cambridge taught me that..." centers Cambridge. "Through my research, I've learned that..." centers your development. The essay should make the reader think about you at their institution, not at your current one.

Example:

  • ❌ "My years at Cambridge have taught me that intellectual growth is best achieved through shared curiosity."
  • ✅ "MIT's theory community offers the concentration of researchers and ideas I need to develop as a scholar."

Rule P11: Post-PhD Goals

Description: Mention what you intend to do after the PhD.

Elaboration: Admissions committees want to see you've thought beyond the degree. Even one sentence about research career goals shows you understand the PhD as a step, not an endpoint.

Example:

  • ❌ Essay ends with: "I look forward to joining MIT's theory group."
  • ✅ Essay ends with: "After my PhD, I aim to continue closing gaps between upper and lower bounds—contributing new techniques for understanding the fundamental limits of efficient computation."

Rule P12: Authentic Research Reflection

Description: Describe what research actually felt like, not what you think admissions wants to hear.

Elaboration: Generic reflections ("perseverance is important") signal you haven't done real research. Authentic reflections describe specific challenges: "When you're stuck, you can't tell if failure comes from the problem's difficulty or your own limitations."

Example:

  • ❌ "This experience taught me that research requires perseverance and determination."
  • ✅ "For much of the project, I was stuck—and in a realm of genuine uncertainty, you can't distinguish whether failure comes from the problem's difficulty or your own limitations. What helped was discovering that the original author had also made no progress: the problem was genuinely hard, not just hard for me."

Quick Checklist

  • P1: Specific research interest clear by paragraph 3?
  • P2: Opening hook threaded throughout and revisited?
  • P3: Journey and realization woven together?
  • P4: Every transition motivated?
  • P5: Experiences show development, not just list events?
  • P6: Faculty connections cite specific work?
  • P7: No "I hope to" language?
  • P8: No CV-redundant dates/details?
  • P9: Side projects framed as toolkit expansion?
  • P10: Target school centered, not current institution?
  • P11: Post-PhD goals mentioned?
  • P12: Research reflection authentic and specific?

"Why This School" Essay Rules

Rules specific to school-specific supplements, "Why X University" essays, and program fit statements.

Prerequisites: Read SKILL.md universal rules first.


Rule W1: Specificity Over Name-Dropping

Description: Show what you'd actually do, not just list programs you've heard of.

Elaboration: Naming a program ("the Data Driven Discovery Initiative") proves you read the website. Describing what you'd do with it proves you've thought about fit. Every program mention should include a specific project, question, or activity you'd pursue.

Example:

  • ❌ "I'm excited to take advantage of the Data Driven Discovery Initiative."
  • ✅ "Through DDDI, I plan to analyze social media discourse patterns using NLP to understand how marginalized communities build counter-narratives."

Rule W2: Copy-Paste Test

Description: Could another applicant use this sentence unchanged?

Elaboration: If the answer is yes, the sentence is too generic. Every sentence should contain something specific to you AND specific to the school. "I'm excited to join debates at the Philomathean Society" passes for the school but fails for you—any applicant could write it.

Example:

  • ❌ "I'm excited to join debates at the Philomathean Society." (any applicant could write this)
  • ✅ "At Philomathean Society, I want to bring debates on digital policy—how do we regulate platforms that shape identity formation?" (specific to your interests + the program)

Rule W3: Values → Opportunities Connection

Description: Connect your values to specific opportunities, not vice versa.

Elaboration: Lead with what you care about, then show how the school's offerings serve that. Don't start with "X University has..." Start with "I want to understand X. At [University], Professor Y's work on Z and the Q program offer exactly the environment for this."

Example:

  • ❌ "MIT has a strong theory of computation group with many excellent faculty."
  • ✅ "I want to understand the limits of efficient computation. MIT's theory group—especially Professor Williams' work on shortest path algorithms and Professor Ghaffari's distributed computing research—represents the concentration of expertise I need."

Rule W4: Avoid Generic Praise

Description: Cut sentences that praise the school without connecting to you.

Elaboration: "X University is renowned for its innovative approach to Y" is filler. The admissions committee knows their school is good. Use that word count to explain what YOU would do there.

Example:

  • ❌ "NYU's Stern School of Business is world-renowned for its approach to combining business education with liberal arts."
  • ✅ [Delete entirely—use the space for your specific plans]

Rule W5: Research Faculty Before Writing

Description: Verify that professors actually work on what you claim.

Elaboration: Faculty research areas change. Before writing "Professor X works on Y," check their recent publications and current research page. Claiming interest in work they no longer do signals you didn't do your homework.

Example:

  • ❌ "I'm drawn to Professor Smith's work on machine learning for healthcare." (She moved to industry two years ago)
  • ✅ Check the department page, verify current faculty, cite a recent paper or ongoing project

Rule W6: Beyond Academics

Description: Include at least one non-academic opportunity.

Elaboration: "Why This School" essays that only mention classes and research feel incomplete. Include one community, club, or cultural element that genuinely interests you. This shows you've thought about life there, not just coursework.

Example:

  • ❌ [Essay mentions only courses and faculty]
  • ✅ "Beyond the theory group, I'm drawn to MIT's handball club—I captained Cambridge's team and want to continue playing at a competitive level."

Rule W7: No Location Clichés

Description: Don't mention location unless it's genuinely relevant to your plans.

Elaboration: "I'm excited about New York's vibrant cultural scene" could apply to thousands of applicants and dozens of schools. If location matters—because you need access to specific archives, communities, or industries—explain how. Otherwise, cut it.

Example:

  • ❌ "Boston's rich history and intellectual atmosphere will inspire my studies."
  • ✅ "Access to the MIT-Harvard library system is essential for my research on [specific topic]—the combined archives contain [specific resource]."

Rule W8: Future Tense Commitment

Description: Write in future tense to show commitment, not conditional.

Elaboration: "I would take" and "I might explore" signal uncertainty. "I will pursue" and "I intend to" signal commitment. Admissions committees want students who have decided, not students still deliberating.

Example:

  • ❌ "If admitted, I would consider exploring the intersection of..."
  • ✅ "At [School], I will pursue research at the intersection of..."

Quick Checklist

  • W1: Every program mention includes your specific plan for it?
  • W2: No sentence another applicant could copy unchanged?
  • W3: Your values lead, school opportunities follow?
  • W4: No generic praise of the school?
  • W5: Faculty research verified as current?
  • W6: At least one non-academic element included?
  • W7: Location mentioned only if genuinely relevant?
  • W8: Future tense commitment, not conditional language?

Ed Post Generator

Generate concise, genuine posts for Ed discussions to earn engagement points.

Format

Structure:

  1. Content/link (if sharing resource)
  2. 1-2 sentence context or insight
  3. Optional: Brief takeaway or question

Length: 2-4 sentences maximum

Style (CLEAR + STYLE rules):

  • Direct and authentic
  • No filler phrases
  • No dramatic language
  • Personal but not self-indulgent
  • Active voice
  • Clear benefit to readers

Examples

Resource sharing:

https://www.youtube.com/watch?v=dHIppEqwi0g

This is an insightful interview about when and when not Vibe Coding works from the lead of the Google Chrome team.

Insight sharing:

I found that switching from sequential to parallel test execution cut our CI time by 60%. Worth considering if you're spending too much time waiting for builds.

Question/discussion:

Has anyone tried using exa for code search? I'm curious if it's better than ripgrep for finding API examples in large codebases.

Anti-patterns

❌ "This is AMAZING and will change everything!" ❌ "I just wanted to share this really cool thing..." ❌ Long explanations or tutorials ❌ Excessive context or backstory ❌ Multiple links without clear focus

Workflow

When user says "EDPOST [topic/link/idea]":

  1. Generate short post following format
  2. Apply CLEAR + STYLE rules
  3. Keep authentic voice
  4. Make it scannable
  5. Show draft for approval

Gmail Workflows Context

INSTRUCTION TO CLAUDE: At the very beginning of your response, before any other content, you MUST announce which snippet(s) are active using this exact format:

📎 Active Context: gmail-workflows

If multiple snippets are detected, combine them:

📎 Active Contexts: gmail-workflows, snippet2, snippet3


VERIFICATION_HASH: gmail_v1_20251107

Trigger Keywords

This snippet should be active when:

  • User mentions: "gmail", "email", "send email", "draft email", "compose", "reply"
  • User uses email addresses in task description
  • User asks about past emails or conversations
  • User says "GMAIL" (all caps) to explicitly trigger

Auto-Invoke Skill

When gmail triggers detected, ALWAYS invoke the gmail-assistant skill first:

Use the Skill tool with skill="gmail-assistant"

This loads complete gmail workflow documentation and best practices.

Quick Reference (When Skill Not Needed)

For simple gmail queries or when skill already loaded:

Before Composing

  1. Search past emails to recipient(s) to extract patterns
  2. Check available email styles with gmail styles list
  3. Draft combining past patterns + style + current context
  4. ALWAYS test to fuchengwarrenzhu@gmail.com first
  5. Review preview then send to real recipient

Essential Commands

Search & Discovery:

gmail list --folder ALL --query "keyword"              # Search all folders
gmail list --folder SENT --query "to:person@example"   # Find past emails to someone
gmail list --folder ALL --query "from:person@example"  # Find emails from someone

Read & Context:

gmail read <message_id>                                # Summary view (snippet only)
gmail read <message_id> --full                         # Full email body
gmail thread <thread_id>                               # View entire conversation

Send & Reply:

gmail send --to user@example.com --subject "X" --body "Y" --yolo
gmail reply <message_id> --body "Reply text" --yolo

Current Limitations & Workarounds

Getting Full Email Body
  • gmail read <id> returns truncated snippets (~100 chars)
  • Workaround: Use --full flag (if implemented) or read raw API
Finding CC'd Recipients
  • gmail read output doesn't show CC/BCC recipients
  • Workaround: Use Python to extract headers:
from gmaillm.gmail_client import GmailClient
client = GmailClient()
msg = client.service.users().messages().get(
    userId='me', id='<message_id>', format='full'
).execute()
headers = msg['payload']['headers']
cc = [h['value'] for h in headers if h['name'].lower() == 'cc']
print(f"CC: {cc}")
Thread Context
  • No single command to view full thread
  • Workaround:
    1. Find thread: gmail list --folder ALL --query "subject:keyword"
    2. Note thread_id from results
    3. Read each message individually with --full

Common Patterns

Pattern 1: Draft reply based on email thread

  1. Search: gmail list --folder ALL --query "subject keywords"
  2. Read messages: gmail read <id> for each
  3. Extract context: who's involved, what's been discussed
  4. Use Python workaround if CC extraction needed
  5. Draft reply matching tone
  6. Send with appropriate recipients

Pattern 2: Find contact information

  1. Search inbox: gmail list --query "from:[name]"
  2. Search sent: gmail list --folder SENT --query "to:[name]"
  3. Extract email from results
  4. If not found, search web (LinkedIn, org directory)

Pattern 3: Compose with style

  1. Check past emails to recipient for patterns
  2. List styles: gmail styles list
  3. View specific style: gmail styles show professional-formal
  4. Draft combining recipient's expected style + situation
  5. Test send first

Notes

Tutoring Parent Report Format

Template for creating professional tutoring progress reports to parents.

When to Use

  • Parent report: Stakeholder update, billing accountability, outcomes-focused
  • NOT for: Detailed timelines, internal notes, comprehensive archives

Report Structure

[Personal Greeting]

[Opening Statement]

[Billing Summary]
- Total time
- Total cost

[Session Breakdown]
第一节课...
第二节课...
第三节课...

[Current Status & Next Steps]

Complete Example

赵娟阿姨,我与您汇报一下这几周和Paris的情况:

这几周我们课时总共上了一小时10分钟。总共收费为2500人民币。

第一节课我们开始了论文写作规划,帮助Paris构建论文框架和方向,与布置阅读材料和写作任务。

第二节课Paris做完了阅读任务,开始制定大纲。我们一起给出了大纲的基本论点与结构。

第三节课Paris完成了大纲。我认为写的很好。现在我们论点与大纲都定完了,开始正式写作,填充论文内容。

Key Principles

1. Billing Upfront

  • Show total time and cost immediately after greeting
  • Demonstrates transparency and accountability
  • Parent knows financial details before reading outcomes

2. Session Numbering

  • Use "第X节课" not timestamps
  • Focus on sequence and progression
  • Stakeholder doesn't need specific dates

3. Outcome-Focused

  • What was accomplished (completed outline)
  • What progress was made (定完了大纲)
  • Current capability/status (开始正式写作)
  • NOT just activities ("we did X, then Y")

4. Progression Narrative

  • Show clear development: planning → outline → writing
  • Each session builds on previous
  • Demonstrates systematic approach and value

5. Professional Tone

  • Personal greeting (阿姨)
  • Formal reporting language (我与您汇报)
  • Confident assessment (我认为写的很好)
  • Clear current status

Format Comparison

Parent Report (Use this format)

  • Purpose: Stakeholder communication, billing
  • Tone: Professional, outcome-focused
  • Structure: Greeting → Billing → Sessions → Status
  • Details: High-level outcomes only
  • Length: Concise (3-4 paragraphs)

Timeline (Different use case)

  • Purpose: Archival, detailed record
  • Tone: Educational, comprehensive
  • Structure: Chronological with timestamps
  • Details: Granular activities and time spent
  • Length: Detailed (multiple sections)

Common Mistakes

❌ Putting billing at the end ❌ Using timestamps instead of session numbers ❌ Listing activities instead of outcomes ❌ Too much detail (parent wants summary) ❌ Missing current status statement

Adaptation Notes

  • Adjust formality based on parent relationship
  • Include specific concerns if parent raised them
  • Mention any challenges if relevant
  • Always end with forward-looking statement

Creating Skills

Step-by-step guidance for creating new Agent Skills in Claude Code.

Quick Start

1. Choose Skill Location

Personal Skills (~/.claude/skills/):

  • Individual workflows
  • Experimental skills
  • Personal productivity tools

Project Skills (.claude/skills/):

  • Team workflows
  • Project-specific expertise
  • Shared utilities (commit to git)

Plugin Skills (plugin's skills/ directory):

  • Distributable skills
  • Part of a plugin package
  • Automatically available when plugin installed

2. Create Skill Directory

# Personal
mkdir -p ~/.claude/skills/my-skill-name

# Project
mkdir -p .claude/skills/my-skill-name

# Plugin
mkdir -p path/to/plugin/skills/my-skill-name

3. Create SKILL.md

Minimum required structure:

---
name: Your Skill Name
description: What it does and when to use it (include trigger terms)
---

# Your Skill Name

## Instructions

Provide clear, step-by-step guidance.

## Examples

Show concrete examples of using this skill.

Writing Effective Descriptions

The description field is critical for skill discovery.

Requirements

  • Write in third person (goes into system prompt)
  • Include WHAT the skill does
  • Include WHEN to use it
  • Add specific trigger terms users would mention
  • Maximum 1024 characters

Good Examples

PDF Processing:

description: Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction.

Excel Analysis:

description: Analyze Excel spreadsheets, create pivot tables, generate charts. Use when analyzing Excel files, spreadsheets, tabular data, or .xlsx files.

Git Commit Helper:

description: Generate descriptive commit messages by analyzing git diffs. Use when the user asks for help writing commit messages or reviewing staged changes.

Bad Examples

description: Helps with documents  # Too vague

description: Processes data  # Not specific enough

description: Does stuff with files  # No trigger terms

Skill Structure Guidelines

Keep Skills Focused

One skill = one capability

Good (focused):

  • "PDF form filling"
  • "Excel data analysis"
  • "Git commit messages"

Too broad (split into multiple skills):

  • "Document processing"
  • "Data tools"
  • "File operations"

Use Progressive Disclosure

Keep SKILL.md under 500 lines. Split content into separate files.

Pattern:

my-skill/
├── SKILL.md              # Main instructions (< 500 lines)
├── reference.md          # Detailed API docs
├── examples.md           # Usage examples
└── scripts/
    └── helper.py         # Utility scripts

In SKILL.md:

# My Skill

## Quick Start
[Brief overview and common usage]

## Advanced Features
For complete API documentation, see [reference.md](reference.md).
For usage patterns, see [examples.md](examples.md).

Claude loads additional files only when needed.

Avoid Deeply Nested References

Keep references one level deep from SKILL.md.

Bad (too deep):

# SKILL.md
See [advanced.md](advanced.md)...

# advanced.md
See [details.md](details.md)...

# details.md
Here's the actual information...

Good (one level):

# SKILL.md

**Basic usage**: [instructions in SKILL.md]
**Advanced features**: See [advanced.md](advanced.md)
**API reference**: See [reference.md](reference.md)
**Examples**: See [examples.md](examples.md)

Structure Longer Reference Files

For reference files >100 lines, include a table of contents:

# API Reference

## Contents
- Authentication and setup
- Core methods (create, read, update, delete)
- Advanced features (batch operations, webhooks)
- Error handling patterns
- Code examples

## Authentication and Setup
...

## Core Methods
...

Content Guidelines

Be Concise

Challenge each piece of information:

  • Does Claude really need this explanation?
  • Can I assume Claude knows this?
  • Does this justify its token cost?

Good (concise):

## Extract PDF Text

Use pdfplumber:

```python
import pdfplumber
with pdfplumber.open("file.pdf") as pdf:
    text = pdf.pages[0].extract_text()
```

Bad (too verbose):

## Extract PDF Text

PDF (Portable Document Format) files are a common file format that contains
text, images, and other content. To extract text from a PDF, you'll need to
use a library. There are many libraries available for PDF processing, but we
recommend pdfplumber because it's easy to use and handles most cases well.
First, you'll need to install it using pip. Then you can use the code below...

Use Consistent Terminology

Choose one term and use it throughout:

Good:

  • Always "API endpoint"
  • Always "field"
  • Always "extract"

Bad:

  • Mix "API endpoint", "URL", "API route", "path"
  • Mix "field", "box", "element", "control"

Avoid Time-Sensitive Information

Bad:

If you're doing this before August 2025, use the old API.

Good:

## Current Method
Use the v2 API: `api.example.com/v2/messages`

## Old Patterns
<details>
<summary>Legacy v1 API (deprecated 2025-08)</summary>
The v1 API used: `api.example.com/v1/messages`
This endpoint is no longer supported.
</details>

Tool Restrictions (Optional)

Use allowed-tools to limit which tools Claude can use when the skill is active:

---
name: Safe File Reader
description: Read files without making changes. Use when you need read-only file access.
allowed-tools: Read, Grep, Glob
---

# Safe File Reader

This skill provides read-only file access.

## Instructions
1. Use Read to view file contents
2. Use Grep to search within files
3. Use Glob to find files by pattern

When this skill is active, Claude can only use the specified tools without asking permission.

Use cases:

  • Read-only skills that shouldn't modify files
  • Limited scope skills (e.g., only data analysis, no file writing)
  • Security-sensitive workflows

Testing Your Skill

1. Test by Asking Relevant Questions

Ask questions that match your description:

Example: If your description mentions "PDF files":

Can you help me extract text from this PDF?

Claude should autonomously use your skill.

2. Check Skill Discovery

List all skills: Ask Claude: "What skills are available?"

Verify file structure:

# Personal
ls ~/.claude/skills/my-skill/SKILL.md

# Project
ls .claude/skills/my-skill/SKILL.md

3. Debug Common Issues

Skill doesn't activate:

  • Make description more specific
  • Include trigger terms users would mention
  • Add "when to use" guidance

YAML syntax errors:

cat SKILL.md | head -n 10

Ensure:

  • Opening --- on line 1
  • Closing --- before markdown
  • Valid YAML (no tabs, correct indentation)

Wrong location: Check skill is in correct directory with SKILL.md file.

Complete Examples

Simple Skill (Single File)

commit-helper/
└── SKILL.md

SKILL.md:

---
name: Generating Commit Messages
description: Generates clear commit messages from git diffs. Use when writing commit messages or reviewing staged changes.
---

# Generating Commit Messages

## Instructions

1. Run `git diff --staged` to see changes
2. Suggest a commit message with:
   - Summary under 50 characters
   - Detailed description
   - Affected components

## Best Practices

- Use present tense
- Explain what and why, not how

Multi-File Skill

pdf-processing/
├── SKILL.md
├── FORMS.md
├── REFERENCE.md
└── scripts/
    ├── fill_form.py
    └── validate.py

SKILL.md:

---
name: PDF Processing
description: Extract text, fill forms, merge PDFs. Use when working with PDF files, forms, or document extraction. Requires pypdf and pdfplumber packages.
---

# PDF Processing

## Quick Start

Extract text:
```python
import pdfplumber
with pdfplumber.open("doc.pdf") as pdf:
    text = pdf.pages[0].extract_text()
```

For form filling, see [FORMS.md](FORMS.md).
For detailed API reference, see [REFERENCE.md](REFERENCE.md).

## Requirements

Install packages:
```bash
pip install pypdf pdfplumber
```

Best Practices Summary

✅ Do:

  • Write descriptions in third person
  • Include trigger terms in description
  • Keep SKILL.md under 500 lines
  • Use progressive disclosure for large content
  • Be concise - assume Claude is smart
  • Use consistent terminology
  • Test with relevant questions
  • Keep skills focused (one capability per skill)

❌ Don't:

  • Write vague descriptions
  • Include time-sensitive information
  • Nest references more than one level deep
  • Over-explain things Claude already knows
  • Create overly broad skills
  • Use inconsistent terminology

Deleting Skills

Guidance for safely removing Agent Skills from Claude Code.

Quick Deletion Process

1. Locate the Skill

# Personal skills
ls ~/.claude/skills/

# Project skills
ls .claude/skills/

# Find specific skill
find ~/.claude/skills -name "SKILL.md" -path "*/my-skill/*"

2. Create Backup (Recommended)

Before deleting, create a backup:

# Backup entire skill directory
cp -r ~/.claude/skills/my-skill ~/.claude/skills/my-skill.backup

# Or backup to a dedicated location
cp -r ~/.claude/skills/my-skill ~/skill-backups/my-skill-$(date +%Y%m%d)

3. Delete the Skill

# Personal skill
rm -rf ~/.claude/skills/my-skill

# Project skill
rm -rf .claude/skills/my-skill

4. Verify Removal

Restart Claude Code and verify the skill is no longer available:

Ask Claude: "What skills are available?"

Deletion Scenarios

Delete Personal Skill

# Check it exists
ls ~/.claude/skills/my-skill/SKILL.md

# Backup
cp -r ~/.claude/skills/my-skill ~/.claude/skills/my-skill.backup

# Delete
rm -rf ~/.claude/skills/my-skill

# Verify
ls ~/.claude/skills/

No restart needed for personal skills if Claude Code wasn't using them.

Delete Project Skill

For skills in .claude/skills/ that are committed to git:

# Backup first
cp -r .claude/skills/my-skill ~/skill-backups/my-skill-backup

# Remove from git
git rm -rf .claude/skills/my-skill

# Commit
git commit -m "Remove my-skill: no longer needed"

# Push
git push

Important: Notify team members so they can pull the changes and restart Claude Code.

Delete Plugin Skill

Plugin skills are managed by the plugin system. To remove:

Option 1: Disable the plugin

/plugin disable plugin-name@marketplace-name

Option 2: Uninstall the plugin

/plugin uninstall plugin-name@marketplace-name

You cannot delete individual skills from plugins. To modify plugin skills, fork the plugin or contact the plugin author.

Bulk Deletion

Delete Multiple Personal Skills

# List all personal skills
ls ~/.claude/skills/

# Backup all before deletion
cp -r ~/.claude/skills ~/skill-backups/all-skills-$(date +%Y%m%d)

# Delete specific skills
rm -rf ~/.claude/skills/skill1
rm -rf ~/.claude/skills/skill2
rm -rf ~/.claude/skills/skill3

Delete All Unused Skills

# Backup first
cp -r ~/.claude/skills ~/skill-backups/all-skills-$(date +%Y%m%d)

# Review each skill before deleting
for skill in ~/.claude/skills/*; do
    echo "Skill: $(basename $skill)"
    echo "Description:"
    head -n 10 "$skill/SKILL.md"
    read -p "Delete this skill? (y/n) " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        rm -rf "$skill"
        echo "Deleted: $(basename $skill)"
    fi
done

Backup Strategies

Before Major Cleanup

Create a timestamped backup of all skills:

# Backup all personal skills
tar -czf ~/skill-backups/personal-skills-$(date +%Y%m%d-%H%M%S).tar.gz \
    -C ~ .claude/skills

# Backup all project skills (from project root)
tar -czf ~/skill-backups/project-skills-$(date +%Y%m%d-%H%M%S).tar.gz \
    .claude/skills

Restore from Backup

# Restore all personal skills
tar -xzf ~/skill-backups/personal-skills-20251016-143022.tar.gz \
    -C ~

# Restore specific skill
cp -r ~/skill-backups/my-skill-20251016 ~/.claude/skills/my-skill

Version Control Best Practices

For Project Skills

When deleting project skills from git repositories:

# Create feature branch
git checkout -b remove-unused-skills

# Remove skill
git rm -rf .claude/skills/old-skill

# Commit with explanation
git commit -m "Remove old-skill: replaced by new-skill

The old-skill has been superseded by new-skill which provides
better performance and additional features.

Team members should:
1. Pull this change
2. Restart Claude Code
3. The skill will no longer be available"

# Push and create PR
git push origin remove-unused-skills

Document Removal

Update project documentation:

# Changelog

## 2025-10-16

### Removed
- **old-skill**: Replaced by new-skill. See migration guide below.

### Migration Guide
If you were using old-skill:
1. Update your workflows to use new-skill instead
2. Key differences: [list changes]
3. See examples: [link to new-skill examples]

Common Deletion Scenarios

Skill No Longer Needed

# Simple removal
rm -rf ~/.claude/skills/deprecated-skill

Skill Replaced by Better Version

# Backup old version (might need reference)
cp -r ~/.claude/skills/old-skill ~/skill-backups/old-skill-reference

# Delete old version
rm -rf ~/.claude/skills/old-skill

# The new version is already in place
ls ~/.claude/skills/new-skill

Skill Conflicts with Another

If two skills activate on similar triggers:

# Review both skills
cat ~/.claude/skills/skill-a/SKILL.md | head -n 10
cat ~/.claude/skills/skill-b/SKILL.md | head -n 10

# Decide which to keep (usually the more specific one)
# Delete the less useful one
rm -rf ~/.claude/skills/skill-b

Experimental Skill Didn't Work Out

# No backup needed for failed experiments
rm -rf ~/.claude/skills/experiment-skill

Safety Checks

Before Deleting, Ask:

  1. Is this skill used by others?

    • For project skills, check with team
    • For personal skills, just you
  2. Is there a migration path?

    • If replacing, document new approach
    • If removing, explain alternatives
  3. Have I backed it up?

    • Can I restore if needed?
    • Do I have the content archived?
  4. Will this break workflows?

    • Check dependencies
    • Update documentation
    • Notify affected users

Validation Checklist

Before deleting a project skill:

  • Created backup
  • Checked for dependents (other skills referencing this one)
  • Notified team members
  • Updated documentation
  • Committed to version control with clear message
  • Verified skill is not critical to current workflows

Troubleshooting

Skill Still Appears After Deletion

Problem: Deleted skill still shows up in available skills

Solution: Restart Claude Code to refresh skill registry

Cannot Delete (Permission Denied)

# Check permissions
ls -la ~/.claude/skills/my-skill/

# Fix permissions if needed
chmod -R u+w ~/.claude/skills/my-skill/

# Then delete
rm -rf ~/.claude/skills/my-skill

Accidentally Deleted Important Skill

If you have a backup:

# Restore from backup
cp -r ~/skill-backups/my-skill ~/.claude/skills/my-skill

# Restart Claude Code

If no backup:

  • Check git history (for project skills)
  • Check Time Machine or system backups
  • Recreate from memory or documentation

Team Member Still Has Deleted Skill

For project skills:

# Team member should pull latest changes
git pull

# Remove any local-only changes
rm -rf .claude/skills/deleted-skill

# Restart Claude Code

Post-Deletion Cleanup

Verify Skill List

After deletion, verify skills are as expected:

Ask Claude: "What skills are available?"

Or check filesystem:

# Personal skills
ls ~/.claude/skills/

# Project skills
ls .claude/skills/

Update Documentation

If maintaining skill documentation:

# Available Skills

## Active Skills
- skill-a: Description
- skill-b: Description

## Deprecated Skills
- ~~old-skill~~: Removed 2025-10-16, replaced by new-skill

Clean Up References

Check for references to deleted skills in:

  • Documentation files
  • README files
  • Other skills that might reference it
  • Workflow documentation
# Find references
grep -r "old-skill" .claude/
grep -r "old-skill" docs/

Reading Skills

Guidance for listing, viewing, and inspecting Agent Skills in Claude Code.

Quick Reference

List All Available Skills

Ask Claude:

What skills are available?

or

List all available skills

Claude will show all skills from:

  • Personal skills (~/.claude/skills/)
  • Project skills (.claude/skills/)
  • Plugin skills (from installed plugins)

View Specific Skill

# Personal skill
cat ~/.claude/skills/my-skill/SKILL.md

# Project skill
cat .claude/skills/my-skill/SKILL.md

# Open in editor
code ~/.claude/skills/my-skill/SKILL.md

Filesystem Commands

List Personal Skills

# List all personal skills
ls ~/.claude/skills/

# List with details
ls -la ~/.claude/skills/

# Show skill names only
ls -1 ~/.claude/skills/

List Project Skills

# From project root
ls .claude/skills/

# Find all project skills recursively
find . -path "*/.claude/skills/*/SKILL.md"

View Skill Metadata

Extract name and description from YAML frontmatter:

# View frontmatter
head -n 10 ~/.claude/skills/my-skill/SKILL.md

# Extract just description
grep "description:" ~/.claude/skills/my-skill/SKILL.md

Check Skill Structure

# List all files in skill directory
ls -la ~/.claude/skills/my-skill/

# Show directory tree
tree ~/.claude/skills/my-skill/

# Or without tree command
find ~/.claude/skills/my-skill/ -type f

Inspection Patterns

View Complete Skill Content

# View entire SKILL.md
cat ~/.claude/skills/my-skill/SKILL.md

# View with pagination
less ~/.claude/skills/my-skill/SKILL.md

# View with line numbers
cat -n ~/.claude/skills/my-skill/SKILL.md

View Skill Supporting Files

# List all markdown files
ls ~/.claude/skills/my-skill/*.md

# View reference file
cat ~/.claude/skills/my-skill/reference.md

# View examples
cat ~/.claude/skills/my-skill/examples.md

Search Within Skills

# Search for keyword in specific skill
grep -r "PDF" ~/.claude/skills/pdf-processing/

# Search across all personal skills
grep -r "authentication" ~/.claude/skills/

# Case-insensitive search
grep -ri "docker" ~/.claude/skills/

Check Skill Size

# Size of SKILL.md
wc -l ~/.claude/skills/my-skill/SKILL.md

# Total size of skill directory
du -sh ~/.claude/skills/my-skill/

# Detailed size breakdown
du -h ~/.claude/skills/my-skill/*

Finding Skills

By Name Pattern

# Find skills with "pdf" in name
ls ~/.claude/skills/ | grep -i pdf

# Find all skills with "processing" in name
find ~/.claude/skills/ -type d -name "*processing*"

By Description Content

# Find skills mentioning "Excel"
grep -l "Excel" ~/.claude/skills/*/SKILL.md

# Find skills with "API" in description
grep "description:.*API" ~/.claude/skills/*/SKILL.md

By Trigger Terms

# Find which skill handles "docker"
for skill in ~/.claude/skills/*/SKILL.md; do
    if grep -qi "docker" "$skill"; then
        echo "Found in: $(dirname $skill)"
        grep "description:" "$skill"
    fi
done

Understanding Skill Structure

Check if Skill Has allowed-tools

# Check frontmatter for allowed-tools
head -n 15 ~/.claude/skills/my-skill/SKILL.md | grep "allowed-tools"

If present, the skill restricts which tools Claude can use.

Identify Progressive Disclosure

# Check if skill references other files
grep -E "\[.*\]\(.*\.md\)" ~/.claude/skills/my-skill/SKILL.md

# List referenced files
ls ~/.claude/skills/my-skill/*.md

Skills with multiple .md files use progressive disclosure.

Check for Scripts

# Check if skill has scripts
ls ~/.claude/skills/my-skill/scripts/

# Check for templates
ls ~/.claude/skills/my-skill/templates/

Comparing Skills

Compare Two Skill Descriptions

# View both descriptions
echo "=== Skill A ==="
head -n 10 ~/.claude/skills/skill-a/SKILL.md

echo "=== Skill B ==="
head -n 10 ~/.claude/skills/skill-b/SKILL.md

Find Overlapping Skills

# Check if two skills have similar descriptions
skill_a_desc=$(grep "description:" ~/.claude/skills/skill-a/SKILL.md)
skill_b_desc=$(grep "description:" ~/.claude/skills/skill-b/SKILL.md)

echo "Skill A: $skill_a_desc"
echo "Skill B: $skill_b_desc"

If descriptions overlap significantly, consider consolidating.

Diff Two Skills

# Compare skill structures
diff ~/.claude/skills/skill-a/SKILL.md ~/.claude/skills/skill-b/SKILL.md

# Or use a better diff tool
code --diff ~/.claude/skills/skill-a/SKILL.md ~/.claude/skills/skill-b/SKILL.md

Validation Checks

Verify YAML Frontmatter

# Check frontmatter syntax
head -n 15 ~/.claude/skills/my-skill/SKILL.md

# Verify required fields present
head -n 10 ~/.claude/skills/my-skill/SKILL.md | grep -E "(name:|description:)"

Required fields:

  • name: - Skill name
  • description: - What it does and when to use it

Check File Existence

# Verify SKILL.md exists
test -f ~/.claude/skills/my-skill/SKILL.md && echo "✓ SKILL.md exists" || echo "✗ SKILL.md missing"

# Check for broken references
for ref in $(grep -oE "\[.*\]\((.*\.md)\)" ~/.claude/skills/my-skill/SKILL.md | grep -oE "\(.*\.md\)" | tr -d '()'); do
    if [ -f "~/.claude/skills/my-skill/$ref" ]; then
        echo "✓ $ref exists"
    else
        echo "✗ $ref missing"
    fi
done

Validate Description Length

# Check description character count
desc=$(grep "description:" ~/.claude/skills/my-skill/SKILL.md | cut -d':' -f2-)
echo "Description length: ${#desc} characters (max 1024)"

if [ ${#desc} -gt 1024 ]; then
    echo "⚠️  Description too long!"
fi

Organizing Skill Information

Create Skill Inventory

# Generate list of all skills with descriptions
for skill in ~/.claude/skills/*/SKILL.md; do
    skill_name=$(dirname $skill | xargs basename)
    description=$(grep "description:" "$skill" | cut -d':' -f2-)
    echo "- **$skill_name**: $description"
done

Export Skill Documentation

# Create markdown file with all skill info
{
    echo "# Personal Skills Inventory"
    echo ""
    for skill in ~/.claude/skills/*/SKILL.md; do
        echo "## $(grep "name:" $skill | cut -d':' -f2-)"
        echo ""
        echo "**Description**: $(grep "description:" $skill | cut -d':' -f2-)"
        echo ""
        echo "**Location**: $skill"
        echo ""
        echo "---"
        echo ""
    done
} > ~/skills-inventory.md

Generate Skills Summary

# Count skills by location
personal_count=$(ls ~/.claude/skills/ 2>/dev/null | wc -l)
project_count=$(ls .claude/skills/ 2>/dev/null | wc -l)

echo "Skills Summary:"
echo "  Personal: $personal_count"
echo "  Project:  $project_count"
echo "  Total:    $((personal_count + project_count))"

Troubleshooting

Skill Not Appearing

Check if file exists:

ls ~/.claude/skills/my-skill/SKILL.md

Check YAML syntax:

head -n 10 ~/.claude/skills/my-skill/SKILL.md

Verify location:

  • Personal: ~/.claude/skills/skill-name/SKILL.md
  • Project: .claude/skills/skill-name/SKILL.md

Cannot Read Skill File

Check permissions:

ls -la ~/.claude/skills/my-skill/SKILL.md

# Fix if needed
chmod 644 ~/.claude/skills/my-skill/SKILL.md

Skill Directory Empty

# Check if skills directory exists
ls -la ~/.claude/skills/

# Create if missing
mkdir -p ~/.claude/skills/

Best Practices

Regular Skill Audits

Periodically review your skills:

# List all skills with last modified date
ls -lt ~/.claude/skills/*/SKILL.md

# Find skills not modified in 90 days
find ~/.claude/skills/ -name "SKILL.md" -mtime +90

Consider updating or removing stale skills.

Document Your Skills

Maintain a skills inventory:

# My Claude Code Skills

## Active Skills
- **pdf-processing**: Extract and manipulate PDFs
- **data-analysis**: Analyze CSV and Excel files
- **commit-helper**: Generate git commit messages

## Experimental
- **new-skill**: Testing new approach

## Deprecated
- **old-skill**: Replaced by new-skill

Track Skill Usage

Note which skills you use frequently:

# Skill Usage Notes

## Frequently Used
- commit-helper (daily)
- pdf-processing (weekly)

## Rarely Used
- legacy-api (consider removing)

## Never Used
- experiment-1 (delete)

Updating Skills

Guidance for modifying and maintaining existing Agent Skills in Claude Code.

Quick Update Process

1. Locate the Skill

# Personal skills
ls ~/.claude/skills/*/SKILL.md

# Project skills
ls .claude/skills/*/SKILL.md

# Find specific skill
find ~/.claude/skills -name "SKILL.md" -path "*/my-skill/*"

2. Edit SKILL.md

# Personal
code ~/.claude/skills/my-skill/SKILL.md

# Project
code .claude/skills/my-skill/SKILL.md

3. Apply Changes

Changes take effect the next time Claude Code starts.

If Claude Code is already running: Restart it to load updates.

Common Update Scenarios

Update Description

The description is critical for skill discovery. Update it when:

  • Skill's purpose has expanded
  • Trigger terms need refinement
  • Usage context has changed

Requirements:

  • Write in third person
  • Include what the skill does AND when to use it
  • Add specific trigger terms
  • Maximum 1024 characters

Before:

description: Helps with PDFs

After:

description: Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction.

Update Instructions

When adding new features or improving clarity:

Before (vague):

## Instructions

Process the data and generate output.

After (specific):

## Instructions

1. Load data from CSV file using pandas:
   ```python
   import pandas as pd
   df = pd.read_csv('data.csv')
  1. Clean data:

    • Remove null values
    • Normalize formats
    • Validate ranges
  2. Generate summary statistics:

    summary = df.describe()
    
  3. Export results to Excel:

    summary.to_excel('output.xlsx')
    

### Add Examples

Examples improve skill effectiveness. Add input/output pairs:

````markdown
## Examples

**Example 1: Simple Extraction**
Input: PDF with plain text
Output:
```python
import pdfplumber
with pdfplumber.open("document.pdf") as pdf:
    for page in pdf.pages:
        text = page.extract_text()
        print(text)

Example 2: Table Extraction Input: PDF with tables Output:

import pdfplumber
with pdfplumber.open("tables.pdf") as pdf:
    for page in pdf.pages:
        tables = page.extract_tables()
        for table in tables:
            # Process table data
            pass

### Add or Update allowed-tools

Restrict which tools Claude can use when the skill is active:

**Before** (no restrictions):
```yaml
---
name: Data Analyzer
description: Analyze data files and generate reports
---
```

**After** (read-only):
```yaml
---
name: Data Analyzer
description: Analyze data files and generate reports
allowed-tools: Read, Grep, Glob
---
```

This ensures Claude can't modify files when using this skill.

### Split Large Skills

If SKILL.md exceeds 500 lines, use progressive disclosure:

**Before** (single large file):
```markdown
# PDF Processing

## Basic Text Extraction
[100 lines of content...]

## Advanced Table Extraction
[150 lines of content...]

## Form Filling
[200 lines of content...]

## API Reference
[300 lines of content...]
```

**After** (split into multiple files):

```
pdf-processing/
├── SKILL.md              # Overview and quick start
├── tables.md             # Table extraction guide
├── forms.md              # Form filling guide
└── reference.md          # Complete API docs
```

**SKILL.md**:
```markdown
# PDF Processing

## Quick Start
[Brief overview]

## Text Extraction
[Common usage]

## Advanced Features
- **Table Extraction**: See [tables.md](tables.md)
- **Form Filling**: See [forms.md](forms.md)
- **Complete API**: See [reference.md](reference.md)
```

### Update Reference Files

When updating longer reference files (>100 lines), include a table of contents:

```markdown
# API Reference

## Contents
- Authentication and setup
- Core methods (create, read, update, delete)
- Advanced features (batch operations, webhooks)
- Error handling patterns
- Code examples

## Authentication and Setup
...

## Core Methods
...
```

## Refactoring Patterns

### Make Skills More Concise

Remove unnecessary explanations:

**Before** (too verbose):
```markdown
JSON (JavaScript Object Notation) is a data format that is commonly used
for APIs and configuration files. It uses key-value pairs and is human-readable.
To parse JSON in Python, you'll need to import the json module, which is
part of the standard library so you don't need to install anything extra.
```

**After** (concise):
```markdown
Parse JSON:
```python
import json
with open('data.json') as f:
    data = json.load(f)
```
```

### Improve Terminology Consistency

**Before** (inconsistent):
```markdown
Use the API endpoint to send a request to the URL. The route will return...
The path can be accessed via the API...
```

**After** (consistent):
```markdown
Use the API endpoint to send a request. The endpoint will return...
The endpoint can be accessed via...
```

(Always use "API endpoint", never mix with "URL", "route", "path")

### Add Workflows for Complex Tasks

When users struggle with multi-step processes:

````markdown
## Data Analysis Workflow

Copy this checklist and track your progress:

```
Task Progress:
- [ ] Step 1: Load and validate data
- [ ] Step 2: Clean and normalize data
- [ ] Step 3: Perform analysis
- [ ] Step 4: Generate visualizations
- [ ] Step 5: Export results
```

**Step 1: Load and validate data**
```python
import pandas as pd
df = pd.read_csv('data.csv')
assert len(df) > 0, "Data file is empty"
assert not df.isnull().all().any(), "Column has all null values"
```

**Step 2: Clean and normalize data**
[Detailed instructions...]

**Step 3: Perform analysis**
[Detailed instructions...]

**Step 4: Generate visualizations**
[Detailed instructions...]

**Step 5: Export results**
[Detailed instructions...]

Add Feedback Loops

For error-prone operations:

Before (no validation):

1. Make changes to config.json
2. Deploy application
3. Test in production

After (with validation loop):

1. Make changes to config.json
2. **Validate immediately**: `python scripts/validate_config.py`
3. If validation fails:
   - Review error messages
   - Fix issues in config.json
   - Run validation again
4. **Only proceed when validation passes**
5. Deploy to staging
6. Test in staging environment
7. Deploy to production

Version Management

Document Changes

Add a version history section to track updates:

# My Skill

## Version History
- v2.1.0 (2025-10-16): Added batch processing support
- v2.0.0 (2025-10-01): Breaking changes to API
- v1.1.0 (2025-09-15): Added table extraction
- v1.0.0 (2025-09-01): Initial release

## Instructions
...

Deprecate Features

When removing old approaches:

## Current Method

Use the v2 API for all new integrations:
```python
from api.v2 import Client
client = Client(api_key="...")

Old Patterns

Legacy v1 API (deprecated 2025-08)

The v1 API used a different client:

from api.v1 import OldClient  # Don't use

This API is no longer supported. Migrate to v2.

```

Testing Updates

1. Verify YAML Syntax

After updating frontmatter:

cat SKILL.md | head -n 10

Check:

  • Opening --- on line 1
  • Closing --- before markdown content
  • Valid YAML (no tabs, correct indentation)
  • No special characters in unquoted strings

2. Test Description Changes

If you updated the description, test that Claude uses the skill appropriately:

Ask questions that match your new description and verify Claude activates the skill.

3. Check File References

If you added or renamed reference files, verify links work:

cd ~/.claude/skills/my-skill

# Check that referenced files exist
ls -l *.md

4. Verify Examples Run

If you added code examples, test them:

# Extract and run Python examples
python test_examples.py

Common Update Mistakes

❌ Forgetting to Restart

Problem: Updates don't appear after editing SKILL.md

Solution: Restart Claude Code to load changes

❌ Breaking YAML Frontmatter

Problem: Skill stops working after update

Check:

cat SKILL.md | head -n 10

Common issues:

  • Missing closing ---
  • Tabs instead of spaces
  • Unquoted strings with colons
  • Incorrect indentation

❌ Making Description Too Generic

Problem: Skill activates too often or not at all

Before:

description: Helps with files

After:

description: Analyzes log files and system metrics for performance monitoring, debugging, and diagnostics. Use when analyzing logs, system performance, or troubleshooting issues.

❌ Adding Too Much Content

Problem: SKILL.md becomes >500 lines

Solution: Use progressive disclosure:

  • Keep core instructions in SKILL.md
  • Move detailed content to separate reference files
  • Link to reference files from SKILL.md

❌ Nested References

Problem: Claude doesn't find information in deeply nested files

Bad (too deep):

# SKILL.md → references advanced.md
# advanced.md → references details.md
# details.md → has the actual info

Good (one level):

# SKILL.md → directly references all docs
- advanced.md
- details.md
- examples.md

Rollback Strategy

Create Backup Before Major Changes

# Backup entire skill
cp -r ~/.claude/skills/my-skill ~/.claude/skills/my-skill.backup

# Or just backup SKILL.md
cp ~/.claude/skills/my-skill/SKILL.md ~/.claude/skills/my-skill/SKILL.md.backup

Restore from Backup

# Restore entire skill
rm -rf ~/.claude/skills/my-skill
mv ~/.claude/skills/my-skill.backup ~/.claude/skills/my-skill

# Or just restore SKILL.md
mv ~/.claude/skills/my-skill/SKILL.md.backup ~/.claude/skills/my-skill/SKILL.md

Use Version Control

For project skills (in git repositories):

# See what changed
git diff .claude/skills/my-skill/SKILL.md

# Revert changes
git checkout .claude/skills/my-skill/SKILL.md

# Commit updates
git add .claude/skills/my-skill/
git commit -m "Update my-skill: add batch processing support"

Team Collaboration

Communicate Changes

For project skills, notify team members:

git commit -m "Update PDF skill: add form filling capability

- Added form filling workflow
- Updated description to include 'forms' trigger
- Added forms.md reference guide

Team members should restart Claude Code to get updates."

git push

Review Process

For shared skills, consider a review process:

  1. Create feature branch
  2. Update skill
  3. Test thoroughly
  4. Create pull request
  5. Have teammate review
  6. Merge when approved
  7. Team members pull and restart

Dense Paragraph Response Style

When this snippet is active, respond using the following style:

Response Format

  • Write in flowing paragraphs rather than bullet points or numbered lists
  • Each sentence should pack high informational density
  • Avoid filler words and redundant phrasing
  • Connect ideas smoothly with logical transitions
  • Prioritize clarity and conciseness over exhaustive structure

What to Avoid

  • Long bulleted lists that could be condensed into prose
  • Excessive use of headers and subheaders that fragment the narrative
  • Repetitive phrasing like "It's important to note that..." or "Additionally..."
  • Overly formal or academic tone when simpler language suffices

Example Transformation

Before (structured):

The main benefits are:
- Faster processing
- Lower memory usage
- Better scalability

Additionally, it's important to note that the implementation requires:
- Python 3.8+
- Docker installed
- At least 4GB RAM

After (dense paragraphs):

The approach offers faster processing, lower memory usage, and better scalability. Implementation requires Python 3.8+, Docker, and at least 4GB RAM.

Key Principle

Every sentence earns its place by conveying meaningful information. If a sentence can be removed without losing substance, it should be condensed or eliminated.

Common Apache License 2.0 Violations

Examples of common mistakes when working with Apache-licensed code and how to fix them.


Violation 1: Removing Original Copyright

❌ What NOT to Do

# Original file had:
# Copyright 2024 Original Author
# Licensed under the Apache License, Version 2.0...

# Your derivative work:
# Copyright 2025 Your Name
# Licensed under the Apache License, Version 2.0...

Problem: Original copyright removed, violating Section 4c (retain attribution notices).

✅ How to Fix

# Copyright 2024 Original Author
# Copyright 2025 Your Name (modifications)
#
# Licensed under the Apache License, Version 2.0...

Key: Always retain original copyright. Add your copyright alongside it, not instead of it.


Violation 2: No Change Documentation

❌ What NOT to Do

# Copyright 2024 Original Author
# Copyright 2025 Your Name
#
# Licensed under the Apache License, Version 2.0...

def process_data(data):
    # Completely rewrote this function
    # But didn't document that it was modified
    return transformed_data

Problem: Modified file without prominent notice stating changes, violating Section 4b.

✅ How to Fix

Option 1: In-file notice

# Copyright 2024 Original Author
# Modified 2025-10-26 by Your Name
# Changes: Rewrote process_data() to use streaming instead of batch processing
#
# Licensed under the Apache License, Version 2.0...

def process_data(data):
    # Modified implementation
    return transformed_data

Option 2: CHANGELOG file

## Modified 2025-10-26 by Your Name

### src/processor.py
- Rewrote process_data() function to use streaming
- Changed from batch processing to real-time processing
- Updated error handling

Violation 3: Missing LICENSE File

❌ What NOT to Do

myproject/
├── README.md
└── src/
    ├── main.py (uses Apache-licensed code)
    └── utils.py (modified from Apache project)

Problem: No LICENSE file included, violating Section 4a (must provide license copy).

✅ How to Fix

myproject/
├── LICENSE.txt          # ← Add this!
├── README.md
└── src/
    ├── main.py
    └── utils.py

LICENSE.txt must contain:

  • Complete Apache License 2.0 text
  • Not just a link or reference

Violation 4: Ignoring NOTICE File

❌ What NOT to Do

Original project has:

original-project/
├── LICENSE
├── NOTICE              # Original has NOTICE
└── src/

Your derivative work:

my-derivative/
├── LICENSE             # You included LICENSE
└── src/               # But forgot NOTICE!

Problem: Original had NOTICE file, but derivative doesn't include it, violating Section 4d.

✅ How to Fix

my-derivative/
├── LICENSE
├── NOTICE              # ← Must include this!
└── src/

NOTICE file content:

[Original NOTICE content - copy verbatim]

=====================================================

Derivative Work Modifications:
Copyright 2025 Your Name

Modified components:
- [List your changes]

Violation 5: Vague Change Documentation

❌ What NOT to Do

# Modified by Someone
# Changes: Updated the code

Problem: Change notice lacks detail - who is "Someone"? What was "Updated"? When?

✅ How to Fix

# Modified 2025-10-26 by Jane Smith <jane@example.com>
# Changes:
#   - Added null check in parseInput()
#   - Refactored error handling for clarity
#   - Updated default timeout from 30s to 60s

Key elements:

  • Who: Full name or identifier
  • What: Specific changes made
  • When: Date of modification (optional but recommended)

Violation 6: LICENSE Link Instead of Full Text

❌ What NOT to Do

LICENSE file contains:

This project is licensed under Apache License 2.0.
See: http://www.apache.org/licenses/LICENSE-2.0

Problem: LICENSE file must contain full license text, not just a link (Section 4a).

✅ How to Fix

LICENSE file must contain complete text:

                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

   [... full license text ...]

Violation 7: Modifying Original NOTICE Content

❌ What NOT to Do

Original NOTICE:

Apache Example Project
Copyright 2024 The Apache Software Foundation

This product includes software developed at
The Apache Software Foundation (http://www.apache.org/).

Your modified NOTICE:

Apache Example Project
Copyright 2024 The Apache Software Foundation
Enhanced and improved by Your Name 2025  ← WRONG!

This product includes software developed at
The Apache Software Foundation (http://www.apache.org/).

Problem: Modified original attribution text, violating Section 4d.

✅ How to Fix

Apache Example Project
Copyright 2024 The Apache Software Foundation

This product includes software developed at
The Apache Software Foundation (http://www.apache.org/).

=====================================================

Derivative Work:
Copyright 2025 Your Name

Modifications and enhancements to the original software.

Key: Original NOTICE content must remain unchanged. Add your notices separately.


Violation 8: Claiming Original as Your Own

❌ What NOT to Do

README.md:

# My Awesome Project

Created by Your Name, 2025.

This project does amazing things...

Problem: No mention of original Apache-licensed work or attribution.

✅ How to Fix

README.md:

# My Awesome Project

Created by Your Name, 2025.

This project is based on [Original Project](url) by Original Author,
licensed under Apache License 2.0.

## Modifications

This derivative work includes:
- Feature X
- Enhancement Y
- Bug fix Z

## License

This project is licensed under Apache License 2.0.
See LICENSE file for details.

## Attribution

Original work: [Original Project](url)
Copyright: Original Author
License: Apache License 2.0

Violation 9: Incomplete Binary Distribution

❌ What NOT to Do

Source distribution has LICENSE, but binary doesn't:

myapp-1.0-binary.zip
├── myapp.exe
├── README.txt
└── config.ini

Problem: Binary distribution must include LICENSE (Section 4a).

✅ How to Fix

myapp-1.0-binary.zip
├── LICENSE.txt         # ← Add this!
├── NOTICE.txt          # ← If original had NOTICE
├── myapp.exe
├── README.txt
└── config.ini

Violation 10: No Change Notice in CHANGELOG

❌ What NOT to Do

CHANGELOG.md:

# Changelog

## v2.0.0 - 2025-10-26

- Added feature X
- Fixed bug Y
- Improved performance

Problem: No indication that this is derivative work, who made changes, or attribution to original.

✅ How to Fix

CHANGELOG.md:

# Changelog

## Modified 2025-10-26 by Your Name

**Derivative Work Based on Original Project v1.0**

Changes to derivative work:
- Added feature X
- Fixed bug Y in data processing
- Improved performance of query handler

**Original work attribution:**
- Source: https://github.com/original/project
- License: Apache License 2.0
- Copyright: Original Author

---

[Original changelog below]

## v1.0.0 - 2024-01-01 (Original Release)
...

Violation 11: Selectively Retaining Copyright

❌ What NOT to Do

# Kept copyright from main.py:
# Copyright 2024 Original Author

# But removed copyright from utils.py because "I rewrote most of it":
# Copyright 2025 Your Name (modifications)

Problem: Must retain ALL original copyright notices, even for heavily modified files.

✅ How to Fix

# main.py:
# Copyright 2024 Original Author
# Licensed under the Apache License, Version 2.0...

# utils.py (even though heavily modified):
# Copyright 2024 Original Author
# Copyright 2025 Your Name (modifications)
# Licensed under the Apache License, Version 2.0...

Key: Retain original copyright regardless of how much you modified the file. If you modified it substantially, add your copyright alongside original.


Violation 12: Wrong License File Location

❌ What NOT to Do

myproject/
├── README.md
├── src/
│   └── main.py
└── legal/
    └── licenses/
        └── apache/
            └── LICENSE.txt  ← Too buried!

Problem: LICENSE file is hard to find, not "prominent."

✅ How to Fix

Option 1: Root directory (best)

myproject/
├── LICENSE.txt         # ← Easy to find!
├── README.md
└── src/
    └── main.py

Option 2: If you must use subdirectory, document it

myproject/
├── README.md           # README mentions: "See legal/LICENSE.txt"
├── src/
│   └── main.py
└── legal/
    └── LICENSE.txt

Violation 13: Generic "Based On" Without Details

❌ What NOT to Do

# README.md

Based on some Apache-licensed code.

Problem: Vague attribution doesn't meet Apache requirements.

✅ How to Fix

# README.md

## Attribution

This project is a derivative work based on:

**Original Work:** [Project Name](https://github.com/original/project)
**Original Author:** Original Author Name
**Original Copyright:** Copyright 2024 Original Author
**License:** Apache License 2.0

**Modifications:** See CHANGELOG.md for complete list of changes.

Violation 14: Forgetting File Headers

❌ What NOT to Do

# main.py - no license header

def my_function():
    pass

Problem: While not strictly required, missing file headers make it unclear what license applies to individual files.

✅ How to Fix (Recommended Best Practice)

# Copyright 2024 Original Author
# Copyright 2025 Your Name (modifications)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

def my_function():
    pass

Quick Violation Check

Run this checklist to avoid common violations:

LICENSE File:
- [ ] LICENSE file in root or documented location
- [ ] Contains FULL Apache 2.0 text (not just a link)
- [ ] Included in both source AND binary distributions

Copyright Notices:
- [ ] ALL original copyright notices retained
- [ ] Did NOT modify any original copyright text
- [ ] Added your copyright alongside (not replacing) original

Change Documentation:
- [ ] Modified files have change notices
- [ ] Change notices include: who, what, when
- [ ] CHANGELOG or in-file documentation exists
- [ ] Attribution to original work is clear

NOTICE File:
- [ ] If original had NOTICE, yours includes it
- [ ] Original NOTICE content is UNCHANGED
- [ ] Your additions are clearly separated
- [ ] NOTICE file is in prominent location

README/Documentation:
- [ ] Mentions Apache License 2.0
- [ ] Attributes original work with specifics
- [ ] Links to original source
- [ ] Documents your modifications

Real-World Example: Correct Derivative Work

Here's a complete example of a properly licensed derivative work:

my-derivative-project/
├── LICENSE.txt                    # Full Apache 2.0 text
├── NOTICE.txt                     # Preserved original + additions
├── CHANGELOG.md                   # Documents all changes
├── README.md                      # Attribution & license info
└── src/
    ├── main.py                   # Proper file headers
    └── utils.py                  # Change notices

LICENSE.txt:

[Complete Apache License 2.0 text]

NOTICE.txt:

Original Project Name
Copyright 2024 Original Author

[Original NOTICE content - unchanged]

=====================================================

Derivative Work:
Copyright 2025 Your Name

This derivative work includes modifications to the original software.
See CHANGELOG.md for details.

Original source: https://github.com/original/project

CHANGELOG.md:

# CHANGELOG

## Modified 2025-10-26 by Your Name

**Changes to derivative work:**

### src/main.py
- Added error handling for network timeouts
- Refactored data processing loop
- Updated logging format

### src/utils.py
- Added new utility function: validate_input()
- Fixed bug in date parsing

**Original work attribution:**
- Source: https://github.com/original/project
- License: Apache License 2.0
- Copyright: Original Author

README.md:

# My Derivative Project

## Description
This project is based on Original Project and adds features X, Y, Z.

## License
Licensed under Apache License 2.0. See LICENSE.txt.

## Attribution
This is a derivative work based on:
- **Original Project:** [link]
- **Copyright:** Original Author
- **License:** Apache License 2.0

See CHANGELOG.md for complete modification history.

src/main.py:

# Copyright 2024 Original Author
# Modified 2025-10-26 by Your Name
#
# Changes:
#   - Added error handling for network timeouts
#   - Refactored data processing loop
#
# Licensed under the Apache License, Version 2.0 (the "License");
# [... full license header ...]

def main():
    pass

Summary

Most common violations:

  1. Removing original copyright
  2. No change documentation
  3. Missing LICENSE file
  4. Ignoring NOTICE file requirements
  5. Vague or missing attribution

Golden rules:

  • Retain all original notices
  • Document all changes prominently
  • Include LICENSE in all distributions
  • Preserve NOTICE file (if original had one)
  • Attribute original work clearly

When in doubt: Over-attribute rather than under-attribute. It's better to be too thorough with attribution than to risk license violation.

Apache License 2.0 Compliance Checklist

Comprehensive checklist for ensuring Apache License 2.0 compliance in derivative works.

Section 4: Redistribution Requirements

The Apache License 2.0 Section 4 contains four key requirements (4a, 4b, 4c, 4d) that must be met when redistributing the Work or Derivative Works.


Requirement 4a: Provide License Copy

Section 4a Text:

"You must give any other recipients of the Work or Derivative Works a copy of this License"

Compliance Checklist

Source Distribution:
- [ ] LICENSE file in root directory
- [ ] LICENSE file contains complete Apache License 2.0 text
- [ ] LICENSE file is named LICENSE, LICENSE.txt, or LICENSE.md
- [ ] LICENSE file is readable (not binary or encrypted)

Binary Distribution:
- [ ] LICENSE included in distribution package
- [ ] LICENSE accessible to end users
- [ ] LICENSE in standard location (root, /licenses/, /legal/, etc.)

Documentation:
- [ ] README mentions Apache License 2.0
- [ ] Installation docs note license requirements
- [ ] File headers reference Apache License 2.0 (recommended)

Examples

✅ Compliant - Source Distribution:

myproject/
├── LICENSE.txt           # Full Apache 2.0 text
├── README.md
└── src/
    └── main.py

✅ Compliant - Binary Distribution:

myapp-installer/
├── LICENSE.txt
├── install.exe
└── docs/
    └── README.txt

❌ Non-Compliant:

  • No LICENSE file included
  • LICENSE file contains only a reference/link to license (must include full text)
  • LICENSE buried in subdirectory with no documentation

Requirement 4b: Document Changes

Section 4b Text:

"You must cause any modified files to carry prominent notices stating that You changed the files"

Compliance Checklist

Modified Files:
- [ ] Each modified file has a change notice
- [ ] Change notices are "prominent" (near top of file or in header)
- [ ] Change notices state WHAT was modified
- [ ] Change notices identify WHO made the modification
- [ ] Change notices optionally include WHEN modification occurred

Documentation:
- [ ] CHANGELOG or CHANGES file documents modifications
- [ ] Documentation lists which files were modified
- [ ] Documentation describes nature of changes

"Prominent" Means

A notice is "prominent" if:

  • It's easy to find when reading the file
  • It's near the top of the file or in a standard header location
  • It's clearly marked as a modification notice
  • It stands out from other comments

Examples

✅ Compliant - In-File Notice (Simple):

# Copyright 2024 Original Author
# Modified 2025-10-26 by Warren Zhu
#
# Licensed under the Apache License, Version 2.0...

def my_function():
    # Modified: Added error handling
    try:
        # ... implementation
    except ValueError:
        # Added exception handling
        pass

✅ Compliant - In-File Notice (Detailed):

# Copyright 2024 Original Author
#
# Modified by Warren Zhu, 2025-10-26
# Changes:
#   - Added error handling for ValueError
#   - Refactored loop for performance
#   - Updated default parameter values
#
# Licensed under the Apache License, Version 2.0...

✅ Compliant - CHANGELOG File:

# CHANGELOG

## Modified 2025-10-26 by Warren Zhu

**Changes to derivative work:**

### src/main.py
- Added error handling for edge case in process_data()
- Refactored data validation loop for performance
- Updated default timeout from 30s to 60s

### src/config.py
- Modified default configuration values
- Added new configuration option: enable_debug

### src/utils.py
- Fixed bug in date parsing function
- Added support for ISO 8601 format

**Original work attribution:**
- Source: https://github.com/original/project
- License: Apache License 2.0
- Copyright: Original Author

❌ Non-Compliant:

# Copyright 2024 Original Author
# Licensed under the Apache License, Version 2.0...

# Modified (no information about who, what, or when)
def my_function():
    pass

❌ Non-Compliant:

# Copyright 2025 Warren Zhu (missing original copyright)
# Licensed under the Apache License, Version 2.0...

def my_function():
    # Changed this function
    pass

Requirement 4c: Retain Attribution Notices

Section 4c Text:

"You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works"

Compliance Checklist

Copyright Notices:
- [ ] All original copyright notices retained
- [ ] Your copyright added for modifications (if applicable)
- [ ] Copyright year updated if file significantly modified

Patent Notices:
- [ ] All patent notices from original retained
- [ ] Patent notices retained even if not modifying patent-related code

Trademark Notices:
- [ ] All trademark notices retained
- [ ] Trademark usage complies with original guidelines

Attribution Notices:
- [ ] All attribution notices retained (e.g., "This includes code from...")
- [ ] NOTICE file content preserved (if present in original)

Exclusions:
- [ ] Only removed notices that don't pertain to derivative work
- [ ] Document rationale if any notices removed

What to Retain

Always retain:

  • Copyright notices (e.g., Copyright 2024 Author Name)
  • Patent notices (e.g., Patent No. 1234567)
  • Trademark notices (e.g., Apache Kafka is a trademark of...)
  • Attribution notices (e.g., Includes code from Project X)
  • NOTICE file contents

May exclude:

  • Notices that pertain to portions you completely removed
  • Notices for files you entirely deleted (not distributed)

Examples

✅ Compliant - Retained Original Copyright:

# Copyright 2023 Original Author
# Copyright 2024 Another Contributor
# Copyright 2025 Warren Zhu (modifications)
#
# Licensed under the Apache License, Version 2.0...

✅ Compliant - Added Your Copyright:

# Original work:
# Copyright 2024 Original Author
#
# Derivative work modifications:
# Copyright 2025 Warren Zhu
#
# Licensed under the Apache License, Version 2.0...

❌ Non-Compliant - Removed Original Copyright:

# Copyright 2025 Warren Zhu
# Licensed under the Apache License, Version 2.0...

❌ Non-Compliant - Modified Original Copyright:

# Copyright 2024-2025 Original Author and Warren Zhu
# (This changes the original notice)

Requirement 4d: Include NOTICE File

Section 4d Text:

"If the Work includes a NOTICE text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file... in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear."

Compliance Checklist

If Original Has NOTICE File:
- [ ] Checked if original work has NOTICE file
- [ ] Copied NOTICE file to derivative work
- [ ] NOTICE file in same location as original (recommended)
- [ ] NOTICE file is readable and accessible

NOTICE File Content:
- [ ] All attribution notices from original NOTICE retained
- [ ] Added your own attribution notices (if applicable)
- [ ] NOTICE clearly identifies original work
- [ ] NOTICE clearly identifies derivative work modifications

Placement Options:
- [ ] Option 1: NOTICE file in root directory (recommended)
- [ ] Option 2: Attribution in source documentation
- [ ] Option 3: Attribution in runtime display (if applicable)

Your Additions to NOTICE:
- [ ] May add your own attribution notices
- [ ] Your additions clearly separate from original notices
- [ ] Your additions do not modify original notices
- [ ] Your additions do not claim endorsement

NOTICE File Template

If original has NOTICE, use this structure:

[Original Project Name]
Copyright [year] [Original Copyright Owner]

[Original NOTICE content - DO NOT MODIFY]

=====================================================

Derivative Work Modifications:
Copyright 2025 Warren Zhu

This derivative work includes modifications to the original software.

Modified components:
- [Component 1]: [Brief description of changes]
- [Component 2]: [Brief description of changes]

Original work source: [URL]
Original work license: Apache License 2.0

Examples

✅ Compliant - Preserved Original NOTICE:

Apache Example Project
Copyright 2024 The Apache Software Foundation

This product includes software developed at
The Apache Software Foundation (http://www.apache.org/).

=====================================================

Derivative Work:
Copyright 2025 Warren Zhu

Modifications made to original Apache Example Project:
- Added feature X
- Modified component Y for performance

Original source: https://github.com/apache/example

❌ Non-Compliant - Missing Original NOTICE:

My Derivative Project
Copyright 2025 Warren Zhu

Based on Apache Example Project.

❌ Non-Compliant - Modified Original NOTICE:

Apache Example Project
Copyright 2024 The Apache Software Foundation
Modified and improved by Warren Zhu 2025  ← WRONG: modifies original notice

This product includes software developed at...

Complete Pre-Release Checklist

Run through this checklist before releasing any derivative work:

Files:
- [ ] LICENSE file present with full Apache 2.0 text
- [ ] NOTICE file present (if original had one)
- [ ] NOTICE file contains original attributions
- [ ] README or docs mention Apache License 2.0

Attribution:
- [ ] All copyright notices from original retained
- [ ] All patent notices from original retained
- [ ] All trademark notices from original retained
- [ ] Your copyright added for new/modified files

Changes:
- [ ] Modified files have change notices
- [ ] Change notices are prominent (near top of file)
- [ ] CHANGELOG or documentation lists all modifications
- [ ] Change documentation identifies who, what, when

Validation:
- [ ] Run grep for original copyright notices - all present?
- [ ] Check LICENSE file readable and complete
- [ ] Check NOTICE file (if applicable) complete
- [ ] Review README for attribution and license reference

Distribution:
- [ ] Source distributions include LICENSE
- [ ] Binary distributions include LICENSE
- [ ] Documentation package includes LICENSE
- [ ] All distribution formats have license access

Automation Scripts

Check for LICENSE File

#!/bin/bash
# check-license.sh - Verify LICENSE file exists and is valid

if [ -f "LICENSE" ] || [ -f "LICENSE.txt" ] || [ -f "LICENSE.md" ]; then
    echo "✓ LICENSE file found"

    # Check if it contains Apache License 2.0 text
    if grep -q "Apache License" LICENSE* 2>/dev/null; then
        echo "✓ Contains Apache License text"
    else
        echo "✗ LICENSE file doesn't contain Apache License text"
        exit 1
    fi
else
    echo "✗ LICENSE file not found"
    exit 1
fi

Check for Copyright Notices

#!/bin/bash
# check-copyrights.sh - Find all copyright notices

echo "Copyright notices in source files:"
grep -r "Copyright" --include="*.py" --include="*.js" --include="*.java" . | head -20

echo -e "\nChecking for modification notices:"
grep -r "Modified" --include="*.py" --include="*.js" --include="*.java" . | head -20

Validate NOTICE File

#!/bin/bash
# check-notice.sh - Verify NOTICE file if it should exist

# Check if NOTICE exists
if [ -f "NOTICE" ] || [ -f "NOTICE.txt" ]; then
    echo "✓ NOTICE file found"

    # Display content for manual review
    echo -e "\nNOTICE file content:"
    cat NOTICE*
else
    echo "⚠ No NOTICE file found"
    echo "  If original work had NOTICE, you must include it!"
fi

FAQs

Q: Do I need to add my copyright to every file? A: Only to files you created or substantially modified. Always retain original copyrights.

Q: What counts as a "prominent" change notice? A: Near the top of the file, in a comment header, clearly stating what changed and who changed it.

Q: Can I use a different license for my derivative work? A: No. Derivative works must remain under Apache License 2.0. You can add additional terms, but can't remove Apache requirements.

Q: Do I need a NOTICE file if the original didn't have one? A: No, but you may create one if you want to add attributions. If original had NOTICE, you must include it.

Q: What if I only use a small part of Apache-licensed code? A: Same requirements apply. Include LICENSE, retain attribution, document changes.

Q: Can I remove copyright notices from files I deleted? A: Yes, if you don't redistribute those files. But retain notices for all files you do distribute.

Q: How detailed should change documentation be? A: Enough to identify what was modified. "Fixed bug" is minimal; "Fixed null pointer in parseData() function" is better.


For additional guidance, see common-violations.md for examples of what NOT to do.

Chat Interface Patterns

UI/UX patterns specific to LLM chat applications.


User Configuration

FR-2.1 Expose all settings in a settings UI panel - avoids hidden behaviors FR-2.2 Model type, system prompts, and input context should be viewable and configurable - increases customization and helps user's mental model FR-2.6 Theme selection (light/dark/system) - standard accessibility FR-2.7 Persist settings across browser sessions via localStorage


Message Handling

FR-3.1 Implement message queuing - users can submit while LLM is processing FR-3.2 Show messages immediately with "pending" status - provides instant feedback FR-3.3 Process queue FIFO - predictable ordering FR-3.4 Support cancelling in-flight requests but include partial response in context FR-3.5 Show "cancelled" status (not error) - cancelled is intentional


Input Behavior

FR-4.1 Keep input field always enabled (non-blocking) - disabled inputs feel unresponsive FR-4.2 Allow typing while LLM is processing - users can compose during response FR-4.3 Keep submit button always clickable (adds to queue if processing) FR-4.4 Button text indicates state ("Send" vs "Queued") FR-4.5 Use text editor with multi-line support - plain textarea lacks editing ergonomics


Message Display

FR-5.1 Render LLM responses as markdown (react-markdown) - models produce markdown naturally FR-5.2 User messages may render as plain text - simpler, users rarely use markdown FR-5.4 Show visual state indicators per message:

StateDisplay
PendingDimmed, waiting indicator
ProcessingHighlighted, animated indicator
CompleteNormal display
ErrorError styling with message
CancelledDistinct cancelled styling

API Communication

FR-6.1 Use simple HTTP POST request/response - easier than WebSocket to implement/debug FR-6.2 Client-side history management - frontend stores messages in React state, sends full history with each request, backend stays stateless FR-6.3 Persist history to localStorage - survives page refresh FR-6.4 Show loading indicator during request FR-6.5 Truncate old messages when history exceeds token limit - frontend's responsibility


Error Handling

FR-7.1 Show user-friendly network error messages - raw errors confuse users FR-7.2 Handle API errors (5xx) with "try again later" message FR-7.3 Handle rate limits (429) with specific message FR-7.4 Preserve user's input on errors - losing a long prompt is frustrating FR-7.5 Offer retry for failed messages - one-click recovery


UI/UX Patterns

FR-8.1 Use Tailwind CSS - consistency with stack FR-8.2 Load frontend-design skill if available - elevates visual quality FR-8.4 Keyboard shortcuts:

  • Enter to send
  • Shift+Enter for newline
  • Escape to cancel

FR-8.5 Show loading states during async operations FR-8.6 On new messages: indicate arrival but stay at current scroll position (with option to disable) - auto-scrolling interrupts reading FR-8.7 Display total API cost when available (with option to disable)


Checklist

Verification checklist for LLM chat interfaces:

  • Tailwind CSS for styling
  • Rich text input (CodeMirror/TipTap or multiline textarea)
  • Frontend design skill loaded (if available)
  • .gitignore from template
  • Settings panel with model/prompt options exposed
  • Client-side history (React state + localStorage)
  • Simple HTTP POST for LLM requests (stateless backend)
  • Message queuing (submit while processing)
  • Non-blocking input (always enabled)
  • Markdown rendering for LLM responses
  • Visual message states (pending/processing/complete/error/cancelled)
  • Cancel support for in-flight requests
  • User-friendly error messages
  • Keyboard shortcuts (Enter/Escape)
  • Mobile responsive
  • Makefile with serve/kill/restart/help
  • Prompts as composable .txt files in prompts/ directory
  • E2E Playwright test for full user journey
realtime-streaming.mdstorage-patterns.mdRESEARCH_GUIDE.mdpython-build-cache.mduv-cli-reference.mdbash.mdpython.mdSNIPPET.mdCOMPLETION_REPORT.mdDOCUMENTATION_UPDATES_SUMMARY.mdIMPLEMENTATION_NOTES.mdINDEX.mdREADME.mdREFRESHED_REQUIREMENTS_OVERVIEW.mdSESSION_SUMMARY.mdTASK_COMPLETION_REPORT.mdUI_AND_CONTENT_REQUIREMENTS.mdreference.mdagent-sdk-patterns.mddebugging-guide.mdheadless-patterns.mdmcp-configuration.mdsnippet-verification.mdREADME.mdWORKFLOWS.mdlinear-api-comprehensive-guide.mdfaithful.mdSNIPPET.mdkindle-cli.mdFORMAT.mdSNIPPET.mdSNIPPET.mdTEST-EXECUTION-SUMMARY.mdintegration-tts.mdbilingual-practice.mdworkflow-conversation-logging.mdworkflow-practice-sessions.mdworkflow-spaced-repetition.mdworkflow-vocabulary-saving.mdworkflow-weekly-error-review.mdarctic-frost.mdbotanical-garden.mddesert-rose.mdforest-canopy.mdgolden-hour.mdmidnight-galaxy.mdmodern-minimalist.mdocean-depths.mdsunset-boulevard.mdtech-innovation.mdSNIPPET.mdREADME.mdstyle-template.mdapi-reference.mdemail-styles.mdgmail-search-syntax.mdquick-reference.mdapi_reference.mdauth_setup.mdsearch_queries.mdphase-0-discover.mdphase-1-setup.mdphase-2-learn.mdphase-3-customize.mdphase-4-manage.mdSNIPPET.mdbenchmarks.mdquality-metrics.mdtool-comparison.mdrapid-response.mdsearch-cli.mdSNIPPET.mdwarren-wechat-style.mdREADME.mdREORGANIZATION_SUMMARY.md

Sponsors

Details

Marketplace
WarrenZhu050413/Warren-Claude-Code-Plugin-Marketplace
Source
claude-context-orchestrator
Category
Community

More from WarrenZhu050413/Warren-Claude-Code-Plugin-Marketplace

All 3