Agent Skills › Totoro-jam/battle-tested-patterns

Totoro-jam/battle-tested-patterns

GitHub

用于结构化调试测试失败或构建错误。遵循复现、隔离、假设、验证的闭环流程,通过最小化修改定位并修复问题,最终运行完整套件确保无回归。

5 skills 315

Install All Skills

npx skills add Totoro-jam/battle-tested-patterns --all -g -y
More Options

List skills in collection

npx skills add Totoro-jam/battle-tested-patterns --list

Skills in Collection (5)

用于结构化调试测试失败或构建错误。遵循复现、隔离、假设、验证的闭环流程,通过最小化修改定位并修复问题,最终运行完整套件确保无回归。
测试用例执行失败 项目构建过程报错
.claude/skills/diagnose/SKILL.md
npx skills add Totoro-jam/battle-tested-patterns --skill diagnose -g -y
SKILL.md
Frontmatter
{
    "name": "diagnose",
    "description": "Structured debugging loop for exercise tests or build failures. Reproduce → isolate → hypothesize → fix → verify."
}

Diagnose a Failure

You are debugging a test failure or build error in this project. Follow the structured loop — do NOT jump to a fix without reproducing first.

Loop

1. Reproduce

Run the failing command and capture the exact error:

pnpm test          # All tests (docs + exercises in TS/Rust/Go/Python)
pnpm test:rust     # Rust only
pnpm test:go       # Go only
pnpm test:python   # Python only (auto-finds Python ≥ 3.10)
pnpm build         # VitePress

2. Isolate

Narrow down to the smallest failing unit:

  • Which test file?
  • Which test case?
  • Which assertion?

3. Hypothesize

State your hypothesis in one sentence before changing any code.

4. Instrument

Add minimal logging or assertions to confirm/deny your hypothesis. Do NOT change production code yet.

5. Fix

Apply the minimal fix. Change as little as possible.

6. Verify

Run the full test suite, not just the failing test:

pnpm test && pnpm build

If it still fails, return to step 1 with what you learned.

7. Regression Test

If the bug was non-trivial, add a test that would have caught it.

指导创建符合项目规范的新设计模式文档。涵盖主题验证、源码核实、文档编写(含图表与多语言实现)、代码测试及练习设计,确保内容真实、跨语言且无重复。
用户要求创建新的设计模式 需要按照模板生成技术文档
.claude/skills/new-pattern/SKILL.md
npx skills add Totoro-jam/battle-tested-patterns --skill new-pattern -g -y
SKILL.md
Frontmatter
{
    "name": "new-pattern",
    "description": "Guided workflow to create a new pattern following the project template and quality standards. Walks through topic validation, source verification, implementation, exercises, challenge questions, and bilingual docs."
}

Create a New Pattern

You are creating a new pattern for battle-tested-patterns. Follow each step in order. Do NOT skip source verification. Reference SOP 01 for the full checklist.

Step 1: Topic Validation

Ask these questions before proceeding:

  1. What is the pattern name?
  2. Can you name ≥ 2 production projects that use it (with source links)?
  3. Is it cross-language (not specific to one language/framework)?
  4. Is it a code-level technique (not purely architectural)?
  5. Does it NOT duplicate an existing pattern in docs/patterns/?

If any answer is "no", stop and explain why this pattern doesn't fit.

Step 2: Source Code Location

For each production project:

  1. Search the project repo for the exact usage
  2. Get the GitHub URL with line numbers: https://github.com/{org}/{repo}/blob/main/{path}#L{start}-L{end}
  3. Verify with curl -sI <url> | head -1 — must return HTTP 200
  4. Read the code to confirm your understanding
  5. Write a Production Proof description specific enough to learn WITHOUT clicking the link

CRITICAL: Never fabricate a URL. If you cannot verify a link, write <!-- TODO: verify source link --> instead.

Step 3: Write the Document

Create docs/patterns/<pattern-name>/index.md with ALL required sections:

# Pattern: [Name]
## One Liner          ← ≤ 30 English words, capture WHY not just WHAT
## Core Idea          ← concept + diagram (choose best representation for this pattern)
## Production Proof   ← table with ≥ 2 verified URLs, descriptions show HOW not just WHAT
## Implementation     ← TypeScript (required) + ≥ 1 other language in ::: code-group
## Exercises          ← table with basic + intermediate exercise links
## When to Use        ← ≥ 3 concrete scenarios
## When NOT to Use    ← ≥ 2 concrete alternatives
## More Production Uses ← bullet list with repo links
## Challenge Questions ← 3-4 scenario Q&A using ::: details syntax

Diagram Guidelines

  • Choose the representation that best matches the pattern's nature:
    • Ring/circular → for hash rings, ring buffers
    • Timeline → for temporal patterns (WAL, MVCC, retry)
    • State diagram → for state machines, circuit breakers (use mermaid)
    • Tree → for tries, heaps, B-trees
    • Box-and-arrow → for data structures (LRU, skip list)
  • ASCII text blocks: every box border must be vertically aligned
  • ZH docs: CJK characters = 2 display columns; compensate with fewer spaces
  • Verify alignment in a monospace font before committing

Step 4: Implement

In the ::: code-group block:

  • TypeScript (required) — idiomatic, strict types, no any
  • At least one of: Rust / Go / Python
  • Each implementation must be idiomatic, not a line-by-line translation
  • Go: do NOT add import blocks — the verify-code script auto-detects imports
  • Rust: wrap standalone code in fn main() or use pub struct/pub fn
  • Verify: pnpm verify-code

Step 5: Design Exercises

Create in exercises/typescript/<pattern>/:

  • 01-basic.test.ts — basic pattern mechanics (required)
  • 02-intermediate.test.ts — real-world application scenario (required)
  • Use TODO-stub format with // TODO: implement markers
  • Include working implementations so CI passes
  • Separator: // ─── Tests (do not modify below this line) ───────────────────────
  • 4-5 meaningful test cases per exercise
  • Verify: pnpm test:exercises AND pnpm typecheck

Step 6: Write Challenge Questions

Add ## Challenge Questions at the end of the EN doc:

  • 3-4 questions using ::: details Q1: [question] ... ::: syntax
  • Questions test understanding through production scenarios
  • Verify factual accuracy of all answers
  • Escape | in table cells, use × instead of * for multiplication
  • Copy to ZH doc with header ## 挑战题, translate Q&A to Chinese (keep technical terms and code in English)

Step 7: Create Chinese Translation

Create docs/zh/patterns/<pattern-name>/index.md:

  • Translate structural content (headings, explanations, When to Use)
  • Keep code blocks identical to English
  • Keep Production Proof links identical
  • Challenge Questions: translate questions + answers to Chinese, keep technical terms/code in English
  • ASCII diagrams: use English labels inside box-drawing diagrams (no CJK in diagrams)

Step 8: Update Navigation

All of these must be updated:

  • docs/.vitepress/config.ts — BOTH English and Chinese sidebar
  • docs/index.md — English homepage pattern table
  • docs/zh/index.md — Chinese homepage pattern table
  • README.md — pattern table + cheat sheet table
  • README.zh-CN.md — pattern table + cheat sheet table
  • docs/by-project/*.md — add to ALL relevant project pages (React, Linux, Go, Redis, etc.)
  • docs/by-project/more-projects.md — add if project not covered by specific pages
  • docs/zh/by-project/*.md — sync Chinese versions
  • README.md cheat sheet — add to correct category table
  • README.zh-CN.md cheat sheet — sync Chinese version
  • docs/guide/pattern-connections.md + ZH — update if pattern fits a system case study

Step 9: Full Verification

Run ALL checks before committing:

pnpm check         # All checks (lint + typecheck + test + verify-code + verify-mermaid + check:content)
pnpm build         # VitePress builds

Step 10: Site Accessibility Verification

After build, verify all new pages are reachable:

  • ls docs/.vitepress/dist/patterns/<name>/index.html — EN page exists
  • ls docs/.vitepress/dist/zh/patterns/<name>/index.html — ZH page exists
  • After deploy, spot-check live URLs in both languages

Step 11: Commit and Tag

  • Commit message: feat: add <pattern-name> pattern
  • If adding multiple patterns: one commit per batch with list
  • Push and verify CI is green before tagging
  • Tag: git tag -a v1.X.0 -m "description" + git push origin v1.X.0
用于验证生产证明源链接的准确性。自动检查HTTP状态、SHA永久链接及行范围内容,将分支链接转换为SHA,并辅助手动复核警告项,确保文档链接有效且内容匹配。
需要验证文档中的生产证明链接是否有效 发现或怀疑链接存在格式错误、断链或内容不匹配
.claude/skills/verify-source/SKILL.md
npx skills add Totoro-jam/battle-tested-patterns --skill verify-source -g -y
SKILL.md
Frontmatter
{
    "name": "verify-source",
    "description": "Verify all production proof source links in pattern documents. Run automated checks for HTTP status, format, SHA permanence, and line-range content accuracy."
}

Verify Source Links

You are verifying production proof links in this repository. This is the most critical quality check — every pattern's credibility depends on accurate, live source links.

Steps

1. Run automated link check

pnpm verify-links

This scans all docs/**/*.md and root README.md/README.zh-CN.md files, extracts GitHub URLs, and checks:

  • HTTP status (with automatic retry on 5xx)
  • Whether Production Proof links include line numbers (#L18-L22)
  • Whether links use SHA permalinks vs branch names
  • Whether any #L1 file-level links exist in Production Proof

Output categories:

  • ✅ [proof] — valid Production Proof link with line numbers
  • ✅ [other] — valid non-Production-Proof link
  • ⚠️ [proof] — Production Proof link missing line numbers
  • ℹ️ — branch-based link (not SHA permalink)
  • — broken link (HTTP error)

For CI mode (exit 1 on broken links): pnpm verify-links -- --ci

2. Convert branch links to SHA permalinks

If the report shows branch-based links, convert them:

tsx scripts/convert-to-sha-links.ts --dry-run    # preview changes
tsx scripts/convert-to-sha-links.ts               # execute conversion

Authentication: prefers gh auth token (system keyring), falls back to GITHUB_TOKEN env var.

3. Verify line-range content

For links that pass HTTP checks, verify that the referenced code lines actually match the pattern:

pnpm verify-lines                    # Check all Production Proof links
pnpm verify-lines --pattern <name>   # Check a single pattern
pnpm verify-lines --verbose          # Show all results including passes
pnpm verify-lines --section all      # Also check "More Production Uses" section
pnpm verify-lines --no-cache         # Re-fetch everything (ignore cache)

This script performs two layers of verification:

  • L1: Range validity — checks that line numbers are within file bounds
  • L2: Keyword presence — checks that pattern-related keywords appear in the referenced code

Output:

  • — line range valid and keywords found
  • ⚠️ — line range valid but no keywords found (review manually)
  • ❌ FAIL — line range exceeds file length (must fix)
  • ❌ ERROR — fetch failed (network issue, retry)

Results are cached in tmp/line-range-cache.json (SHA links are immutable, so cache is permanent).

4. Manual verification (for warnings)

For any ⚠️ warnings from verify-lines, manually confirm:

  • Open the GitHub link in a browser
  • Verify the code at the specified lines actually demonstrates the pattern
  • The usage description in the table is accurate

For ❌ FAIL results (line range out of bounds), the link must be fixed:

  1. Open the raw file at the SHA commit
  2. Find the correct line range for the relevant code
  3. Update the link in both EN and ZH pattern docs
  4. Also check README.md / README.zh-CN.md for the same link

5. Report

Output a summary:

  • ✅ Valid links (count)
  • ⚠️ Format issues or keyword warnings (list each)
  • ❌ Broken links (list each with file location)

For broken links, suggest the fix per .sop/06-broken-link-fix.md.

Rules

  • Never fabricate a replacement URL — if you can't find the new location, leave a <!-- TODO --> marker
  • Always verify with automated tools first (pnpm verify-links, pnpm verify-lines), then manually for warnings
  • When fixing line-range errors in pattern docs, also update README.md and README.zh-CN.md if they contain the same link
  • Check the actual code content, not just HTTP status
用于指导开发者从46个生产验证模式中选择并适配低层、系统或并发设计模式。通过匹配问题、验证适用性、适配代码及编写不变量测试,确保模式正确落地。
开发者命名具体设计模式(如环形缓冲区、断路器) 描述需解决的系统问题但未提及模式名称 询问哪个模式适合特定场景或比较两个相关模式
plugins/pattern-skills/skills/adopt-pattern/SKILL.md
npx skills add Totoro-jam/battle-tested-patterns --skill adopt-pattern -g -y
SKILL.md
Frontmatter
{
    "name": "adopt-pattern",
    "description": "Use when a developer wants to apply a low-level, systems, or concurrency design pattern in their own code, drawing on the Battle-Tested Patterns catalog of 46 production-proven patterns. Triggers three ways: they name a pattern (ring buffer, circuit breaker, actor model, LRU cache, rate limiter, trie, bloom filter, WAL, semaphore, ...); they describe a problem one solves without naming it (fixed-size buffer that overwrites the oldest entry, cascading failures across services, throttling requests, deduplicating identical strings, ordering events without wall-clock time, snapshot isolation, prefix search, set membership without storing every key, ...); or they ask which pattern fits a problem or how two related patterns differ."
}

Adopt a Pattern

Overview

The Battle-Tested Patterns catalog documents 46 patterns, each in a GitHub source doc (URLs in the catalog below) with a When to Use / When NOT to Use / Related Patterns decision guide, a Production Proof table of real source links, and a multi-language Implementation. Those doc pages are the source of truth — fetch the relevant one rather than relying on memory. This skill routes a developer's problem to the right pattern and then drives a disciplined adoption into their codebase; it does not reproduce the pattern content here.

Two principles do the work:

  1. A pattern is only worth adopting if it fits — the common failure is reaching for a named pattern that doesn't match the problem; the fit-gate catches that before any code is written.
  2. A pattern adopted without a durable test for its invariant is not done — a correct-looking implementation that leaves no regression test lets the invariant rot on the next edit. The verify step leaves that test behind.

When to use

  • A developer names a pattern and wants it in their code.
  • A developer describes a problem (see the catalog cues) without naming a pattern.
  • A developer asks "which pattern fits?" or "X vs Y — which?".

When NOT to use: general feature work with no pattern in play, or a problem no catalog entry matches (say so plainly rather than forcing a fit).

Workflow

Work the four steps in order. Do not skip the fit-gate.

1. Match

Map the problem to candidate patterns using the catalog below. If the developer named a pattern, still confirm it against the cue. If a problem matches several (e.g. "throttle requests" → Rate Limiter, Semaphore, Backpressure), keep 2–3 candidates for the fit-gate.

2. Fit-gate

Fetch only the candidate patterns' doc pages (the Doc URL in the catalog) and focus on When to Use, When NOT to Use, and Related Patterns.

  • If the pattern fits, continue to step 3.
  • If When NOT to Use describes the developer's situation, stop and steer to the better-fit pattern named in Related Patterns. Explain why in one or two sentences.
  • If nothing fits, say so. Do not adopt a pattern to satisfy the request.

Do not fetch all 46 docs. Fetch the 1–3 you are actually deciding between.

3. Adapt

Read the chosen doc's Implementation (in the developer's language) and skim Production Proof for how real systems shape it. Then write it into their codebase — match their naming, types, error handling, and module boundaries.

  • Adapt, do not copy-paste. The reference impl is a teaching version; production code needs the project's conventions and edge-case handling.
  • Carry over the invariants the doc calls out (e.g. a ring buffer's overwrite-on- full rule, a circuit breaker's half-open probe). Those are the point.

4. Verify — leave a durable invariant test

This is where adoption is won or lost: a capable agent will usually pick the right pattern and implement it correctly, then "confirm it works" with a throwaway check and move on — leaving nothing that protects the invariant on the next edit.

Write a focused test as a committed file in the developer's own project and runner that exercises the pattern's defining behavior — use the doc's Exercises and Challenge Questions as a checklist of cases (the boundary conditions, not the happy path). Run it. An inline or throwaway check does not count. A pattern adopted without a durable test for its invariant is not done.

Pattern catalog

Each row links to the pattern's doc source on GitHub — fetch it during the fit-gate. (Maintainers: this block is generated; see the skill's source repo.)

46 patterns. Match the developer's problem to a row, then fetch only that pattern's doc URL.

🧠 Data Structures

Pattern Reach for it when Level Doc URL
Bitmask flags in one int — Pack multiple boolean flags into a single integer and manipulate them with bitwise operators for constant-time set operations. beginner https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/bitmask/index.md
Min Heap priority queue — A binary tree stored in an array where the smallest element is always at the root, enabling O(1) peek and O(log n) insert/remove. intermediate https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/min-heap/index.md
Ring Buffer fixed-size FIFO — A fixed-size buffer that wraps around using modular arithmetic, enabling constant-time enqueue and dequeue without memory allocation. beginner https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/ring-buffer/index.md
Trie prefix search — Store strings in a tree where each edge represents a character — shared prefixes share nodes, enabling O(k) lookup by key length. intermediate https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/trie/index.md
Skip List probabilistic order — A probabilistic sorted data structure with O(log n) search, insert, and delete — simpler to implement than balanced trees with comparable performance. advanced https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/skip-list/index.md
Bloom Filter set membership — Test set membership in O(k) time with zero false negatives — at the cost of a tunable false positive rate. intermediate https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/bloom-filter/index.md
LRU Cache eviction policy — Evict the least recently used entry when the cache is full — O(1) get and put using a hash map plus a doubly linked list. intermediate https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/lru-cache/index.md
B+ Tree disk-optimized index — Self-balancing tree with high branching factor — internal nodes guide, leaf nodes store, all leaves linked for efficient range scans. advanced https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/b-plus-tree/index.md
Tagged Union type-safe dispatch — Store a type tag alongside a value union so one variable safely holds different types, dispatching behavior via the tag. beginner https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/tagged-union/index.md
Merkle Tree integrity proof — Hash leaves, then hash pairs upward to a root — verify any leaf's integrity in O(log n) without re-hashing the entire dataset. advanced https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/merkle-tree/index.md
Merge Iterator k-way merge — Combine K sorted streams into one sorted output using a min-heap — the universal "unified view" over multiple data sources. advanced https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/merge-iterator/index.md

⚡ Concurrency

Pattern Reach for it when Level Doc URL
Semaphore bounded access — Limit the number of concurrent operations by maintaining a counter — acquire before work, release after, block when the limit is reached. beginner https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/semaphore/index.md
Actor Model message passing — Each actor has a mailbox and processes messages sequentially — no shared state, no locks, just message passing for safe concurrency. advanced https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/actor-model/index.md
Work Stealing load balance — Idle threads steal tasks from busy threads' queues — balancing load dynamically without central coordination. advanced https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/work-stealing/index.md
MVCC snapshot isolation — Keep multiple timestamped versions of each value so readers never block writers — each transaction sees a consistent snapshot without locks. advanced https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/mvcc/index.md
Cooperative Scheduling yield control — Break long-running work into small chunks, yielding control back to the host between each chunk to keep the system responsive. advanced https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/cooperative-scheduling/index.md
Double Buffering atomic swap — Maintain two copies of state and atomically swap between them so readers always see a consistent snapshot. beginner https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/double-buffering/index.md
Backpressure flow control — Slow down producers when consumers can't keep up — use bounded buffers and demand signals to prevent resource exhaustion. intermediate https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/backpressure/index.md
Event Loop I/O multiplexing — A single-threaded loop that multiplexes I/O via epoll/kqueue, dispatching ready events to callbacks — thousands of connections without threads. intermediate https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/event-loop/index.md
Logical Clock event ordering — A monotonically increasing counter that orders events without wall-clock time — enabling consistent snapshots and staleness detection. advanced https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/logical-clock/index.md

🏗️ Systems

Pattern Reach for it when Level Doc URL
Circuit Breaker fault tolerance — Stop calling a failing service by tracking errors and tripping open — fail fast instead of piling up timeouts. intermediate https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/circuit-breaker/index.md
Rate Limiter throttle — Protect services from overload by draining tokens from a bucket that refills at a fixed rate — reject requests when empty. intermediate https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/rate-limiter/index.md
Retry Backoff resilience — When an operation fails, retry it with progressively longer delays plus random jitter to avoid thundering herd. beginner https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/retry-backoff/index.md
Write-Ahead Log durability — Log every mutation to durable storage before applying it — replay the log to recover from crashes without data loss. intermediate https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/write-ahead-log/index.md
Batch Processing throughput — Accumulate individual operations and execute them together as a group, amortizing per-operation overhead across the batch. beginner https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/batch-processing/index.md
Consistent Hashing distribution — Distribute keys across nodes on a virtual ring so that adding or removing a node only remaps ~1/n of the keys. advanced https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/consistent-hashing/index.md
Dependency Graph ordering — Model dependencies as a directed acyclic graph and topologically sort to determine a valid execution order — detecting cycles before they deadlock. intermediate https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/dependency-graph/index.md
Middleware Chain pipeline — Compose handlers where each wraps the next — pre-process, call next, post-process — forming a bidirectional pipeline. intermediate https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/middleware-chain/index.md
Registry self-register — Components register themselves into a global lookup table by name — consumers discover implementations at runtime without hardcoded dependencies. beginner https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/registry/index.md
Dirty Flag deferred recompute — Mark objects as "dirty" on mutation, defer expensive recomputation until the value is actually needed, then clear the flag. beginner https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/dirty-flag/index.md
LSM Tree write-optimized store — Buffer writes in memory, flush to sorted files on disk, merge files in background — trading read amplification for fast writes. advanced https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/lsm-tree/index.md
Checkpointing snapshot recovery — Periodically snapshot consistent state so recovery replays only from the checkpoint — not from the beginning of time. intermediate https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/checkpointing/index.md

♻️ Memory

Pattern Reach for it when Level Doc URL
Object Pool reuse instances — Pre-allocate a set of reusable objects to avoid the cost of repeated allocation and garbage collection on hot paths. beginner https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/object-pool/index.md
Flyweight share immutables — Share identical immutable objects instead of creating duplicates, trading a lookup cost for massive memory savings when many instances have the same value. beginner https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/flyweight/index.md
Arena Allocator bump alloc — Allocate objects by bumping a pointer in a pre-allocated region — free everything at once when the region is no longer needed. intermediate https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/arena-allocator/index.md
Free List O(1) alloc/free — Maintain a linked list of freed slots so allocation and deallocation are O(1) — reuse memory without calling the system allocator. intermediate https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/free-list/index.md
Copy-on-Write defer copy — Share data by reference until someone modifies it — only then make a private copy, saving memory and allocation cost for read-heavy workloads. intermediate https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/copy-on-write/index.md
Reference Counting auto-cleanup — Track owners via atomic counter, auto-cleanup at zero — deterministic resource lifetime without garbage collection. beginner https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/reference-counting/index.md
Tombstone deferred deletion — Mark deleted entries with a tombstone marker instead of removing them — a background process reclaims space later. beginner https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/tombstone/index.md
Interning deduplicate values — Deduplicate immutable values through a canonical lookup table — O(1) equality by pointer comparison instead of O(n) content comparison. intermediate https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/interning/index.md

🔄 Behavioral

Pattern Reach for it when Level Doc URL
State Machine transitions — Model an entity's lifecycle as a set of states with explicit transitions, making impossible states unrepresentable and every state change auditable. beginner https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/state-machine/index.md
Observer pub/sub — Decouple producers from consumers by letting objects subscribe to events and get notified when something happens, without the source knowing who's listening. beginner https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/observer/index.md
Iterator lazy eval — Process sequences one element at a time without materializing the entire collection, enabling composable transformations with zero intermediate allocations. beginner https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/iterator/index.md
Diff / Patch minimal edits — Compare two sequences to compute the minimal set of operations (insert, delete, move) needed to transform one into the other. intermediate https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/diff-patch/index.md
Vtable manual polymorphism — Group function pointers into a struct to achieve runtime polymorphism — the manual foundation behind interfaces, traits, and virtual methods. advanced https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/vtable/index.md
Visitor tree traversal dispatch — Decouple tree traversal from operations by dispatching to type-specific callbacks — enabling new operations without modifying the tree. advanced https://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/visitor/index.md

Common mistakes

  • Skipping the fit-gate because the developer named a pattern. Named ≠ correct — confirm against When NOT to Use first.
  • Copy-pasting the reference implementation verbatim. It teaches the shape; it is not drop-in production code.
  • Loading many pattern docs at once. Match from the catalog cues, then open only the 1–3 candidates.
  • Choosing by familiarity ("I know LRU") instead of fit. Check Related Patterns — the better tool is often one row away.
  • Declaring done without a test for the pattern's invariant.

Example

Developer: "Downloads are hammering the API — I want to cap it at 5 in flight."

  1. Match — "cap concurrent access" → candidates: Semaphore, Rate Limiter, Backpressure.
  2. Fit-gate — the Semaphore doc's When to Use directly lists "control access to a fixed number of resources" and "limit concurrent network requests" — a concurrency cap, which is what the developer asked for. Rate Limiter's When to Use governs rate over time (API rate limiting, traffic shaping), a different axis. → Semaphore.
  3. Adapt — port the doc's TypeScript semaphore into their download module, wrapping the fetch call in acquire()/release() with their existing error/cleanup handling so a failed download always releases its permit.
  4. Verify — test that with the cap at 5 and 20 queued downloads, no more than 5 run concurrently and all 20 eventually complete.
用于审查现有代码库中的设计模式是否符合生产级规范。通过比对文档不变量,识别模式误标、实现偏差或缺失,确保架构正确性,而非仅凭名称判断。
audit our architecture against best practices do we implement X correctly are our patterns right pattern conformance is this really a <pattern>?
plugins/pattern-skills/skills/audit-pattern/SKILL.md
npx skills add Totoro-jam/battle-tested-patterns --skill audit-pattern -g -y
SKILL.md
Frontmatter
{
    "name": "audit-pattern",
    "description": "Use when reviewing or auditing an existing codebase against production-proven implementation patterns — checking whether the patterns it already implements (actor model, rate limiter, circuit breaker, LRU cache, write-ahead log, semaphore, ...) actually honor the canonical invariants, whether any are mislabeled (a \"semaphore\" that is really a mutex; an \"MVCC\" that keeps one version), whether any diverge from the reference, and which catalog patterns are absent. Triggers on \"audit our architecture against best practices\", \"do we implement X correctly\", \"are our patterns right\", \"pattern conformance\", \"is this really a <pattern>?\". This grades patterns already present; its companion adopt-pattern adds new ones."
}

Audit Patterns

Overview

Grade a codebase against the Battle-Tested Patterns catalog: for each pattern it implements, fetch the canonical doc page and check the implementation against that doc's invariants — not against the name the codebase gave it. The most valuable output of an audit is not a score; it is the mislabel — code called a "semaphore" that is actually a mutex, an "MVCC" that keeps a single version. Those are the claims that mislead developers into expecting guarantees the code does not provide.

Companion skill: Inventory using the adopt-pattern skill's catalog, or the pattern docs at https://github.com/Totoro-jam/battle-tested-patterns/tree/main/docs/patterns. This skill is the inverse of adopt-pattern: that one runs the catalog forward (add a pattern); this one runs it backward (grade patterns already there).

When to use

  • A reviewer asks whether a codebase's patterns are implemented correctly.
  • Someone asks "is this really a <pattern>?" or "do we honor X's invariants?".
  • A periodic conformance check after a release, to catch new mislabels/drift.

When NOT to use: adding a new pattern (use adopt-pattern), or general code review with no pattern claim in play.

Workflow

1. Inventory

List the catalog patterns the codebase implements. Match by shape, not name — a class named RateLimiter may be a different pattern, and a circuit breaker may exist unnamed. Hunt by shape: retry/backoff loops, lock or lease primitives, caches with eviction, state enums with transition switches, ring/circular buffers, breaker/trip counters, subscriber lists. Record the file(s) for each candidate. Only inventory patterns the codebase actually engages; do not pad the audit with absent ones.

2. Conformance — fetch the doc, never grade from memory

For each candidate, fetch the canonical doc page and read Core Idea (the invariant), When NOT to Use, and Production Proof (the reference shape). Then read the actual implementation. Grade against the doc's headline invariant.

3. Gap analysis — classify the deviation

Assign a verdict (scale below). The judgment is distinguishing faithful from divergent from mislabeled:

  • Meets the invariant faithfully → ✅
  • Meets the intent a different way (different algorithm/model) → 🟡
  • The developer/framework enables it but does not provide it → 🔵
  • It is actually a different catalog pattern → 🔁 (the mislabel — flag loudly)
  • Not present → ⚪ (absence is N/A, not a failure, unless the pattern is clearly needed)

4. Evidence — cite code + doc

Every verdict cites a file:line in the codebase and the doc invariant it was graded against. A verdict without a citation is an opinion, not an audit.

Verdict scale

Symbol Meaning
Faithful — honors the doc's headline invariant.
🟡 Intent met, model/algorithm diverges from the reference.
🔵 Enabled, not provided — the developer brings it.
🔁 Mislabeled — it is actually a different catalog pattern.
Absent / N-A — not present (only a gap if the pattern is needed).

Scorecard format (the output)

Produce one table, optionally grouped by catalog category:

Pattern Verdict Evidence & note
name sym path:line — one-line check against the doc's invariant

Then 2–4 headline findings, leading with the mislabels (🔁) and real gaps — those are what the audit is for. Faithful rows are reassurance, not the point.

Common mistakes

  • Grading from memory instead of fetching the doc — invents invariants. Fetch every candidate's doc page.
  • Accepting the code's own label — you will rubber-stamp a mutex called "Semaphore." Grade against the doc, not the class name.
  • Treating absence as a bug — a pattern not present is ⚪/N-A unless the codebase clearly needs it.
  • Verdicts without file:line — an audit is evidence, not vibes.
  • Auditing all 46 — grade only the patterns the codebase engages.

Example (compressed)

Auditing an HTTP/MCP framework:

Pattern Verdict Evidence & note
Actor Model in-memory-runtime.ts:144,156 — per-identity serialized turns; handler gets a clone, rollback on throw.
Semaphore 🔁 redis-actor-runtime.ts:18 — the lease is SET NX (count=1) = mutex; the doc routes max=1 → mutex.
MVCC 🟡 in-memory-runtime.ts:113 — lease-free reads never block writers, but only one version is kept (snapshot read, not multi-version).
Circuit Breaker Absent across all packages — a real gap for an outbound-heavy framework.

Headline: two over-claims (Semaphore→mutex, MVCC→single-version) that would mislead a developer expecting counting-semaphore or multi-version guarantees; one genuine gap (no circuit breaker).

Accueil - Wiki
Copyright © 2011-2026 iteam. Current version is 2.155.2. UTC+08:00, 2026-07-09 01:06
浙ICP备14020137号-1 $Carte des visiteurs$