[skipci]Merge pull request #2975 from milutinke/master

This commit is contained in:
Anon 2026-03-24 16:35:23 +01:00 committed by GitHub
commit bce1cd9290
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
19 changed files with 1664 additions and 0 deletions

View file

@ -0,0 +1,268 @@
---
name: csharp-optimization
description: >-
Use when optimizing C# code in MCC, reducing GC pressure, profiling hot paths,
fixing latency spikes, or reviewing code for allocation or throughput issues.
metadata:
category: technique
triggers: performance, allocations, GC, hot path, latency, throughput,
memory pressure, optimize, slow, freeze, lag spike, packet processing speed
version: 0.2.0
---
# C# Performance Optimization for MCC
Hands-on optimization recipes for Minecraft Console Client hot paths.
Complements `csharp-best-practices` (conventions) with measurement-driven
performance work.
## When to Use
- Profiling or reducing GC pressure in a running MCC session
- Optimizing per-packet code (`Protocol18.HandlePacket`, `DataTypes.ReadNext*`)
- Optimizing per-tick code (`PlayerPhysics.Tick`, `CollisionDetector.Collide`)
- Speeding up chunk decoding (`Protocol18Terrain.ProcessChunkColumnData`)
- Improving A* pathfinding (`Movement.CalculatePath`)
- Reviewing any code change for allocation or throughput regressions
**NOT for:**
- Login, config parsing, or one-shot command handlers (prefer clarity there)
- Style/convention questions (use `csharp-best-practices` instead)
---
## Iron Rule: Measure First
**NEVER optimize without profiling data.**
Guessing which code is slow is wrong more often than right. Measure, change,
re-measure. If you cannot show a before/after number, the optimization is not
justified.
| Rationalization | Reality |
|-----------------|---------|
| "This is obviously slow" | Obvious to you is not obvious to the JIT. Measure. |
| "I'll profile later" | Later never comes. Profile now or don't optimize. |
| "It's just one allocation" | On a 20 TPS tick, one allocation = 20 per second = GC pressure. Measure. |
| "AggressiveInlining everywhere" | The JIT already inlines small methods. Prove it helps before adding. |
---
## MCC Hot-Path Map
Know which code runs at which frequency before deciding where to invest:
| Frequency | Key paths (actual files) | Priority |
|---|---|---|
| Per-packet (100s/sec) | `Protocol/Handlers/Protocol18.cs` HandlePacket, `Protocol/Handlers/DataTypes.cs` ReadNext* | **High** |
| Per-tick (20/sec) | `Physics/PlayerPhysics.cs` Tick, `Physics/CollisionDetector.cs` Collide, ChatBot `Update()` | **High** |
| Per-chunk-load | `Protocol/Handlers/Protocol18Terrain.cs` ProcessChunkColumnData, ReadBlockStatesField | Medium |
| Per-pathfind | `Mapping/Movement.cs` CalculatePath (A*) | Medium |
| Per-connection | Login, registry sync, config | Low |
| Per-user-action | Commands, chat | Low |
---
## Profiling Recipes
### 1. Live GC monitoring
```bash
dotnet-counters ps # find MinecraftClient PID
dotnet-counters monitor --process-id <PID> \
--counters System.Runtime[gen-0-gc-count,gen-1-gc-count,gen-2-gc-count,alloc-rate]
```
Healthy idle MCC: near-zero Gen-1/Gen-2 collections. Frequent Gen-0 during idle
means a hot-path allocation needs attention.
### 2. Allocation tracking
```bash
dotnet-trace collect --process-id <PID> \
--providers Microsoft-Windows-DotNETRuntime:0x1:5
```
Open `.nettrace` in PerfView to find top-allocated types and call stacks.
### 3. Isolated benchmarks (BenchmarkDotNet)
Extract the hot method, add `[MemoryDiagnoser]`. Key columns: **Mean**,
**Allocated**, **Gen0**.
---
## Allocation Reduction (Highest Impact)
Reducing GC pressure directly reduces latency spikes in a long-running client.
### Pattern: Reuse per-tick buffers
```csharp
// BEFORE: new List every tick (20 allocations/sec)
var result = new List<Aabb>();
// AFTER: thread-local reuse (0 allocations/sec)
[ThreadStatic] private static List<Aabb>? t_buf;
var result = t_buf ??= new List<Aabb>(64);
result.Clear();
```
`[ThreadStatic]` works when single-threaded and non-reentrant (physics tick).
If reentrant: use `ObjectPool<T>`. If cross-thread: use `ArrayPool<T>`.
### Pattern: stackalloc for small fixed buffers
MCC already does this in `DataTypes.cs` for endian-swapped reads:
```csharp
Span<byte> rawValue = stackalloc byte[8];
for (int i = 7; i >= 0; --i) rawValue[i] = cache.Dequeue();
return BitConverter.ToDouble(rawValue);
```
Rules: under 512 bytes, known size at compile time, never inside loops or recursion.
### Pattern: Span slicing instead of array copies
```csharp
// BEFORE: allocates
byte[] sub = new byte[length];
Array.Copy(source, offset, sub, 0, length);
// AFTER: zero-copy
ReadOnlySpan<byte> sub = source.AsSpan(offset, length);
```
Critical in packet parsing where many fields are sliced from one buffer.
---
## Hot-Path Tuning
### MethodImpl attributes
MCC uses `[MethodImpl]` on its hottest paths. Match the attribute to the method:
| Attribute | When | MCC examples |
|---|---|---|
| `AggressiveInlining` | Tiny methods (< ~32 bytes IL), called millions of times | `Vec3d.Add`, `Aabb.Intersects`, `Chunk.SetWithoutCheck` |
| `AggressiveOptimization` | Larger critical-path methods | `ReadBlockStatesField`, `ProcessChunkColumnData` |
| Both | Medium methods, very high frequency | `DataTypes.ReadNextVarInt`, `ReadDataReverse` |
| Neither | Infrequent code | Login, config, commands |
**Do not scatter `AggressiveInlining` without profiling evidence.** The JIT
already inlines small methods.
### BinaryPrimitives over BitConverter
```csharp
// BEFORE: manual endian swap
(buf[0], buf[3]) = (buf[3], buf[0]);
int val = BitConverter.ToInt32(buf);
// AFTER: direct big-endian read, no branch
int val = BinaryPrimitives.ReadInt32BigEndian(buf);
```
### MemoryMarshal for bulk reads
Already used in chunk decoding for zero-copy packed-long reads:
```csharp
ReadOnlySpan<long> longs = MemoryMarshal.Cast<byte, long>(entryData);
```
---
## Data Structure Selection
### Frozen collections for palettes
Palette maps are built once and read millions of times. `FrozenDictionary`
gives ~50% faster reads than `Dictionary`:
```csharp
private static readonly FrozenDictionary<int, Material> s_palette =
new Dictionary<int, Material> { ... }.ToFrozenDictionary();
```
Apply to: `BlockPalettes/*.cs`, `EntityPalettes/*.cs`, `ItemPalettes/*.cs`,
`PacketPalettes/*.cs`, any `static readonly Dictionary` populated once.
### PriorityQueue for A*
`Movement.cs` has a custom `BinaryHeap`. The built-in `PriorityQueue<TElement,
TPriority>` (.NET 6+) is well-optimized and avoids maintenance burden.
### ConcurrentDictionary sizing
Pre-size `World.chunks` to avoid rehashing:
```csharp
new ConcurrentDictionary<(int, int), ChunkColumn>(
concurrencyLevel: Environment.ProcessorCount, capacity: 1024);
```
---
## Threading
### Minimize lock scope
Copy data out under the lock, process outside:
```csharp
List<Item> snapshot;
lock (_lock) { snapshot = [.. _items]; }
foreach (var item in snapshot) ExpensiveProcess(item);
```
### Batch InvokeOnMainThread
Each `InvokeOnMainThread()` call blocks until the main thread runs it.
In loops, batch into a single call:
```csharp
handler.InvokeOnMainThread(() =>
{
foreach (var entity in entities) UpdateEntity(entity);
});
```
### Channel\<T\> over BlockingCollection\<T\>
Lower overhead, async-friendly:
```csharp
var ch = Channel.CreateUnbounded<(int Id, Memory<byte> Data)>(
new UnboundedChannelOptions { SingleReader = true });
```
---
## Common Optimization Anti-Patterns
These are things agents (and humans) rationalize doing. Every one of them
makes performance worse or wastes effort.
| Anti-pattern | Why it's wrong |
|---|---|
| Adding `AggressiveInlining` to large methods | Bloats call sites, causes more cache misses, makes code *slower* |
| Optimizing login/config code | Runs once per session; clarity matters more than speed |
| Using `ConcurrentDictionary` where a plain `Dictionary` + lock suffices | Concurrent overhead on uncontested paths costs more than a lock |
| Replacing LINQ with manual loops on cold paths | No measurable gain, worse readability |
| Caching mutable state to avoid re-reads | Stale cache bugs are harder to diagnose than the perf hit |
| `Task.Result` / `.Wait()` on hot paths | Deadlock risk and thread-pool starvation |
---
## Pre-Commit Checklist
ALWAYS verify before submitting a performance change:
- [ ] Hot path identified with profiling data, not guesswork
- [ ] Before/after measurements recorded (allocation count, throughput, or latency)
- [ ] No new allocations inside per-tick or per-packet methods
- [ ] `[MethodImpl]` attributes match method call frequency and IL size
- [ ] Frozen collections used for any static lookup table
- [ ] Lock scopes contain no I/O or expensive work
- [ ] No `Task.Result`, `.Wait()`, or `GetAwaiter().GetResult()` on hot paths
- [ ] Thread safety preserved (checked existing lock/concurrent patterns)
- [ ] Optimization comments explain non-obvious choices
- [ ] Code still compiles and passes all existing checks

View file

@ -0,0 +1,101 @@
---
name: writing-skills
description: "Use when creating, updating, or improving agent skills."
category: meta
risk: unknown
source: community
date_added: "2026-02-27"
---
# Writing Skills (Excellence)
Dispatcher for skill creation excellence. Use the decision tree below to find the right template and standards.
## Quick Decision Tree
### What do you need to do?
1. **Create a NEW skill:**
- Is it simple (single file, <200 lines)? -> [Tier 1 Architecture](references/tier-1-simple/README.md)
- Is it complex (multi-concept, 200-1000 lines)? -> [Tier 2 Architecture](references/tier-2-expanded/README.md)
- Is it a massive platform (10+ products, AWS, Convex)? -> [Tier 3 Architecture](references/tier-3-platform/README.md)
2. **Improve an EXISTING skill:**
- Fix "it's too long" -> [Modularize (Tier 3)](references/templates/tier-3-platform.md)
- Fix "AI ignores rules" -> [Anti-Rationalization](references/anti-rationalization/README.md)
- Fix "users can't find it" -> [CSO (Search Optimization)](references/cso/README.md)
3. **Verify Compliance:**
- Check metadata/naming -> [Standards](references/standards/README.md)
- Add tests -> [Testing Guide](references/testing/README.md)
## Component Index
| Component | Purpose |
|-----------|---------|
| **[CSO](references/cso/README.md)** | "SEO for LLMs". How to write descriptions that trigger. |
| **[Standards](references/standards/README.md)** | File naming, YAML frontmatter, directory structure. |
| **[Anti-Rationalization](references/anti-rationalization/README.md)**| How to write rules that agents won't ignore. |
| **[Testing](references/testing/README.md)** | How to ensure your skill actually works. |
## Templates
- [Technique Skill](references/templates/technique.md) (How-to)
- [Reference Skill](references/templates/reference.md) (Docs)
- [Discipline Skill](references/templates/discipline.md) (Rules)
- [Pattern Skill](references/templates/pattern.md) (Design Patterns)
## When to Use
- Creating a NEW skill from scratch
- Improving an EXISTING skill that agents ignore
- Debugging why a skill isn't being triggered
- Standardizing skills across a team
## How It Works
1. **Identify goal** -> Use decision tree above
2. **Select template** -> From `references/templates/`
3. **Apply CSO** -> Optimize description for discovery
4. **Add anti-rationalization** -> For discipline skills
5. **Test** -> RED-GREEN-REFACTOR cycle
## Quick Example
```yaml
---
name: my-technique
description: Use when [specific symptom occurs].
metadata:
category: technique
triggers: error-text, symptom, tool-name
---
# My Technique
## When to Use
- [Symptom A]
- [Error message]
```
## Common Mistakes
| Mistake | Fix |
|---------|-----|
| Description summarizes workflow | Use "Use when..." triggers only |
| No `metadata.triggers` | Add 3+ keywords |
| Generic name ("helper") | Use gerund (`creating-skills`) |
| Long monolithic SKILL.md | Split into `references/` |
See [gotchas.md](gotchas.md) for more.
## Pre-Deploy Checklist
Before deploying any skill:
- [ ] `name` field matches directory name exactly
- [ ] `SKILL.md` filename is ALL CAPS
- [ ] Description starts with "Use when..."
- [ ] `metadata.triggers` has 3+ keywords
- [ ] Total lines < 500 (use `references/` for more)
- [ ] No `@` force-loading in cross-references
- [ ] Tested with real scenarios

View file

@ -0,0 +1,236 @@
# Skill Templates & Examples
Complete, copy-paste templates for each skill type.
---
## Template: Technique Skill
For how-to guides that teach a specific method.
```markdown
---
name: technique-name
description: >-
Use when [specific symptom].
metadata:
category: technique
triggers: error-text, symptom, tool-name
---
# Technique Name
## Overview
[1-2 sentence core principle]
## When to Use
- [Symptom A]
- [Symptom B]
- [Error message text]
**NOT for:**
- [When to avoid]
## The Problem
\`\`\`javascript
// Bad example
function badCode() {
// problematic pattern
}
\`\`\`
## The Solution
\`\`\`javascript
// Good example
function goodCode() {
// improved pattern
}
\`\`\`
## Step-by-Step
1. [First step]
2. [Second step]
3. [Final step]
## Quick Reference
| Scenario | Approach |
|----------|----------|
| Case A | Solution A |
| Case B | Solution B |
## Common Mistakes
**Mistake 1:** [Description]
- Wrong: \`bad code\`
- Right: \`good code\`
```
---
## Template: Reference Skill
For documentation, APIs, and lookup tables.
```markdown
---
name: reference-name
description: >-
Use when working with [domain].
metadata:
category: reference
triggers: tool, api, specific-terms
---
# Reference Name
## Quick Reference
| Command | Purpose |
|---------|---------|
| \`cmd1\` | Does X |
| \`cmd2\` | Does Y |
## Common Patterns
**Pattern A:**
\`\`\`bash
example command
\`\`\`
**Pattern B:**
\`\`\`bash
another example
\`\`\`
## Detailed Docs
For more options, run \`--help\` or see:
- patterns.md
- [examples.md](examples.md)
```
---
## Template: Discipline Skill
For rules that agents must follow. Requires anti-rationalization techniques.
```markdown
---
name: discipline-name
description: >-
Use when [BEFORE violation].
metadata:
category: discipline
triggers: new feature, code change, implementation
---
# Rule Name
## Iron Law
**[SINGLE SENTENCE ABSOLUTE RULE]**
Violating the letter IS violating the spirit.
## The Rule
1. ALWAYS [step 1]
2. NEVER [step 2]
3. [Step 3]
## Violations
[Action before rule]? **Delete it. Start over.**
**No exceptions:**
- Don't keep it as "reference"
- Don't "adapt" it
- Delete means delete
## Common Rationalizations
| Excuse | Reality |
|--------|---------|
| "Too simple" | Simple code breaks. Rule takes 30 seconds. |
| "I'll do it after" | After = never. Do it now. |
| "Spirit not ritual" | The ritual IS the spirit. |
## Red Flags - STOP
- [Flag 1]
- [Flag 2]
- "This is different because..."
**All mean:** Delete. Start over.
## Valid Exceptions
- [Exception 1]
- [Exception 2]
**Everything else:** Follow the rule.
```
---
## Template: Pattern Skill
For mental models and design patterns.
```markdown
---
name: pattern-name
description: >-
Use when [recognizable symptom].
metadata:
category: pattern
triggers: complexity, hard-to-follow, nested
---
# Pattern Name
## The Pattern
[1-2 sentence core idea]
## Recognition Signs
- [Sign that pattern applies]
- [Another sign]
- [Code smell]
## Before
\`\`\`typescript
// Complex/problematic
function before() {
// nested, confusing
}
\`\`\`
## After
\`\`\`typescript
// Clean/improved
function after() {
// flat, clear
}
\`\`\`
## When NOT to Use
- [Over-engineering case]
- [Simple case that doesn't need it]
## Impact
**Before:** [Problem metric]
**After:** [Improved metric]
```

View file

@ -0,0 +1,175 @@
---
description: Common pitfalls and tribal knowledge for skill creation.
metadata:
tags: [gotchas, troubleshooting, mistakes]
---
# Skill Writing Gotchas
Tribal knowledge to avoid common mistakes.
## YAML Frontmatter
### Invalid Syntax
```yaml
# BAD: Mixed list and map
metadata:
references:
triggers: a, b, c
- item1
- item2
# GOOD: Consistent structure
metadata:
triggers: a, b, c
references:
- item1
- item2
```
### Multiline Description
```yaml
# BAD: Line breaks create parsing errors
description: Use when creating skills.
Also for updating.
# GOOD: Use YAML multiline syntax
description: >-
Use when creating or updating skills.
Triggers: new skill, update skill
```
## Naming
### Directory Must Match `name` Field
```
# BAD
directory: my-skill/
name: mySkill # Mismatch!
# GOOD
directory: my-skill/
name: my-skill # Exact match
```
### SKILL.md Must Be ALL CAPS
```
# BAD
skill.md
Skill.md
# GOOD
SKILL.md
```
## Discovery
### Description = Triggers, NOT Workflow
```yaml
# BAD: Agent reads this and skips the full skill
description: Analyzes code, finds bugs, suggests fixes
# GOOD: Agent reads full skill to understand workflow
description: Use when debugging errors or reviewing code quality
```
### Pre-Violation Triggers for Discipline Skills
```yaml
# BAD: Triggers AFTER violation
description: Use when you forgot to write tests
# GOOD: Triggers BEFORE violation
description: Use when implementing any feature, before writing code
```
## Token Efficiency
### Skill Loaded Every Conversation = Token Drain
- Frequently-loaded skills: <200 words
- All others: <500 words
- Move details to `references/` files
### Don't Duplicate CLI Help
```markdown
# BAD: 50 lines documenting all flags
# GOOD: One line
Run `mytool --help` for all options.
```
## Anti-Rationalization (Discipline Skills Only)
### Agents Are Smart at Finding Loopholes
```markdown
# BAD: Trust agents will "get the spirit"
Write test before code.
# GOOD: Close every loophole explicitly
Write test before code.
**No exceptions:**
- Don't keep code as "reference"
- Don't "adapt" existing code
- Delete means delete
```
### Build Rationalization Table
Every excuse from baseline testing goes in the table:
| Excuse | Reality |
|--------|---------|
| "Too simple to test" | Simple code breaks. Test takes 30 seconds. |
| "I'll test after" | Tests-after prove nothing immediately. |
## Cross-References
### Keep References One Level Deep
```markdown
# BAD: Nested chain (A -> B -> C)
See [patterns.md] -> which links to [advanced.md] -> which links to [deep.md]
# GOOD: Flat (A -> B, A -> C)
See [patterns.md] and [advanced.md]
```
### Never Force-Load with @
```markdown
# BAD: Burns context immediately
@skills/my-skill/SKILL.md
# GOOD: Agent loads when needed
See [my-skill] for details.
```
## Tier Selection
### Don't Overthink Tier Choice
```markdown
# BAD: Starting with Tier 3 "just in case"
# Result: Wasted effort, empty reference files
# GOOD: Start with Tier 1, upgrade when needed
# Can always add references/ later
```
### Signals You Need to Upgrade
| Signal | Action |
|--------|--------|
| SKILL.md > 200 lines | -> Tier 2 |
| 3+ related sub-topics | -> Tier 2 |
| 10+ products/services | -> Tier 3 |
| "I need X" vs "I want Y" | -> Tier 3 decision trees |

View file

@ -0,0 +1,86 @@
# Persuasion Principles for Skill Design
## Overview
LLMs respond to the same persuasion principles as humans. Understanding this psychology helps you design more effective skills - not to manipulate, but to ensure critical practices are followed even under pressure.
**Research foundation:** Meincke et al. (2025) tested 7 persuasion principles with N=28,000 AI conversations. Persuasion techniques more than doubled compliance rates (33% to 72%, p < .001).
## The Seven Principles
### 1. Authority
**What it is:** Deference to expertise, credentials, or official sources.
**How it works in skills:**
- Imperative language: "YOU MUST", "Never", "Always"
- Non-negotiable framing: "No exceptions"
- Eliminates decision fatigue and rationalization
**When to use:**
- Discipline-enforcing skills (TDD, verification requirements)
- Safety-critical practices
- Established best practices
### 2. Commitment
**What it is:** Consistency with prior actions, statements, or public declarations.
**How it works in skills:**
- Require announcements: "Announce skill usage"
- Force explicit choices: "Choose A, B, or C"
- Use tracking: TodoWrite for checklists
### 3. Scarcity
**What it is:** Urgency from time limits or limited availability.
**How it works in skills:**
- Time-bound requirements: "Before proceeding"
- Sequential dependencies: "Immediately after X"
- Prevents procrastination
### 4. Social Proof
**What it is:** Conformity to what others do or what's considered normal.
**How it works in skills:**
- Universal patterns: "Every time", "Always"
- Failure modes: "X without Y = failure"
- Establishes norms
### 5. Unity
**What it is:** Shared identity, "we-ness", in-group belonging.
**How it works in skills:**
- Collaborative language: "our codebase", "we're colleagues"
- Shared goals: "we both want quality"
### 6. Reciprocity
**What it is:** Obligation to return benefits received.
- Use sparingly - can feel manipulative
- Rarely needed in skills
### 7. Liking
**What it is:** Preference for cooperating with those we like.
- **DON'T USE for compliance**
- Conflicts with honest feedback culture
## Principle Combinations by Skill Type
| Skill Type | Use | Avoid |
|------------|-----|-------|
| Discipline-enforcing | Authority + Commitment + Social Proof | Liking, Reciprocity |
| Guidance/technique | Moderate Authority + Unity | Heavy authority |
| Collaborative | Unity + Commitment | Authority, Liking |
| Reference | Clarity only | All persuasion |
## Ethical Use
**Legitimate:**
- Ensuring critical practices are followed
- Creating effective documentation
- Preventing predictable failures
**The test:** Would this technique serve the user's genuine interests if they fully understood it?
## Research Citations
**Cialdini, R. B. (2021).** *Influence: The Psychology of Persuasion (New and Expanded).* Harper Business.
**Meincke, L., et al. (2025).** Call Me A Jerk: Persuading AI to Comply with Objectionable Requests. University of Pennsylvania.

View file

@ -0,0 +1,85 @@
# Anti-Rationalization Guide
Techniques for bulletproofing skills against agent rationalization.
## The Problem
Discipline-enforcing skills face a unique challenge: smart agents under pressure will find loopholes.
## Technique 1: Close Every Loophole Explicitly
Don't just state the rule - forbid specific workarounds.
### Bad Example
```markdown
Write code before test? Delete it.
```
### Good Example
```markdown
Write code before test? Delete it. Start over.
**No exceptions**:
- Don't keep it as "reference"
- Don't "adapt" it while writing tests
- Don't look at it
- Delete means delete
```
## Technique 2: Address "Spirit vs Letter" Arguments
Add foundational principle early:
```markdown
**Violating the letter of the rules is violating the spirit of the rules.**
```
## Technique 3: Build Rationalization Table
| Excuse | Reality |
|--------|---------|
| "Too simple to test" | Simple code breaks. Test takes 30 seconds. |
| "I'll test after" | Tests passing immediately prove nothing. |
| "Spirit not ritual" | The letter IS the spirit. |
## Technique 4: Create Red Flags List
```markdown
## Red Flags - STOP and Start Over
- Code before test
- "I already manually tested it"
- "This is different because..."
**All of these mean**: Delete code. Start over.
```
## Technique 5: Use Strong Language
```markdown
# Weak (invites rationalization)
You should write tests first.
# Strong (no wiggle room)
ALWAYS write test first.
NEVER write code before test.
```
## Technique 6: Provide Escape Hatch for Legitimate Cases
```markdown
## When NOT to Use
- Spike solutions (throwaway exploratory code)
- One-time scripts deleting in 1 hour
**Everything else**: Follow the rule. No exceptions.
```
## Complete Bulletproofing Checklist
- [ ] Forbidden each specific workaround explicitly?
- [ ] Added "spirit vs letter" principle?
- [ ] Built rationalization table from baseline tests?
- [ ] Created red flags list?
- [ ] Used strong language (ALWAYS/NEVER)?
- [ ] Provided explicit escape hatch?
- [ ] Description includes pre-violation symptoms?

View file

@ -0,0 +1,90 @@
# CSO Guide - Claude Search Optimization
Advanced techniques for making skills discoverable by agents.
## The Discovery Problem
You have 100+ skills. Agent receives a task. How does it find the RIGHT skill?
**Answer**: The `description` field.
## Critical Rule: Description = Triggers, NOT Workflow
### The Trap
When description summarizes workflow, agents take a shortcut.
**Real example that failed**:
```yaml
# Agent did ONE review instead of TWO
description: Code review between tasks
# Skill body had flowchart showing TWO reviews
```
**Why it failed**: Agent read description, thought "code review between tasks means one review", never read the flowchart.
**Fix**:
```yaml
# Agent now reads full skill and follows flowchart
description: Use when executing implementation plans with independent tasks
```
### The Pattern
```yaml
# BAD: Workflow summary
description: Analyzes git diff, generates commit message in conventional format
# GOOD: Trigger conditions only
description: Use when generating commit messages or reviewing staged changes
```
## Token Efficiency
**Target word counts**:
- Frequently-loaded skills: <200 words total
- Other skills: <500 words
## Keyword Strategy
### Error Messages
Include EXACT error text users will see.
### Symptoms
Use words users naturally say: "flaky", "hangs", "slow", "timeout", "race condition"
### Tools & Commands
Actual names, not descriptions: "pytest", not "Python testing"
### Synonyms
Cover multiple ways to describe same thing: timeout/hang/freeze
## Description Template
```yaml
description: "Use when [SPECIFIC TRIGGER]."
metadata:
triggers: [error1], [symptom2], [tool3]
```
## Third Person Rule
```yaml
# BAD: First person
description: "I can help you with async tests"
# GOOD: Third person
description: "Handles async tests with race conditions"
```
## Verification Checklist
- [ ] Description starts with "Use when..."?
- [ ] Description is <500 characters?
- [ ] Description lists ONLY triggers, not workflow?
- [ ] Includes 3+ keywords (errors/symptoms/tools)?
- [ ] Third person throughout?
- [ ] Name uses gerund or verb-first format?

View file

@ -0,0 +1,87 @@
---
description: Standards and naming rules for creating agent skills.
metadata:
tags: [standards, naming, yaml, structure]
---
# Skill Development Guide
## Directory Structure
```
skills/
{skill-name}/ # kebab-case, matches `name` field
SKILL.md # Required: main skill definition
references/ # Optional: supporting documentation
README.md # Sub-topic entry point
*.md # Additional files
```
## Naming Rules
| Element | Rule | Example |
|---------|------|---------|
| Directory | kebab-case, 1-64 chars | `react-best-practices` |
| `SKILL.md` | ALL CAPS, exact filename | `SKILL.md` (not `skill.md`) |
| `name` field | Must match directory name | `name: react-best-practices` |
## SKILL.md Structure
```markdown
---
name: {skill-name}
description: >-
Use when [trigger condition].
metadata:
category: technique
triggers: keyword1, keyword2, error-text
---
# Skill Title
Brief description of what this skill does.
## When to Use
- Symptom or situation A
- Symptom or situation B
## How It Works
Step-by-step instructions or reference content.
## Examples
Concrete usage examples.
## Common Mistakes
What to avoid and why.
```
## Description Best Practices
```yaml
# BAD: Workflow summary
description: Analyzes code, finds bugs, suggests fixes
# GOOD: Trigger conditions only
description: Use when debugging errors or reviewing code quality.
```
**Rules:**
- Start with "Use when..."
- Keep under 500 characters
- Use third person
## Context Efficiency
| Guideline | Reason |
|-----------|--------|
| Keep SKILL.md < 500 lines | Reduces context consumption |
| Put details in supporting files | Agent reads only what's needed |
| Use tables for reference data | More compact than prose |
## Verification Checklist
- [ ] `name` matches directory name?
- [ ] `SKILL.md` is ALL CAPS?
- [ ] Description starts with "Use when..."?
- [ ] Under 500 lines?
- [ ] Tested with real scenarios?

View file

@ -0,0 +1,39 @@
# SKILL.md Metadata Standard
Official frontmatter fields.
## Required Fields
```yaml
---
name: skill-name
description: >-
Use when [trigger condition].
---
```
| Field | Rules |
|-------|-------|
| `name` | 1-64 chars, lowercase, hyphens only, must match directory name |
| `description` | 1-1024 chars, should describe when to use |
## Optional Fields
```yaml
---
name: skill-name
description: Purpose and triggers.
metadata:
category: "reference"
version: "1.0.0"
---
```
## Name Validation
```regex
^[a-z0-9]+(-[a-z0-9]+)*$
```
**Valid**: `my-skill`, `git-release`, `tdd`
**Invalid**: `My-Skill`, `my_skill`, `-my-skill`

View file

@ -0,0 +1,54 @@
---
name: discipline-name
description: >-
Use when [BEFORE violation].
metadata:
category: discipline
triggers: new feature, code change, implementation
---
# Rule Name
## Iron Law
**[SINGLE SENTENCE ABSOLUTE RULE]**
Violating the letter IS violating the spirit.
## The Rule
1. ALWAYS [step 1]
2. NEVER [step 2]
3. [Step 3]
## Violations
[Action before rule]? **Delete it. Start over.**
**No exceptions:**
- Don't keep it as "reference"
- Don't "adapt" it
- Delete means delete
## Common Rationalizations
| Excuse | Reality |
|--------|---------|
| "Too simple" | Simple code breaks. Rule takes 30 seconds. |
| "I'll do it after" | After = never. Do it now. |
| "Spirit not ritual" | The ritual IS the spirit. |
## Red Flags - STOP
- [Flag 1]
- [Flag 2]
- "This is different because..."
**All mean:** Delete. Start over.
## Valid Exceptions
- [Exception 1]
- [Exception 2]
**Everything else:** Follow the rule.

View file

@ -0,0 +1,48 @@
---
name: pattern-name
description: >-
Use when [recognizable symptom].
metadata:
category: pattern
triggers: complexity, hard-to-follow, nested
---
# Pattern Name
## The Pattern
[1-2 sentence core idea]
## Recognition Signs
- [Sign that pattern applies]
- [Another sign]
- [Code smell]
## Before
```typescript
// Complex/problematic
function before() {
// nested, confusing
}
```
## After
```typescript
// Clean/improved
function after() {
// flat, clear
}
```
## When NOT to Use
- [Over-engineering case]
- [Simple case that doesn't need it]
## Impact
**Before:** [Problem metric]
**After:** [Improved metric]

View file

@ -0,0 +1,35 @@
---
name: reference-name
description: >-
Use when working with [domain].
metadata:
category: reference
triggers: tool, api, specific-terms
---
# Reference Name
## Quick Reference
| Command | Purpose |
|---------|---------|
| `cmd1` | Does X |
| `cmd2` | Does Y |
## Common Patterns
**Pattern A:**
```bash
example command
```
**Pattern B:**
```bash
another example
```
## Detailed Docs
For more options, run `--help` or see:
- patterns.md
- examples.md

View file

@ -0,0 +1,59 @@
---
name: technique-name
description: Use when [specific symptom].
metadata:
category: technique
triggers: error-text, symptom, tool-name
---
# Technique Name
## Overview
[1-2 sentence core principle]
## When to Use
- [Symptom A]
- [Symptom B]
- [Error message text]
**NOT for:**
- [When to avoid]
## The Problem
```javascript
// Bad example
function badCode() {
// problematic pattern
}
```
## The Solution
```javascript
// Good example
function goodCode() {
// improved pattern
}
```
## Step-by-Step
1. [First step]
2. [Second step]
3. [Final step]
## Quick Reference
| Scenario | Approach |
|----------|----------|
| Case A | Solution A |
| Case B | Solution B |
## Common Mistakes
**Mistake 1:** [Description]
- Wrong: `bad code`
- Right: `good code`

View file

@ -0,0 +1,17 @@
# Platform Name Skill
Template for complex Tier 3 skills.
## Structure
```
skill/
SKILL.md # Dispatcher
references/
topic/
README.md # Overview
api.md # API Reference
config.md # Configuration
patterns.md # Recipes
gotchas.md # Critical Errors
```

View file

@ -0,0 +1,66 @@
# Testing Guide - TDD for Skills
Complete methodology for testing skills using RED-GREEN-REFACTOR cycle.
## Testing All Skill Types
### Discipline-Enforcing Skills (rules/requirements)
**Test with**:
- Academic questions: Do they understand the rules?
- Pressure scenarios: Do they comply under stress?
- Multiple pressures combined: time + sunk cost + exhaustion
**Success criteria**: Agent follows rule under maximum pressure
### Technique Skills (how-to guides)
**Test with**:
- Application scenarios: Can they apply the technique correctly?
- Variation scenarios: Do they handle edge cases?
- Missing information tests: Do instructions have gaps?
**Success criteria**: Agent successfully applies technique to new scenario
### Pattern Skills (mental models)
**Test with**:
- Recognition scenarios: Do they recognize when pattern applies?
- Counter-examples: Do they know when NOT to apply?
**Success criteria**: Agent correctly identifies when/how to apply pattern
### Reference Skills (documentation/APIs)
**Test with**:
- Retrieval scenarios: Can they find the right information?
- Gap testing: Are common use cases covered?
**Success criteria**: Agent finds and correctly applies reference information
## Pressure Types for Testing
| Pressure | Example |
|----------|---------|
| Time | "You have 5 minutes to complete this task" |
| Sunk cost | "You already spent 2 hours on this" |
| Authority | "Senior developer said to skip tests" |
| Exhaustion | "This is the 10th task today" |
## Complete Test Checklist
**Baseline (RED)**:
- [ ] Designed 3+ pressure scenarios
- [ ] Ran scenarios WITHOUT skill
- [ ] Documented verbatim agent responses
**Implementation (GREEN)**:
- [ ] Skill addresses SPECIFIC baseline failures
- [ ] Re-ran scenarios WITH skill
- [ ] Agent complied in all scenarios
**Bulletproofing (REFACTOR)**:
- [ ] Tested with combined pressures
- [ ] Found and documented new rationalizations
- [ ] Added explicit counters
- [ ] Re-tested until no more loopholes

View file

@ -0,0 +1,30 @@
---
description: When to use Tier 1 (Simple) skill architecture.
metadata:
tags: [tier-1, simple, single-file]
---
# Tier 1: Simple Skills
Single-file skills for focused, specific purposes.
## When to Use
- **Single concept**: One technique, one pattern, one reference
- **Under 200 lines**: Can fit comfortably in one file
- **No complex decision logic**: User knows exactly what they need
- **Frequently loaded**: Needs minimal token footprint
## Structure
```
my-skill/
SKILL.md # Everything in one file
```
## Checklist
- [ ] Fits in <200 lines
- [ ] Single focused purpose
- [ ] No need for `references/` directory
- [ ] Description uses "Use when..." pattern

View file

@ -0,0 +1,52 @@
---
description: When to use Tier 2 (Expanded) skill architecture.
metadata:
tags: [tier-2, expanded, multi-file]
---
# Tier 2: Expanded Skills
Multi-file skills for complex topics with multiple sub-concepts.
## When to Use
- **Multiple related concepts**: Needs separation of concerns
- **200-1000 lines total**: Too big for one file
- **Needs reference files**: Patterns, examples, troubleshooting
- **Cross-linking**: Users need to navigate between sub-topics
## Structure
```
my-skill/
SKILL.md # Overview + navigation
references/
core/
README.md # Main concept
patterns/
README.md # Usage patterns
troubleshooting/
README.md # Common issues
```
## Progressive Disclosure
1. **Metadata** (~100 tokens): Name + description loaded at startup
2. **SKILL.md** (<500 lines): Decision tree + index
3. **References** (as needed): Loaded only when user navigates
## Key Differences from Tier 1
| Aspect | Tier 1 | Tier 2 |
|--------|--------|--------|
| Files | 1 | 5-20 |
| Total lines | <200 | 200-1000 |
| Decision logic | None | Simple tree |
| Token cost | Minimal | Medium (progressive) |
## Checklist
- [ ] SKILL.md has clear navigation links
- [ ] Each `references/` subdir has README.md
- [ ] No circular references between files
- [ ] Decision tree points to specific files

View file

@ -0,0 +1,51 @@
---
description: When to use Tier 3 (Platform) skill architecture for large platforms.
metadata:
tags: [tier-3, platform, enterprise]
---
# Tier 3: Platform Skills
Enterprise-grade skills for entire platforms (AWS, Cloudflare, Convex, etc).
## When to Use
- **Entire platform**: 10+ products/services
- **1000+ lines total**: Would overwhelm context if monolithic
- **Complex decision logic**: Users start with "I need X" not "I want product Y"
## The 5-File Pattern
Each product directory has exactly 5 files:
| File | Purpose | When to Load |
|------|---------|--------------|
| `README.md` | Overview, when to use | Always first |
| `api.md` | Runtime APIs, methods | Implementing features |
| `configuration.md` | Config, environment | Setting up |
| `patterns.md` | Common workflows | Best practices |
| `gotchas.md` | Pitfalls, limits | Debugging |
## Decision Trees
```markdown
Need to store data?
Simple key-value -> kv/
Relational queries -> d1/
Large files/blobs -> r2/
Per-user state -> durable-objects/
```
## Progressive Disclosure in Action
- **Startup**: Only name + description (~100 tokens)
- **Activation**: SKILL.md with trees (<5000 tokens)
- **Navigation**: One product's 5 files (as needed)
## Checklist
- [ ] SKILL.md contains ONLY decision trees + index
- [ ] Each product has exactly 5 files
- [ ] Decision trees cover all "I need X" scenarios
- [ ] Cross-references stay one level deep
- [ ] Every product has `gotchas.md`

View file

@ -0,0 +1,85 @@
# Testing Skills With Subagents
**Load this reference when:** creating or editing skills, before deployment, to verify they work under pressure and resist rationalization.
## Overview
**Testing skills is just TDD applied to process documentation.**
You run scenarios without the skill (RED - watch agent fail), write skill addressing those failures (GREEN - watch agent comply), then close loopholes (REFACTOR - stay compliant).
**Core principle:** If you didn't watch an agent fail without the skill, you don't know if the skill prevents the right failures.
## When to Use
Test skills that:
- Enforce discipline (TDD, testing requirements)
- Have compliance costs (time, effort, rework)
- Could be rationalized away ("just this once")
- Contradict immediate goals (speed over quality)
Don't test:
- Pure reference skills (API docs, syntax guides)
- Skills without rules to violate
- Skills agents have no incentive to bypass
## TDD Mapping for Skill Testing
| TDD Phase | Skill Testing | What You Do |
|-----------|---------------|-------------|
| **RED** | Baseline test | Run scenario WITHOUT skill, watch agent fail |
| **Verify RED** | Capture rationalizations | Document exact failures verbatim |
| **GREEN** | Write skill | Address specific baseline failures |
| **Verify GREEN** | Pressure test | Run scenario WITH skill, verify compliance |
| **REFACTOR** | Plug holes | Find new rationalizations, add counters |
| **Stay GREEN** | Re-verify | Test again, ensure still compliant |
## RED Phase: Baseline Testing (Watch It Fail)
**Goal:** Run test WITHOUT the skill - watch agent fail, document exact failures.
**Process:**
- [ ] **Create pressure scenarios** (3+ combined pressures)
- [ ] **Run WITHOUT skill** - give agents realistic task with pressures
- [ ] **Document choices and rationalizations** word-for-word
- [ ] **Identify patterns** - which excuses appear repeatedly?
- [ ] **Note effective pressures** - which scenarios trigger violations?
## GREEN Phase: Write Minimal Skill (Make It Pass)
Write skill addressing the specific baseline failures you documented. Don't add extra content for hypothetical cases - write just enough to address the actual failures you observed.
Run same scenarios WITH skill. Agent should now comply.
If agent still fails: skill is unclear or incomplete. Revise and re-test.
## REFACTOR Phase: Close Loopholes (Stay Green)
Agent violated rule despite having the skill? Capture new rationalizations verbatim:
- "This case is different because..."
- "I'm following the spirit not the letter"
- "Being pragmatic means adapting"
- "Deleting X hours is wasteful"
**Document every excuse.** These become your rationalization table.
## Testing Checklist (TDD for Skills)
**RED Phase:**
- [ ] Created pressure scenarios (3+ combined pressures)
- [ ] Ran scenarios WITHOUT skill (baseline)
- [ ] Documented agent failures and rationalizations verbatim
**GREEN Phase:**
- [ ] Wrote skill addressing specific baseline failures
- [ ] Ran scenarios WITH skill
- [ ] Agent now complies
**REFACTOR Phase:**
- [ ] Identified NEW rationalizations from testing
- [ ] Added explicit counters for each loophole
- [ ] Updated rationalization table
- [ ] Updated red flags list
- [ ] Re-tested - agent still complies
- [ ] Meta-tested to verify clarity
- [ ] Agent follows rule under maximum pressure