{"owner":"nibzard","repo":"awesome-agentic-patterns","hasSkills":true,"totalSkillsCount":12,"totalTokensCount":37910,"categories":["anthropic-skill","claude-rule","root-instruction"],"hasMcp":false,"mcpConfig":null,"found":[".claude/skills/create-pattern/PATTERN_INDEX.md","CLAUDE.md",".claude/skills/arxiv-pattern-discovery/SKILL.md","skills/pr-review/SKILL.md",".claude/skills/create-pattern/SKILL.md","llms.txt",".claude/skills/arxiv-pattern-discovery/RUBRIC.md",".claude/skills/arxiv-pattern-discovery/WORKFLOW.md",".claude/skills/create-pattern/scripts/validate.py",".claude/skills/arxiv-pattern-discovery/scripts/pattern_similarity_checker.py",".claude/skills/arxiv-pattern-discovery/scripts/pattern_validator.py",".claude/skills/arxiv-pattern-discovery/scripts/arxiv_scanner.py"],"skills":{".claude/skills/create-pattern/PATTERN_INDEX.md":"# Pattern Index\n\nQuick reference for all 105+ patterns in the repository for semantic matching.\n\n## Category Summary\n\n| Category | Count | Key Themes |\n|----------|-------|------------|\n| Orchestration & Control | 32 | Task decomposition, sub-agents, tool routing |\n| Tool Use & Environment | 20 | Shell, browser, DB, sandbox tools |\n| UX & Collaboration | 16 | Prompts, hand-offs, staged commits |\n| Context & Memory | 14 | Window curation, vector cache, episodic memory |\n| Feedback Loops | 12 | CI, review, self-healing |\n| Reliability & Eval | 10 | Guardrails, evals, logging |\n| Security & Safety | 3 | Isolation, PII, scanning |\n| Learning & Adaptation | 3 | Agent RFT, skill libraries |\n\n## Common Tags (appear 4+ times)\n\n- tool-use, security, search, reinforcement-learning, reasoning\n- feedback, prompt-injection, planning, mcp, learning, evaluation\n- coding-agent, code-review, cli, automation\n\n## Pattern Clusters (for Matching)\n\n### Context Management Patterns\n- `context-minimization-pattern.md`\n- `context-window-anxiety-management.md`\n- `curated-code-context-window.md`\n- `layered-configuration-context.md`\n- `agentic-search-over-vector-embeddings.md`\n\n### Planning Patterns\n- `plan-then-execute-pattern.md`\n- `explicit-posterior-sampling-planner.md`\n- `tree-of-thought-reasoning.md`\n\n### Multi-Agent Patterns\n- `oracle-and-worker-multi-model.md`\n- `initializer-maintainer-dual-agent.md`\n- `sub-agent-spawning.md`\n- `continuous-autonomous-task-loop-pattern.md`\n\n### Memory/State Patterns\n- `episodic-memory-retrieval-injection.md`\n- `filesystem-based-agent-state.md`\n- `proactive-agent-state-externalization.md`\n\n### Security Patterns\n- `action-selector-pattern.md`\n- `egress-lockdown-no-exfiltration-channel.md`\n- `pii-tokenization.md`\n\n### Code Review Patterns\n- `criticgpt-style-evaluation.md`\n- `ai-assisted-code-review-verification.md`\n- `abstracted-code-representation-for-review.md`\n\n### Progressive Autonomy Chain\n- `progressive-autonomy-with-model-evolution.md`\n- `progressive-complexity-escalation.md`\n- `skill-library-evolution.md`\n\n### Tool Design Patterns\n- `dual-use-tool-design.md`\n- `tool-use-steering-via-prompting.md`\n- `tool-use-incentivization-via-reward-shaping.md`\n\n## Top Pattern Sources\n\n| Source | Patterns |\n|--------|----------|\n| Will Brown (Prime Intellect) | 8 patterns |\n| Boris Cherny (Anthropic) | 7 patterns |\n| Anthropic Engineering | 7 patterns |\n| Luca Beurer-Kellner et al. (2025) | 6 patterns |\n| Aman Sanger (Cursor) | 6 patterns |\n| Thorsten Ball | 5 patterns |\n| Quinn Slack | 5 patterns |\n| Lukas Möller (Cursor) | 5 patterns |\n\n## Matching Heuristics\n\nWhen analyzing a new source:\n\n1. **Check by author** - If source is from Will Brown, Boris Cherny, etc., likely matches existing pattern\n2. **Check by category** - Context management has 14 patterns with high overlap\n3. **Check by tags** - \"tool-use\", \"security\", \"reasoning\" indicate clusters\n4. **Problem similarity** - Same core challenge → likely existing pattern\n5. **Solution similarity** - Same mechanism → likely existing pattern\n\n## Decision Thresholds\n\n- **>80% confidence** - Update existing (same problem + solution + category)\n- **50-80% confidence** - Ask user (partial overlap)\n- **<50% confidence** - Create new (different problem/solution)\n","CLAUDE.md":"# CLAUDE.md\n\nThis file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.\n\n## Project Overview\n\nThis is a documentation website for \"Awesome Agentic Patterns\" - a curated catalogue of AI agent design patterns. It uses Astro (apps/web/) to generate a static documentation site that can be deployed to Vercel.\n\n## Key Commands\n\n> **NOTE:** This project uses **bun** as the package manager, not npm.\n\n### Development Workflow\n```bash\n# Initial setup (run once)\nbun install                            # Install dependencies\n\n# Standard development cycle\nbun run dev                            # Serve docs locally at http://localhost:4321\n\n# Building and deployment\nbun run build                          # Build static site to apps/web/dist/\nvercel deploy                          # Deploy to Vercel (primary)\n```\n\n## Architecture\n\nThe project has a unique architecture where pattern documentation drives the entire site:\n\n1. **Pattern Files** (`patterns/*.md`): Source of truth for all patterns\n   - Must include YAML front-matter with: title, status, authors, category, source, tags, summary, signals, anti_signals, updated_at\n   - Content sections: Problem, Solution, How to use it, Trade-offs, References\n\n2. **Data Pipeline**: Pattern files are converted to JSON in `apps/web/public/patterns/`\n   - Astro build reads JSON files to generate pages\n   - Pattern metadata drives navigation and listings\n\n3. **Build Process**:\n   - Astro builds from apps/web/ to apps/web/dist/\n   - Site can be served locally or deployed to Vercel\n\n## Pattern Development Workflow\n\n### Adding New Patterns\n1. **Start with template**: Copy `TEMPLATE.md` (repository root) to create new pattern files in `patterns/`\n2. **Required YAML front-matter**: Every pattern must include:\n   ```yaml\n   ---\n   title: \"Clear, Descriptive Title\"\n   status: \"proposed | emerging | production | foundational\"\n   authors: [\"Contributor Name (@username)\"]\n   based_on: [\"Original Creator (Source)\"]\n   category: \"Orchestration & Control | Context & Memory | Feedback Loops | Learning & Adaptation | Reliability & Eval | Security & Safety | Tool Use & Environment | UX & Collaboration | Uncategorized\"\n   source: \"URL to primary source\"\n   tags: [relevant, keywords, here]\n   summary: \"One sentence that says what the pattern does (the solution)\"  # Shown in the catalog list\n   signals: [\"When to use it\"]          # 2-4 items, shown as \"Use when\"\n   anti_signals: [\"When not to use it\"] # 2-3 items, shown as \"Avoid when\"\n   updated_at: \"YYYY-MM-DD\"  # Required: last content change date — file mtimes differ per machine, so generated data needs an explicit date\n   ---\n   ```\n3. **Required sections**: Problem, Solution, How to use it, Trade-offs, References\n4. **Data sync**: Pattern files must be converted to JSON for the Astro site\n   - Run `bun run build:data` to update the JSON files\n   - JSON files are stored in `apps/web/public/patterns/` and `apps/web/public/data/patterns/`\n   - CI fails if the committed JSON files differ from what the pipeline produces; run the pipeline and commit its output together with the pattern `.md` change\n\n### Content Guidelines\n- Use Mermaid diagrams in patterns for architectural visualization\n- Pattern files support full Markdown with front-matter\n- Community policy for pattern submissions:\n  - Treat this as a community project, not a promotional channel\n  - Reject promotional, sales, affiliate, or backlink-seeding content\n  - For external contributors, prefer links to `github.com`, `github.io`, or non-vendor neutral references\n  - Allow vendor/product links only when the contribution is truly novel and adds clear value\n  - Require submissions to be materially novel and non-repetitive versus existing patterns\n- **CRITICAL**: Always add blank lines after headers before starting bullet point lists\n  - Incorrect: `**Header:**\\n- Item 1` (renders inline)\n  - Correct: `**Header:**\\n\\n- Item 1` (renders as proper list)\n  - This is required for Astro to properly convert Markdown lists to HTML `<ul><li>` elements\n\n### Asset Path Handling\n\n**CRITICAL**: When adding images or other assets that need to work on both localhost and deployed sites:\n\n- **Use absolute paths starting with `/`** in all asset references\n- **Image references**: Use `/image.jpeg` instead of `image.jpeg` in markdown files\n- **Rationale**: Relative paths can work locally but fail on Vercel due to different path resolution behavior\n- **Example fix**: Change `![Image](image.jpeg)` to `![Image](/image.jpeg)`\n\nThis ensures assets load correctly on both local development (`localhost:4321`) and production deployment (`agentic-patterns.com`).\n\n## Technical Architecture\n\n### Build System Components\n- **Astro**: Modern static site generator in `apps/web/`\n- **Pattern JSON files**: Generated data in `apps/web/public/patterns/`\n- **Vercel config**: Build settings in `vercel.json`\n- **TypeScript/Node.js**: Build toolchain\n\n### File Structure\n```\nTEMPLATE.md           # Template for new patterns (repository root)\n\npatterns/              # Source of truth - all pattern .md files\n└── *.md              # Individual pattern files with YAML front-matter\n\napps/web/             # Astro web application\n├── public/\n│   └── patterns/    # JSON pattern data for site generation\n├── src/             # Astro components and pages\n└── dist/            # Build output (deployment artifact)\n```\n\n### Dependencies\n- **Node.js**: Astro framework and build toolchain\n- **Vercel**: Primary deployment platform\n\n## Deployment\n\n- Primary deployment: Vercel (`vercel deploy`)\n- For detailed deployment instructions, see DEPLOYMENT.md\n",".claude/skills/arxiv-pattern-discovery/SKILL.md":"---\nname: arxiv-pattern-discovery\ndescription: Search arXiv for academic papers describing agentic AI patterns. Use when user asks to find new patterns from academic literature, search arXiv, discover patterns from papers, or review academic sources for pattern extraction.\n---\n\n# arXiv Pattern Discovery\n\nSearch arXiv for academic papers describing agentic AI patterns and score them using the Pattern Quality Rubric.\n\n## Quick Start\n\nInvoke this skill when the user asks to:\n- Search arXiv for new agent patterns\n- Find academic papers about multi-agent orchestration\n- Discover patterns from academic literature\n- Review the latest papers for extractable patterns\n- What new patterns are emerging from recent AI research?\n\n## Workflow\n\nThis skill implements a 3-phase discovery workflow:\n\n### Phase 1: Discovery\n```bash\n# Search for recent papers (last 30 days, max 50 results)\npython scripts/arxiv_scanner.py --days=30 --max-results=50 --export-md results.md\n\n# Search for specific topics\npython scripts/arxiv_scanner.py --query=\"multi-agent systems\" --max-results=100\n\n# Search with minimum quality threshold\npython scripts/arxiv_scanner.py --min-score=7.0 --export-md high-quality.md\n```\n\n### Phase 2: Review\n- Read the exported Markdown report\n- Identify high-quality papers (score >= 7.0)\n- Check for potential duplicates flagged by the scanner\n- Select candidates for pattern extraction\n\n### Phase 3: Next Steps\n- Use the `create-pattern` skill to extract patterns from selected papers\n- Or manually create patterns using `patterns/TEMPLATE.md`\n- Run the similarity checker before committing to avoid duplicates\n- Run the validator to ensure pattern quality\n\n## Script Reference\n\n### arxiv_scanner.py\n\nMain script for querying arXiv API and scoring papers.\n\n**Usage:**\n```bash\npython scripts/arxiv_scanner.py [OPTIONS]\n```\n\n**Options:**\n- `--query, -q`: arXiv search query (default: agent/agentic/multi-agent papers)\n- `--max-results, -n`: Maximum results to fetch (default: 100)\n- `--days, -d`: Only include papers from last N days (default: 365)\n- `--min-score, -m`: Minimum quality score to include (default: 5.0)\n- `--export-json`: Export results to JSON file\n- `--export-md`: Export results to Markdown file\n- `--patterns-dir`: Path to patterns directory (default: patterns)\n- `--verbose, -v`: Print detailed output for each paper\n\n**Examples:**\n```bash\n# Recent high-quality papers\npython scripts/arxiv_scanner.py --days=7 --min-score=7.0\n\n# Search specific topic\npython scripts/arxiv_scanner.py --query=\"multi-agent orchestration\" --max-results=50\n\n# Full scan with export\npython scripts/arxiv_scanner.py --days=30 --export-md arxiv_report.md --verbose\n```\n\n### pattern_similarity_checker.py\n\nDetect potentially duplicate or very similar patterns.\n\n**Usage:**\n```bash\n# Check a single pattern against existing patterns\npython scripts/pattern_similarity_checker.py patterns/new-pattern.md\n\n# Check all patterns against each other\npython scripts/pattern_similarity_checker.py --all\n\n# Custom threshold and export\npython scripts/pattern_similarity_checker.py --all --threshold=0.7 --export report.md\n```\n\n**Options:**\n- `--all, -a`: Check all patterns against each other\n- `--patterns-dir, -d`: Path to patterns directory (default: patterns)\n- `--threshold, -t`: Similarity threshold for reporting (default: 0.5)\n- `--export, -e`: Export report to Markdown file\n\n### pattern_validator.py\n\nValidate pattern files for completeness and quality.\n\n**Usage:**\n```bash\n# Validate a single pattern\npython scripts/pattern_validator.py patterns/new-pattern.md\n\n# Validate all patterns\npython scripts/pattern_validator.py --all --verbose\n\n# Export validation report\npython scripts/pattern_validator.py --all --export validation_report.md\n```\n\n**Options:**\n- `--all, -a`: Validate all pattern files\n- `--patterns-dir, -d`: Path to patterns directory (default: patterns)\n- `--verbose, -v`: Print detailed output for each issue\n- `--strict, -s`: Treat warnings as errors\n- `--export, -e`: Export report to Markdown file\n\n## Next Steps After Discovery\n\nAfter identifying candidate papers from arXiv:\n\n1. **Extract the Pattern**: Use the `create-pattern` skill with the paper URL or PDF\n2. **Validate**: Run `pattern_validator.py` on the new pattern file\n3. **Check for Duplicates**: Run `pattern_similarity_checker.py` on the new pattern\n4. **Review**: Ensure the pattern meets the quality threshold (score >= 5.0)\n5. **Commit**: Add the pattern to the repository\n\n## Quality Scoring\n\nPapers are scored using the Pattern Quality Rubric (see RUBRIC.md for details):\n\n- **Reusability (30%)**: Domain-specific → Multi-domain → Universal\n- **Novelty (25%)**: Existing → Incremental → Fundamentally new\n- **Clarity (20%)**: Vague → Clear → Crystal clear\n- **Evidence (15%)**: No eval → Some eval → Strong empirical\n- **Completeness (10%)**: Idea only → Partial details → Production-ready\n\n**Threshold**: Score >= 5.0 qualifies for pattern extraction\n","skills/pr-review/SKILL.md":"---\nname: awesome-agentic-patterns-pr-review\ndescription: Review pull requests for the awesome-agentic-patterns repository. Use when asked to validate a PR, assess whether a contribution fits the repo, inspect pattern submissions under patterns/, check merge readiness, repair a small submission issue on top of a contributor branch, draft a polite contributor comment, or apply the repository's pattern-first and non-promotional contribution policy to a GitHub pull request.\n---\n\n# Awesome Agentic Patterns PR Review\n\n## Overview\n\nReview PRs in this repository by applying the local contribution policy and checking the actual changed files. Treat `CONTRIBUTING.md` as the source of truth for acceptance criteria, `TEMPLATE.md` as the source of truth for expected pattern structure, and the validation scripts in `scripts/` as the source of truth for structural checks and generated-file expectations.\n\n## Read First\n\n- `CONTRIBUTING.md`\n- `README.md`\n- `SCHEMA.md` for the status tiers and field definitions\n- `TEMPLATE.md` at the repository root\n- `scripts/validate-patterns.ts`, the authoritative front-matter and section validator\n- `scripts/build-data.ts` when the PR touches patterns, generated README sections, or generated site data\n\nDo not restate repo policy from memory when those files are available. Quote or summarize the repository's own rules instead.\n\n## Workflow\n\n### 1. Inspect the PR\n\nUse `gh` first:\n\n- `gh pr view <number> --repo nibzard/awesome-agentic-patterns --json title,number,state,isDraft,author,baseRefName,headRefName,headRepository,headRepositoryOwner,maintainerCanModify,files,additions,deletions,mergeable,mergeStateStatus,reviewDecision,statusCheckRollup,labels,url,body`\n- `gh pr diff <number> --repo nibzard/awesome-agentic-patterns --patch`\n- `gh pr checks <number> --repo nibzard/awesome-agentic-patterns`\n\nIf you need the exact branch locally, fetch it with:\n\n- `git fetch origin refs/pull/<number>/head:pr-<number>`\n\nCapture these facts before deciding anything:\n\n- Whether the PR is a new pattern submission, a pattern edit, or a broader repo/tooling change\n- Whether the change correctly uses `patterns/<slug>.md` rather than editing generated docs directly\n- Whether `README.md` or `apps/web/public/` generated outputs changed because the contributor regenerated outputs, or because they hand-edited generated files\n- Whether `maintainerCanModify` is enabled and which fork/branch must be updated if you need to fix the PR\n- Whether GitHub mergeability is trustworthy yet; `UNKNOWN` can be transient right after a push\n\n### 2. Validate the submission contract\n\nFor pattern submissions, check the repository's exact contract before debating fit:\n\n- One pattern per PR\n- New patterns live in `patterns/` and use kebab-case filenames\n- PR title should use `Add: pattern-name`\n- The pattern should be concise, roughly capped at about 200 lines\n- Do not edit README auto-generated sections manually\n- `docs/index.md` is only a compatibility symlink to `README.md`\n- Required front-matter fields (enforced by `scripts/validate-patterns.ts`):\n  `title`\n  `status`\n  `authors`\n  `category`\n  `source`\n  `tags`\n  `summary`\n  `signals`\n  `anti_signals`\n  `updated_at` in `YYYY-MM-DD` form\n- `based_on` is optional, but a contributor-owned source must be disclosed in `authors` / `based_on`\n- `source_link` is invalid here; use `source`\n- Required content sections (enforced with `--check-content`):\n  `## Problem`\n  `## Solution`\n  `## How to use it`\n  `## Trade-offs`\n  `## References`\n- Status tier, one of `proposed`, `emerging`, `production`, `foundational`, judged against the independent-adoption bar:\n\n  - A submission backed only by a contributor-owned repo, a personal experiment, or a launch-stage product must use `status: proposed`. Downgrade anything higher to `proposed`.\n  - `emerging` needs 2+ independent implementations or teams, or 1 detailed production write-up or major lab paper with active industry iteration.\n  - `production` needs proof across multiple independent production systems, with documented failure modes and operational trade-offs.\n  - `foundational` is for an industry-default baseline whenever its `signals` apply, and the catalogue keeps the tier to roughly 12-18 patterns.\n\n- Agent-centric technical scope: the pattern must describe a control loop in which an agent senses, reasons, remembers, uses tools, or stays safe. Product strategy, startup philosophy, career advice, and generic non-agent software architecture belong in `principles/`, not `patterns/`.\n- Known Implementations cap: `Known Implementations` and tool references are limited to 3-5 entries per pattern. A PR that only appends another vendor or tool link is acceptable only when the tool replaces a deprecated reference or demonstrates a materially distinct architectural variant.\n- Differentiation: the PR description must answer \"Closest existing pattern(s) & how this is distinct\" and justify why the idea cannot live as a section inside an existing pattern.\n\nBefore judging novelty, run `python3 scripts/pattern_similarity_checker.py <pattern-file.md>`, then search `patterns/` for duplicates and near-overlaps by title, tags, and Problem wording. Compare what you find with the contributor's differentiation answer. When the primary `source` or a reference belongs to the contributor or an affiliated project, confirm the relationship is disclosed and the write-up frames it as an example rather than the center of the PR.\n\nFor generated-file sync, check whether the PR also updated the outputs that CI compares against `patterns/*.md`:\n\n- `README.md`\n- `apps/web/public/data/patterns.json`\n- other generated files under `apps/web/public/` when the pattern catalog changed\n- `llms.txt` at the repository root, which `bun run build:data` keeps identical to `apps/web/public/llms.txt`\n\nCall out structural violations explicitly. These are repository requirements, not style nits.\n\n### 3. Apply local policy\n\nUse `CONTRIBUTING.md` for the actual acceptance rubric. Evaluate:\n\n- Whether the PR documents a reusable pattern rather than a product announcement\n- Whether the pattern is materially novel and non-repetitive relative to existing patterns\n- Whether the write-up clearly explains Problem, Solution, and Trade-offs or practical mechanics\n- Whether references are public and verifiable\n- Whether the contribution is community-first and non-promotional\n- Whether external links are mostly `github.com`, `github.io`, or neutral technical references for outside contributors\n- Whether any vendor or product links are justified by clear novelty rather than marketing\n- Whether contributor-owned projects are disclosed and framed as examples rather than the center of the PR\n- Whether the category is the best fit for existing repo taxonomy\n- Whether the `status` tier matches its objective criterion; a contributor-owned repo or launch-stage product is `proposed`\n- Whether the pattern is an agent-specific technical control loop rather than product strategy or generic software architecture\n- Whether the PR description names the closest existing pattern(s) and justifies why the submission is not a section inside one of them\n- Whether a reference-addition PR stays within the 3-5 entry cap and adds a tool that replaces a deprecated reference or shows a materially distinct variant\n\nSeparate policy fit from technical mergeability. A PR can be in scope but still need a maintainer fix before merge.\n\n### 4. Run structural validation\n\nWhen reviewing a local branch or checking CI behavior, run from the repository root:\n\n- `bun run validate:patterns:content` for front matter, required sections, referential integrity, status vs. evidence, and length guardrails; this is the authoritative validator, and CI runs it\n- `bun run validate:patterns` for front matter only (`scripts/validate-patterns.ts`)\n- `python3 scripts/pattern_similarity_checker.py <pattern-file.md>` to surface near-duplicates before you judge novelty\n- `bun run build:data` when checking generated README or site data changes; it also fails on a missing or malformed `updated_at`. CI syncs the root `llms.txt` alongside `README.md` and `apps/web/public/`.\n\nTreat the scripts as structural checks, not the decision-maker. Human review still decides repository fit, novelty, promotion risk, and category choice.\n\n### 5. Repair the branch when the PR is acceptable but stale\n\nIf the PR is acceptable and the user wants it fixed or merged, prefer the smallest possible maintainer correction:\n\n- Fetch the PR branch locally\n- Rebase or replay it onto `origin/main`\n- Fix only the minimum structural issue\n- Normalize front-matter keys or section headings to repo expectations\n- Regenerate `README.md` and site data with `bun run build:data` only if the PR already requires generated-file sync\n- Push back to the contributor's exact head branch, preferably with `--force-with-lease`\n- Re-check `gh pr view` after the push because `mergeable` and `mergeStateStatus` may temporarily show `UNKNOWN`\n\nDo not turn a small submission repair into a broader cleanup.\n\n### 6. Produce the review\n\nUse a code-review mindset:\n\n- Present findings first, ordered by severity, with file references when applicable\n- If there are no findings, say that explicitly\n- After findings, give one clear decision: `Accept`, `Request changes`, or `Close`\n- Include mergeability as a separate line: `clean`, `needs maintainer repair`, or `blocked`\n- When the user wants to merge, include the exact next action: `comment`, `fix and push`, `merge`, or `close`\n\n## Output Shape\n\nKeep the final review compact and consistent. Use this exact structure:\n\n`Summary`\n- One short sentence on PR state or scope if useful\n\n`Findings`\n- Findings first, ordered by severity\n- If there are no findings, say `No blocking findings.`\n\n`Decision`\n- `Policy fit: Accept | Request changes | Close`\n- `Mergeability: clean | needs maintainer repair | blocked`\n- `Recommended action: comment | fix and push | merge | close`\n\n`Proposed comment to contributor`\n- Draft a short, polite comment suitable for posting on the PR\n- If the maintainer already fixed the PR, say what was adjusted and thank the contributor\n- If requesting changes, state the minimum changes needed\n\n`What next`\n- End with a direct question to the user asking what they want next\n- Example: `Do you want me to post the comment, push the small fix, or merge it?`\n",".claude/skills/create-pattern/SKILL.md":"---\nname: create-pattern\ndescription: Analyze sources (blog posts, PDFs, YouTube videos, codebases, pasted text) for agentic patterns, match against 105+ existing patterns, create new patterns or update existing with new sources and insights.\nallowed-tools:\n  - Read\n  - Write\n  - Glob\n  - Grep\n  - Bash\n  - mcp__web_reader__webReader\n  - mcp__4_5v_mcp__analyze_image\n---\n\n# Pattern Ingestion Skill\n\nThis skill intelligently analyzes sources for agentic AI patterns, matches them against existing patterns in the repository, and either creates new patterns or updates existing ones with additional sources and insights.\n\n## Overview\n\n**Input:** A source (URL, PDF file, YouTube link, codebase path, or pasted text)\n\n**Process:**\n1. Ingest and analyze the source\n2. Extract pattern concepts\n3. Match against existing 105+ patterns\n4. Decide: create new OR update existing\n5. Execute and build\n\n**Output:** New pattern file OR updated existing pattern + build confirmation\n\n---\n\n## Phase 1: Ingest Source\n\nDetect the input type and process accordingly:\n\n### URL (blog post, documentation, article)\nUse `mcp__web_reader__webReader` with the URL:\n```json\n{\"url\": \"USER_PROVIDED_URL\", \"return_format\": \"markdown\"}\n```\n\n### PDF File\nUse `Read` tool with the PDF path.\n\n### YouTube Video\nUse `mcp__web_reader__webReader` with the YouTube URL (transcript extraction).\n\n### Codebase/Repository\nUse `Glob` to find key files, then `Read` to analyze:\n- `**/*.md` - Documentation\n- `**/*.py` - Python implementation\n- `**/*.ts` - TypeScript implementation\n- README files\n\n### Pasted Text\nAnalyze directly (no tool needed).\n\n---\n\n## Phase 2: Analyze & Extract\n\nFrom the source content, extract:\n\n1. **Pattern Title** - What is this pattern called?\n2. **Problem Statement** - What challenge does it solve?\n3. **Solution** - What's the core approach/mechanism?\n4. **Category** - Which of 8 categories fits best?\n5. **Source URL** - The original source\n6. **Author/Originator** - Who created/originated this?\n7. **Tags** - 3+ relevant keywords\n8. **Key Insights** - Any novel techniques, constraints, trade-offs\n\n**Generate candidate metadata:**\n- Title: descriptive, concise\n- Category: select from allowed categories (see reference below)\n- Tags: generate 5-10 relevant tags\n- Status: default to \"emerging\" unless evidence suggests otherwise\n\n---\n\n## Phase 3: Match Against Existing Patterns\n\nSearch for similar patterns in `patterns/` directory:\n\n### Step 3a: Read All Pattern Frontmatter\nUse `Glob` to find all `.md` files in `patterns/`, then `Grep` with output_mode `content` to extract frontmatter from each:\n```bash\ngrep -A 10 \"^title:\" patterns/*.md\n```\n\nOr read multiple pattern files in parallel to compare:\n- Problem statements\n- Solution approaches\n- Categories\n- Tags\n- Sources\n\n### Step 3b: Semantic Comparison\n\nFor each existing pattern, assess similarity using these signals:\n\n**Primary Signals (weight: 30% each)**\n1. **Problem Statement** - Same fundamental challenge?\n2. **Solution Mechanism** - Same core approach/technique?\n3. **Category** - Same category?\n\n**Secondary Signals (weight: 10% each)**\n4. **Tag Overlap** - Shared keywords?\n5. **Source/Author** - Same contributor's follow-up work?\n6. **Title** - Similar naming/description?\n\n### Step 3c: Calculate Confidence Score\n\n```\nScore = Σ(matching_signals × weights)\n```\n\n- All 3 primary match → 90%+ confidence\n- 2 primary + 1+ secondary → 70-90% confidence\n- 1 primary + 2+ secondary → 50-70% confidence\n- 0-1 primary only → <50% confidence\n\n### Step 3d: Identify Top Matches\n\nList top 3 matching patterns with:\n- Pattern title and file path\n- Confidence score\n- Matching rationale (which signals matched)\n\n---\n\n## Phase 4: Decision\n\nBased on confidence score:\n\n### High Confidence (>80%) → Update Existing\nUpdate the top-matching existing pattern with new source.\n\n### Low Confidence (<50%) → Create New\nCreate a brand new pattern file.\n\n### Medium Confidence (50-80%) → Ask User\nPresent the top match and ask:\n\n```\nThis source seems related to:\n- [Match Pattern] (X% confidence)\n  - Similar problem: [problem summary]\n  - Similar solution: [solution summary]\n\nShould I:\n1. Create a new pattern\n2. Update the existing pattern with this new source\n```\n\n---\n\n## Phase 5a: Create New Pattern\n\n### Step 5a-1: Generate Metadata\n```yaml\n---\ntitle: \"Extracted Title\"\nstatus: emerging\nauthors: [\"Your Name (@yourusername)\"]\nbased_on: [\"Originator Name (Source/Context)\"]\ncategory: \"Selected Category\"\nsource: \"SOURCE_URL\"\ntags: [tag1, tag2, tag3, ...]\n---\n```\n\n### Step 5a-2: Generate Slug\nConvert title to kebab-case:\n- Lowercase\n- Spaces → hyphens\n- Remove special characters\n- Example: \"Tree of Thought Reasoning\" → `tree-of-thought-reasoning`\n\n### Step 5a-3: Write Pattern File\nCreate `patterns/{slug}.md` with structure:\n\n```markdown\n---\ntitle: \"Title\"\nstatus: emerging\nauthors: [\"Your Name (@yourusername)\"]\nbased_on: [\"Originator (Source)\"]\ncategory: \"Category\"\nsource: \"URL\"\ntags: [tag1, tag2, tag3]\n---\n\n## Problem\n[Extracted problem statement]\n\n## Solution\n[Extracted solution description]\n\n- Key components: [list]\n- Mechanism: [describe]\n\n```pseudo\n[Optional: pseudocode if helpful]\n```\n\n## How to use it\n[Extracted usage guidance]\n\n## Trade-offs\n[Extracted pros and cons]\n\n* **Pros:** [benefits]\n* **Cons:** [drawbacks]\n\n## References\n* [Original Source Title](URL)\n```\n\n---\n\n## Phase 5b: Update Existing Pattern\n\n### Step 5b-1: Read Existing Pattern\nRead the matched pattern file at `patterns/{existing-slug}.md`\n\n### Step 5b-2: Update Frontmatter\n\n**Add to `based_on` array:**\n```yaml\nbased_on:\n  - \"Existing Source (Existing Context)\"\n  - \"New Originator (New Source/Context)\"  # Add this\n```\n\n**Add new tags** (if not duplicates):\n```yaml\ntags:\n  - existing-tag\n  - new-tag-from-source  # Add unique new tags\n```\n\n### Step 5b-3: Add to References Section\n\nAppend to the `## References` section:\n```markdown\n## References\n* [Existing Source](existing-url)\n* [New Source Title](new-url)  # Add this\n```\n\n### Step 5b-4: Auto-Expand Content (If Applicable)\n\n**IF** the new source adds substantial new insights (not just a citation):\n\n**To Solution section:**\n```markdown\n## Solution\n[existing content...]\n\n**Additional insights from [New Source]:**\n[Extracted new insights with attribution]\n```\n\n**To How to use it section:**\n```markdown\n## How to use it\n[existing content...]\n\n**According to [New Source]:**\n[New usage guidance or implementation details]\n```\n\n**To Trade-offs section:**\n```markdown\n## Trade-offs\n* **Pros:** [existing..., new pros from source]\n* **Cons:** [existing..., new cons from source]\n```\n\n### Step 5b-5: Write Updated File\nWrite the updated content back to `patterns/{existing-slug}.md`\n\n---\n\n## Phase 6: Build\n\n### Step 6-1: Run Build Script\n```bash\ncd apps/web && bun run build-data\n```\n\n### Step 6-2: Verify Success\nCheck for:\n- Pattern JSON files updated in `apps/web/public/patterns/`\n- No error messages\n\n---\n\n## Reference: Allowed Values\n\n### Categories (8 options)\n- Orchestration & Control\n- Context & Memory\n- Feedback Loops\n- Learning & Adaptation\n- Reliability & Eval\n- Security & Safety\n- Tool Use & Environment\n- UX & Collaboration\n- Uncategorized\n\n### Status Values (7 options)\n- proposed - Initial concept\n- emerging - Early adoption\n- established - Proven approach\n- validated-in-production - Production-tested\n- best-practice - Industry standard\n- experimental-but-awesome - Novel but effective\n- rapidly-improving - Fast-evolving\n\n### Front-matter Template\n```yaml\n---\ntitle: \"Pattern Title\"\nstatus: emerging\nauthors: [\"Contributor Name (@username)\"]\nbased_on: [\"Originator Name (Source Context)\"]\ncategory: \"Category Name\"\nsource: \"https://example.com/source\"\ntags: [tag1, tag2, tag3]\n---\n```\n\n---\n\n## Output Summary\n\nAfter completion, provide:\n\n**For New Pattern:**\n```\n✅ Created new pattern: patterns/{slug}.md\n- Title: [title]\n- Category: [category]\n- Tags: [tags]\n\nNext steps:\n1. Review and edit the pattern file for completeness\n2. Run: cd apps/web && bun run dev\n3. Commit: git add patterns/{slug}.md\n```\n\n**For Updated Pattern:**\n```\n✅ Updated existing pattern: patterns/{slug}.md\n- Added source to based_on: [source]\n- Added [N] new tags\n- [Expanded Solution/How-to sections]\n\nNext steps:\n1. Review the updated pattern file\n2. Run: cd apps/web && bun run dev\n3. Commit: git add patterns/{slug}.md\n```\n\n---\n\n## Tips\n\n- **When in doubt, ask the user** - Pattern matching can be nuanced\n- **Preserve existing content** - When updating, don't remove or overwrite existing insights\n- **Clear attribution** - Always cite sources when adding new content\n- **Tag thoughtfully** - Tags help with future matching\n- **Check for duplicates** - If `based_on` already includes the source, just inform the user\n","llms.txt":"# Awesome Agentic Patterns\n\nA curated catalogue of AI agent design patterns.\n\nEvery pattern is also available as Markdown at https://agentic-patterns.com/patterns/<slug>.md. Full text of all patterns: https://agentic-patterns.com/llms-full.txt. Usage notes for agents: https://agentic-patterns.com/agents.\n\n## Patterns\n\n### 402-first-machine-payments\n402-First Machine Payments (Price-Before-Work Tool Purchases): Server returns an HTTP 402 price quote before doing work, and the agent pays the exact amount only if it fits its budget cap\nURL: https://agentic-patterns.com/patterns/402-first-machine-payments\nMarkdown: https://agentic-patterns.com/patterns/402-first-machine-payments.md\n\n### abstracted-code-representation-for-review\nAbstracted Code Representation for Review: Shows reviewers pseudocode, intent summaries, and logical diffs of code changes, with drill-down to the real code to confirm the mapping\nURL: https://agentic-patterns.com/patterns/abstracted-code-representation-for-review\nMarkdown: https://agentic-patterns.com/patterns/abstracted-code-representation-for-review.md\n\n### action-caching-replay\nAction Caching & Replay Pattern: Records each agent action with XPath and frame metadata so later runs replay it without LLM calls, with LLM fallback when replay fails\nURL: https://agentic-patterns.com/patterns/action-caching-replay\nMarkdown: https://agentic-patterns.com/patterns/action-caching-replay.md\n\n### action-selector-pattern\nAction-Selector Pattern: LLM maps user intent to a pre-approved action ID with schema-validated parameters, and tool outputs never return to the selector\nURL: https://agentic-patterns.com/patterns/action-selector-pattern\nMarkdown: https://agentic-patterns.com/patterns/action-selector-pattern.md\n\n### adaptive-sandbox-fanout-controller\nAdaptive Sandbox Fan-Out Controller: Starts a small batch of parallel sandboxes, then scales up, stops early, or refines the prompt based on early success, variance, and error signals\nURL: https://agentic-patterns.com/patterns/adaptive-sandbox-fanout-controller\nMarkdown: https://agentic-patterns.com/patterns/adaptive-sandbox-fanout-controller.md\n\n### agent-circuit-breaker\nAgent Circuit Breaker: Prevents agents from wasting tokens and time on repeatedly failing tools by tracking failure rates and temporarily disabling broken tool endpoints\nURL: https://agentic-patterns.com/patterns/agent-circuit-breaker\nMarkdown: https://agentic-patterns.com/patterns/agent-circuit-breaker.md\n\n### agent-modes-by-model-personality\nAgent Modes by Model Personality: Offers separate working modes, each with its own prompts, tools, UI, and expectations, tuned to one model's working style\nURL: https://agentic-patterns.com/patterns/agent-modes-by-model-personality\nMarkdown: https://agentic-patterns.com/patterns/agent-modes-by-model-personality.md\n\n### agent-reinforcement-fine-tuning\nAgent Reinforcement Fine-Tuning (Agent RFT): Trains model weights with reinforcement learning on real tool calls and custom graders to improve domain-specific tool use and multi-step reasoning\nURL: https://agentic-patterns.com/patterns/agent-reinforcement-fine-tuning\nMarkdown: https://agentic-patterns.com/patterns/agent-reinforcement-fine-tuning.md\n\n### agent-sdk-for-programmatic-control\nAgent SDK for Programmatic Control: Exposes agent functions through an SDK and CLI so code can run the agent headless with set tools, permissions, and resource limits\nURL: https://agentic-patterns.com/patterns/agent-sdk-for-programmatic-control\nMarkdown: https://agentic-patterns.com/patterns/agent-sdk-for-programmatic-control.md\n\n### agent-assisted-scaffolding\nAgent-Assisted Scaffolding: Agent generates initial files, boilerplate, and directory structure from a high-level description so developers start on core logic\nURL: https://agentic-patterns.com/patterns/agent-assisted-scaffolding\nMarkdown: https://agentic-patterns.com/patterns/agent-assisted-scaffolding.md\n\n### agent-driven-research\nAgent-Driven Research: Agent plans its own queries, fans out parallel search workers across sources, reflects on evidence gaps, and iterates until it can write a sourced report\nURL: https://agentic-patterns.com/patterns/agent-driven-research\nMarkdown: https://agentic-patterns.com/patterns/agent-driven-research.md\n\n### agent-first-tool-discovery\nAgent-First Tool Discovery: Indexes tools and agents across MCP registries, A2A cards, OpenAPI specs, and custom directories into one normalized search surface ranked by agent-relevant signals\nURL: https://agentic-patterns.com/patterns/agent-first-tool-discovery\nMarkdown: https://agentic-patterns.com/patterns/agent-first-tool-discovery.md\n\n### agent-first-tooling-and-logging\nAgent-First Tooling and Logging: Designs logs and tool output for agent consumption with one unified log stream, structured JSON, and agent-aware CLI flags\nURL: https://agentic-patterns.com/patterns/agent-first-tooling-and-logging\nMarkdown: https://agentic-patterns.com/patterns/agent-first-tooling-and-logging.md\n\n### agent-friendly-workflow-design\nAgent-Friendly Workflow Design: Gives agents clear high-level goals, room for implementation choices, structured I/O, and plan review before execution\nURL: https://agentic-patterns.com/patterns/agent-friendly-workflow-design\nMarkdown: https://agentic-patterns.com/patterns/agent-friendly-workflow-design.md\n\n### agent-powered-codebase-qa-onboarding\nAgent-Powered Codebase Q&A / Onboarding: Agent indexes the codebase with embeddings and code graphs and answers natural-language questions about where code is and how it behaves\nURL: https://agentic-patterns.com/patterns/agent-powered-codebase-qa-onboarding\nMarkdown: https://agentic-patterns.com/patterns/agent-powered-codebase-qa-onboarding.md\n\n### agentic-search-over-vector-embeddings\nAgentic Search Over Vector Embeddings: Replaces vector indexes with agent-driven grep, find, and file traversal that searches current file state on demand and refines iteratively\nURL: https://agentic-patterns.com/patterns/agentic-search-over-vector-embeddings\nMarkdown: https://agentic-patterns.com/patterns/agentic-search-over-vector-embeddings.md\n\n### ai-assisted-code-review-verification\nAI-Assisted Code Review / Verification: Uses AI tools to flag issues, summarize change intent, and explain code so human reviewers focus on intent and business logic\nURL: https://agentic-patterns.com/patterns/ai-assisted-code-review-verification\nMarkdown: https://agentic-patterns.com/patterns/ai-assisted-code-review-verification.md\n\n### anchored-structured-context-compaction\nAnchored Structured Context Compaction: Maintains a typed state block (pinned goal and constraints, verified decisions, an artifact registry, open blockers) and merges only the newly evicted span into it at each compaction, so that long sessions keep exact details instead of drifting\nURL: https://agentic-patterns.com/patterns/anchored-structured-context-compaction\nMarkdown: https://agentic-patterns.com/patterns/anchored-structured-context-compaction.md\n\n### anti-reward-hacking-grader-design\nAnti-Reward-Hacking Grader Design: Design reward functions with multi-criteria evaluation and iterative hardening to prevent models from gaming graders, ensuring training rewards align with actual task quality.\nURL: https://agentic-patterns.com/patterns/anti-reward-hacking-grader-design\nMarkdown: https://agentic-patterns.com/patterns/anti-reward-hacking-grader-design.md\n\n### multi-step-analysis-pipeline-orchestration\nArtifact-Driven Analysis Pipeline Orchestration: Has an agent run independent analysis scripts, read their structured reports, and merge them into one final report or visualization\nURL: https://agentic-patterns.com/patterns/multi-step-analysis-pipeline-orchestration\nMarkdown: https://agentic-patterns.com/patterns/multi-step-analysis-pipeline-orchestration.md\n\n### asynchronous-coding-agent-pipeline\nAsynchronous Coding Agent Pipeline: Splits inference, tool execution, reward modeling, and learning into asynchronous workers linked by message queues so GPUs stay busy\nURL: https://agentic-patterns.com/patterns/asynchronous-coding-agent-pipeline\nMarkdown: https://agentic-patterns.com/patterns/asynchronous-coding-agent-pipeline.md\n\n### authenticated-authority-channel\nAuthenticated Authority Channel: Preserve a distinguishable channel for authenticated intent so retrieved content can inform reasoning without granting itself authority.\nURL: https://agentic-patterns.com/patterns/authenticated-authority-channel\nMarkdown: https://agentic-patterns.com/patterns/authenticated-authority-channel.md\n\n### autonomous-workflow-agent-architecture\nAutonomous Workflow Agent Architecture: Runs multi-step engineering workflows in containers with tmux sessions, sleep-based monitoring, checkpoints, and context-aware error recovery\nURL: https://agentic-patterns.com/patterns/autonomous-workflow-agent-architecture\nMarkdown: https://agentic-patterns.com/patterns/autonomous-workflow-agent-architecture.md\n\n### background-agent-ci\nBackground Agent with CI Feedback: Runs the agent in the background on its own branch and uses CI results as feedback to patch failures until green or blocked\nURL: https://agentic-patterns.com/patterns/background-agent-ci\nMarkdown: https://agentic-patterns.com/patterns/background-agent-ci.md\n\n### black-box-skill-invocation\nBlack-Box Skill Invocation: Shares skills through input and output schemas only and runs them on the provider side, so prompts and code never cross the boundary\nURL: https://agentic-patterns.com/patterns/black-box-skill-invocation\nMarkdown: https://agentic-patterns.com/patterns/black-box-skill-invocation.md\n\n### board-mediated-inter-agent-coordination\nBoard-Mediated Async Inter-Agent Coordination: Routes agent-to-agent messages through comment threads on board cards, with a prefix that creates an inbox card to notify the target agent\nURL: https://agentic-patterns.com/patterns/board-mediated-inter-agent-coordination\nMarkdown: https://agentic-patterns.com/patterns/board-mediated-inter-agent-coordination.md\n\n### budget-aware-model-routing-with-hard-cost-caps\nBudget-Aware Model Routing with Hard Cost Caps: Routes each request to the cheapest model that meets its needs under hard cost caps, and escalates only when quality gates fail\nURL: https://agentic-patterns.com/patterns/budget-aware-model-routing-with-hard-cost-caps\nMarkdown: https://agentic-patterns.com/patterns/budget-aware-model-routing-with-hard-cost-caps.md\n\n### canary-rollout-and-automatic-rollback-for-agent-policy-changes\nCanary Rollout and Automatic Rollback for Agent Policy Changes: Ships agent policy changes to a small traffic slice first, monitors guardrail metrics, and rolls back to the last stable version automatically\nURL: https://agentic-patterns.com/patterns/canary-rollout-and-automatic-rollback-for-agent-policy-changes\nMarkdown: https://agentic-patterns.com/patterns/canary-rollout-and-automatic-rollback-for-agent-policy-changes.md\n\n### capability-escrow-receipt\nCapability-Escrow-Receipt: Binds a signed capability listing, an atomic escrow-plus-hire step, and a signed work receipt into one loop for agent-to-agent payment\nURL: https://agentic-patterns.com/patterns/capability-escrow-receipt\nMarkdown: https://agentic-patterns.com/patterns/capability-escrow-receipt.md\n\n### chain-of-thought-monitoring-interruption\nChain-of-Thought Monitoring & Interruption: Streams agent reasoning and tool calls in real time so a human can interrupt and redirect early when the approach is wrong\nURL: https://agentic-patterns.com/patterns/chain-of-thought-monitoring-interruption\nMarkdown: https://agentic-patterns.com/patterns/chain-of-thought-monitoring-interruption.md\n\n### classify-then-act-for-background-agents\nClassify-Then-Act for Background Agents: Sorts each task into has-default, needs-intent, or out-of-scope, builds only has-default work in a sandbox, and queues it for human review\nURL: https://agentic-patterns.com/patterns/classify-then-act-for-background-agents\nMarkdown: https://agentic-patterns.com/patterns/classify-then-act-for-background-agents.md\n\n### cli-native-agent-orchestration\nCLI-Native Agent Orchestration: Drives agents through their non-interactive CLI mode (claude -p with JSON output and exit codes) so Makefiles, Git hooks, cron jobs, and CI can script and replay agent runs\nURL: https://agentic-patterns.com/patterns/cli-native-agent-orchestration\nMarkdown: https://agentic-patterns.com/patterns/cli-native-agent-orchestration.md\n\n### code-over-api-pattern\nCode-Over-API (Code Mode): Agent writes code that calls tools and processes data inside a sandbox, so only summaries and samples return to the context window instead of every intermediate result\nURL: https://agentic-patterns.com/patterns/code-over-api-pattern\nMarkdown: https://agentic-patterns.com/patterns/code-over-api-pattern.md\n\n### code-then-execute-pattern\nCode-Then-Execute Pattern: LLM writes a sandboxed program or DSL script, a static taint checker verifies data flows, and an interpreter runs it in a locked sandbox\nURL: https://agentic-patterns.com/patterns/code-then-execute-pattern\nMarkdown: https://agentic-patterns.com/patterns/code-then-execute-pattern.md\n\n### codebase-optimization-for-agents\nCodebase Optimization for Agents: Optimizes tooling, CLIs, tests, and docs for agents first, with one-command verify loops and machine-readable output, even if human DX regresses\nURL: https://agentic-patterns.com/patterns/codebase-optimization-for-agents\nMarkdown: https://agentic-patterns.com/patterns/codebase-optimization-for-agents.md\n\n### commitment-ledger-reality-gated-credit\nCommitment Ledger with Reality-Gated Credit: Records agent promises and credits retrieved memory only after an externally verifiable outcome settles.\nURL: https://agentic-patterns.com/patterns/commitment-ledger-reality-gated-credit\nMarkdown: https://agentic-patterns.com/patterns/commitment-ledger-reality-gated-credit.md\n\n### compounding-engineering-pattern\nCompounding Engineering Pattern: After each feature, codifies agent mistakes and learnings into CLAUDE.md, slash commands, subagents, and hooks so the next feature is easier to build\nURL: https://agentic-patterns.com/patterns/compounding-engineering-pattern\nMarkdown: https://agentic-patterns.com/patterns/compounding-engineering-pattern.md\n\n### parallel-tool-execution\nConditional Parallel Tool Execution: Runs a batch of tool calls in parallel when all are read-only and in sequence when any modifies state, then returns results in request order\nURL: https://agentic-patterns.com/patterns/parallel-tool-execution\nMarkdown: https://agentic-patterns.com/patterns/parallel-tool-execution.md\n\n### consequence-family-coverage-audit\nConsequence-Family Coverage Audit: Audit an agent's risk policy by enumerating families of consequence and asking which rule covers each, because a hand-written risk list reliably encodes one family and stays silent on the rest\nURL: https://agentic-patterns.com/patterns/consequence-family-coverage-audit\nMarkdown: https://agentic-patterns.com/patterns/consequence-family-coverage-audit.md\n\n### context-budget-as-a-governed-resource\nContext Budget as a Governed Resource: Measures always-loaded context per source, alerts on trend growth, and puts hard spend caps and fan-out bounds on unattended agent runs\nURL: https://agentic-patterns.com/patterns/context-budget-as-a-governed-resource\nMarkdown: https://agentic-patterns.com/patterns/context-budget-as-a-governed-resource.md\n\n### context-window-anxiety-management\nContext Window Anxiety Management: Enables a large context window but caps usage lower, and adds prompts that state the token budget so the model does not rush to finish\nURL: https://agentic-patterns.com/patterns/context-window-anxiety-management\nMarkdown: https://agentic-patterns.com/patterns/context-window-anxiety-management.md\n\n### context-window-auto-compaction\nContext Window Auto-Compaction: Catches context overflow errors, compacts and validates the transcript with capped reserve headroom, and retries the request automatically\nURL: https://agentic-patterns.com/patterns/context-window-auto-compaction\nMarkdown: https://agentic-patterns.com/patterns/context-window-auto-compaction.md\n\n### context-minimization-pattern\nContext-Minimization Pattern: Removes untrusted user text and tool output from context after it becomes a safe structured artifact, so later steps see only trusted data\nURL: https://agentic-patterns.com/patterns/context-minimization-pattern\nMarkdown: https://agentic-patterns.com/patterns/context-minimization-pattern.md\n\n### continuous-autonomous-task-loop-pattern\nContinuous Autonomous Task Loop Pattern: Runs a loop where subagents pick the next task from a todo file, execute it in fresh context, commit it, and back off on rate limits\nURL: https://agentic-patterns.com/patterns/continuous-autonomous-task-loop-pattern\nMarkdown: https://agentic-patterns.com/patterns/continuous-autonomous-task-loop-pattern.md\n\n### credential-free-outbox\nCredential-Free Outbox: The agent writes finished work as a file to an outbox and a separate short-lived job with its own token delivers it, so the agent never holds a credential that can publish anything\nURL: https://agentic-patterns.com/patterns/credential-free-outbox\nMarkdown: https://agentic-patterns.com/patterns/credential-free-outbox.md\n\n### criticgpt-style-evaluation\nCriticGPT-Style Code Review: Runs a specialized critic model over generated code to find bugs, security flaws, and quality issues, and feeds critical findings back for regeneration\nURL: https://agentic-patterns.com/patterns/criticgpt-style-evaluation\nMarkdown: https://agentic-patterns.com/patterns/criticgpt-style-evaluation.md\n\n### cross-agent-lesson-sharing\nCross-Agent Lesson Sharing via Git: Agents write solved problems as markdown lessons in a shared Git repo and search them before debugging, with GitHub Issues as the coordination layer\nURL: https://agentic-patterns.com/patterns/cross-agent-lesson-sharing\nMarkdown: https://agentic-patterns.com/patterns/cross-agent-lesson-sharing.md\n\n### cross-cycle-consensus-relay\nCross-Cycle Consensus Relay: Each loop cycle reads a structured relay document, does its work, and atomically writes back decisions, open questions, and the single next action\nURL: https://agentic-patterns.com/patterns/cross-cycle-consensus-relay\nMarkdown: https://agentic-patterns.com/patterns/cross-cycle-consensus-relay.md\n\n### cross-domain-agent-conflict-resolution\nCross-Domain Agent Conflict Resolution: A coordination layer that cross-references recommendations from independent domain agents, detects conflicts on shared resources, and resolves them through policy-as-code.\nURL: https://agentic-patterns.com/patterns/cross-domain-agent-conflict-resolution\nMarkdown: https://agentic-patterns.com/patterns/cross-domain-agent-conflict-resolution.md\n\n### cryptographic-governance-audit-trail\nCryptographic Governance Audit Trail: Middleware checks each tool call against a policy file, then signs a receipt of the action with ML-DSA and appends it to a tamper-evident chain\nURL: https://agentic-patterns.com/patterns/cryptographic-governance-audit-trail\nMarkdown: https://agentic-patterns.com/patterns/cryptographic-governance-audit-trail.md\n\n### curated-code-context-window\nCurated Code Context Window: A search subagent finds the few relevant files for a task and injects only top snippets or summaries into the main coding agent's context\nURL: https://agentic-patterns.com/patterns/curated-code-context-window\nMarkdown: https://agentic-patterns.com/patterns/curated-code-context-window.md\n\n### custom-sandboxed-background-agent\nCustom Sandboxed Background Agent: Builds an in-house background coding agent that runs in sandboxed dev environments, streams progress over WebSocket, and iterates on compiler and test feedback\nURL: https://agentic-patterns.com/patterns/custom-sandboxed-background-agent\nMarkdown: https://agentic-patterns.com/patterns/custom-sandboxed-background-agent.md\n\n### dead-mans-switch-for-scheduled-agent-jobs\nDead-Man's Switch for Scheduled Agent Jobs: Each scheduled job writes a success sentinel to its log, and a separate checker files a task when the sentinel is missing or stale\nURL: https://agentic-patterns.com/patterns/dead-mans-switch-for-scheduled-agent-jobs\nMarkdown: https://agentic-patterns.com/patterns/dead-mans-switch-for-scheduled-agent-jobs.md\n\n### debiased-llm-as-a-judge-evaluation\nDebiased LLM-as-a-Judge Evaluation: Removes the systematic distortions of a model judge before its scores gate a release: swaps the order of each pairwise comparison, grades narrow pass/fail rubric items that cite evidence, supplies a reference answer and a judge from another model family, and measures the agreement with human labels first\nURL: https://agentic-patterns.com/patterns/debiased-llm-as-a-judge-evaluation\nMarkdown: https://agentic-patterns.com/patterns/debiased-llm-as-a-judge-evaluation.md\n\n### declarative-multi-agent-topology-definition\nDeclarative Multi-Agent Topology Definition: Define multi-agent systems declaratively in a single topology file — agents, flows, gates, hooks, group chats — then compile to platform-specific configurations for any agentic framework.\nURL: https://agentic-patterns.com/patterns/declarative-multi-agent-topology-definition\nMarkdown: https://agentic-patterns.com/patterns/declarative-multi-agent-topology-definition.md\n\n### delegated-user-auth-token-exchange\nDelegated User Authorization (OAuth Token Exchange): Exchanges the user's token and the agent's own identity for a short-lived, single-audience, minimally scoped token immediately before each tool call, so that the agent acts with delegated and attributable authority instead of a shared super-credential\nURL: https://agentic-patterns.com/patterns/delegated-user-auth-token-exchange\nMarkdown: https://agentic-patterns.com/patterns/delegated-user-auth-token-exchange.md\n\n### denial-tracking-permission-escalation\nDenial Tracking & Permission Escalation: Track repeated tool denials and auto-escalate to blanket permission prompts or fallback strategies, preventing wasted iterations in non-interactive contexts.\nURL: https://agentic-patterns.com/patterns/denial-tracking-permission-escalation\nMarkdown: https://agentic-patterns.com/patterns/denial-tracking-permission-escalation.md\n\n### design-time-file-partition\nDesign-Time File Partition as Concurrency Control: Each task declares every path it will write; overlapping tasks get a blocking dependency so only disjoint work runs at once on a shared checkout\nURL: https://agentic-patterns.com/patterns/design-time-file-partition\nMarkdown: https://agentic-patterns.com/patterns/design-time-file-partition.md\n\n### deterministic-grader-in-the-loop\nDeterministic Grader in the Loop: Replace the LLM-as-judge in an agent's self-review loop with a deterministic scorer that returns the raw counts behind each sub-score, so the agent has something specific to fix.\nURL: https://agentic-patterns.com/patterns/deterministic-grader-in-the-loop\nMarkdown: https://agentic-patterns.com/patterns/deterministic-grader-in-the-loop.md\n\n### deterministic-security-scanning-build-loop\nDeterministic Security Scanning Build Loop: Adds SAST, SCA, and secret scanners to the build target that the agent must run after each change, so scanner failures force the agent to fix the code\nURL: https://agentic-patterns.com/patterns/deterministic-security-scanning-build-loop\nMarkdown: https://agentic-patterns.com/patterns/deterministic-security-scanning-build-loop.md\n\n### deterministic-threat-rule-scanning\nDeterministic Threat Rule Scanning: Apply deterministic regex rules as a first-pass security layer to detect known threat patterns in AI agent tool calls and skill definitions.\nURL: https://agentic-patterns.com/patterns/deterministic-threat-rule-scanning\nMarkdown: https://agentic-patterns.com/patterns/deterministic-threat-rule-scanning.md\n\n### deterministic-zero-llm-orchestration\nDeterministic Zero-LLM Orchestration: A deterministic code orchestrator splits goals, runs parallel coding agents, verifies with tests, and commits, spending LLM tokens only on the one-time goal decomposition\nURL: https://agentic-patterns.com/patterns/deterministic-zero-llm-orchestration\nMarkdown: https://agentic-patterns.com/patterns/deterministic-zero-llm-orchestration.md\n\n### discrete-phase-separation\nDiscrete Phase Separation: Splits work into separate research, planning, and implementation conversations, each with fresh context, passing only distilled outputs between phases\nURL: https://agentic-patterns.com/patterns/discrete-phase-separation\nMarkdown: https://agentic-patterns.com/patterns/discrete-phase-separation.md\n\n### distributed-execution-cloud-workers\nDistributed Execution with Cloud Workers: Runs many agent sessions in parallel on cloud workers, each in its own git worktree, with dependency-aware scheduling, merge coordination, and approval gates\nURL: https://agentic-patterns.com/patterns/distributed-execution-cloud-workers\nMarkdown: https://agentic-patterns.com/patterns/distributed-execution-cloud-workers.md\n\n### dual-llm-pattern\nDual LLM Pattern: Splits work between a privileged LLM that calls tools but never sees untrusted data and a quarantined LLM that reads untrusted data but has no tools\nURL: https://agentic-patterns.com/patterns/dual-llm-pattern\nMarkdown: https://agentic-patterns.com/patterns/dual-llm-pattern.md\n\n### dual-rail-message-delivery\nDual-Rail Message Delivery: Sends every inter-agent message on two independent channels through one entry point, alerts when the rails diverge, and requires ACKs to confirm completion\nURL: https://agentic-patterns.com/patterns/dual-rail-message-delivery\nMarkdown: https://agentic-patterns.com/patterns/dual-rail-message-delivery.md\n\n### dual-speed-talker-reasoner-architecture\nDual-Speed Realtime Architecture (Talker-Reasoner): Splits an agent into a fast Talker that owns the live conversation and a slow Reasoner that plans and calls tools in the background, with a shared belief state as their only coupling, so that the user gets a reply at once while the deep work runs\nURL: https://agentic-patterns.com/patterns/dual-speed-talker-reasoner-architecture\nMarkdown: https://agentic-patterns.com/patterns/dual-speed-talker-reasoner-architecture.md\n\n### dual-use-tool-design\nDual-Use Tool Design: Builds each tool or skill as one CLI interface that both humans and agents call, with JSON output, exit codes, and the same permissions and logs\nURL: https://agentic-patterns.com/patterns/dual-use-tool-design\nMarkdown: https://agentic-patterns.com/patterns/dual-use-tool-design.md\n\n### durable-execution-step-checkpointing\nDurable Execution & Step Checkpointing: Replays a durable step history to resume crashed, rate-limited, or approval-paused agent runs from the last completed step, without repeating finished LLM calls or committed side effects\nURL: https://agentic-patterns.com/patterns/durable-execution-step-checkpointing\nMarkdown: https://agentic-patterns.com/patterns/durable-execution-step-checkpointing.md\n\n### dynamic-context-injection\nDynamic Context Injection: Lets users inject files, folders, or saved prompts into the agent's context mid-session with @-mentions and custom slash commands\nURL: https://agentic-patterns.com/patterns/dynamic-context-injection\nMarkdown: https://agentic-patterns.com/patterns/dynamic-context-injection.md\n\n### egress-lockdown-no-exfiltration-channel\nEgress Lockdown (No-Exfiltration Channel): Puts the agent behind a default-deny egress firewall with allowlisted destinations so stolen data has no outbound channel\nURL: https://agentic-patterns.com/patterns/egress-lockdown-no-exfiltration-channel\nMarkdown: https://agentic-patterns.com/patterns/egress-lockdown-no-exfiltration-channel.md\n\n### episodic-memory-retrieval-injection\nEpisodic Memory Retrieval & Injection: Writes a structured memory record after each episode and injects the top-k similar past memories as hints when a new task starts\nURL: https://agentic-patterns.com/patterns/episodic-memory-retrieval-injection\nMarkdown: https://agentic-patterns.com/patterns/episodic-memory-retrieval-injection.md\n\n### evidence-questions-not-verdict-questions\nEvidence Questions, Not Verdict Questions: Never ask the model for allow/ask/block. Ask it narrow, typed, observational questions and let code reduce the answers to the verdict, because the collapsed question is the low-confidence one.\nURL: https://agentic-patterns.com/patterns/evidence-questions-not-verdict-questions\nMarkdown: https://agentic-patterns.com/patterns/evidence-questions-not-verdict-questions.md\n\n### evidence-layered-evaluation-for-interactive-agents\nEvidence-Layered Evaluation for Interactive Agents: Scores interactive agent runs on a task outcome assertion and links each result to layered evidence: actions, screenshots, replays, network, and messages\nURL: https://agentic-patterns.com/patterns/evidence-layered-evaluation-for-interactive-agents\nMarkdown: https://agentic-patterns.com/patterns/evidence-layered-evaluation-for-interactive-agents.md\n\n### exact-action-authorization-binding\nExact-Action Authorization Binding: Bind a short-lived approval to the complete action presented to the reviewer, rederive and compare that identity at the acting boundary before execution, and commit the write with its postcondition check and idempotency receipt in one transaction.\nURL: https://agentic-patterns.com/patterns/exact-action-authorization-binding\nMarkdown: https://agentic-patterns.com/patterns/exact-action-authorization-binding.md\n\n### explicit-posterior-sampling-planner\nExplicit Posterior-Sampling Planner: Embeds Posterior Sampling for RL in the LLM's reasoning: sample a task model, plan, act, observe reward, and update the posterior\nURL: https://agentic-patterns.com/patterns/explicit-posterior-sampling-planner\nMarkdown: https://agentic-patterns.com/patterns/explicit-posterior-sampling-planner.md\n\n### extended-coherence-work-sessions\nExtended Coherence Work Sessions: Combines models with long coherence windows with context compaction, prompt caching, and persisted state so agents stay on task for hours\nURL: https://agentic-patterns.com/patterns/extended-coherence-work-sessions\nMarkdown: https://agentic-patterns.com/patterns/extended-coherence-work-sessions.md\n\n### external-credential-sync\nExternal Credential Sync: Reads AI credentials from other tools' keychains and config files and syncs them into the agent's store, with TTL-cached reads, refresh fences, and persisted ownership\nURL: https://agentic-patterns.com/patterns/external-credential-sync\nMarkdown: https://agentic-patterns.com/patterns/external-credential-sync.md\n\n### factory-over-assistant\nFactory over Assistant: Spawns several autonomous agents in parallel with automated feedback loops such as tests and builds, and checks on them later instead of watching one agent\nURL: https://agentic-patterns.com/patterns/factory-over-assistant\nMarkdown: https://agentic-patterns.com/patterns/factory-over-assistant.md\n\n### failover-aware-model-fallback\nFailover-Aware Model Fallback: Classifies each model failure by reason and falls back along a model chain only for retryable errors, failing fast on auth, billing, and user aborts\nURL: https://agentic-patterns.com/patterns/failover-aware-model-fallback\nMarkdown: https://agentic-patterns.com/patterns/failover-aware-model-fallback.md\n\n### fair-share-task-queues-with-heartbeat-leases\nFair-Share Task Queues with Heartbeat Leases: Distributes tasks across a shared agent fleet using weighted deficit-round-robin scheduling, with heartbeat leases and dead-letter retries to recover from crashed workers\nURL: https://agentic-patterns.com/patterns/fair-share-task-queues-with-heartbeat-leases\nMarkdown: https://agentic-patterns.com/patterns/fair-share-task-queues-with-heartbeat-leases.md\n\n### feature-list-as-immutable-contract\nFeature List as Immutable Contract: Defines every feature up front in a JSON list with acceptance steps; the agent may only flip a feature to passing after it verifies it\nURL: https://agentic-patterns.com/patterns/feature-list-as-immutable-contract\nMarkdown: https://agentic-patterns.com/patterns/feature-list-as-immutable-contract.md\n\n### filesystem-based-agent-state\nFilesystem-Based Agent State: Agents persist intermediate results and working state to files, creating durable checkpoints that enable workflow resumption, recovery from failures, and support for long-running tasks.\nURL: https://agentic-patterns.com/patterns/filesystem-based-agent-state\nMarkdown: https://agentic-patterns.com/patterns/filesystem-based-agent-state.md\n\n### filesystem-mediated-host-delegation\nFilesystem-Mediated Host Delegation: Lets a sandboxed agent write request files to a shared spool directory that a host daemon runs against a whitelist, with idempotent results the agent polls for\nURL: https://agentic-patterns.com/patterns/filesystem-mediated-host-delegation\nMarkdown: https://agentic-patterns.com/patterns/filesystem-mediated-host-delegation.md\n\n### fleet-cost-simulation-before-dispatch\nFleet Cost Simulation Before Dispatch: Replays an agent fleet's budget, priority, and failure-recovery policy against deterministic scenarios before committing real spend, so starvation and exhaustion verdicts arrive in CI instead of in production\nURL: https://agentic-patterns.com/patterns/fleet-cost-simulation-before-dispatch\nMarkdown: https://agentic-patterns.com/patterns/fleet-cost-simulation-before-dispatch.md\n\n### graph-of-thoughts\nGraph of Thoughts (GoT): Represents reasoning as a directed graph of thoughts so the model can branch, aggregate, refine, and revisit reasoning paths\nURL: https://agentic-patterns.com/patterns/graph-of-thoughts\nMarkdown: https://agentic-patterns.com/patterns/graph-of-thoughts.md\n\n### hook-based-safety-guard-rails\nHook-Based Safety Guard Rails for Autonomous Code Agents: Runs small shell scripts on PreToolUse and PostToolUse hooks to block destructive commands, lint edits, and warn on context use outside the agent's reasoning\nURL: https://agentic-patterns.com/patterns/hook-based-safety-guard-rails\nMarkdown: https://agentic-patterns.com/patterns/hook-based-safety-guard-rails.md\n\n### human-in-loop-approval-framework\nHuman-in-the-Loop Approval Framework: Systematically insert human approval gates for designated high-risk functions while maintaining agent autonomy for safe operations, with multi-channel approval interfaces and comprehensive audit trails.\nURL: https://agentic-patterns.com/patterns/human-in-loop-approval-framework\nMarkdown: https://agentic-patterns.com/patterns/human-in-loop-approval-framework.md\n\n### hybrid-gui-visual-grounding\nHybrid GUI & Visual Grounding: Grounds each GUI action in a filtered accessibility tree first, falls back to numbered visual marks or scaled coordinates only for what the tree cannot see, and confirms the effect of each action from a state diff before the next step\nURL: https://agentic-patterns.com/patterns/hybrid-gui-visual-grounding\nMarkdown: https://agentic-patterns.com/patterns/hybrid-gui-visual-grounding.md\n\n### hybrid-llm-code-workflow-coordinator\nHybrid LLM/Code Workflow Coordinator: Lets each workflow pick an LLM or a code script as its coordinator, so teams prototype with the LLM and move to reviewed code when determinism matters\nURL: https://agentic-patterns.com/patterns/hybrid-llm-code-workflow-coordinator\nMarkdown: https://agentic-patterns.com/patterns/hybrid-llm-code-workflow-coordinator.md\n\n### incident-to-eval-synthesis\nIncident-to-Eval Synthesis: Converts each production incident into executable eval cases with pass/fail criteria and gates future releases on them\nURL: https://agentic-patterns.com/patterns/incident-to-eval-synthesis\nMarkdown: https://agentic-patterns.com/patterns/incident-to-eval-synthesis.md\n\n### inference-healed-code-review-reward\nInference-Healed Code Review Reward: Replaces a binary tests-passed reward with a critic that scores correctness, style, performance, and security, explains low scores, and combines them\nURL: https://agentic-patterns.com/patterns/inference-healed-code-review-reward\nMarkdown: https://agentic-patterns.com/patterns/inference-healed-code-review-reward.md\n\n### inference-time-scaling\nInference-Time Scaling: Spends extra compute at inference time with best-of-N sampling, longer reasoning, self-refinement, search, and verification to improve output quality\nURL: https://agentic-patterns.com/patterns/inference-time-scaling\nMarkdown: https://agentic-patterns.com/patterns/inference-time-scaling.md\n\n### initializer-maintainer-dual-agent\nInitializer-Maintainer Dual Agent Architecture: Uses a one-time initializer agent to create the feature list, progress files, and bootstrap script, then a coding agent that resumes from them one feature per session\nURL: https://agentic-patterns.com/patterns/initializer-maintainer-dual-agent\nMarkdown: https://agentic-patterns.com/patterns/initializer-maintainer-dual-agent.md\n\n### intelligent-bash-tool-execution\nIntelligent Bash Tool Execution: Runs agent shell commands through a multi-mode executor that uses a PTY when needed, falls back to direct exec, and manages approvals, background jobs, and signals\nURL: https://agentic-patterns.com/patterns/intelligent-bash-tool-execution\nMarkdown: https://agentic-patterns.com/patterns/intelligent-bash-tool-execution.md\n\n### intent-level-cost-attribution\nIntent-Level Cost Attribution: Records every LLM call against the projectId/intentId/user key that caused it, at call time, so spend can be queried and enforced per work item instead of as an opaque total\nURL: https://agentic-patterns.com/patterns/intent-level-cost-attribution\nMarkdown: https://agentic-patterns.com/patterns/intent-level-cost-attribution.md\n\n### inversion-of-control\nInversion of Control: Gives the agent tools, a high-level objective, and guardrails, then lets it choose sequencing and recovery while humans set policy and review\nURL: https://agentic-patterns.com/patterns/inversion-of-control\nMarkdown: https://agentic-patterns.com/patterns/inversion-of-control.md\n\n### isolated-vm-per-rl-rollout\nIsolated VM per RL Rollout: Spin up an isolated virtual machine for each RL rollout to prevent cross-contamination between parallel agent executions, ensuring safe training with destructive tool access.\nURL: https://agentic-patterns.com/patterns/isolated-vm-per-rl-rollout\nMarkdown: https://agentic-patterns.com/patterns/isolated-vm-per-rl-rollout.md\n\n### iterative-multi-agent-brainstorming\nIterative Multi-Agent Brainstorming: Spawns several agents in parallel on the same problem, often with different perspectives, then merges their ideas into one set of options\nURL: https://agentic-patterns.com/patterns/iterative-multi-agent-brainstorming\nMarkdown: https://agentic-patterns.com/patterns/iterative-multi-agent-brainstorming.md\n\n### iterative-prompt-skill-refinement\nIterative Prompt & Skill Refinement: Combines a feedback channel, editable prompt documents, log-driven skill fixes, and usage dashboards to improve agent prompts and skills continuously\nURL: https://agentic-patterns.com/patterns/iterative-prompt-skill-refinement\nMarkdown: https://agentic-patterns.com/patterns/iterative-prompt-skill-refinement.md\n\n### judge-gated-finding-exchange-between-sub-agents\nJudge-Gated Finding Exchange Between Parallel Sub-Agents: Puts an append-only board between parallel sub-agents and lets a small judge decide what goes on it, who receives each note, and when a later note retracts an earlier one\nURL: https://agentic-patterns.com/patterns/judge-gated-finding-exchange-between-sub-agents\nMarkdown: https://agentic-patterns.com/patterns/judge-gated-finding-exchange-between-sub-agents.md\n\n### lane-based-execution-queueing\nLane-Based Execution Queueing: Routes work into named lanes, each with its own queue and concurrency limit, so sessions never interleave and background jobs never block users\nURL: https://agentic-patterns.com/patterns/lane-based-execution-queueing\nMarkdown: https://agentic-patterns.com/patterns/lane-based-execution-queueing.md\n\n### language-agent-tree-search-lats\nLanguage Agent Tree Search (LATS): Runs Monte Carlo Tree Search over reasoning steps, with the LLM generating candidate actions and scoring partial solutions to pick the best path\nURL: https://agentic-patterns.com/patterns/language-agent-tree-search-lats\nMarkdown: https://agentic-patterns.com/patterns/language-agent-tree-search-lats.md\n\n### layered-configuration-context\nLayered Configuration Context: Loads context files from enterprise, user, project, and local levels automatically and merges them into the agent's baseline context\nURL: https://agentic-patterns.com/patterns/layered-configuration-context\nMarkdown: https://agentic-patterns.com/patterns/layered-configuration-context.md\n\n### lethal-trifecta-threat-model\nLethal Trifecta Threat Model: Classifies each tool by private-data access, untrusted-content exposure, and external communication, and blocks any execution path that has all three\nURL: https://agentic-patterns.com/patterns/lethal-trifecta-threat-model\nMarkdown: https://agentic-patterns.com/patterns/lethal-trifecta-threat-model.md\n\n### llm-map-reduce-pattern\nLLM Map-Reduce Pattern: Processes each untrusted document in its own sandboxed LLM call with a constrained output, then aggregates the results with deterministic code\nURL: https://agentic-patterns.com/patterns/llm-map-reduce-pattern\nMarkdown: https://agentic-patterns.com/patterns/llm-map-reduce-pattern.md\n\n### llm-observability\nLLM Observability: Sends agent runs to an LLM observability platform for span-level traces of each LLM call and tool use, plus aggregate cost, latency, and success metrics\nURL: https://agentic-patterns.com/patterns/llm-observability\nMarkdown: https://agentic-patterns.com/patterns/llm-observability.md\n\n### llm-friendly-api-design\nLLM-Friendly API Design: Designs APIs with visible versions, self-descriptive names and schemas, simple calls, actionable errors, and few indirection levels so LLMs call them correctly\nURL: https://agentic-patterns.com/patterns/llm-friendly-api-design\nMarkdown: https://agentic-patterns.com/patterns/llm-friendly-api-design.md\n\n### local-first-credential-broker\nLocal-First Credential Broker: Keep raw secrets out of the agent process by injecting credentials at the network layer through a local broker, rather than handing the agent environment variables or config files.\nURL: https://agentic-patterns.com/patterns/local-first-credential-broker\nMarkdown: https://agentic-patterns.com/patterns/local-first-credential-broker.md\n\n### markdown-polis-coordination\nMarkdown Polis — Multi-Vendor Agent Coordination via Filesystem Constitution: Coordinates agents from different vendors through versioned markdown files: capability cards, work contracts, and bandit routing that learns from settled work\nURL: https://agentic-patterns.com/patterns/markdown-polis-coordination\nMarkdown: https://agentic-patterns.com/patterns/markdown-polis-coordination.md\n\n### mcp-pattern-injection\nMCP Pattern Injection: Runs an MCP server that exposes framework best-practice patterns as tools, so the coding assistant fetches current patterns on demand\nURL: https://agentic-patterns.com/patterns/mcp-pattern-injection\nMarkdown: https://agentic-patterns.com/patterns/mcp-pattern-injection.md\n\n### memory-consolidation-decay-contradiction\nMemory Consolidation, Decay & Contradiction Resolution: Gives each stored fact a lifecycle: reconciles each new fact against the related stored facts when it arrives, stamps facts with event time and ingestion time so that a superseded fact is invalidated and not deleted, and runs a background job that merges duplicates and expires spent state\nURL: https://agentic-patterns.com/patterns/memory-consolidation-decay-contradiction\nMarkdown: https://agentic-patterns.com/patterns/memory-consolidation-decay-contradiction.md\n\n### memory-reinforcement-learning-memrl\nMemory Reinforcement Learning (MemRL): Stores memories with learned utility scores, retrieves by similarity then re-ranks by utility, and updates scores from outcomes while the LLM stays frozen\nURL: https://agentic-patterns.com/patterns/memory-reinforcement-learning-memrl\nMarkdown: https://agentic-patterns.com/patterns/memory-reinforcement-learning-memrl.md\n\n### memory-synthesis-from-execution-logs\nMemory Synthesis from Execution Logs: Has the agent write a structured diary per task, then runs synthesis agents over many diaries to turn recurring patterns into rules, commands, and tests\nURL: https://agentic-patterns.com/patterns/memory-synthesis-from-execution-logs\nMarkdown: https://agentic-patterns.com/patterns/memory-synthesis-from-execution-logs.md\n\n### merged-code-language-skill-model\nMerged Code + Language Skill Model: Fine-tunes separate language and code specialists from the same base model, then merges their weights into one model instead of one large joint training run\nURL: https://agentic-patterns.com/patterns/merged-code-language-skill-model\nMarkdown: https://agentic-patterns.com/patterns/merged-code-language-skill-model.md\n\n### milestone-escrow-agent-funding\nMilestone Escrow for Agent Resource Funding: Holds agent funding in escrow and releases each payment only after independent verification of a measurable milestone\nURL: https://agentic-patterns.com/patterns/milestone-escrow-agent-funding\nMarkdown: https://agentic-patterns.com/patterns/milestone-escrow-agent-funding.md\n\n### multi-model-orchestration-for-complex-edits\nMulti-Model Orchestration for Complex Edits: Splits complex code edits across specialized models: a retrieval model gathers context, a large model writes the changes, and smaller models apply them\nURL: https://agentic-patterns.com/patterns/multi-model-orchestration-for-complex-edits\nMarkdown: https://agentic-patterns.com/patterns/multi-model-orchestration-for-complex-edits.md\n\n### multi-platform-communication-aggregation\nMulti-Platform Communication Aggregation: Queries every communication platform in parallel through adapters that share one schema, then merges, deduplicates, and ranks the results\nURL: https://agentic-patterns.com/patterns/multi-platform-communication-aggregation\nMarkdown: https://agentic-patterns.com/patterns/multi-platform-communication-aggregation.md\n\n### multi-platform-webhook-triggers\nMulti-Platform Webhook Triggers: Starts agent workflows from Slack, Notion, and Jira webhooks, emoji reactions, and schedules, with idempotency and signature checks on each event\nURL: https://agentic-patterns.com/patterns/multi-platform-webhook-triggers\nMarkdown: https://agentic-patterns.com/patterns/multi-platform-webhook-triggers.md\n\n### multi-tenant-agent-isolation\nMulti-Tenant Agent & Memory Isolation: Enforces a tenant boundary on all four agent state planes (execution, retrieval and memory, cache, credential and egress), with tenant identity bound outside the model, so that one tenant's data or instructions cannot reach another\nURL: https://agentic-patterns.com/patterns/multi-tenant-agent-isolation\nMarkdown: https://agentic-patterns.com/patterns/multi-tenant-agent-isolation.md\n\n### non-custodial-spending-controls\nNon-Custodial Spending Controls: Puts a policy layer between the agent and the transaction signer that checks each intent against allowlists, budgets, and rate limits, and fails closed\nURL: https://agentic-patterns.com/patterns/non-custodial-spending-controls\nMarkdown: https://agentic-patterns.com/patterns/non-custodial-spending-controls.md\n\n### non-generative-judgment-routing\nNon-Generative Judgment Routing with Typed Escalation: Sends decision-only loop steps as batched typed questions to a non-generative judgment model and escalates what it cannot answer back to the LLM\nURL: https://agentic-patterns.com/patterns/non-generative-judgment-routing\nMarkdown: https://agentic-patterns.com/patterns/non-generative-judgment-routing.md\n\n### one-os-user-per-agent\nOne OS User per Agent: Give each long-lived agent its own OS user account and a templated init-system unit, so identity, supervision and privilege come from the host instead of from a per-agent container.\nURL: https://agentic-patterns.com/patterns/one-os-user-per-agent\nMarkdown: https://agentic-patterns.com/patterns/one-os-user-per-agent.md\n\n### opponent-processor-multi-agent-debate\nOpponent Processor / Multi-Agent Debate Pattern: Spawns agents with opposing roles on the same context, lets them critique each other, then synthesizes their positions to expose bias and blind spots\nURL: https://agentic-patterns.com/patterns/opponent-processor-multi-agent-debate\nMarkdown: https://agentic-patterns.com/patterns/opponent-processor-multi-agent-debate.md\n\n### oracle-and-worker-multi-model\nOracle and Worker Multi-Model Approach: Uses a fast, low-cost worker model for most tool use and code generation, and lets it consult an expensive oracle model when it is stuck\nURL: https://agentic-patterns.com/patterns/oracle-and-worker-multi-model\nMarkdown: https://agentic-patterns.com/patterns/oracle-and-worker-multi-model.md\n\n### orchestration-prompt-writing-benchmark\nOrchestration Prompt-Writing Benchmark: Scores an orchestrator on whether its sub-agent prompts give the right information fragments to the right roles, separate from end-task success\nURL: https://agentic-patterns.com/patterns/orchestration-prompt-writing-benchmark\nMarkdown: https://agentic-patterns.com/patterns/orchestration-prompt-writing-benchmark.md\n\n### out-of-process-provider-boundary-replay\nOut-of-Process Provider-Boundary Replay: Capture an agent run at the model-provider HTTP boundary from outside the process, then serve those bytes back so the agent re-executes its own logic with no provider call.\nURL: https://agentic-patterns.com/patterns/out-of-process-provider-boundary-replay\nMarkdown: https://agentic-patterns.com/patterns/out-of-process-provider-boundary-replay.md\n\n### output-verification-loop\nOutput Verification Loop: Verify LLM outputs by extracting individual claims, checking each against evidence sources, and returning per-claim trust scores before acting on the resu",".claude/skills/arxiv-pattern-discovery/RUBRIC.md":"# Pattern Quality Rubric\n\nReference for the Pattern Quality Rubric used to score arXiv papers for pattern extraction potential.\n\n## Overview\n\nPapers are scored on a scale of 0-10 using five weighted criteria. Only papers scoring >= 5.0 qualify for pattern extraction.\n\n## Scoring Criteria\n\n| Criterion | Weight | Description | Levels |\n|-----------|--------|-------------|--------|\n| **Reusability** | 30% | How widely applicable is the pattern? | Domain-specific (1.0) → Multi-domain (2.0) → Universal (3.0) |\n| **Novelty** | 25% | How new is the approach? | Existing (1.0) → Incremental (2.0) → Fundamentally new (3.0) |\n| **Clarity** | 20% | How well is it described? | Vague (1.0) → Clear (2.0) → Crystal clear (3.0) |\n| **Evidence** | 15% | Is there empirical validation? | No eval (1.0) → Some eval (2.0) → Strong empirical (3.0) |\n| **Completeness** | 10% | How complete is the implementation? | Idea only (1.0) → Partial details (2.0) → Production-ready (3.0) |\n\n## Detailed Scoring\n\n### Reusability (30% weight)\n\n| Score | Level | Indicators |\n|-------|-------|------------|\n| 1.0 | Domain-specific | \"specific to\", \"in the field of\", \"domain-specific\" |\n| 2.0 | Multi-domain | \"multi-domain\", \"cross-domain\", \"versatile\", \"adaptable\" |\n| 3.0 | Universal | \"general\", \"universal\", \"framework\", \"generic\", \"wide range\", \"variety of\" |\n\n### Novelty (25% weight)\n\n| Score | Level | Indicators |\n|-------|-------|------------|\n| 1.0 | Existing | No novelty indicators, describes existing approaches |\n| 2.0 | Incremental | \"improves\", \"extends\", \"builds on\", \"enhances\", \"optimizes\", \"refines\" |\n| 3.0 | Fundamentally new | \"novel\", \"new architecture\", \"new framework\", \"first to\", \"pioneering\", \"groundbreaking\" |\n\n### Clarity (20% weight)\n\n| Score | Level | Indicators |\n|-------|-------|------------|\n| 1.0 | Vague | \"may\", \"might\", \"potentially\", \"could be\", \"some ways\" |\n| 2.0 | Clear | \"we propose\", \"our approach\", \"the method\", abstract 100-150 words |\n| 3.0 | Crystal clear | Multiple clear indicators + abstract >150 words + concrete language |\n\n### Evidence (15% weight)\n\n| Score | Level | Indicators |\n|-------|-------|------------|\n| 1.0 | No eval | No evaluation or experiment mentioned |\n| 2.0 | Some eval | \"evaluation\", \"experiment\", \"benchmark\", \"results\", \"dataset\" |\n| 3.0 | Strong empirical | \"significant improvement\", \"state-of-the-art\", \"outperforms\", \"empirical\", \"real-world\" |\n\n### Completeness (10% weight)\n\n| Score | Level | Indicators |\n|-------|-------|------------|\n| 1.0 | Idea only | No implementation mentioned |\n| 1.5 | Partial idea | \"algorithm\", \"method\", \"approach\" mentioned |\n| 2.0 | Partial details | Implementation details or architecture described |\n| 3.0 | Production-ready | \"implementation\", \"open source\", \"code available\", \"github\", \"production\", \"deployed\" |\n\n## Score Calculation\n\nThe total score is calculated as a weighted sum:\n\n```\nTotal = (Reusability × 0.30) + (Novelty × 0.25) + (Clarity × 0.20) + (Evidence × 0.15) + (Completeness × 0.10)\n```\n\nMaximum possible score: 10.0\n\n## Threshold\n\n- **Score >= 5.0**: Qualifies for pattern extraction\n- **Score >= 7.0**: High-quality candidate, prioritize for extraction\n- **Score >= 8.5**: Exceptional candidate, immediate extraction recommended\n\n## Example Scoring\n\n### Example 1: High-quality paper (8.5)\n\n| Criterion | Score | Weighted |\n|-----------|-------|----------|\n| Reusability | 3.0 (Universal) | 0.90 |\n| Novelty | 3.0 (Fundamentally new) | 0.75 |\n| Clarity | 2.5 (Very clear) | 0.50 |\n| Evidence | 2.0 (Some eval) | 0.30 |\n| Completeness | 2.0 (Partial details) | 0.20 |\n| **Total** | | **8.5/10** |\n\n### Example 2: Marginal paper (5.2)\n\n| Criterion | Score | Weighted |\n|-----------|-------|----------|\n| Reusability | 2.0 (Multi-domain) | 0.60 |\n| Novelty | 2.0 (Incremental) | 0.50 |\n| Clarity | 2.0 (Clear) | 0.40 |\n| Evidence | 1.5 (Some eval) | 0.23 |\n| Completeness | 1.0 (Idea only) | 0.10 |\n| **Total** | | **5.2/10** |\n",".claude/skills/arxiv-pattern-discovery/WORKFLOW.md":"# arXiv Pattern Discovery Workflow\n\nEnd-to-end workflow for discovering agentic patterns from academic literature on arXiv.\n\n## Overview\n\nThis workflow guides you through the process of discovering new agentic patterns from academic papers:\n\n1. **Discovery** - Search arXiv and score papers\n2. **Review** - Identify high-quality candidates\n3. **Extract** - Create patterns from selected papers (user-driven)\n\n---\n\n## Phase 1: Discovery\n\n### Step 1.1: Run the arXiv Scanner\n\nSearch for recent papers with agentic patterns:\n\n```bash\n# Recent papers (last 30 days)\npython scripts/arxiv_scanner.py --days=30 --max-results=50 --export-md arxiv_results.md\n\n# All-time papers with higher quality threshold\npython scripts/arxiv_scanner.py --max-results=100 --min-score=7.0 --export-md high_quality.md\n\n# Specific topic search\npython scripts/arxiv_scanner.py --query=\"multi-agent memory systems\" --max-results=50 --export-md memory_patterns.md\n```\n\n### Step 1.2: Review the Output\n\nThe scanner produces:\n- Console output with top 10 papers by quality score\n- Optional Markdown report (with `--export-md`)\n- Optional JSON export (with `--export-json`)\n\nEach paper includes:\n- **Title**, **arXiv ID**, **URL**\n- **Quality Score** (0-10) with breakdown\n- **Suggested Category** (based on keywords)\n- **Extracted Tags**\n- **Abstract**\n- **Potential Duplicates** warning (if applicable)\n\n### Step 1.3: Filter Candidates\n\nFilter papers by:\n- **Quality Score**: Focus on papers >= 7.0 for best results\n- **Category**: Group by your area of interest\n- **Duplicate Warnings**: Skip papers flagged as duplicates\n\n---\n\n## Phase 2: Review\n\n### Step 2.1: Read the Markdown Report\n\nOpen the exported Markdown file and review candidates:\n\n```bash\n# View the report\ncat arxiv_results.md\n# or open in your editor\ncode arxiv_results.md\n```\n\n### Step 2.2: Visit Paper URLs\n\nFor each high-scoring paper:\n1. Click the arXiv URL to read the full paper\n2. Focus on the \"architecture\" or \"method\" section\n3. Look for reusable patterns (not just single techniques)\n\n### Step 2.3: Select Extraction Candidates\n\nPrioritize papers with:\n- Score >= 7.0 (high quality)\n- Clear architectural description\n- Novel approach not yet in the pattern catalog\n- Universal or multi-domain applicability\n\n---\n\n## Phase 3: Extract (User-Driven)\n\nAfter selecting candidate papers, you have two options:\n\n### Option A: Use the create-pattern Skill\n\nThe `create-pattern` skill can extract patterns from:\n- arXiv URLs\n- PDF files\n- Blog posts\n- Code repositories\n\n```\n# Ask Claude to extract a pattern from a paper\n\"Use create-pattern to extract a pattern from https://arxiv.org/abs/2401.12345\"\n```\n\n### Option B: Manual Pattern Creation\n\n1. Copy the template:\n   ```bash\n   cp patterns/TEMPLATE.md patterns/my-new-pattern.md\n   ```\n\n2. Fill in the required fields:\n   - `title`: Descriptive pattern name\n   - `status`: Based on quality score and evidence\n   - `authors`: Paper authors (@arxiv)\n   - `based_on`: Paper title (arXiv link)\n   - `category`: From the scanner's suggestion\n   - `source`: arXiv URL\n   - `tags`: From the scanner's extraction\n\n3. Write the pattern sections:\n   - **Problem**: What problem does this pattern solve?\n   - **Solution**: How does the architecture work?\n   - **Example**: Include a Mermaid diagram\n   - **References**: Link to the paper\n\n---\n\n## Phase 4: Validate (Before Committing)\n\n### Step 4.1: Check for Duplicates\n\n```bash\npython scripts/pattern_similarity_checker.py patterns/my-new-pattern.md\n```\n\nIf similarity > 0.7, consider:\n- Merging with existing pattern\n- Finding a more specific angle\n- Marking as variant of existing pattern\n\n### Step 4.2: Validate Quality\n\n```bash\npython scripts/pattern_validator.py patterns/my-new-pattern.md\n```\n\nFix any errors before committing.\n\n---\n\n## Example Session\n\n```bash\n# Step 1: Search arXiv\npython scripts/arxiv_scanner.py --days=30 --min-score=7.0 --export-md candidates.md\n\n# Output:\n# Scanning arXiv...\n# Fetched 100 papers\n# Filtered to 15 papers within last 30 days\n# Papers meeting threshold (7.0): 8\n\n# Step 2: Review the markdown report\ncat candidates.md\n\n# Step 3: Extract a pattern (using create-pattern skill)\n# \"Extract a pattern from https://arxiv.org/abs/2401.12345\"\n\n# Step 4: Validate\npython scripts/pattern_similarity_checker.py patterns/hierarchical-memory.md\npython scripts/pattern_validator.py patterns/hierarchical-memory.md\n```\n\n---\n\n## Tips for Success\n\n1. **Quality Over Quantity**: Focus on papers scoring >= 7.0\n2. **Avoid Duplicates**: Always run the similarity checker before committing\n3. **Validate Early**: Run the validator to catch issues early\n4. **Use the Rubric**: Understand why papers score the way they do (see RUBRIC.md)\n5. **Be Selective**: Not every good paper deserves a pattern—focus on reusable architectures\n",".claude/skills/create-pattern/scripts/validate.py":"#!/usr/bin/env python3\n\"\"\"Validate pattern front-matter against repository schema.\"\"\"\n\nimport sys\nfrom pathlib import Path\n\n# Allowed values for validation\nALLOWED_CATEGORIES = [\n    \"Orchestration & Control\",\n    \"Context & Memory\",\n    \"Feedback Loops\",\n    \"Learning & Adaptation\",\n    \"Reliability & Eval\",\n    \"Security & Safety\",\n    \"Tool Use & Environment\",\n    \"UX & Collaboration\",\n    \"Uncategorized\",\n]\n\nALLOWED_STATUSES = [\n    \"proposed\",\n    \"emerging\",\n    \"established\",\n    \"validated-in-production\",\n    \"best-practice\",\n    \"experimental-but-awesome\",\n    \"rapidly-improving\",\n]\n\nREQUIRED_FIELDS = [\"title\", \"status\", \"authors\", \"based_on\", \"category\", \"source\", \"tags\"]\n\n\ndef extract_frontmatter(file_path: Path) -> tuple[str, dict]:\n    \"\"\"Extract YAML frontmatter from a markdown file.\"\"\"\n    content = file_path.read_text()\n    if not content.startswith(\"---\"):\n        raise ValueError(\"File does not start with frontmatter delimiter\")\n\n    # Find the end of frontmatter\n    end_idx = content.find(\"\\n---\", 4)\n    if end_idx == -1:\n        raise ValueError(\"Frontmatter not properly closed\")\n\n    yaml_str = content[4:end_idx]\n    return content, parse_yaml_simple(yaml_str)\n\n\ndef parse_yaml_simple(yaml_str: str) -> dict:\n    \"\"\"Simple YAML parser for frontmatter - handles basic key: value pairs.\"\"\"\n    result = {}\n    for line in yaml_str.strip().split(\"\\n\"):\n        if \":\" in line and not line.strip().startswith(\"#\"):\n            key, value = line.split(\":\", 1)\n            key = key.strip()\n            value = value.strip()\n\n            # Handle lists\n            if value.startswith(\"[\") and value.endswith(\"]\"):\n                value = [v.strip().strip('\"\\'') for v in value[1:-1].split(\",\")]\n            # Strip quotes from strings\n            elif value.startswith('\"') and value.endswith('\"'):\n                value = value[1:-1]\n            elif value.startswith(\"'\") and value.endswith(\"'\"):\n                value = value[1:-1]\n\n            result[key] = value\n\n    return result\n\n\ndef validate_pattern(file_path: str | Path) -> bool:\n    \"\"\"Validate a pattern file's frontmatter.\"\"\"\n    path = Path(file_path)\n\n    if not path.exists():\n        print(f\"❌ File not found: {path}\")\n        return False\n\n    try:\n        content, frontmatter = extract_frontmatter(path)\n    except ValueError as e:\n        print(f\"❌ {e}\")\n        return False\n\n    errors = []\n\n    # Check required fields\n    for field in REQUIRED_FIELDS:\n        if field not in frontmatter:\n            errors.append(f\"Missing required field: {field}\")\n\n    # Validate category\n    if \"category\" in frontmatter and frontmatter[\"category\"] not in ALLOWED_CATEGORIES:\n        errors.append(\n            f\"Invalid category: {frontmatter['category']}. \"\n            f\"Must be one of: {', '.join(ALLOWED_CATEGORIES)}\"\n        )\n\n    # Validate status\n    if \"status\" in frontmatter and frontmatter[\"status\"] not in ALLOWED_STATUSES:\n        errors.append(\n            f\"Invalid status: {frontmatter['status']}. \"\n            f\"Must be one of: {', '.join(ALLOWED_STATUSES)}\"\n        )\n\n    # Validate authors is a list\n    if \"authors\" in frontmatter and not isinstance(frontmatter[\"authors\"], list):\n        errors.append(\"authors must be a list (e.g., [\\\"Name (@username)\\\"])\")\n\n    # Validate tags is a list\n    if \"tags\" in frontmatter and not isinstance(frontmatter[\"tags\"], list):\n        errors.append(\"tags must be a list (e.g., [tag1, tag2, tag3])\")\n\n    if errors:\n        for error in errors:\n            print(f\"❌ {error}\")\n        return False\n\n    # Check for required sections in content\n    required_sections = [\"## Problem\", \"## Solution\", \"## References\"]\n    for section in required_sections:\n        if section not in content:\n            errors.append(f\"Missing section: {section}\")\n\n    if errors:\n        for error in errors:\n            print(f\"❌ {error}\")\n        return False\n\n    print(f\"✅ Pattern validation passed: {path.name}\")\n    return True\n\n\nif __name__ == \"__main__\":\n    if len(sys.argv) < 2:\n        print(\"Usage: python validate.py <pattern-file.md>\")\n        sys.exit(1)\n\n    success = validate_pattern(sys.argv[1])\n    sys.exit(0 if success else 1)\n",".claude/skills/arxiv-pattern-discovery/scripts/pattern_similarity_checker.py":"#!/usr/bin/env python3\n\"\"\"\npattern_similarity_checker.py\n\nDuplicate detection for pattern files using tag similarity and content analysis.\n\nDetects potentially duplicate or very similar patterns by comparing:\n- Tag overlap (Jaccard similarity)\n- Title similarity\n- Category overlap\n- Problem/Solution section content\n\nUsage:\n    python scripts/pattern_similarity_checker.py <new-pattern.md>\n    python scripts/pattern_similarity_checker.py --all\n    python scripts/pattern_similarity_checker.py --threshold=0.7 <pattern.md>\n\"\"\"\n\nimport argparse\nimport math\nimport os\nimport re\nimport sys\nfrom collections import Counter\nfrom pathlib import Path\nfrom typing import Dict, List, Optional, Set, Tuple\n\n\n# Add parent directory to path for imports\nsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))\n\nfrom build_readme import parse_front_matter\n\n\ndef slugify(value: str) -> str:\n    \"\"\"Normalize string for comparison.\"\"\"\n    value = re.sub(r'[^\\w\\s-]', '', value).strip().lower()\n    value = re.sub(r'[-\\s]+', ' ', value)\n    return value\n\n\ndef tokenize(text: str) -> Set[str]:\n    \"\"\"Tokenize text into words, removing common stop words.\"\"\"\n    if not text:\n        return set()\n\n    # Common stop words to ignore\n    stop_words = {\n        \"a\", \"an\", \"the\", \"and\", \"or\", \"but\", \"in\", \"on\", \"at\", \"to\", \"for\",\n        \"of\", \"with\", \"by\", \"from\", \"as\", \"is\", \"was\", \"are\", \"were\", \"be\",\n        \"been\", \"being\", \"have\", \"has\", \"had\", \"do\", \"does\", \"did\", \"will\",\n        \"would\", \"could\", \"should\", \"may\", \"might\", \"must\", \"can\", \"this\",\n        \"that\", \"these\", \"those\", \"it\", \"its\", \"they\", \"them\", \"their\",\n        \"what\", \"which\", \"who\", \"whom\", \"when\", \"where\", \"why\", \"how\",\n    }\n\n    # Tokenize and filter\n    words = re.findall(r'\\b\\w+\\b', text.lower())\n    return {w for w in words if len(w) > 3 and w not in stop_words}\n\n\ndef jaccard_similarity(set1: Set[str], set2: Set[str]) -> float:\n    \"\"\"\n    Calculate Jaccard similarity between two sets.\n\n    J(A, B) = |A ∩ B| / |A ∪ B|\n    \"\"\"\n    if not set1 or not set2:\n        return 0.0\n\n    intersection = len(set1.intersection(set2))\n    union = len(set1.union(set2))\n\n    return intersection / union if union > 0 else 0.0\n\n\ndef cosine_similarity(set1: Set[str], set2: Set[str]) -> float:\n    \"\"\"\n    Calculate cosine similarity between two sets (treating as binary vectors).\n    \"\"\"\n    if not set1 or not set2:\n        return 0.0\n\n    intersection = len(set1.intersection(set2))\n    magnitude = math.sqrt(len(set1)) * math.sqrt(len(set2))\n\n    return intersection / magnitude if magnitude > 0 else 0.0\n\n\ndef levenshtein_distance(s1: str, s2: str) -> int:\n    \"\"\"Calculate Levenshtein distance between two strings.\"\"\"\n    if len(s1) < len(s2):\n        return levenshtein_distance(s2, s1)\n\n    if len(s2) == 0:\n        return len(s1)\n\n    previous_row = range(len(s2) + 1)\n    for i, c1 in enumerate(s1):\n        current_row = [i + 1]\n        for j, c2 in enumerate(s2):\n            insertions = previous_row[j + 1] + 1\n            deletions = current_row[j] + 1\n            substitutions = previous_row[j] + (c1 != c2)\n            current_row.append(min(insertions, deletions, substitutions))\n        previous_row = current_row\n\n    return previous_row[-1]\n\n\ndef string_similarity(s1: str, s2: str) -> float:\n    \"\"\"\n    Calculate normalized string similarity based on Levenshtein distance.\n\n    Returns 1.0 for identical strings, 0.0 for completely different.\n    \"\"\"\n    if not s1 or not s2:\n        return 0.0\n\n    max_len = max(len(s1), len(s2))\n    if max_len == 0:\n        return 1.0\n\n    distance = levenshtein_distance(s1.lower(), s2.lower())\n    return 1.0 - (distance / max_len)\n\n\ndef extract_sections(filepath: str) -> Dict[str, str]:\n    \"\"\"\n    Extract main sections from a pattern file.\n\n    Returns dict with keys: problem, solution, how_to_use, trade_offs\n    \"\"\"\n    with open(filepath, 'r', encoding='utf-8') as f:\n        content = f.read()\n\n    # Remove front matter\n    if content.startswith('---'):\n        end_idx = content.find('\\n---', 4)\n        if end_idx > 0:\n            content = content[end_idx + 4:]\n\n    sections = {}\n    current_section = None\n    current_content = []\n\n    # Section markers we care about\n    section_markers = ['## Problem', '## Solution', '## How to use it', '## Trade-offs']\n\n    for line in content.split('\\n'):\n        if line.startswith('## '):\n            # Save previous section\n            if current_section:\n                sections[current_section] = ' '.join(current_content)\n\n            # Start new section\n            current_section = line[3:].strip().lower()\n            if 'problem' in current_section:\n                current_section = 'problem'\n            elif 'solution' in current_section:\n                current_section = 'solution'\n            elif 'how to use' in current_section:\n                current_section = 'how_to_use'\n            elif 'trade-off' in current_section:\n                current_section = 'trade_offs'\n            else:\n                current_section = None\n            current_content = []\n        elif current_section:\n            # Skip code blocks and mermaid diagrams\n            if line.strip().startswith('```') or line.strip().startswith('~~~'):\n                continue\n            current_content.append(line.strip())\n\n    # Save last section\n    if current_section:\n        sections[current_section] = ' '.join(current_content)\n\n    return sections\n\n\nclass PatternSimilarityChecker:\n    \"\"\"Checker for finding similar/duplicate patterns.\"\"\"\n\n    def __init__(self, patterns_dir: str, threshold: float = 0.5):\n        \"\"\"\n        Initialize the checker.\n\n        Args:\n            patterns_dir: Path to patterns directory\n            threshold: Minimum similarity score to report (0-1)\n        \"\"\"\n        self.patterns_dir = Path(patterns_dir)\n        self.threshold = threshold\n        self.patterns = self._load_patterns()\n\n    def _load_patterns(self) -> List[Dict]:\n        \"\"\"Load all pattern metadata and content.\"\"\"\n        patterns = []\n\n        for filepath in self.patterns_dir.glob(\"*.md\"):\n            if filepath.name == \"TEMPLATE.md\":\n                continue\n\n            try:\n                metadata = parse_front_matter(str(filepath))\n                sections = extract_sections(filepath)\n\n                patterns.append({\n                    \"file\": filepath.name,\n                    \"path\": str(filepath),\n                    \"title\": metadata.get(\"title\", \"\"),\n                    \"tags\": [t.lower() for t in metadata.get(\"tags\", [])],\n                    \"category\": metadata.get(\"category\", \"\"),\n                    \"sections\": sections,\n                    \"metadata\": metadata,\n                })\n            except Exception as e:\n                print(f\"Warning: Could not load {filepath.name}: {e}\")\n\n        return patterns\n\n    def compare_to_pattern(self, filepath: str) -> List[Dict]:\n        \"\"\"\n        Compare a single pattern file against all existing patterns.\n\n        Returns list of similarity results, sorted by total similarity.\n        \"\"\"\n        try:\n            metadata = parse_front_matter(filepath)\n            sections = extract_sections(filepath)\n        except Exception as e:\n            print(f\"Error: Could not parse pattern file: {e}\")\n            return []\n\n        new_pattern = {\n            \"file\": Path(filepath).name,\n            \"title\": metadata.get(\"title\", \"\"),\n            \"tags\": [t.lower() for t in metadata.get(\"tags\", [])],\n            \"category\": metadata.get(\"category\", \"\"),\n            \"sections\": sections,\n        }\n\n        results = []\n\n        for existing in self.patterns:\n            if existing[\"file\"] == new_pattern[\"file\"]:\n                continue  # Skip self\n\n            similarity = self._calculate_similarity(new_pattern, existing)\n            if similarity[\"total\"] >= self.threshold:\n                results.append({\n                    \"existing_file\": existing[\"file\"],\n                    \"existing_title\": existing[\"title\"],\n                    \"similarity\": similarity,\n                })\n\n        # Sort by total similarity\n        results.sort(key=lambda x: x[\"similarity\"][\"total\"], reverse=True)\n        return results\n\n    def check_all_similarities(self) -> List[Dict]:\n        \"\"\"\n        Check all patterns against each other for similarities.\n\n        Returns list of potential duplicates (each pair once).\n        \"\"\"\n        results = []\n\n        for i, pattern1 in enumerate(self.patterns):\n            for pattern2 in self.patterns[i + 1:]:\n                similarity = self._calculate_similarity(pattern1, pattern2)\n                if similarity[\"total\"] >= self.threshold:\n                    results.append({\n                        \"pattern1\": pattern1[\"file\"],\n                        \"pattern2\": pattern2[\"file\"],\n                        \"title1\": pattern1[\"title\"],\n                        \"title2\": pattern2[\"title\"],\n                        \"similarity\": similarity,\n                    })\n\n        # Sort by total similarity\n        results.sort(key=lambda x: x[\"similarity\"][\"total\"], reverse=True)\n        return results\n\n    def _calculate_similarity(self, pattern1: Dict, pattern2: Dict) -> Dict[str, float]:\n        \"\"\"Calculate detailed similarity metrics between two patterns.\"\"\"\n\n        # 1. Tag similarity (Jaccard)\n        tags1 = set(pattern1[\"tags\"])\n        tags2 = set(pattern2[\"tags\"])\n        tag_sim = jaccard_similarity(tags1, tags2)\n\n        # 2. Title similarity\n        title_sim = string_similarity(pattern1[\"title\"], pattern2[\"title\"])\n\n        # 3. Category match\n        category_match = 1.0 if pattern1[\"category\"] == pattern2[\"category\"] else 0.0\n\n        # 4. Content similarity (problem + solution)\n        content1_tokens = set()\n        content2_tokens = set()\n\n        for section in [\"problem\", \"solution\"]:\n            if section in pattern1[\"sections\"]:\n                content1_tokens.update(tokenize(pattern1[\"sections\"][section]))\n            if section in pattern2[\"sections\"]:\n                content2_tokens.update(tokenize(pattern2[\"sections\"][section]))\n\n        content_sim = jaccard_similarity(content1_tokens, content2_tokens)\n\n        # Weighted total (adjust weights as needed)\n        total = (\n            tag_sim * 0.30 +\n            title_sim * 0.20 +\n            category_match * 0.15 +\n            content_sim * 0.35\n        )\n\n        return {\n            \"tag\": tag_sim,\n            \"title\": title_sim,\n            \"category\": category_match,\n            \"content\": content_sim,\n            \"total\": total,\n        }\n\n    def suggest_action(self, similarity: Dict[str, float]) -> str:\n        \"\"\"Suggest action based on similarity score.\"\"\"\n        total = similarity[\"total\"]\n\n        if total >= 0.8:\n            return \"MERGE - Patterns are very similar, consider merging\"\n        elif total >= 0.7:\n            return \"REVIEW - High similarity, manual review needed\"\n        elif total >= 0.6:\n            return \"CHECK - Moderate similarity, check if related\"\n        elif total >= 0.5:\n            return \"RELATED - May be related patterns\"\n        else:\n            return \"OK - Below similarity threshold\"\n\n\ndef print_similarity_report(results: List[Dict], threshold: float, checker):\n    \"\"\"Print a formatted similarity report.\"\"\"\n\n    if not results:\n        print(f\"\\n✅ No patterns found with similarity >= {threshold}\")\n        return\n\n    print(f\"\\n{'='*80}\")\n    print(f\"⚠️  FOUND {len(results)} POTENTIAL DUPLICATE/RELATED PATTERN PAIRS\")\n    print(f\"{'='*80}\")\n\n    for i, result in enumerate(results, 1):\n        if \"existing_file\" in result:\n            # Single pattern comparison\n            print(f\"\\n{i}. {result['existing_title']}\")\n            print(f\"   File: {result['existing_file']}\")\n        else:\n            # All-pairs comparison\n            print(f\"\\n{i}. {result['title1']} <-> {result['title2']}\")\n            print(f\"   Files: {result['pattern1']} <-> {result['pattern2']}\")\n\n        sim = result[\"similarity\"]\n        action = checker.suggest_action(sim)\n\n        print(f\"   Total Similarity: {sim['total']:.2f}\")\n        print(f\"   Tag Similarity:    {sim['tag']:.2f} (Jaccard)\")\n        print(f\"   Title Similarity:  {sim['title']:.2f}\")\n        print(f\"   Category Match:    {sim['category']:.2f}\")\n        print(f\"   Content Similarity:{sim['content']:.2f}\")\n        print(f\"   Suggested Action:  {action}\")\n\n    # Print warning for high similarities\n    high_sim = [r for r in results if r[\"similarity\"][\"total\"] >= 0.7]\n    if high_sim:\n        print(f\"\\n{'='*80}\")\n        print(f\"⚠️  WARNING: {len(high_sim)} patterns with similarity >= 0.7\")\n        print(f\"   These may be duplicates or variants that need merging.\")\n        print(f\"{'='*80}\")\n\n\ndef export_similarity_report(results: List[Dict], output_file: str, checker):\n    \"\"\"Export similarity report to Markdown file.\"\"\"\n\n    lines = [\n        \"# Pattern Similarity Report\",\n        \"\",\n        f\"Generated: {__import__('datetime').datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\",\n        f\"Total pairs found: {len(results)}\",\n        \"\",\n        \"---\",\n        \"\",\n    ]\n\n    for i, result in enumerate(results, 1):\n        if \"existing_file\" in result:\n            lines.extend([\n                f\"## {i}. {result['existing_title']}\",\n                \"\",\n                f\"**File:** `{result['existing_file']}`  \",\n                f\"**Similarity:** {result['similarity']['total']:.2f}  \",\n            ])\n        else:\n            lines.extend([\n                f\"## {i}. {result['title1']} ↔ {result['title2']}\",\n                \"\",\n                f\"**Files:** `{result['pattern1']}` ↔ `{result['pattern2']}`  \",\n                f\"**Similarity:** {result['similarity']['total']:.2f}  \",\n            ])\n\n        sim = result[\"similarity\"]\n        action = checker.suggest_action(sim)\n\n        lines.extend([\n            \"\",\n            f\"**Breakdown:**\",\n            f\"- Tag Similarity: {sim['tag']:.2f}\",\n            f\"- Title Similarity: {sim['title']:.2f}\",\n            f\"- Category Match: {sim['category']:.2f}\",\n            f\"- Content Similarity: {sim['content']:.2f}\",\n            \"\",\n            f\"**Suggested Action:** {action}\",\n            \"\",\n            \"---\",\n            \"\",\n        ])\n\n    with open(output_file, \"w\") as f:\n        f.write(\"\\n\".join(lines))\n\n    print(f\"Report exported to: {output_file}\")\n\n\ndef main():\n    parser = argparse.ArgumentParser(\n        description=\"Check patterns for duplicates or high similarity\",\n        formatter_class=argparse.RawDescriptionHelpFormatter,\n        epilog=\"\"\"\nExamples:\n  %(prog)s patterns/new-pattern.md\n  %(prog)s --all\n  %(prog)s --all --threshold=0.7 --export report.md\n        \"\"\",\n    )\n    parser.add_argument(\n        \"pattern_file\",\n        nargs=\"?\",\n        help=\"Path to pattern file to check against existing patterns\",\n    )\n    parser.add_argument(\n        \"--all\",\n        \"-a\",\n        action=\"store_true\",\n        help=\"Check all patterns against each other\",\n    )\n    parser.add_argument(\n        \"--patterns-dir\",\n        \"-d\",\n        type=str,\n        default=\"patterns\",\n        help=\"Path to patterns directory (default: patterns)\",\n    )\n    parser.add_argument(\n        \"--threshold\",\n        \"-t\",\n        type=float,\n        default=0.5,\n        help=\"Similarity threshold for reporting (default: 0.5)\",\n    )\n    parser.add_argument(\n        \"--export\",\n        \"-e\",\n        type=str,\n        help=\"Export report to Markdown file\",\n    )\n\n    args = parser.parse_args()\n\n    # Validate arguments\n    if not args.all and not args.pattern_file:\n        parser.error(\"Either specify a pattern file or use --all\")\n\n    if args.all and args.pattern_file:\n        parser.error(\"Cannot use --all with a specific pattern file\")\n\n    # Check patterns directory\n    patterns_dir = Path(args.patterns_dir)\n    if not patterns_dir.exists():\n        print(f\"Error: Patterns directory not found: {patterns_dir}\")\n        return 1\n\n    # Initialize checker\n    checker = PatternSimilarityChecker(str(patterns_dir), args.threshold)\n    print(f\"Loaded {len(checker.patterns)} patterns for comparison\")\n\n    # Run comparison\n    if args.all:\n        print(f\"\\n🔍 Checking all patterns for similarities (threshold: {args.threshold})...\")\n        results = checker.check_all_similarities()\n    else:\n        pattern_path = Path(args.pattern_file)\n        if not pattern_path.exists():\n            print(f\"Error: Pattern file not found: {pattern_path}\")\n            return 1\n\n        print(f\"\\n🔍 Comparing '{pattern_path.name}' against existing patterns...\")\n        results = checker.compare_to_pattern(str(pattern_path))\n\n    # Print report\n    print_similarity_report(results, args.threshold, checker)\n\n    # Export if requested\n    if args.export:\n        export_similarity_report(results, args.export, checker)\n\n    # Return exit code based on findings\n    if results:\n        return 1  # Found potential duplicates\n    return 0\n\n\nif __name__ == \"__main__\":\n    sys.exit(main())\n",".claude/skills/arxiv-pattern-discovery/scripts/pattern_validator.py":"#!/usr/bin/env python3\n\"\"\"\npattern_validator.py\n\nPre-commit validation for pattern files.\n\nValidates:\n- YAML front-matter completeness\n- Required sections presence\n- Mermaid diagram syntax\n- URL validity\n- Content quality checks\n\nUsage:\n    python scripts/pattern_validator.py <pattern-file.md>\n    python scripts/pattern_validator.py --all\n    python scripts/pattern_validator.py --fix <pattern-file.md>\n\"\"\"\n\nimport argparse\nimport os\nimport re\nimport sys\nimport urllib.request\nimport urllib.error\nfrom dataclasses import dataclass, field\nfrom enum import Enum\nfrom pathlib import Path\nfrom typing import List, Optional, Set, Tuple\n\n\n# Add parent directory to path for imports\nsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))\n\nfrom build_readme import parse_front_matter\n\n\nclass Severity(Enum):\n    \"\"\"Severity levels for validation issues.\"\"\"\n    ERROR = \"ERROR\"\n    WARNING = \"WARNING\"\n    INFO = \"INFO\"\n\n\n@dataclass\nclass ValidationIssue:\n    \"\"\"Represents a validation issue found in a pattern file.\"\"\"\n    severity: Severity\n    category: str\n    message: str\n    line: Optional[int] = None\n    column: Optional[int] = None\n    fix_suggestion: Optional[str] = None\n\n\n@dataclass\nclass ValidationResult:\n    \"\"\"Result of validating a pattern file.\"\"\"\n    file_path: str\n    is_valid: bool\n    issues: List[ValidationIssue] = field(default_factory=list)\n\n    def add_issue(self, severity: Severity, category: str, message: str,\n                  line: Optional[int] = None, fix_suggestion: Optional[str] = None):\n        self.issues.append(ValidationIssue(\n            severity=severity, category=category, message=message,\n            line=line, fix_suggestion=fix_suggestion\n        ))\n        if severity == Severity.ERROR:\n            self.is_valid = False\n\n\n# Valid values for pattern metadata\nVALID_STATUSES = {\n    \"proposed\",\n    \"emerging\",\n    \"established\",\n    \"validated-in-production\",\n    \"best-practice\",\n    \"experimental-but-awesome\",\n    \"rapidly-improving\",\n}\n\nVALID_CATEGORIES = {\n    \"Orchestration & Control\",\n    \"Context & Memory\",\n    \"Feedback Loops\",\n    \"Learning & Adaptation\",\n    \"Reliability & Eval\",\n    \"Security & Safety\",\n    \"Tool Use & Environment\",\n    \"UX & Collaboration\",\n    \"Uncategorized\",\n}\n\n# Required YAML fields\nREQUIRED_YAML_FIELDS = {\"title\", \"status\", \"authors\", \"based_on\", \"category\", \"source\", \"tags\"}\n\n# Required markdown sections\nREQUIRED_SECTIONS = {\"## Problem\", \"## Solution\", \"## References\"}\n\n\nclass PatternValidator:\n    \"\"\"Validator for pattern files.\"\"\"\n\n    def __init__(self, strict: bool = False):\n        \"\"\"\n        Initialize the validator.\n\n        Args:\n            strict: If True, treat warnings as errors\n        \"\"\"\n        self.strict = strict\n\n    def validate_file(self, filepath: str) -> ValidationResult:\n        \"\"\"\n        Validate a single pattern file.\n\n        Returns ValidationResult with all issues found.\n        \"\"\"\n        result = ValidationResult(file_path=filepath, is_valid=True)\n\n        try:\n            with open(filepath, 'r', encoding='utf-8') as f:\n                content = f.read()\n                lines = content.split('\\n')\n        except FileNotFoundError:\n            result.add_issue(Severity.ERROR, \"File\", f\"File not found: {filepath}\")\n            return result\n        except Exception as e:\n            result.add_issue(Severity.ERROR, \"File\", f\"Could not read file: {e}\")\n            return result\n\n        # Validate YAML front-matter\n        self._validate_yaml_front_matter(content, lines, result)\n\n        # Parse metadata for further validation\n        metadata = parse_front_matter(filepath)\n\n        # Validate metadata values\n        self._validate_metadata(metadata, result)\n\n        # Validate required sections\n        self._validate_sections(content, lines, result)\n\n        # Validate Mermaid diagrams\n        self._validate_mermaid_diagrams(content, lines, result)\n\n        # Validate URLs\n        self._validate_urls(content, lines, result)\n\n        # Content quality checks\n        self._validate_content_quality(content, metadata, result)\n\n        return result\n\n    def _validate_yaml_front_matter(self, content: str, lines: List[str], result: ValidationResult):\n        \"\"\"Validate YAML front-matter structure.\"\"\"\n        if not content.startswith('---'):\n            result.add_issue(\n                Severity.ERROR,\n                \"YAML\",\n                \"Pattern must start with YAML front-matter delimited by '---'\",\n                line=1,\n                fix_suggestion=\"Add YAML front-matter at the top of the file\"\n            )\n            return\n\n        # Find end of front-matter (second occurrence of ---)\n        end_marker_pos = content.find('\\n---', 4)\n        if end_marker_pos == -1:\n            result.add_issue(\n                Severity.ERROR,\n                \"YAML\",\n                \"YAML front-matter must be closed with '---'\",\n                fix_suggestion=\"Close front-matter with '---' on its own line\"\n            )\n            return\n\n        # Convert character position to line number (approximate)\n        end_line_num = content[:end_marker_pos].count('\\n') + 1\n\n        # Extract only the YAML section (lines 1 to end_line_num)\n        yaml_section = lines[1:end_line_num] if end_line_num > 1 else []\n        yaml_content = '\\n'.join(yaml_section)\n\n        # Check for empty front-matter\n        if not yaml_content.strip():\n            result.add_issue(\n                Severity.ERROR,\n                \"YAML\",\n                \"YAML front-matter is empty\",\n                line=2,\n                fix_suggestion=\"Add required YAML fields: title, status, authors, based_on, category, source, tags\"\n            )\n\n        # Check for proper YAML syntax (key: value pairs)\n        for i, yaml_line in enumerate(yaml_section, start=2):\n            if yaml_line.strip() and not yaml_line.strip().startswith('#'):\n                # Skip empty lines and comments\n                if ':' not in yaml_line and not yaml_line.strip().startswith('-'):\n                    result.add_issue(\n                        Severity.WARNING,\n                        \"YAML\",\n                        f\"Line may not be valid YAML: {yaml_line[:50]}\",\n                        line=i\n                    )\n\n    def _validate_metadata(self, metadata: dict, result: ValidationResult):\n        \"\"\"Validate metadata field values.\"\"\"\n\n        # Check required fields\n        for field in REQUIRED_YAML_FIELDS:\n            if field not in metadata:\n                result.add_issue(\n                    Severity.ERROR,\n                    \"Metadata\",\n                    f\"Missing required field: '{field}'\",\n                    fix_suggestion=f'Add \"{field}: <value>\" to YAML front-matter'\n                )\n\n        # Validate status\n        if \"status\" in metadata:\n            status = metadata[\"status\"]\n            if status not in VALID_STATUSES:\n                result.add_issue(\n                    Severity.ERROR,\n                    \"Metadata\",\n                    f\"Invalid status: '{status}'. Must be one of: {', '.join(sorted(VALID_STATUSES))}\",\n                    fix_suggestion=f\"Use one of: {', '.join(sorted(VALID_STATUSES))}\"\n                )\n\n        # Validate category\n        if \"category\" in metadata:\n            category = metadata[\"category\"]\n            if category not in VALID_CATEGORIES:\n                result.add_issue(\n                    Severity.WARNING,\n                    \"Metadata\",\n                    f\"Unknown category: '{category}'. Known categories: {', '.join(sorted(VALID_CATEGORIES))}\",\n                    fix_suggestion=f\"Use one of: {', '.join(sorted(VALID_CATEGORIES))}\"\n                )\n\n        # Validate authors is a list\n        if \"authors\" in metadata:\n            authors = metadata[\"authors\"]\n            if not isinstance(authors, list):\n                result.add_issue(\n                    Severity.ERROR,\n                    \"Metadata\",\n                    f\"'authors' must be a list: ['Name (@username)']\",\n                    fix_suggestion=\"Format as: authors: [\\\"Name (@username)\\\"]\"\n                )\n\n        # Validate tags is a list\n        if \"tags\" in metadata:\n            tags = metadata[\"tags\"]\n            if not isinstance(tags, list):\n                result.add_issue(\n                    Severity.ERROR,\n                    \"Metadata\",\n                    f\"'tags' must be a list: [tag1, tag2, tag3]\",\n                    fix_suggestion=\"Format as: tags: [tag1, tag2, tag3]\"\n                )\n            # Check for empty tags\n            elif any(not tag.strip() for tag in tags):\n                result.add_issue(\n                    Severity.WARNING,\n                    \"Metadata\",\n                    \"Tags list contains empty strings\",\n                    fix_suggestion=\"Remove empty tags\"\n                )\n\n        # Validate source is a URL\n        if \"source\" in metadata:\n            source = metadata[\"source\"]\n            if not source.startswith((\"http://\", \"https://\", \"arxiv://\")):\n                result.add_issue(\n                    Severity.WARNING,\n                    \"Metadata\",\n                    f\"'source' should be a URL: {source}\",\n                    fix_suggestion=\"Use a valid URL starting with http:// or https://\"\n                )\n\n        # Title quality checks\n        if \"title\" in metadata:\n            title = metadata[\"title\"]\n            if len(title) < 10:\n                result.add_issue(\n                    Severity.WARNING,\n                    \"Metadata\",\n                    f\"Title seems too short: '{title}'\",\n                    fix_suggestion=\"Use a more descriptive title\"\n                )\n            if title.islower():\n                result.add_issue(\n                    Severity.INFO,\n                    \"Metadata\",\n                    \"Title should use Title Case\",\n                    fix_suggestion=\"Capitalize the first letter of each word\"\n                )\n\n    def _validate_sections(self, content: str, lines: List[str], result: ValidationResult):\n        \"\"\"Validate required markdown sections.\"\"\"\n        # Skip YAML front-matter\n        start_idx = content.find('\\n---', 4)\n        if start_idx == -1:\n            start_idx = 0\n        else:\n            start_idx += 5\n\n        main_content = content[start_idx:]\n\n        for section in REQUIRED_SECTIONS:\n            if section not in main_content:\n                result.add_issue(\n                    Severity.ERROR,\n                    \"Structure\",\n                    f\"Missing required section: '{section}'\",\n                    fix_suggestion=f\"Add '## {section}' section\"\n                )\n\n        # Check for recommended sections (without ## prefix for matching)\n        recommended = {\"How to use it\", \"Trade-offs\"}\n        found_sections = set(re.findall(r'^## (.+)$', main_content, re.MULTILINE))\n        missing_recommended = recommended - found_sections\n\n        if missing_recommended:\n            for section in missing_recommended:\n                result.add_issue(\n                    Severity.INFO,\n                    \"Structure\",\n                    f\"Missing recommended section: '## {section}'\",\n                    fix_suggestion=f\"Consider adding '## {section}' section\"\n                )\n\n    def _validate_mermaid_diagrams(self, content: str, lines: List[str], result: ValidationResult):\n        \"\"\"Validate Mermaid diagram syntax.\"\"\"\n\n        # Find all Mermaid code blocks\n        mermaid_blocks = re.finditer(r'```mermaid\\n(.*?)```', content, re.DOTALL)\n\n        if not mermaid_blocks:\n            # Check if pattern might benefit from a diagram\n            if \"## Solution\" in content and len(content) > 2000:\n                result.add_issue(\n                    Severity.INFO,\n                    \"Content\",\n                    \"Consider adding a Mermaid diagram to illustrate the pattern\",\n                    fix_suggestion=\"Add a Mermaid diagram in the Solution section\"\n                )\n            return\n\n        for match in mermaid_blocks:\n            diagram = match.group(1)\n            block_start = content[:match.start()].count('\\n') + 1\n\n            # Basic Mermaid syntax checks\n            valid_diagram_types = {\n                \"graph\", \"flowchart\", \"sequenceDiagram\", \"classDiagram\",\n                \"stateDiagram\", \"erDiagram\", \"gantt\", \"pie\", \"gitGraph\"\n            }\n\n            first_line = diagram.strip().split('\\n')[0].strip()\n            diagram_type = first_line.split()[0] if first_line else \"\"\n\n            if diagram_type and diagram_type not in valid_diagram_types:\n                result.add_issue(\n                    Severity.WARNING,\n                    \"Mermaid\",\n                    f\"Unrecognized diagram type: '{diagram_type}'\",\n                    line=block_start + 1,\n                    fix_suggestion=f\"Use one of: {', '.join(valid_diagram_types)}\"\n                )\n\n            # Check for common syntax errors\n            if ' --' in diagram and '-->' not in diagram:\n                result.add_issue(\n                    Severity.WARNING,\n                    \"Mermaid\",\n                    \"Found ' --' which might be a typo for ' -->' (arrow)\",\n                    line=block_start\n                )\n\n            # Check for unclosed brackets/parentheses (basic check)\n            open_brackets = diagram.count('[') + diagram.count('(') + diagram.count('{')\n            close_brackets = diagram.count(']') + diagram.count(')') + diagram.count('}')\n            if open_brackets != close_brackets:\n                result.add_issue(\n                    Severity.WARNING,\n                    \"Mermaid\",\n                    \"Unclosed brackets or parentheses detected\",\n                    line=block_start\n                )\n\n    def _validate_urls(self, content: str, lines: List[str], result: ValidationResult):\n        \"\"\"Validate URLs in the document.\"\"\"\n        # Find all URLs\n        url_pattern = re.compile(r'https?://[^\\s\\)]+')\n\n        for i, line in enumerate(lines, start=1):\n            urls = url_pattern.findall(line)\n            for url in urls:\n                # Clean URL (remove trailing punctuation)\n                clean_url = re.sub(r'[.,;:]$', '', url)\n\n                # Basic URL format check\n                if not re.match(r'^https?://[a-zA-Z0-9\\-._~:/?#\\[\\]@!$&\\'()*+,;=%]+$', clean_url):\n                    result.add_issue(\n                        Severity.WARNING,\n                        \"URL\",\n                        f\"Potentially malformed URL: {clean_url[:60]}...\",\n                        line=i\n                    )\n\n                # Check for common issues\n                if 'arxiv.org' in clean_url.lower():\n                    if 'abs/' in clean_url and not clean_url.startswith('https://arxiv.org/abs/'):\n                        result.add_issue(\n                            Severity.INFO,\n                            \"URL\",\n                            f\"arXiv URL format may need standardization\",\n                            line=i\n                        )\n\n    def _validate_content_quality(self, content: str, metadata: dict, result: ValidationResult):\n        \"\"\"Perform content quality checks.\"\"\"\n\n        # Get word counts for sections\n        def count_section_text(section_name):\n            pattern = rf'## {section_name}\\s*\\n(.*?)(?=\\n## |\\Z)'\n            match = re.search(pattern, content, re.DOTALL)\n            if match:\n                text = match.group(1)\n                # Remove code blocks\n                text = re.sub(r'```.*?```', '', text, flags=re.DOTALL)\n                return len(text.split())\n            return 0\n\n        # Check Problem section length\n        problem_words = count_section_text(\"Problem\")\n        if problem_words > 0 and problem_words < 20:\n            result.add_issue(\n                Severity.WARNING,\n                \"Content\",\n                f\"Problem section seems too short ({problem_words} words)\",\n                fix_suggestion=\"Expand the problem description to at least 2-3 sentences\"\n            )\n\n        # Check Solution section length\n        solution_words = count_section_text(\"Solution\")\n        if solution_words > 0 and solution_words < 50:\n            result.add_issue(\n                Severity.WARNING,\n                \"Content\",\n                f\"Solution section seems too short ({solution_words} words)\",\n                fix_suggestion=\"Expand the solution description with more implementation details\"\n            )\n\n        # Check for empty sections\n        section_pattern = re.compile(r'## ([^\\n]+)\\s*\\n(.*?)(?=\\n## |\\Z)', re.DOTALL)\n        for match in section_pattern.finditer(content):\n            section_name = match.group(1)\n            section_content = match.group(2).strip()\n            if not section_content or section_content == \"```\":\n                result.add_issue(\n                    Severity.ERROR,\n                    \"Content\",\n                    f\"Section '{section_name}' is empty\",\n                    fix_suggestion=f\"Add content to the '{section_name}' section\"\n                )\n\n        # Check for required blank lines after headers\n        header_pattern = re.compile(r'##[^\\n]+\\n([^\\s#])')\n        for match in header_pattern.finditer(content):\n            line_num = content[:match.start()].count('\\n') + 2\n            char_after = match.group(1)\n            if char_after and char_after != '\\n':\n                result.add_issue(\n                    Severity.WARNING,\n                    \"Formatting\",\n                    \"Headers should be followed by a blank line for proper list rendering\",\n                    line=line_num,\n                    fix_suggestion=\"Add a blank line after the header\"\n                )\n\n\ndef print_validation_result(result: ValidationResult, verbose: bool = False):\n    \"\"\"Print validation results to stdout.\"\"\"\n\n    # Group issues by severity\n    errors = [i for i in result.issues if i.severity == Severity.ERROR]\n    warnings = [i for i in result.issues if i.severity == Severity.WARNING]\n    infos = [i for i in result.issues if i.severity == Severity.INFO]\n\n    # Print status\n    status_icon = \"✅\" if result.is_valid else \"❌\"\n    filename = Path(result.file_path).name\n    print(f\"{status_icon} {filename}: {len(result.issues)} issue(s)\")\n\n    if not verbose and result.is_valid and not warnings:\n        return\n\n    # Print issues\n    for issue in result.issues:\n        severity_icon = {\n            Severity.ERROR: \"❌\",\n            Severity.WARNING: \"⚠️ \",\n            Severity.INFO: \"ℹ️ \",\n        }[issue.severity]\n\n        line_info = f\":{issue.line}\" if issue.line else \"\"\n        print(f\"  {severity_icon} [{issue.category}]{line_info} {issue.message}\")\n\n        if issue.fix_suggestion:\n            print(f\"     💡 {issue.fix_suggestion}\")\n\n    # Print summary\n    if errors:\n        print(f\"  Summary: {len(errors)} error(s), {len(warnings)} warning(s), {len(infos)} info\")\n\n\ndef print_validation_summary(results: List[ValidationResult]):\n    \"\"\"Print overall validation summary.\"\"\"\n\n    total = len(results)\n    valid = sum(1 for r in results if r.is_valid)\n    total_issues = sum(len(r.issues) for r in results)\n\n    print(f\"\\n{'='*60}\")\n    print(f\"SUMMARY: {valid}/{total} files valid, {total_issues} total issue(s)\")\n    print(f\"{'='*60}\")\n\n    # Aggregate counts\n    all_errors = []\n    all_warnings = []\n\n    for result in results:\n        all_errors.extend([i for i in result.issues if i.severity == Severity.ERROR])\n        all_warnings.extend([i for i in result.issues if i.severity == Severity.WARNING])\n\n    # Common issues\n    if all_errors:\n        error_cats = {}\n        for e in all_errors:\n            error_cats[e.category] = error_cats.get(e.category, 0) + 1\n        print(f\"\\nTop error categories:\")\n        for cat, count in sorted(error_cats.items(), key=lambda x: -x[1])[:5]:\n            print(f\"  - {cat}: {count}\")\n\n\ndef export_validation_report(results: List[ValidationResult], output_file: str):\n    \"\"\"Export validation report to Markdown.\"\"\"\n\n    lines = [\n        \"# Pattern Validation Report\",\n        \"\",\n        f\"Generated: {__import__('datetime').datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\",\n        \"\",\n        \"---\",\n        \"\",\n    ]\n\n    for result in results:\n        filename = Path(result.file_path).name\n        status = \"✅ PASS\" if result.is_valid else \"❌ FAIL\"\n\n        lines.extend([\n            f\"## {status}: {filename}\",\n            \"\",\n            f\"Issues found: {len(result.issues)}\",\n            \"\",\n        ])\n\n        if result.issues:\n            for issue in result.issues:\n                severity = issue.severity.value\n                line_info = f\":{issue.line}\" if issue.line else \"\"\n                lines.extend([\n                    f\"**{severity}** [{issue.category}]{line_info}\",\n                    f\"{issue.message}\",\n                ])\n                if issue.fix_suggestion:\n                    lines.append(f\"_Fix: {issue.fix_suggestion}_\")\n                lines.append(\"\")\n\n        lines.extend([\"---\", \"\"])\n\n    with open(output_file, \"w\") as f:\n        f.write(\"\\n\".join(lines))\n\n    print(f\"\\nReport exported to: {output_file}\")\n\n\ndef main():\n    parser = argparse.ArgumentParser(\n        description=\"Validate pattern files for completeness and quality\",\n        formatter_class=argparse.RawDescriptionHelpFormatter,\n        epilog=\"\"\"\nExamples:\n  %(prog)s patterns/new-pattern.md\n  %(prog)s --all\n  %(prog)s --all --verbose --export report.md\n        \"\"\",\n    )\n    parser.add_argument(\n        \"pattern_file\",\n        nargs=\"?\",\n        help=\"Path to pattern file to validate\",\n    )\n    parser.add_argument(\n        \"--all\",\n        \"-a\",\n        action=\"store_true\",\n        help=\"Validate all pattern files\",\n    )\n    parser.add_argument(\n        \"--patterns-dir\",\n        \"-d\",\n        type=str,\n        default=\"patterns\",\n        help=\"Path to patterns directory (default: patterns)\",\n    )\n    parser.add_argument(\n        \"--verbose\",\n        \"-v\",\n        action=\"store_true\",\n        help=\"Print detailed output for each issue\",\n    )\n    parser.add_argument(\n        \"--strict\",\n        \"-s\",\n        action=\"store_true\",\n        help=\"Treat warnings as errors\",\n    )\n    parser.add_argument(\n        \"--export\",\n        \"-e\",\n        type=str,\n        help=\"Export report to Markdown file\",\n    )\n\n    args = parser.parse_args()\n\n    # Validate arguments\n    if not args.all and not args.pattern_file:\n        parser.error(\"Either specify a pattern file or use --all\")\n\n    if args.all and args.pattern_file:\n        parser.error(\"Cannot use --all with a specific pattern file\")\n\n    # Initialize validator\n    validator = PatternValidator(strict=args.strict)\n\n    # Collect files to validate\n    files_to_validate = []\n\n    if args.all:\n        patterns_dir = Path(args.patterns_dir)\n        if not patterns_dir.exists():\n            print(f\"Error: Patterns directory not found: {patterns_dir}\")\n            return 1\n\n        for filepath in sorted(patterns_dir.glob(\"*.md\")):\n            if filepath.name != \"TEMPLATE.md\":\n                files_to_validate.append(str(filepath))\n    else:\n        files_to_validate.append(args.pattern_file)\n\n    # Run validation\n    print(f\"Validating {len(files_to_validate)} file(s)...\\n\")\n\n    results = []\n    for filepath in files_to_validate:\n        if not Path(filepath).exists():\n            print(f\"❌ File not found: {filepath}\")\n            continue\n\n        result = validator.validate_file(filepath)\n        results.append(result)\n        print_validation_result(result, verbose=args.verbose)\n\n    # Print summary\n    if len(results) > 1:\n        print_validation_summary(results)\n\n    # Export if requested\n    if args.export:\n        export_validation_report(results, args.export)\n\n    # Return exit code\n    return 0 if all(r.is_valid for r in results) else 1\n\n\nif __name__ == \"__main__\":\n    sys.exit(main())\n",".claude/skills/arxiv-pattern-discovery/scripts/arxiv_scanner.py":"#!/usr/bin/env python3\n\"\"\"\narxiv_scanner.py\n\nAutomated paper discovery for new agentic patterns from arXiv.\n\nQueries arXiv API with targeted search terms, filters by date/citation count/keywords,\nand scores papers using the Pattern Quality Rubric (0-10).\n\nUsage:\n    python scripts/arxiv_scanner.py --days=7 --min-citations=3\n    python scripts/arxiv_scanner.py --query=\"multi-agent systems\" --max-results=50\n\"\"\"\n\nimport argparse\nimport configparser\nimport dataclasses\nimport datetime\nimport json\nimport re\nimport sys\nimport time\nimport urllib.parse\nimport urllib.request\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Optional, Set\n\n\n# Configuration\nDEFAULT_SEARCH_QUERY = '(cat:cs.AI OR cat:cs.CL OR cat:cs.LG OR cat:cs.CR) AND all:\"agent\" OR all:\"agentic\" OR all:\"multi-agent\"'\nARXIV_API_URL = \"http://export.arxiv.org/api/query?\"\nUSER_AGENT = \"arxiv-scanner/0.1 (https://github.com/nibzard/awesome-agentic-patterns)\"\n\n\n# Valid status values for patterns\nVALID_STATUSES = {\n    \"proposed\",\n    \"emerging\",\n    \"established\",\n    \"validated-in-production\",\n    \"best-practice\",\n    \"experimental-but-awesome\",\n    \"rapidly-improving\",\n}\n\n# Valid category values\nVALID_CATEGORIES = {\n    \"Orchestration & Control\",\n    \"Context & Memory\",\n    \"Feedback Loops\",\n    \"Learning & Adaptation\",\n    \"Reliability & Eval\",\n    \"Security & Safety\",\n    \"Tool Use & Environment\",\n    \"UX & Collaboration\",\n    \"Uncategorized\",\n}\n\n\n@dataclasses.dataclass\nclass Paper:\n    \"\"\"Represents an arXiv paper with metadata.\"\"\"\n\n    arxiv_id: str\n    title: str\n    authors: List[str]\n    abstract: str\n    published: str\n    updated: str\n    categories: List[str]\n    url: str\n    citation_count: int = 0\n    quality_score: float = 0.0\n\n\n@dataclasses.dataclass\nclass PatternCandidate:\n    \"\"\"Represents a potential pattern extracted from a paper.\"\"\"\n\n    paper: Paper\n    pattern_name: Optional[str] = None\n    category: Optional[str] = None\n    tags: List[str] = dataclasses.field(default_factory=list)\n    score_breakdown: Dict[str, float] = dataclasses.field(default_factory=dict)\n    total_score: float = 0.0\n\n\nclass ArxivAPIError(Exception):\n    \"\"\"Raised when arXiv API request fails.\"\"\"\n\n    pass\n\n\ndef fetch_arxiv_papers(\n    query: str,\n    max_results: int = 100,\n    sort_by: str = \"submittedDate\",\n    sort_order: str = \"descending\",\n) -> List[Paper]:\n    \"\"\"\n    Fetch papers from arXiv API.\n\n    Args:\n        query: Search query string\n        max_results: Maximum number of results to return\n        sort_by: Sort field (lastUpdatedDate, submittedDate)\n        sort_order: ascending or descending\n\n    Returns:\n        List of Paper objects\n    \"\"\"\n    encoded_query = urllib.parse.quote(query)\n    url = f\"{ARXIV_API_URL}search_query={encoded_query}&start=0&max_results={max_results}&sortBy={sort_by}&sortOrder={sort_order}\"\n\n    headers = {\"User-Agent\": USER_AGENT}\n\n    try:\n        req = urllib.request.Request(url, headers=headers)\n        with urllib.request.urlopen(req, timeout=30) as response:\n            xml_data = response.read().decode(\"utf-8\")\n    except urllib.error.URLError as e:\n        raise ArxivAPIError(f\"Failed to fetch papers: {e}\")\n\n    return parse_arxiv_response(xml_data)\n\n\ndef parse_arxiv_response(xml_data: str) -> List[Paper]:\n    \"\"\"Parse arXiv API XML response into Paper objects.\"\"\"\n    papers = []\n\n    # Extract entries using regex (simple approach, could use xml.etree)\n    entry_pattern = re.compile(r\"<entry>(.*?)</entry>\", re.DOTALL)\n    title_pattern = re.compile(r\"<title>(.*?)</title>\", re.DOTALL)\n    author_pattern = re.compile(r\"<name>(.*?)</name>\")\n    summary_pattern = re.compile(r\"<summary>(.*?)</summary>\", re.DOTALL)\n    published_pattern = re.compile(r\"<published>(.*?)</published>\")\n    updated_pattern = re.compile(r\"<updated>(.*?)</updated>\")\n    category_pattern = re.compile(r'<term[^>]*>([^<]+)</term>')\n    id_pattern = re.compile(r\"<id>(.*?)</id>\")\n    arxiv_id_pattern = re.compile(r\"arxiv.org/abs/(\\d+\\.\\d+)\")\n\n    for entry_match in entry_pattern.finditer(xml_data):\n        entry = entry_match.group(1)\n\n        # Extract title\n        title_match = title_pattern.search(entry)\n        title = title_match.group(1).strip().replace(\"\\n\", \" \") if title_match else \"Unknown\"\n\n        # Extract authors\n        authors = [a.strip() for a in author_pattern.findall(entry)]\n\n        # Extract abstract\n        summary_match = summary_pattern.search(entry)\n        abstract = summary_match.group(1).strip().replace(\"\\n\", \" \") if summary_match else \"\"\n\n        # Extract dates\n        published_match = published_pattern.search(entry)\n        published = published_match.group(1) if published_match else \"\"\n\n        updated_match = updated_pattern.search(entry)\n        updated = updated_match.group(1) if updated_match else \"\"\n\n        # Extract categories (primary and secondary)\n        categories = list(set(category_pattern.findall(entry)))\n\n        # Extract arXiv ID\n        id_match = id_pattern.search(entry)\n        arxiv_id = \"unknown\"\n        if id_match:\n            arxiv_id_match = arxiv_id_pattern.search(id_match.group(1))\n            if arxiv_id_match:\n                arxiv_id = arxiv_id_match.group(1)\n\n        # Build URL\n        url = f\"https://arxiv.org/abs/{arxiv_id}\"\n\n        papers.append(\n            Paper(\n                arxiv_id=arxiv_id,\n                title=title,\n                authors=authors,\n                abstract=abstract,\n                published=published,\n                updated=updated,\n                categories=categories,\n                url=url,\n            )\n        )\n\n    return papers\n\n\ndef parse_date(date_string: str) -> datetime.datetime:\n    \"\"\"Parse arXiv date string to datetime object.\"\"\"\n    # arXiv dates are in format: 2025-01-15T12:34:56Z\n    try:\n        return datetime.datetime.fromisoformat(date_string.replace(\"Z\", \"+00:00\"))\n    except ValueError:\n        # Fallback for other formats\n        return datetime.datetime.min\n\n\ndef filter_papers_by_date(papers: List[Paper], days: int) -> List[Paper]:\n    \"\"\"Filter papers to those published/updated within the last N days.\"\"\"\n    cutoff = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(days=days)\n    return [p for p in papers if parse_date(p.published) >= cutoff or parse_date(p.updated) >= cutoff]\n\n\ndef filter_papers_by_keywords(papers: List[Paper]) -> List[Paper]:\n    \"\"\"Filter papers to those containing architecture/pattern keywords in abstract.\"\"\"\n    architectural_terms = {\n        \"architecture\",\n        \"pattern\",\n        \"framework\",\n        \"design\",\n        \"orchestration\",\n        \"coordination\",\n        \"hierarchy\",\n        \"protocol\",\n        \"memory\",\n        \"agent\",\n        \"agentic\",\n        \"multi-agent\",\n        \"autonomous\",\n        \"workflow\",\n        \"control\",\n        \"feedback\",\n        \"adapter\",\n        \"interface\",\n        \"abstraction\",\n    }\n\n    filtered = []\n    for paper in papers:\n        abstract_lower = paper.abstract.lower()\n        title_lower = paper.title.lower()\n        combined = title_lower + \" \" + abstract_lower\n\n        if any(term in combined for term in architectural_terms):\n            filtered.append(paper)\n\n    return filtered\n\n\ndef score_reusability(paper: Paper) -> float:\n    \"\"\"\n    Score paper on reusability (30% weight).\n\n    Domain-specific (1.0) → Multi-domain (2.0) → Universal (3.0)\n    \"\"\"\n    abstract_lower = paper.abstract.lower()\n    title_lower = paper.title.lower()\n    combined = title_lower + \" \" + abstract_lower\n\n    # Check for universal language\n    universal_indicators = [\"general\", \"universal\", \"framework\", \"generic\", \"generic approach\"]\n    multi_domain_indicators = [\"multi-domain\", \"cross-domain\", \"versatile\", \"adaptable\"]\n    domain_specific_indicators = [\"specific to\", \"in the field of\", \"domain-specific\"]\n\n    universal_count = sum(1 for term in universal_indicators if term in combined)\n    multi_domain_count = sum(1 for term in multi_domain_indicators if term in combined)\n    domain_specific_count = sum(1 for term in domain_specific_indicators if term in combined)\n\n    # Also check for broad application potential\n    broad_terms = [\"wide range\", \"variety of\", \"multiple use cases\", \"flexible\"]\n    broad_count = sum(1 for term in broad_terms if term in combined)\n\n    if universal_count >= 1 or broad_count >= 1:\n        return 3.0\n    elif multi_domain_count >= 1:\n        return 2.0\n    elif domain_specific_count >= 1:\n        return 1.0\n    else:\n        # Default to mid-range\n        return 2.0\n\n\ndef score_novelty(paper: Paper) -> float:\n    \"\"\"\n    Score paper on novelty (25% weight).\n\n    Existing (1.0) → Incremental (2.0) → Fundamentally new (3.0)\n    \"\"\"\n    abstract_lower = paper.abstract.lower()\n    title_lower = paper.title.lower()\n    combined = title_lower + \" \" + abstract_lower\n\n    # Check for novelty indicators\n    novel_indicators = [\n        \"novel\",\n        \"new\",\n        \"first\",\n        \"pioneering\",\n        \"groundbreaking\",\n        \"innovative\",\n        \"unprecedented\",\n        \"original\",\n        \"unique approach\",\n    ]\n    incremental_indicators = [\n        \"improves\",\n        \"extends\",\n        \"builds on\",\n        \"enhances\",\n        \"optimizes\",\n        \"refines\",\n        \"extension of\",\n    ]\n\n    novel_count = sum(1 for term in novel_indicators if term in combined)\n    incremental_count = sum(1 for term in incremental_indicators if term in combined)\n\n    # Check for strong claims of new approaches\n    strong_novel = [\"new architecture\", \"new framework\", \"new paradigm\", \"first to\"]\n    strong_novel_count = sum(1 for term in strong_novel if term in combined)\n\n    if strong_novel_count >= 1 or novel_count >= 2:\n        return 3.0\n    elif novel_count >= 1 and incremental_count == 0:\n        return 2.5\n    elif incremental_count >= 1:\n        return 2.0\n    else:\n        return 1.5\n\n\ndef score_clarity(paper: Paper) -> float:\n    \"\"\"\n    Score paper on clarity (20% weight).\n\n    Vague (1.0) → Clear (2.0) → Crystal clear (3.0)\n    \"\"\"\n    abstract_lower = paper.abstract.lower()\n    title_lower = paper.title.lower()\n    combined = title_lower + \" \" + abstract_lower\n\n    # Clarity indicators\n    clear_indicators = [\n        \"we propose\",\n        \"we present\",\n        \"our approach\",\n        \"the method\",\n        \"the algorithm\",\n        \"specifically\",\n        \"concretely\",\n    ]\n    vague_indicators = [\n        \"some ways\",\n        \"somewhat\",\n        \"may\",\n        \"might\",\n        \"potentially\",\n        \"could be\",\n    ]\n\n    clear_count = sum(1 for term in clear_indicators if term in combined)\n    vague_count = sum(1 for term in vague_indicators if term in combined)\n\n    # Abstract length (too short might indicate lack of detail)\n    abstract_words = len(paper.abstract.split())\n    length_score = 0\n    if abstract_words > 150:\n        length_score = 1\n    elif abstract_words > 100:\n        length_score = 0.5\n\n    base_score = 2.0\n    if clear_count >= 3:\n        base_score = 2.5\n    if vague_count >= 3:\n        base_score = max(1.0, base_score - 0.5)\n\n    return min(3.0, base_score + length_score)\n\n\ndef score_evidence(paper: Paper) -> float:\n    \"\"\"\n    Score paper on empirical evidence (15% weight).\n\n    No eval (1.0) → Some eval (2.0) → Strong empirical (3.0)\n    \"\"\"\n    abstract_lower = paper.abstract.lower()\n\n    # Evidence indicators\n    eval_indicators = [\n        \"evaluation\",\n        \"experiment\",\n        \"benchmark\",\n        \"results\",\n        \"performance\",\n        \"compared\",\n        \"comparison\",\n        \"metric\",\n    ]\n    strong_eval_indicators = [\n        \"significant improvement\",\n        \"state-of-the-art\",\n        \"sota\",\n        \"outperforms\",\n        \"empirical\",\n        \"real-world\",\n        \"deployment\",\n    ]\n\n    eval_count = sum(1 for term in eval_indicators if term in abstract_lower)\n    strong_eval_count = sum(1 for term in strong_eval_indicators if term in abstract_lower)\n\n    # Check for datasets (indicates empirical work)\n    dataset_indicators = [\"dataset\", \"benchmark\", \"we evaluate on\", \"tested on\"]\n    dataset_count = sum(1 for term in dataset_indicators if term in abstract_lower)\n\n    if strong_eval_count >= 1 or eval_count >= 3:\n        return 3.0\n    elif eval_count >= 1:\n        return 2.0\n    elif dataset_count >= 1:\n        return 2.0\n    else:\n        return 1.0\n\n\ndef score_completeness(paper: Paper) -> float:\n    \"\"\"\n    Score paper on implementation completeness (10% weight).\n\n    Idea only (1.0) → Partial details (2.0) → Production-ready (3.0)\n    \"\"\"\n    abstract_lower = paper.abstract.lower()\n\n    # Completeness indicators\n    implementation_indicators = [\n        \"implementation\",\n        \"open source\",\n        \"code\",\n        \"available\",\n        \"github\",\n        \"released\",\n        \"library\",\n    ]\n    detail_indicators = [\n        \"algorithm\",\n        \"architecture\",\n        \"framework\",\n        \"protocol\",\n        \"method\",\n        \"approach\",\n    ]\n\n    implementation_count = sum(1 for term in implementation_indicators if term in abstract_lower)\n    detail_count = sum(1 for term in detail_indicators if term in abstract_lower)\n\n    # Check for production mentions\n    production_indicators = [\"production\", \"deployed\", \"real-world\", \"industry\"]\n    production_count = sum(1 for term in production_indicators if term in abstract_lower)\n\n    if implementation_count >= 2 or production_count >= 1:\n        return 3.0\n    elif implementation_count >= 1 or detail_count >= 3:\n        return 2.0\n    elif detail_count >= 1:\n        return 1.5\n    else:\n        return 1.0\n\n\ndef calculate_quality_score(paper: Paper) -> tuple[float, Dict[str, float]]:\n    \"\"\"\n    Calculate overall quality score using the Pattern Quality Rubric.\n\n    Returns:\n        Tuple of (total_score, score_breakdown)\n    \"\"\"\n    # Weighted scoring\n    reusability = score_reusability(paper)\n    novelty = score_novelty(paper)\n    clarity = score_clarity(paper)\n    evidence = score_evidence(paper)\n    completeness = score_completeness(paper)\n\n    # Weights\n    total_score = (\n        reusability * 0.30 +\n        novelty * 0.25 +\n        clarity * 0.20 +\n        evidence * 0.15 +\n        completeness * 0.10\n    )\n\n    breakdown = {\n        \"reusability\": reusability,\n        \"novelty\": novelty,\n        \"clarity\": clarity,\n        \"evidence\": evidence,\n        \"completeness\": completeness,\n    }\n\n    return total_score, breakdown\n\n\ndef categorize_paper(paper: Paper, existing_patterns: List[Dict]) -> Optional[str]:\n    \"\"\"\n    Attempt to categorize a paper into one of the pattern categories.\n\n    Returns the category name or None if uncertain.\n    \"\"\"\n    abstract_lower = paper.abstract.lower()\n    title_lower = paper.title.lower()\n    combined = title_lower + \" \" + abstract_lower\n\n    # Category-specific keywords\n    category_keywords = {\n        \"Orchestration & Control\": [\n            \"orchestration\", \"coordination\", \"control\", \"hierarchy\", \"planner\",\n            \"workflow\", \"supervisor\", \"manager\", \"scheduler\", \"decomposition\",\n            \"sub-agent\", \"spawning\", \"multi-agent coordination\",\n        ],\n        \"Context & Memory\": [\n            \"memory\", \"context\", \"recall\", \"retrieval\", \"episodic\",\n            \"vector\", \"embedding\", \"rag\", \"knowledge base\", \"state\",\n            \"continuum\", \"temporal context\",\n        ],\n        \"Feedback Loops\": [\n            \"feedback\", \"iteration\", \"refinement\", \"self-improve\",\n            \"critique\", \"eval\", \"evaluation\", \"monitor\", \"adjust\",\n            \"adaptive\", \"learning from feedback\",\n        ],\n        \"Learning & Adaptation\": [\n            \"learning\", \"reinforcement\", \"rl\", \"fine-tuning\", \"adaptation\",\n            \"skill\", \"evolution\", \"training\", \"optimizer\",\n        ],\n        \"Reliability & Eval\": [\n            \"reliability\", \"safety\", \"guardrail\", \"error\", \"robust\",\n            \"testing\", \"validation\", \"verification\", \"deterministic\",\n        ],\n        \"Security & Safety\": [\n            \"security\", \"privacy\", \"attack\", \"malicious\", \"adversarial\",\n            \"sandbox\", \"isolation\", \"monitoring\", \"threat model\",\n            \"exfiltration\", \"laundering\",\n        ],\n        \"Tool Use & Environment\": [\n            \"tool\", \"api\", \"function call\", \"environment\", \"execution\",\n            \"browser\", \"shell\", \"filesystem\", \"external\", \"integration\",\n        ],\n        \"UX & Collaboration\": [\n            \"user experience\", \"ux\", \"collaboration\", \"human-in-loop\",\n            \"handoff\", \"notification\", \"interaction\", \"interface\",\n        ],\n    }\n\n    # Count keyword matches for each category\n    category_scores = {}\n    for category, keywords in category_keywords.items():\n        score = sum(1 for kw in keywords if kw in combined)\n        if score > 0:\n            category_scores[category] = score\n\n    # Return category with highest score (if any)\n    if category_scores:\n        return max(category_scores, key=category_scores.get)\n\n    return None\n\n\ndef extract_tags(paper: Paper) -> List[str]:\n    \"\"\"\n    Extract relevant tags from paper metadata.\n\n    Returns a list of lowercase tags suitable for pattern files.\n    \"\"\"\n    abstract_lower = paper.abstract.lower()\n    title_lower = paper.title.lower()\n    combined = title_lower + \" \" + abstract_lower\n\n    # Common agentic pattern keywords\n    tag_keywords = [\n        \"agent\", \"multi-agent\", \"orchestration\", \"coordination\",\n        \"memory\", \"context\", \"rag\", \"retrieval\",\n        \"feedback\", \"iteration\", \"self-improve\",\n        \"tool\", \"api\", \"function-call\",\n        \"planning\", \"planner\", \"decomposition\",\n        \"parallel\", \"concurrent\", \"async\",\n        \"hierarchy\", \"hierarchical\", \"layered\",\n        \"security\", \"privacy\", \"sandbox\",\n        \"evaluation\", \"benchmark\", \"testing\",\n        \"autonomous\", \"automation\",\n        \"workflow\", \"pipeline\",\n        \"communication\", \"protocol\",\n    ]\n\n    tags = []\n    for keyword in tag_keywords:\n        if keyword in combined:\n            tags.append(keyword)\n\n    return tags\n\n\ndef print_paper_summary(paper: Paper, score: float, breakdown: Dict[str, float], category: Optional[str]):\n    \"\"\"Print a formatted summary of a paper with its scores.\"\"\"\n    print(f\"\\n{'='*70}\")\n    print(f\"Title: {paper.title}\")\n    print(f\"arXiv: {paper.arxiv_id} | Score: {score:.2f}/10.0\")\n    print(f\"URL: {paper.url}\")\n    if category:\n        print(f\"Suggested Category: {category}\")\n    print(f\"\\nScore Breakdown:\")\n    print(f\"  Reusability (30%):    {breakdown['reusability']:.1f}/3.0\")\n    print(f\"  Novelty (25%):        {breakdown['novelty']:.1f}/3.0\")\n    print(f\"  Clarity (20%):        {breakdown['clarity']:.1f}/3.0\")\n    print(f\"  Evidence (15%):       {breakdown['evidence']:.1f}/3.0\")\n    print(f\"  Completeness (10%):   {breakdown['completeness']:.1f}/3.0\")\n    print(f\"\\nAbstract: {paper.abstract[:300]}...\")\n\n\ndef export_results(papers: List[Dict[str, Any]], output_file: str):\n    \"\"\"Export scan results to JSON file.\"\"\"\n    with open(output_file, \"w\") as f:\n        json.dump(papers, f, indent=2)\n    print(f\"\\nResults exported to: {output_file}\")\n\n\ndef export_markdown_report(papers: List[Dict[str, Any]], output_file: str):\n    \"\"\"Export scan results as a Markdown report.\"\"\"\n    lines = [\n        \"# arXiv Pattern Discovery Report\",\n        f\"Generated: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\",\n        \"\",\n        f\"**Total papers scanned: {len(papers)}**\",\n        \"\",\n        \"---\",\n        \"\",\n    ]\n\n    for i, paper in enumerate(papers, 1):\n        p = paper[\"paper\"]\n        lines.extend([\n            f\"## {i}. {p['title']}\",\n            \"\",\n            f\"**arXiv ID:** {p['arxiv_id']}  \",\n            f\"**Quality Score:** {paper['total_score']:.2f}/10.0  \",\n            f\"**Suggested Category:** {paper.get('category', 'Uncategorized')}  \",\n            f\"**URL:** {p['url']}  \",\n            \"\",\n            f\"**Score Breakdown:**\",\n            f\"- Reusability (30%): {paper['score_breakdown']['reusability']:.1f}/3.0\",\n            f\"- Novelty (25%): {paper['score_breakdown']['novelty']:.1f}/3.0\",\n            f\"- Clarity (20%): {paper['score_breakdown']['clarity']:.1f}/3.0\",\n            f\"- Evidence (15%): {paper['score_breakdown']['evidence']:.1f}/3.0\",\n            f\"- Completeness (10%): {paper['score_breakdown']['completeness']:.1f}/3.0\",\n            \"\",\n            f\"**Tags:** {', '.join(paper.get('tags', []))}\",\n            \"\",\n            \"**Abstract:**\",\n            p[\"abstract\"],\n            \"\",\n            \"---\",\n            \"\",\n        ])\n\n    with open(output_file, \"w\") as f:\n        f.write(\"\\n\".join(lines))\n    print(f\"Markdown report exported to: {output_file}\")\n\n\ndef load_existing_patterns(patterns_dir: Path) -> List[Dict]:\n    \"\"\"Load existing patterns to check for duplicates.\"\"\"\n    from build_readme import parse_front_matter\n\n    patterns = []\n    for file in patterns_dir.glob(\"*.md\"):\n        if file.name == \"TEMPLATE.md\":\n            continue\n        try:\n            metadata = parse_front_matter(str(file))\n            patterns.append({\n                \"file\": file.name,\n                \"title\": metadata.get(\"title\", \"\"),\n                \"tags\": metadata.get(\"tags\", []),\n                \"category\": metadata.get(\"category\", \"\"),\n            })\n        except Exception:\n            continue\n    return patterns\n\n\ndef check_for_duplicates(paper: Paper, existing_patterns: List[Dict]) -> List[str]:\n    \"\"\"Check if paper might duplicate existing patterns.\"\"\"\n    title_lower = paper.title.lower()\n    abstract_lower = paper.abstract.lower()\n\n    potential_dupes = []\n    for pattern in existing_patterns:\n        pattern_title = pattern[\"title\"].lower()\n        pattern_tags = [t.lower() for t in pattern.get(\"tags\", [])]\n\n        # Check title similarity\n        if any(word in title_lower for word in pattern_title.split() if len(word) > 4):\n            potential_dupes.append(pattern[\"file\"])\n\n        # Check tag overlap\n        paper_words = set(title_lower.split() + abstract_lower.split())\n        tag_overlap = len(paper_words.intersection(pattern_tags)) / max(len(pattern_tags), 1)\n        if tag_overlap > 0.3:\n            potential_dupes.append(pattern[\"file\"])\n\n    return list(set(potential_dupes))\n\n\ndef main():\n    parser = argparse.ArgumentParser(\n        description=\"Scan arXiv for papers describing agentic patterns\",\n        formatter_class=argparse.RawDescriptionHelpFormatter,\n        epilog=\"\"\"\nExamples:\n  %(prog)s --days=7 --min-citations=3\n  %(prog)s --query=\"multi-agent orchestration\" --max-results=50\n  %(prog)s --min-score=7.0 --export-json results.json\n        \"\"\",\n    )\n    parser.add_argument(\n        \"--query\",\n        \"-q\",\n        type=str,\n        default=DEFAULT_SEARCH_QUERY,\n        help=\"arXiv search query (default: agent/agentic/multi-agent papers)\",\n    )\n    parser.add_argument(\n        \"--max-results\",\n        \"-n\",\n        type=int,\n        default=100,\n        help=\"Maximum number of results to fetch (default: 100)\",\n    )\n    parser.add_argument(\n        \"--days\",\n        \"-d\",\n        type=int,\n        default=365,\n        help=\"Only include papers from last N days (default: 365)\",\n    )\n    parser.add_argument(\n        \"--min-score\",\n        \"-m\",\n        type=float,\n        default=5.0,\n        help=\"Minimum quality score to include (default: 5.0)\",\n    )\n    parser.add_argument(\n        \"--export-json\",\n        type=str,\n        help=\"Export results to JSON file\",\n    )\n    parser.add_argument(\n        \"--export-md\",\n        type=str,\n        help=\"Export results to Markdown file\",\n    )\n    parser.add_argument(\n        \"--patterns-dir\",\n        type=str,\n        default=\"patterns\",\n        help=\"Path to patterns directory (default: patterns)\",\n    )\n    parser.add_argument(\n        \"--verbose\",\n        \"-v\",\n        action=\"store_true\",\n        help=\"Print detailed output for each paper\",\n    )\n\n    args = parser.parse_args()\n\n    # Load existing patterns\n    patterns_dir = Path(args.patterns_dir)\n    if patterns_dir.exists():\n        existing_patterns = load_existing_patterns(patterns_dir)\n        print(f\"Loaded {len(existing_patterns)} existing patterns for duplicate detection\")\n    else:\n        existing_patterns = []\n        print(f\"Warning: Patterns directory not found at {patterns_dir}\")\n\n    print(f\"\\n🔍 Scanning arXiv with query: {args.query[:100]}...\")\n    print(f\"   Max results: {args.max_results}, Time window: {args.days} days\")\n\n    try:\n        papers = fetch_arxiv_papers(args.query, args.max_results)\n        print(f\"   Fetched {len(papers)} papers from arXiv\")\n\n        # Apply filters\n        if args.days < 365:\n            papers = filter_papers_by_date(papers, args.days)\n            print(f\"   Filtered to {len(papers)} papers within last {args.days} days\")\n\n        papers = filter_papers_by_keywords(papers)\n        print(f\"   Filtered to {len(papers)} papers with architectural keywords\")\n\n        if not papers:\n            print(\"\\n❌ No papers found matching criteria\")\n            return 0\n\n    except ArxivAPIError as e:\n        print(f\"\\n❌ Error fetching from arXiv: {e}\")\n        return 1\n\n    # Score papers\n    print(f\"\\n📊 Scoring {len(papers)} papers using Pattern Quality Rubric...\")\n\n    results = []\n    high_quality_count = 0\n\n    for paper in papers:\n        score, breakdown = calculate_quality_score(paper)\n        category = categorize_paper(paper, existing_patterns)\n        tags = extract_tags(paper)\n        duplicates = check_for_duplicates(paper, existing_patterns)\n\n        result = {\n            \"paper\": {\n                \"arxiv_id\": paper.arxiv_id,\n                \"title\": paper.title,\n                \"authors\": paper.authors,\n                \"abstract\": paper.abstract,\n                \"published\": paper.published,\n                \"categories\": paper.categories,\n                \"url\": paper.url,\n            },\n            \"pattern_name\": None,\n            \"category\": category,\n            \"tags\": tags,\n            \"score_breakdown\": breakdown,\n            \"total_score\": score,\n            \"potential_duplicates\": duplicates,\n            \"meets_threshold\": score >= args.min_score,\n        }\n        results.append(result)\n\n        if score >= args.min_score:\n            high_quality_count += 1\n            if args.verbose:\n                print_paper_summary(paper, score, breakdown, category)\n                if duplicates:\n                    print(f\"⚠️  Potential duplicates: {', '.join(duplicates)}\")\n\n    # Sort by score\n    results.sort(key=lambda x: x[\"total_score\"], reverse=True)\n\n    # Print summary\n    print(f\"\\n{'='*70}\")\n    print(f\"📈 SCAN SUMMARY\")\n    print(f\"{'='*70}\")\n    print(f\"Total papers analyzed: {len(papers)}\")\n    print(f\"Papers meeting threshold ({args.min_score}): {high_quality_count}\")\n    print(f\"\\n🏆 Top 10 papers by quality score:\")\n    print(f\"{'-'*70}\")\n\n    for i, r in enumerate(results[:10], 1):\n        p = r[\"paper\"]\n        dupes = f\" [⚠️ duplicates: {len(r['potential_duplicates'])}]\" if r[\"potential_duplicates\"] else \"\"\n        print(f\"{i:2}. {r['total_score']:.2f} | {p['title'][:60]}...{dupes}\")\n\n    # Export results if requested\n    if args.export_json:\n        export_results(results, args.export_json)\n\n    if args.export_md:\n        export_markdown_report(results, args.export_md)\n\n    return 0\n\n\nif __name__ == \"__main__\":\n    sys.exit(main())\n"},"files":{".claude/skills/create-pattern/PATTERN_INDEX.md":"# Pattern Index\n\nQuick reference for all 105+ patterns in the repository for semantic matching.\n\n## Category Summary\n\n| Category | Count | Key Themes |\n|----------|-------|------------|\n| Orchestration & Control | 32 | Task decomposition, sub-agents, tool routing |\n| Tool Use & Environment | 20 | Shell, browser, DB, sandbox tools |\n| UX & Collaboration | 16 | Prompts, hand-offs, staged commits |\n| Context & Memory | 14 | Window curation, vector cache, episodic memory |\n| Feedback Loops | 12 | CI, review, self-healing |\n| Reliability & Eval | 10 | Guardrails, evals, logging |\n| Security & Safety | 3 | Isolation, PII, scanning |\n| Learning & Adaptation | 3 | Agent RFT, skill libraries |\n\n## Common Tags (appear 4+ times)\n\n- tool-use, security, search, reinforcement-learning, reasoning\n- feedback, prompt-injection, planning, mcp, learning, evaluation\n- coding-agent, code-review, cli, automation\n\n## Pattern Clusters (for Matching)\n\n### Context Management Patterns\n- `context-minimization-pattern.md`\n- `context-window-anxiety-management.md`\n- `curated-code-context-window.md`\n- `layered-configuration-context.md`\n- `agentic-search-over-vector-embeddings.md`\n\n### Planning Patterns\n- `plan-then-execute-pattern.md`\n- `explicit-posterior-sampling-planner.md`\n- `tree-of-thought-reasoning.md`\n\n### Multi-Agent Patterns\n- `oracle-and-worker-multi-model.md`\n- `initializer-maintainer-dual-agent.md`\n- `sub-agent-spawning.md`\n- `continuous-autonomous-task-loop-pattern.md`\n\n### Memory/State Patterns\n- `episodic-memory-retrieval-injection.md`\n- `filesystem-based-agent-state.md`\n- `proactive-agent-state-externalization.md`\n\n### Security Patterns\n- `action-selector-pattern.md`\n- `egress-lockdown-no-exfiltration-channel.md`\n- `pii-tokenization.md`\n\n### Code Review Patterns\n- `criticgpt-style-evaluation.md`\n- `ai-assisted-code-review-verification.md`\n- `abstracted-code-representation-for-review.md`\n\n### Progressive Autonomy Chain\n- `progressive-autonomy-with-model-evolution.md`\n- `progressive-complexity-escalation.md`\n- `skill-library-evolution.md`\n\n### Tool Design Patterns\n- `dual-use-tool-design.md`\n- `tool-use-steering-via-prompting.md`\n- `tool-use-incentivization-via-reward-shaping.md`\n\n## Top Pattern Sources\n\n| Source | Patterns |\n|--------|----------|\n| Will Brown (Prime Intellect) | 8 patterns |\n| Boris Cherny (Anthropic) | 7 patterns |\n| Anthropic Engineering | 7 patterns |\n| Luca Beurer-Kellner et al. (2025) | 6 patterns |\n| Aman Sanger (Cursor) | 6 patterns |\n| Thorsten Ball | 5 patterns |\n| Quinn Slack | 5 patterns |\n| Lukas Möller (Cursor) | 5 patterns |\n\n## Matching Heuristics\n\nWhen analyzing a new source:\n\n1. **Check by author** - If source is from Will Brown, Boris Cherny, etc., likely matches existing pattern\n2. **Check by category** - Context management has 14 patterns with high overlap\n3. **Check by tags** - \"tool-use\", \"security\", \"reasoning\" indicate clusters\n4. **Problem similarity** - Same core challenge → likely existing pattern\n5. **Solution similarity** - Same mechanism → likely existing pattern\n\n## Decision Thresholds\n\n- **>80% confidence** - Update existing (same problem + solution + category)\n- **50-80% confidence** - Ask user (partial overlap)\n- **<50% confidence** - Create new (different problem/solution)\n","CLAUDE.md":"# CLAUDE.md\n\nThis file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.\n\n## Project Overview\n\nThis is a documentation website for \"Awesome Agentic Patterns\" - a curated catalogue of AI agent design patterns. It uses Astro (apps/web/) to generate a static documentation site that can be deployed to Vercel.\n\n## Key Commands\n\n> **NOTE:** This project uses **bun** as the package manager, not npm.\n\n### Development Workflow\n```bash\n# Initial setup (run once)\nbun install                            # Install dependencies\n\n# Standard development cycle\nbun run dev                            # Serve docs locally at http://localhost:4321\n\n# Building and deployment\nbun run build                          # Build static site to apps/web/dist/\nvercel deploy                          # Deploy to Vercel (primary)\n```\n\n## Architecture\n\nThe project has a unique architecture where pattern documentation drives the entire site:\n\n1. **Pattern Files** (`patterns/*.md`): Source of truth for all patterns\n   - Must include YAML front-matter with: title, status, authors, category, source, tags, summary, signals, anti_signals, updated_at\n   - Content sections: Problem, Solution, How to use it, Trade-offs, References\n\n2. **Data Pipeline**: Pattern files are converted to JSON in `apps/web/public/patterns/`\n   - Astro build reads JSON files to generate pages\n   - Pattern metadata drives navigation and listings\n\n3. **Build Process**:\n   - Astro builds from apps/web/ to apps/web/dist/\n   - Site can be served locally or deployed to Vercel\n\n## Pattern Development Workflow\n\n### Adding New Patterns\n1. **Start with template**: Copy `TEMPLATE.md` (repository root) to create new pattern files in `patterns/`\n2. **Required YAML front-matter**: Every pattern must include:\n   ```yaml\n   ---\n   title: \"Clear, Descriptive Title\"\n   status: \"proposed | emerging | production | foundational\"\n   authors: [\"Contributor Name (@username)\"]\n   based_on: [\"Original Creator (Source)\"]\n   category: \"Orchestration & Control | Context & Memory | Feedback Loops | Learning & Adaptation | Reliability & Eval | Security & Safety | Tool Use & Environment | UX & Collaboration | Uncategorized\"\n   source: \"URL to primary source\"\n   tags: [relevant, keywords, here]\n   summary: \"One sentence that says what the pattern does (the solution)\"  # Shown in the catalog list\n   signals: [\"When to use it\"]          # 2-4 items, shown as \"Use when\"\n   anti_signals: [\"When not to use it\"] # 2-3 items, shown as \"Avoid when\"\n   updated_at: \"YYYY-MM-DD\"  # Required: last content change date — file mtimes differ per machine, so generated data needs an explicit date\n   ---\n   ```\n3. **Required sections**: Problem, Solution, How to use it, Trade-offs, References\n4. **Data sync**: Pattern files must be converted to JSON for the Astro site\n   - Run `bun run build:data` to update the JSON files\n   - JSON files are stored in `apps/web/public/patterns/` and `apps/web/public/data/patterns/`\n   - CI fails if the committed JSON files differ from what the pipeline produces; run the pipeline and commit its output together with the pattern `.md` change\n\n### Content Guidelines\n- Use Mermaid diagrams in patterns for architectural visualization\n- Pattern files support full Markdown with front-matter\n- Community policy for pattern submissions:\n  - Treat this as a community project, not a promotional channel\n  - Reject promotional, sales, affiliate, or backlink-seeding content\n  - For external contributors, prefer links to `github.com`, `github.io`, or non-vendor neutral references\n  - Allow vendor/product links only when the contribution is truly novel and adds clear value\n  - Require submissions to be materially novel and non-repetitive versus existing patterns\n- **CRITICAL**: Always add blank lines after headers before starting bullet point lists\n  - Incorrect: `**Header:**\\n- Item 1` (renders inline)\n  - Correct: `**Header:**\\n\\n- Item 1` (renders as proper list)\n  - This is required for Astro to properly convert Markdown lists to HTML `<ul><li>` elements\n\n### Asset Path Handling\n\n**CRITICAL**: When adding images or other assets that need to work on both localhost and deployed sites:\n\n- **Use absolute paths starting with `/`** in all asset references\n- **Image references**: Use `/image.jpeg` instead of `image.jpeg` in markdown files\n- **Rationale**: Relative paths can work locally but fail on Vercel due to different path resolution behavior\n- **Example fix**: Change `![Image](image.jpeg)` to `![Image](/image.jpeg)`\n\nThis ensures assets load correctly on both local development (`localhost:4321`) and production deployment (`agentic-patterns.com`).\n\n## Technical Architecture\n\n### Build System Components\n- **Astro**: Modern static site generator in `apps/web/`\n- **Pattern JSON files**: Generated data in `apps/web/public/patterns/`\n- **Vercel config**: Build settings in `vercel.json`\n- **TypeScript/Node.js**: Build toolchain\n\n### File Structure\n```\nTEMPLATE.md           # Template for new patterns (repository root)\n\npatterns/              # Source of truth - all pattern .md files\n└── *.md              # Individual pattern files with YAML front-matter\n\napps/web/             # Astro web application\n├── public/\n│   └── patterns/    # JSON pattern data for site generation\n├── src/             # Astro components and pages\n└── dist/            # Build output (deployment artifact)\n```\n\n### Dependencies\n- **Node.js**: Astro framework and build toolchain\n- **Vercel**: Primary deployment platform\n\n## Deployment\n\n- Primary deployment: Vercel (`vercel deploy`)\n- For detailed deployment instructions, see DEPLOYMENT.md\n",".claude/skills/arxiv-pattern-discovery/SKILL.md":"---\nname: arxiv-pattern-discovery\ndescription: Search arXiv for academic papers describing agentic AI patterns. Use when user asks to find new patterns from academic literature, search arXiv, discover patterns from papers, or review academic sources for pattern extraction.\n---\n\n# arXiv Pattern Discovery\n\nSearch arXiv for academic papers describing agentic AI patterns and score them using the Pattern Quality Rubric.\n\n## Quick Start\n\nInvoke this skill when the user asks to:\n- Search arXiv for new agent patterns\n- Find academic papers about multi-agent orchestration\n- Discover patterns from academic literature\n- Review the latest papers for extractable patterns\n- What new patterns are emerging from recent AI research?\n\n## Workflow\n\nThis skill implements a 3-phase discovery workflow:\n\n### Phase 1: Discovery\n```bash\n# Search for recent papers (last 30 days, max 50 results)\npython scripts/arxiv_scanner.py --days=30 --max-results=50 --export-md results.md\n\n# Search for specific topics\npython scripts/arxiv_scanner.py --query=\"multi-agent systems\" --max-results=100\n\n# Search with minimum quality threshold\npython scripts/arxiv_scanner.py --min-score=7.0 --export-md high-quality.md\n```\n\n### Phase 2: Review\n- Read the exported Markdown report\n- Identify high-quality papers (score >= 7.0)\n- Check for potential duplicates flagged by the scanner\n- Select candidates for pattern extraction\n\n### Phase 3: Next Steps\n- Use the `create-pattern` skill to extract patterns from selected papers\n- Or manually create patterns using `patterns/TEMPLATE.md`\n- Run the similarity checker before committing to avoid duplicates\n- Run the validator to ensure pattern quality\n\n## Script Reference\n\n### arxiv_scanner.py\n\nMain script for querying arXiv API and scoring papers.\n\n**Usage:**\n```bash\npython scripts/arxiv_scanner.py [OPTIONS]\n```\n\n**Options:**\n- `--query, -q`: arXiv search query (default: agent/agentic/multi-agent papers)\n- `--max-results, -n`: Maximum results to fetch (default: 100)\n- `--days, -d`: Only include papers from last N days (default: 365)\n- `--min-score, -m`: Minimum quality score to include (default: 5.0)\n- `--export-json`: Export results to JSON file\n- `--export-md`: Export results to Markdown file\n- `--patterns-dir`: Path to patterns directory (default: patterns)\n- `--verbose, -v`: Print detailed output for each paper\n\n**Examples:**\n```bash\n# Recent high-quality papers\npython scripts/arxiv_scanner.py --days=7 --min-score=7.0\n\n# Search specific topic\npython scripts/arxiv_scanner.py --query=\"multi-agent orchestration\" --max-results=50\n\n# Full scan with export\npython scripts/arxiv_scanner.py --days=30 --export-md arxiv_report.md --verbose\n```\n\n### pattern_similarity_checker.py\n\nDetect potentially duplicate or very similar patterns.\n\n**Usage:**\n```bash\n# Check a single pattern against existing patterns\npython scripts/pattern_similarity_checker.py patterns/new-pattern.md\n\n# Check all patterns against each other\npython scripts/pattern_similarity_checker.py --all\n\n# Custom threshold and export\npython scripts/pattern_similarity_checker.py --all --threshold=0.7 --export report.md\n```\n\n**Options:**\n- `--all, -a`: Check all patterns against each other\n- `--patterns-dir, -d`: Path to patterns directory (default: patterns)\n- `--threshold, -t`: Similarity threshold for reporting (default: 0.5)\n- `--export, -e`: Export report to Markdown file\n\n### pattern_validator.py\n\nValidate pattern files for completeness and quality.\n\n**Usage:**\n```bash\n# Validate a single pattern\npython scripts/pattern_validator.py patterns/new-pattern.md\n\n# Validate all patterns\npython scripts/pattern_validator.py --all --verbose\n\n# Export validation report\npython scripts/pattern_validator.py --all --export validation_report.md\n```\n\n**Options:**\n- `--all, -a`: Validate all pattern files\n- `--patterns-dir, -d`: Path to patterns directory (default: patterns)\n- `--verbose, -v`: Print detailed output for each issue\n- `--strict, -s`: Treat warnings as errors\n- `--export, -e`: Export report to Markdown file\n\n## Next Steps After Discovery\n\nAfter identifying candidate papers from arXiv:\n\n1. **Extract the Pattern**: Use the `create-pattern` skill with the paper URL or PDF\n2. **Validate**: Run `pattern_validator.py` on the new pattern file\n3. **Check for Duplicates**: Run `pattern_similarity_checker.py` on the new pattern\n4. **Review**: Ensure the pattern meets the quality threshold (score >= 5.0)\n5. **Commit**: Add the pattern to the repository\n\n## Quality Scoring\n\nPapers are scored using the Pattern Quality Rubric (see RUBRIC.md for details):\n\n- **Reusability (30%)**: Domain-specific → Multi-domain → Universal\n- **Novelty (25%)**: Existing → Incremental → Fundamentally new\n- **Clarity (20%)**: Vague → Clear → Crystal clear\n- **Evidence (15%)**: No eval → Some eval → Strong empirical\n- **Completeness (10%)**: Idea only → Partial details → Production-ready\n\n**Threshold**: Score >= 5.0 qualifies for pattern extraction\n","skills/pr-review/SKILL.md":"---\nname: awesome-agentic-patterns-pr-review\ndescription: Review pull requests for the awesome-agentic-patterns repository. Use when asked to validate a PR, assess whether a contribution fits the repo, inspect pattern submissions under patterns/, check merge readiness, repair a small submission issue on top of a contributor branch, draft a polite contributor comment, or apply the repository's pattern-first and non-promotional contribution policy to a GitHub pull request.\n---\n\n# Awesome Agentic Patterns PR Review\n\n## Overview\n\nReview PRs in this repository by applying the local contribution policy and checking the actual changed files. Treat `CONTRIBUTING.md` as the source of truth for acceptance criteria, `TEMPLATE.md` as the source of truth for expected pattern structure, and the validation scripts in `scripts/` as the source of truth for structural checks and generated-file expectations.\n\n## Read First\n\n- `CONTRIBUTING.md`\n- `README.md`\n- `SCHEMA.md` for the status tiers and field definitions\n- `TEMPLATE.md` at the repository root\n- `scripts/validate-patterns.ts`, the authoritative front-matter and section validator\n- `scripts/build-data.ts` when the PR touches patterns, generated README sections, or generated site data\n\nDo not restate repo policy from memory when those files are available. Quote or summarize the repository's own rules instead.\n\n## Workflow\n\n### 1. Inspect the PR\n\nUse `gh` first:\n\n- `gh pr view <number> --repo nibzard/awesome-agentic-patterns --json title,number,state,isDraft,author,baseRefName,headRefName,headRepository,headRepositoryOwner,maintainerCanModify,files,additions,deletions,mergeable,mergeStateStatus,reviewDecision,statusCheckRollup,labels,url,body`\n- `gh pr diff <number> --repo nibzard/awesome-agentic-patterns --patch`\n- `gh pr checks <number> --repo nibzard/awesome-agentic-patterns`\n\nIf you need the exact branch locally, fetch it with:\n\n- `git fetch origin refs/pull/<number>/head:pr-<number>`\n\nCapture these facts before deciding anything:\n\n- Whether the PR is a new pattern submission, a pattern edit, or a broader repo/tooling change\n- Whether the change correctly uses `patterns/<slug>.md` rather than editing generated docs directly\n- Whether `README.md` or `apps/web/public/` generated outputs changed because the contributor regenerated outputs, or because they hand-edited generated files\n- Whether `maintainerCanModify` is enabled and which fork/branch must be updated if you need to fix the PR\n- Whether GitHub mergeability is trustworthy yet; `UNKNOWN` can be transient right after a push\n\n### 2. Validate the submission contract\n\nFor pattern submissions, check the repository's exact contract before debating fit:\n\n- One pattern per PR\n- New patterns live in `patterns/` and use kebab-case filenames\n- PR title should use `Add: pattern-name`\n- The pattern should be concise, roughly capped at about 200 lines\n- Do not edit README auto-generated sections manually\n- `docs/index.md` is only a compatibility symlink to `README.md`\n- Required front-matter fields (enforced by `scripts/validate-patterns.ts`):\n  `title`\n  `status`\n  `authors`\n  `category`\n  `source`\n  `tags`\n  `summary`\n  `signals`\n  `anti_signals`\n  `updated_at` in `YYYY-MM-DD` form\n- `based_on` is optional, but a contributor-owned source must be disclosed in `authors` / `based_on`\n- `source_link` is invalid here; use `source`\n- Required content sections (enforced with `--check-content`):\n  `## Problem`\n  `## Solution`\n  `## How to use it`\n  `## Trade-offs`\n  `## References`\n- Status tier, one of `proposed`, `emerging`, `production`, `foundational`, judged against the independent-adoption bar:\n\n  - A submission backed only by a contributor-owned repo, a personal experiment, or a launch-stage product must use `status: proposed`. Downgrade anything higher to `proposed`.\n  - `emerging` needs 2+ independent implementations or teams, or 1 detailed production write-up or major lab paper with active industry iteration.\n  - `production` needs proof across multiple independent production systems, with documented failure modes and operational trade-offs.\n  - `foundational` is for an industry-default baseline whenever its `signals` apply, and the catalogue keeps the tier to roughly 12-18 patterns.\n\n- Agent-centric technical scope: the pattern must describe a control loop in which an agent senses, reasons, remembers, uses tools, or stays safe. Product strategy, startup philosophy, career advice, and generic non-agent software architecture belong in `principles/`, not `patterns/`.\n- Known Implementations cap: `Known Implementations` and tool references are limited to 3-5 entries per pattern. A PR that only appends another vendor or tool link is acceptable only when the tool replaces a deprecated reference or demonstrates a materially distinct architectural variant.\n- Differentiation: the PR description must answer \"Closest existing pattern(s) & how this is distinct\" and justify why the idea cannot live as a section inside an existing pattern.\n\nBefore judging novelty, run `python3 scripts/pattern_similarity_checker.py <pattern-file.md>`, then search `patterns/` for duplicates and near-overlaps by title, tags, and Problem wording. Compare what you find with the contributor's differentiation answer. When the primary `source` or a reference belongs to the contributor or an affiliated project, confirm the relationship is disclosed and the write-up frames it as an example rather than the center of the PR.\n\nFor generated-file sync, check whether the PR also updated the outputs that CI compares against `patterns/*.md`:\n\n- `README.md`\n- `apps/web/public/data/patterns.json`\n- other generated files under `apps/web/public/` when the pattern catalog changed\n- `llms.txt` at the repository root, which `bun run build:data` keeps identical to `apps/web/public/llms.txt`\n\nCall out structural violations explicitly. These are repository requirements, not style nits.\n\n### 3. Apply local policy\n\nUse `CONTRIBUTING.md` for the actual acceptance rubric. Evaluate:\n\n- Whether the PR documents a reusable pattern rather than a product announcement\n- Whether the pattern is materially novel and non-repetitive relative to existing patterns\n- Whether the write-up clearly explains Problem, Solution, and Trade-offs or practical mechanics\n- Whether references are public and verifiable\n- Whether the contribution is community-first and non-promotional\n- Whether external links are mostly `github.com`, `github.io`, or neutral technical references for outside contributors\n- Whether any vendor or product links are justified by clear novelty rather than marketing\n- Whether contributor-owned projects are disclosed and framed as examples rather than the center of the PR\n- Whether the category is the best fit for existing repo taxonomy\n- Whether the `status` tier matches its objective criterion; a contributor-owned repo or launch-stage product is `proposed`\n- Whether the pattern is an agent-specific technical control loop rather than product strategy or generic software architecture\n- Whether the PR description names the closest existing pattern(s) and justifies why the submission is not a section inside one of them\n- Whether a reference-addition PR stays within the 3-5 entry cap and adds a tool that replaces a deprecated reference or shows a materially distinct variant\n\nSeparate policy fit from technical mergeability. A PR can be in scope but still need a maintainer fix before merge.\n\n### 4. Run structural validation\n\nWhen reviewing a local branch or checking CI behavior, run from the repository root:\n\n- `bun run validate:patterns:content` for front matter, required sections, referential integrity, status vs. evidence, and length guardrails; this is the authoritative validator, and CI runs it\n- `bun run validate:patterns` for front matter only (`scripts/validate-patterns.ts`)\n- `python3 scripts/pattern_similarity_checker.py <pattern-file.md>` to surface near-duplicates before you judge novelty\n- `bun run build:data` when checking generated README or site data changes; it also fails on a missing or malformed `updated_at`. CI syncs the root `llms.txt` alongside `README.md` and `apps/web/public/`.\n\nTreat the scripts as structural checks, not the decision-maker. Human review still decides repository fit, novelty, promotion risk, and category choice.\n\n### 5. Repair the branch when the PR is acceptable but stale\n\nIf the PR is acceptable and the user wants it fixed or merged, prefer the smallest possible maintainer correction:\n\n- Fetch the PR branch locally\n- Rebase or replay it onto `origin/main`\n- Fix only the minimum structural issue\n- Normalize front-matter keys or section headings to repo expectations\n- Regenerate `README.md` and site data with `bun run build:data` only if the PR already requires generated-file sync\n- Push back to the contributor's exact head branch, preferably with `--force-with-lease`\n- Re-check `gh pr view` after the push because `mergeable` and `mergeStateStatus` may temporarily show `UNKNOWN`\n\nDo not turn a small submission repair into a broader cleanup.\n\n### 6. Produce the review\n\nUse a code-review mindset:\n\n- Present findings first, ordered by severity, with file references when applicable\n- If there are no findings, say that explicitly\n- After findings, give one clear decision: `Accept`, `Request changes`, or `Close`\n- Include mergeability as a separate line: `clean`, `needs maintainer repair`, or `blocked`\n- When the user wants to merge, include the exact next action: `comment`, `fix and push`, `merge`, or `close`\n\n## Output Shape\n\nKeep the final review compact and consistent. Use this exact structure:\n\n`Summary`\n- One short sentence on PR state or scope if useful\n\n`Findings`\n- Findings first, ordered by severity\n- If there are no findings, say `No blocking findings.`\n\n`Decision`\n- `Policy fit: Accept | Request changes | Close`\n- `Mergeability: clean | needs maintainer repair | blocked`\n- `Recommended action: comment | fix and push | merge | close`\n\n`Proposed comment to contributor`\n- Draft a short, polite comment suitable for posting on the PR\n- If the maintainer already fixed the PR, say what was adjusted and thank the contributor\n- If requesting changes, state the minimum changes needed\n\n`What next`\n- End with a direct question to the user asking what they want next\n- Example: `Do you want me to post the comment, push the small fix, or merge it?`\n",".claude/skills/create-pattern/SKILL.md":"---\nname: create-pattern\ndescription: Analyze sources (blog posts, PDFs, YouTube videos, codebases, pasted text) for agentic patterns, match against 105+ existing patterns, create new patterns or update existing with new sources and insights.\nallowed-tools:\n  - Read\n  - Write\n  - Glob\n  - Grep\n  - Bash\n  - mcp__web_reader__webReader\n  - mcp__4_5v_mcp__analyze_image\n---\n\n# Pattern Ingestion Skill\n\nThis skill intelligently analyzes sources for agentic AI patterns, matches them against existing patterns in the repository, and either creates new patterns or updates existing ones with additional sources and insights.\n\n## Overview\n\n**Input:** A source (URL, PDF file, YouTube link, codebase path, or pasted text)\n\n**Process:**\n1. Ingest and analyze the source\n2. Extract pattern concepts\n3. Match against existing 105+ patterns\n4. Decide: create new OR update existing\n5. Execute and build\n\n**Output:** New pattern file OR updated existing pattern + build confirmation\n\n---\n\n## Phase 1: Ingest Source\n\nDetect the input type and process accordingly:\n\n### URL (blog post, documentation, article)\nUse `mcp__web_reader__webReader` with the URL:\n```json\n{\"url\": \"USER_PROVIDED_URL\", \"return_format\": \"markdown\"}\n```\n\n### PDF File\nUse `Read` tool with the PDF path.\n\n### YouTube Video\nUse `mcp__web_reader__webReader` with the YouTube URL (transcript extraction).\n\n### Codebase/Repository\nUse `Glob` to find key files, then `Read` to analyze:\n- `**/*.md` - Documentation\n- `**/*.py` - Python implementation\n- `**/*.ts` - TypeScript implementation\n- README files\n\n### Pasted Text\nAnalyze directly (no tool needed).\n\n---\n\n## Phase 2: Analyze & Extract\n\nFrom the source content, extract:\n\n1. **Pattern Title** - What is this pattern called?\n2. **Problem Statement** - What challenge does it solve?\n3. **Solution** - What's the core approach/mechanism?\n4. **Category** - Which of 8 categories fits best?\n5. **Source URL** - The original source\n6. **Author/Originator** - Who created/originated this?\n7. **Tags** - 3+ relevant keywords\n8. **Key Insights** - Any novel techniques, constraints, trade-offs\n\n**Generate candidate metadata:**\n- Title: descriptive, concise\n- Category: select from allowed categories (see reference below)\n- Tags: generate 5-10 relevant tags\n- Status: default to \"emerging\" unless evidence suggests otherwise\n\n---\n\n## Phase 3: Match Against Existing Patterns\n\nSearch for similar patterns in `patterns/` directory:\n\n### Step 3a: Read All Pattern Frontmatter\nUse `Glob` to find all `.md` files in `patterns/`, then `Grep` with output_mode `content` to extract frontmatter from each:\n```bash\ngrep -A 10 \"^title:\" patterns/*.md\n```\n\nOr read multiple pattern files in parallel to compare:\n- Problem statements\n- Solution approaches\n- Categories\n- Tags\n- Sources\n\n### Step 3b: Semantic Comparison\n\nFor each existing pattern, assess similarity using these signals:\n\n**Primary Signals (weight: 30% each)**\n1. **Problem Statement** - Same fundamental challenge?\n2. **Solution Mechanism** - Same core approach/technique?\n3. **Category** - Same category?\n\n**Secondary Signals (weight: 10% each)**\n4. **Tag Overlap** - Shared keywords?\n5. **Source/Author** - Same contributor's follow-up work?\n6. **Title** - Similar naming/description?\n\n### Step 3c: Calculate Confidence Score\n\n```\nScore = Σ(matching_signals × weights)\n```\n\n- All 3 primary match → 90%+ confidence\n- 2 primary + 1+ secondary → 70-90% confidence\n- 1 primary + 2+ secondary → 50-70% confidence\n- 0-1 primary only → <50% confidence\n\n### Step 3d: Identify Top Matches\n\nList top 3 matching patterns with:\n- Pattern title and file path\n- Confidence score\n- Matching rationale (which signals matched)\n\n---\n\n## Phase 4: Decision\n\nBased on confidence score:\n\n### High Confidence (>80%) → Update Existing\nUpdate the top-matching existing pattern with new source.\n\n### Low Confidence (<50%) → Create New\nCreate a brand new pattern file.\n\n### Medium Confidence (50-80%) → Ask User\nPresent the top match and ask:\n\n```\nThis source seems related to:\n- [Match Pattern] (X% confidence)\n  - Similar problem: [problem summary]\n  - Similar solution: [solution summary]\n\nShould I:\n1. Create a new pattern\n2. Update the existing pattern with this new source\n```\n\n---\n\n## Phase 5a: Create New Pattern\n\n### Step 5a-1: Generate Metadata\n```yaml\n---\ntitle: \"Extracted Title\"\nstatus: emerging\nauthors: [\"Your Name (@yourusername)\"]\nbased_on: [\"Originator Name (Source/Context)\"]\ncategory: \"Selected Category\"\nsource: \"SOURCE_URL\"\ntags: [tag1, tag2, tag3, ...]\n---\n```\n\n### Step 5a-2: Generate Slug\nConvert title to kebab-case:\n- Lowercase\n- Spaces → hyphens\n- Remove special characters\n- Example: \"Tree of Thought Reasoning\" → `tree-of-thought-reasoning`\n\n### Step 5a-3: Write Pattern File\nCreate `patterns/{slug}.md` with structure:\n\n```markdown\n---\ntitle: \"Title\"\nstatus: emerging\nauthors: [\"Your Name (@yourusername)\"]\nbased_on: [\"Originator (Source)\"]\ncategory: \"Category\"\nsource: \"URL\"\ntags: [tag1, tag2, tag3]\n---\n\n## Problem\n[Extracted problem statement]\n\n## Solution\n[Extracted solution description]\n\n- Key components: [list]\n- Mechanism: [describe]\n\n```pseudo\n[Optional: pseudocode if helpful]\n```\n\n## How to use it\n[Extracted usage guidance]\n\n## Trade-offs\n[Extracted pros and cons]\n\n* **Pros:** [benefits]\n* **Cons:** [drawbacks]\n\n## References\n* [Original Source Title](URL)\n```\n\n---\n\n## Phase 5b: Update Existing Pattern\n\n### Step 5b-1: Read Existing Pattern\nRead the matched pattern file at `patterns/{existing-slug}.md`\n\n### Step 5b-2: Update Frontmatter\n\n**Add to `based_on` array:**\n```yaml\nbased_on:\n  - \"Existing Source (Existing Context)\"\n  - \"New Originator (New Source/Context)\"  # Add this\n```\n\n**Add new tags** (if not duplicates):\n```yaml\ntags:\n  - existing-tag\n  - new-tag-from-source  # Add unique new tags\n```\n\n### Step 5b-3: Add to References Section\n\nAppend to the `## References` section:\n```markdown\n## References\n* [Existing Source](existing-url)\n* [New Source Title](new-url)  # Add this\n```\n\n### Step 5b-4: Auto-Expand Content (If Applicable)\n\n**IF** the new source adds substantial new insights (not just a citation):\n\n**To Solution section:**\n```markdown\n## Solution\n[existing content...]\n\n**Additional insights from [New Source]:**\n[Extracted new insights with attribution]\n```\n\n**To How to use it section:**\n```markdown\n## How to use it\n[existing content...]\n\n**According to [New Source]:**\n[New usage guidance or implementation details]\n```\n\n**To Trade-offs section:**\n```markdown\n## Trade-offs\n* **Pros:** [existing..., new pros from source]\n* **Cons:** [existing..., new cons from source]\n```\n\n### Step 5b-5: Write Updated File\nWrite the updated content back to `patterns/{existing-slug}.md`\n\n---\n\n## Phase 6: Build\n\n### Step 6-1: Run Build Script\n```bash\ncd apps/web && bun run build-data\n```\n\n### Step 6-2: Verify Success\nCheck for:\n- Pattern JSON files updated in `apps/web/public/patterns/`\n- No error messages\n\n---\n\n## Reference: Allowed Values\n\n### Categories (8 options)\n- Orchestration & Control\n- Context & Memory\n- Feedback Loops\n- Learning & Adaptation\n- Reliability & Eval\n- Security & Safety\n- Tool Use & Environment\n- UX & Collaboration\n- Uncategorized\n\n### Status Values (7 options)\n- proposed - Initial concept\n- emerging - Early adoption\n- established - Proven approach\n- validated-in-production - Production-tested\n- best-practice - Industry standard\n- experimental-but-awesome - Novel but effective\n- rapidly-improving - Fast-evolving\n\n### Front-matter Template\n```yaml\n---\ntitle: \"Pattern Title\"\nstatus: emerging\nauthors: [\"Contributor Name (@username)\"]\nbased_on: [\"Originator Name (Source Context)\"]\ncategory: \"Category Name\"\nsource: \"https://example.com/source\"\ntags: [tag1, tag2, tag3]\n---\n```\n\n---\n\n## Output Summary\n\nAfter completion, provide:\n\n**For New Pattern:**\n```\n✅ Created new pattern: patterns/{slug}.md\n- Title: [title]\n- Category: [category]\n- Tags: [tags]\n\nNext steps:\n1. Review and edit the pattern file for completeness\n2. Run: cd apps/web && bun run dev\n3. Commit: git add patterns/{slug}.md\n```\n\n**For Updated Pattern:**\n```\n✅ Updated existing pattern: patterns/{slug}.md\n- Added source to based_on: [source]\n- Added [N] new tags\n- [Expanded Solution/How-to sections]\n\nNext steps:\n1. Review the updated pattern file\n2. Run: cd apps/web && bun run dev\n3. Commit: git add patterns/{slug}.md\n```\n\n---\n\n## Tips\n\n- **When in doubt, ask the user** - Pattern matching can be nuanced\n- **Preserve existing content** - When updating, don't remove or overwrite existing insights\n- **Clear attribution** - Always cite sources when adding new content\n- **Tag thoughtfully** - Tags help with future matching\n- **Check for duplicates** - If `based_on` already includes the source, just inform the user\n","llms.txt":"# Awesome Agentic Patterns\n\nA curated catalogue of AI agent design patterns.\n\nEvery pattern is also available as Markdown at https://agentic-patterns.com/patterns/<slug>.md. Full text of all patterns: https://agentic-patterns.com/llms-full.txt. Usage notes for agents: https://agentic-patterns.com/agents.\n\n## Patterns\n\n### 402-first-machine-payments\n402-First Machine Payments (Price-Before-Work Tool Purchases): Server returns an HTTP 402 price quote before doing work, and the agent pays the exact amount only if it fits its budget cap\nURL: https://agentic-patterns.com/patterns/402-first-machine-payments\nMarkdown: https://agentic-patterns.com/patterns/402-first-machine-payments.md\n\n### abstracted-code-representation-for-review\nAbstracted Code Representation for Review: Shows reviewers pseudocode, intent summaries, and logical diffs of code changes, with drill-down to the real code to confirm the mapping\nURL: https://agentic-patterns.com/patterns/abstracted-code-representation-for-review\nMarkdown: https://agentic-patterns.com/patterns/abstracted-code-representation-for-review.md\n\n### action-caching-replay\nAction Caching & Replay Pattern: Records each agent action with XPath and frame metadata so later runs replay it without LLM calls, with LLM fallback when replay fails\nURL: https://agentic-patterns.com/patterns/action-caching-replay\nMarkdown: https://agentic-patterns.com/patterns/action-caching-replay.md\n\n### action-selector-pattern\nAction-Selector Pattern: LLM maps user intent to a pre-approved action ID with schema-validated parameters, and tool outputs never return to the selector\nURL: https://agentic-patterns.com/patterns/action-selector-pattern\nMarkdown: https://agentic-patterns.com/patterns/action-selector-pattern.md\n\n### adaptive-sandbox-fanout-controller\nAdaptive Sandbox Fan-Out Controller: Starts a small batch of parallel sandboxes, then scales up, stops early, or refines the prompt based on early success, variance, and error signals\nURL: https://agentic-patterns.com/patterns/adaptive-sandbox-fanout-controller\nMarkdown: https://agentic-patterns.com/patterns/adaptive-sandbox-fanout-controller.md\n\n### agent-circuit-breaker\nAgent Circuit Breaker: Prevents agents from wasting tokens and time on repeatedly failing tools by tracking failure rates and temporarily disabling broken tool endpoints\nURL: https://agentic-patterns.com/patterns/agent-circuit-breaker\nMarkdown: https://agentic-patterns.com/patterns/agent-circuit-breaker.md\n\n### agent-modes-by-model-personality\nAgent Modes by Model Personality: Offers separate working modes, each with its own prompts, tools, UI, and expectations, tuned to one model's working style\nURL: https://agentic-patterns.com/patterns/agent-modes-by-model-personality\nMarkdown: https://agentic-patterns.com/patterns/agent-modes-by-model-personality.md\n\n### agent-reinforcement-fine-tuning\nAgent Reinforcement Fine-Tuning (Agent RFT): Trains model weights with reinforcement learning on real tool calls and custom graders to improve domain-specific tool use and multi-step reasoning\nURL: https://agentic-patterns.com/patterns/agent-reinforcement-fine-tuning\nMarkdown: https://agentic-patterns.com/patterns/agent-reinforcement-fine-tuning.md\n\n### agent-sdk-for-programmatic-control\nAgent SDK for Programmatic Control: Exposes agent functions through an SDK and CLI so code can run the agent headless with set tools, permissions, and resource limits\nURL: https://agentic-patterns.com/patterns/agent-sdk-for-programmatic-control\nMarkdown: https://agentic-patterns.com/patterns/agent-sdk-for-programmatic-control.md\n\n### agent-assisted-scaffolding\nAgent-Assisted Scaffolding: Agent generates initial files, boilerplate, and directory structure from a high-level description so developers start on core logic\nURL: https://agentic-patterns.com/patterns/agent-assisted-scaffolding\nMarkdown: https://agentic-patterns.com/patterns/agent-assisted-scaffolding.md\n\n### agent-driven-research\nAgent-Driven Research: Agent plans its own queries, fans out parallel search workers across sources, reflects on evidence gaps, and iterates until it can write a sourced report\nURL: https://agentic-patterns.com/patterns/agent-driven-research\nMarkdown: https://agentic-patterns.com/patterns/agent-driven-research.md\n\n### agent-first-tool-discovery\nAgent-First Tool Discovery: Indexes tools and agents across MCP registries, A2A cards, OpenAPI specs, and custom directories into one normalized search surface ranked by agent-relevant signals\nURL: https://agentic-patterns.com/patterns/agent-first-tool-discovery\nMarkdown: https://agentic-patterns.com/patterns/agent-first-tool-discovery.md\n\n### agent-first-tooling-and-logging\nAgent-First Tooling and Logging: Designs logs and tool output for agent consumption with one unified log stream, structured JSON, and agent-aware CLI flags\nURL: https://agentic-patterns.com/patterns/agent-first-tooling-and-logging\nMarkdown: https://agentic-patterns.com/patterns/agent-first-tooling-and-logging.md\n\n### agent-friendly-workflow-design\nAgent-Friendly Workflow Design: Gives agents clear high-level goals, room for implementation choices, structured I/O, and plan review before execution\nURL: https://agentic-patterns.com/patterns/agent-friendly-workflow-design\nMarkdown: https://agentic-patterns.com/patterns/agent-friendly-workflow-design.md\n\n### agent-powered-codebase-qa-onboarding\nAgent-Powered Codebase Q&A / Onboarding: Agent indexes the codebase with embeddings and code graphs and answers natural-language questions about where code is and how it behaves\nURL: https://agentic-patterns.com/patterns/agent-powered-codebase-qa-onboarding\nMarkdown: https://agentic-patterns.com/patterns/agent-powered-codebase-qa-onboarding.md\n\n### agentic-search-over-vector-embeddings\nAgentic Search Over Vector Embeddings: Replaces vector indexes with agent-driven grep, find, and file traversal that searches current file state on demand and refines iteratively\nURL: https://agentic-patterns.com/patterns/agentic-search-over-vector-embeddings\nMarkdown: https://agentic-patterns.com/patterns/agentic-search-over-vector-embeddings.md\n\n### ai-assisted-code-review-verification\nAI-Assisted Code Review / Verification: Uses AI tools to flag issues, summarize change intent, and explain code so human reviewers focus on intent and business logic\nURL: https://agentic-patterns.com/patterns/ai-assisted-code-review-verification\nMarkdown: https://agentic-patterns.com/patterns/ai-assisted-code-review-verification.md\n\n### anchored-structured-context-compaction\nAnchored Structured Context Compaction: Maintains a typed state block (pinned goal and constraints, verified decisions, an artifact registry, open blockers) and merges only the newly evicted span into it at each compaction, so that long sessions keep exact details instead of drifting\nURL: https://agentic-patterns.com/patterns/anchored-structured-context-compaction\nMarkdown: https://agentic-patterns.com/patterns/anchored-structured-context-compaction.md\n\n### anti-reward-hacking-grader-design\nAnti-Reward-Hacking Grader Design: Design reward functions with multi-criteria evaluation and iterative hardening to prevent models from gaming graders, ensuring training rewards align with actual task quality.\nURL: https://agentic-patterns.com/patterns/anti-reward-hacking-grader-design\nMarkdown: https://agentic-patterns.com/patterns/anti-reward-hacking-grader-design.md\n\n### multi-step-analysis-pipeline-orchestration\nArtifact-Driven Analysis Pipeline Orchestration: Has an agent run independent analysis scripts, read their structured reports, and merge them into one final report or visualization\nURL: https://agentic-patterns.com/patterns/multi-step-analysis-pipeline-orchestration\nMarkdown: https://agentic-patterns.com/patterns/multi-step-analysis-pipeline-orchestration.md\n\n### asynchronous-coding-agent-pipeline\nAsynchronous Coding Agent Pipeline: Splits inference, tool execution, reward modeling, and learning into asynchronous workers linked by message queues so GPUs stay busy\nURL: https://agentic-patterns.com/patterns/asynchronous-coding-agent-pipeline\nMarkdown: https://agentic-patterns.com/patterns/asynchronous-coding-agent-pipeline.md\n\n### authenticated-authority-channel\nAuthenticated Authority Channel: Preserve a distinguishable channel for authenticated intent so retrieved content can inform reasoning without granting itself authority.\nURL: https://agentic-patterns.com/patterns/authenticated-authority-channel\nMarkdown: https://agentic-patterns.com/patterns/authenticated-authority-channel.md\n\n### autonomous-workflow-agent-architecture\nAutonomous Workflow Agent Architecture: Runs multi-step engineering workflows in containers with tmux sessions, sleep-based monitoring, checkpoints, and context-aware error recovery\nURL: https://agentic-patterns.com/patterns/autonomous-workflow-agent-architecture\nMarkdown: https://agentic-patterns.com/patterns/autonomous-workflow-agent-architecture.md\n\n### background-agent-ci\nBackground Agent with CI Feedback: Runs the agent in the background on its own branch and uses CI results as feedback to patch failures until green or blocked\nURL: https://agentic-patterns.com/patterns/background-agent-ci\nMarkdown: https://agentic-patterns.com/patterns/background-agent-ci.md\n\n### black-box-skill-invocation\nBlack-Box Skill Invocation: Shares skills through input and output schemas only and runs them on the provider side, so prompts and code never cross the boundary\nURL: https://agentic-patterns.com/patterns/black-box-skill-invocation\nMarkdown: https://agentic-patterns.com/patterns/black-box-skill-invocation.md\n\n### board-mediated-inter-agent-coordination\nBoard-Mediated Async Inter-Agent Coordination: Routes agent-to-agent messages through comment threads on board cards, with a prefix that creates an inbox card to notify the target agent\nURL: https://agentic-patterns.com/patterns/board-mediated-inter-agent-coordination\nMarkdown: https://agentic-patterns.com/patterns/board-mediated-inter-agent-coordination.md\n\n### budget-aware-model-routing-with-hard-cost-caps\nBudget-Aware Model Routing with Hard Cost Caps: Routes each request to the cheapest model that meets its needs under hard cost caps, and escalates only when quality gates fail\nURL: https://agentic-patterns.com/patterns/budget-aware-model-routing-with-hard-cost-caps\nMarkdown: https://agentic-patterns.com/patterns/budget-aware-model-routing-with-hard-cost-caps.md\n\n### canary-rollout-and-automatic-rollback-for-agent-policy-changes\nCanary Rollout and Automatic Rollback for Agent Policy Changes: Ships agent policy changes to a small traffic slice first, monitors guardrail metrics, and rolls back to the last stable version automatically\nURL: https://agentic-patterns.com/patterns/canary-rollout-and-automatic-rollback-for-agent-policy-changes\nMarkdown: https://agentic-patterns.com/patterns/canary-rollout-and-automatic-rollback-for-agent-policy-changes.md\n\n### capability-escrow-receipt\nCapability-Escrow-Receipt: Binds a signed capability listing, an atomic escrow-plus-hire step, and a signed work receipt into one loop for agent-to-agent payment\nURL: https://agentic-patterns.com/patterns/capability-escrow-receipt\nMarkdown: https://agentic-patterns.com/patterns/capability-escrow-receipt.md\n\n### chain-of-thought-monitoring-interruption\nChain-of-Thought Monitoring & Interruption: Streams agent reasoning and tool calls in real time so a human can interrupt and redirect early when the approach is wrong\nURL: https://agentic-patterns.com/patterns/chain-of-thought-monitoring-interruption\nMarkdown: https://agentic-patterns.com/patterns/chain-of-thought-monitoring-interruption.md\n\n### classify-then-act-for-background-agents\nClassify-Then-Act for Background Agents: Sorts each task into has-default, needs-intent, or out-of-scope, builds only has-default work in a sandbox, and queues it for human review\nURL: https://agentic-patterns.com/patterns/classify-then-act-for-background-agents\nMarkdown: https://agentic-patterns.com/patterns/classify-then-act-for-background-agents.md\n\n### cli-native-agent-orchestration\nCLI-Native Agent Orchestration: Drives agents through their non-interactive CLI mode (claude -p with JSON output and exit codes) so Makefiles, Git hooks, cron jobs, and CI can script and replay agent runs\nURL: https://agentic-patterns.com/patterns/cli-native-agent-orchestration\nMarkdown: https://agentic-patterns.com/patterns/cli-native-agent-orchestration.md\n\n### code-over-api-pattern\nCode-Over-API (Code Mode): Agent writes code that calls tools and processes data inside a sandbox, so only summaries and samples return to the context window instead of every intermediate result\nURL: https://agentic-patterns.com/patterns/code-over-api-pattern\nMarkdown: https://agentic-patterns.com/patterns/code-over-api-pattern.md\n\n### code-then-execute-pattern\nCode-Then-Execute Pattern: LLM writes a sandboxed program or DSL script, a static taint checker verifies data flows, and an interpreter runs it in a locked sandbox\nURL: https://agentic-patterns.com/patterns/code-then-execute-pattern\nMarkdown: https://agentic-patterns.com/patterns/code-then-execute-pattern.md\n\n### codebase-optimization-for-agents\nCodebase Optimization for Agents: Optimizes tooling, CLIs, tests, and docs for agents first, with one-command verify loops and machine-readable output, even if human DX regresses\nURL: https://agentic-patterns.com/patterns/codebase-optimization-for-agents\nMarkdown: https://agentic-patterns.com/patterns/codebase-optimization-for-agents.md\n\n### commitment-ledger-reality-gated-credit\nCommitment Ledger with Reality-Gated Credit: Records agent promises and credits retrieved memory only after an externally verifiable outcome settles.\nURL: https://agentic-patterns.com/patterns/commitment-ledger-reality-gated-credit\nMarkdown: https://agentic-patterns.com/patterns/commitment-ledger-reality-gated-credit.md\n\n### compounding-engineering-pattern\nCompounding Engineering Pattern: After each feature, codifies agent mistakes and learnings into CLAUDE.md, slash commands, subagents, and hooks so the next feature is easier to build\nURL: https://agentic-patterns.com/patterns/compounding-engineering-pattern\nMarkdown: https://agentic-patterns.com/patterns/compounding-engineering-pattern.md\n\n### parallel-tool-execution\nConditional Parallel Tool Execution: Runs a batch of tool calls in parallel when all are read-only and in sequence when any modifies state, then returns results in request order\nURL: https://agentic-patterns.com/patterns/parallel-tool-execution\nMarkdown: https://agentic-patterns.com/patterns/parallel-tool-execution.md\n\n### consequence-family-coverage-audit\nConsequence-Family Coverage Audit: Audit an agent's risk policy by enumerating families of consequence and asking which rule covers each, because a hand-written risk list reliably encodes one family and stays silent on the rest\nURL: https://agentic-patterns.com/patterns/consequence-family-coverage-audit\nMarkdown: https://agentic-patterns.com/patterns/consequence-family-coverage-audit.md\n\n### context-budget-as-a-governed-resource\nContext Budget as a Governed Resource: Measures always-loaded context per source, alerts on trend growth, and puts hard spend caps and fan-out bounds on unattended agent runs\nURL: https://agentic-patterns.com/patterns/context-budget-as-a-governed-resource\nMarkdown: https://agentic-patterns.com/patterns/context-budget-as-a-governed-resource.md\n\n### context-window-anxiety-management\nContext Window Anxiety Management: Enables a large context window but caps usage lower, and adds prompts that state the token budget so the model does not rush to finish\nURL: https://agentic-patterns.com/patterns/context-window-anxiety-management\nMarkdown: https://agentic-patterns.com/patterns/context-window-anxiety-management.md\n\n### context-window-auto-compaction\nContext Window Auto-Compaction: Catches context overflow errors, compacts and validates the transcript with capped reserve headroom, and retries the request automatically\nURL: https://agentic-patterns.com/patterns/context-window-auto-compaction\nMarkdown: https://agentic-patterns.com/patterns/context-window-auto-compaction.md\n\n### context-minimization-pattern\nContext-Minimization Pattern: Removes untrusted user text and tool output from context after it becomes a safe structured artifact, so later steps see only trusted data\nURL: https://agentic-patterns.com/patterns/context-minimization-pattern\nMarkdown: https://agentic-patterns.com/patterns/context-minimization-pattern.md\n\n### continuous-autonomous-task-loop-pattern\nContinuous Autonomous Task Loop Pattern: Runs a loop where subagents pick the next task from a todo file, execute it in fresh context, commit it, and back off on rate limits\nURL: https://agentic-patterns.com/patterns/continuous-autonomous-task-loop-pattern\nMarkdown: https://agentic-patterns.com/patterns/continuous-autonomous-task-loop-pattern.md\n\n### credential-free-outbox\nCredential-Free Outbox: The agent writes finished work as a file to an outbox and a separate short-lived job with its own token delivers it, so the agent never holds a credential that can publish anything\nURL: https://agentic-patterns.com/patterns/credential-free-outbox\nMarkdown: https://agentic-patterns.com/patterns/credential-free-outbox.md\n\n### criticgpt-style-evaluation\nCriticGPT-Style Code Review: Runs a specialized critic model over generated code to find bugs, security flaws, and quality issues, and feeds critical findings back for regeneration\nURL: https://agentic-patterns.com/patterns/criticgpt-style-evaluation\nMarkdown: https://agentic-patterns.com/patterns/criticgpt-style-evaluation.md\n\n### cross-agent-lesson-sharing\nCross-Agent Lesson Sharing via Git: Agents write solved problems as markdown lessons in a shared Git repo and search them before debugging, with GitHub Issues as the coordination layer\nURL: https://agentic-patterns.com/patterns/cross-agent-lesson-sharing\nMarkdown: https://agentic-patterns.com/patterns/cross-agent-lesson-sharing.md\n\n### cross-cycle-consensus-relay\nCross-Cycle Consensus Relay: Each loop cycle reads a structured relay document, does its work, and atomically writes back decisions, open questions, and the single next action\nURL: https://agentic-patterns.com/patterns/cross-cycle-consensus-relay\nMarkdown: https://agentic-patterns.com/patterns/cross-cycle-consensus-relay.md\n\n### cross-domain-agent-conflict-resolution\nCross-Domain Agent Conflict Resolution: A coordination layer that cross-references recommendations from independent domain agents, detects conflicts on shared resources, and resolves them through policy-as-code.\nURL: https://agentic-patterns.com/patterns/cross-domain-agent-conflict-resolution\nMarkdown: https://agentic-patterns.com/patterns/cross-domain-agent-conflict-resolution.md\n\n### cryptographic-governance-audit-trail\nCryptographic Governance Audit Trail: Middleware checks each tool call against a policy file, then signs a receipt of the action with ML-DSA and appends it to a tamper-evident chain\nURL: https://agentic-patterns.com/patterns/cryptographic-governance-audit-trail\nMarkdown: https://agentic-patterns.com/patterns/cryptographic-governance-audit-trail.md\n\n### curated-code-context-window\nCurated Code Context Window: A search subagent finds the few relevant files for a task and injects only top snippets or summaries into the main coding agent's context\nURL: https://agentic-patterns.com/patterns/curated-code-context-window\nMarkdown: https://agentic-patterns.com/patterns/curated-code-context-window.md\n\n### custom-sandboxed-background-agent\nCustom Sandboxed Background Agent: Builds an in-house background coding agent that runs in sandboxed dev environments, streams progress over WebSocket, and iterates on compiler and test feedback\nURL: https://agentic-patterns.com/patterns/custom-sandboxed-background-agent\nMarkdown: https://agentic-patterns.com/patterns/custom-sandboxed-background-agent.md\n\n### dead-mans-switch-for-scheduled-agent-jobs\nDead-Man's Switch for Scheduled Agent Jobs: Each scheduled job writes a success sentinel to its log, and a separate checker files a task when the sentinel is missing or stale\nURL: https://agentic-patterns.com/patterns/dead-mans-switch-for-scheduled-agent-jobs\nMarkdown: https://agentic-patterns.com/patterns/dead-mans-switch-for-scheduled-agent-jobs.md\n\n### debiased-llm-as-a-judge-evaluation\nDebiased LLM-as-a-Judge Evaluation: Removes the systematic distortions of a model judge before its scores gate a release: swaps the order of each pairwise comparison, grades narrow pass/fail rubric items that cite evidence, supplies a reference answer and a judge from another model family, and measures the agreement with human labels first\nURL: https://agentic-patterns.com/patterns/debiased-llm-as-a-judge-evaluation\nMarkdown: https://agentic-patterns.com/patterns/debiased-llm-as-a-judge-evaluation.md\n\n### declarative-multi-agent-topology-definition\nDeclarative Multi-Agent Topology Definition: Define multi-agent systems declaratively in a single topology file — agents, flows, gates, hooks, group chats — then compile to platform-specific configurations for any agentic framework.\nURL: https://agentic-patterns.com/patterns/declarative-multi-agent-topology-definition\nMarkdown: https://agentic-patterns.com/patterns/declarative-multi-agent-topology-definition.md\n\n### delegated-user-auth-token-exchange\nDelegated User Authorization (OAuth Token Exchange): Exchanges the user's token and the agent's own identity for a short-lived, single-audience, minimally scoped token immediately before each tool call, so that the agent acts with delegated and attributable authority instead of a shared super-credential\nURL: https://agentic-patterns.com/patterns/delegated-user-auth-token-exchange\nMarkdown: https://agentic-patterns.com/patterns/delegated-user-auth-token-exchange.md\n\n### denial-tracking-permission-escalation\nDenial Tracking & Permission Escalation: Track repeated tool denials and auto-escalate to blanket permission prompts or fallback strategies, preventing wasted iterations in non-interactive contexts.\nURL: https://agentic-patterns.com/patterns/denial-tracking-permission-escalation\nMarkdown: https://agentic-patterns.com/patterns/denial-tracking-permission-escalation.md\n\n### design-time-file-partition\nDesign-Time File Partition as Concurrency Control: Each task declares every path it will write; overlapping tasks get a blocking dependency so only disjoint work runs at once on a shared checkout\nURL: https://agentic-patterns.com/patterns/design-time-file-partition\nMarkdown: https://agentic-patterns.com/patterns/design-time-file-partition.md\n\n### deterministic-grader-in-the-loop\nDeterministic Grader in the Loop: Replace the LLM-as-judge in an agent's self-review loop with a deterministic scorer that returns the raw counts behind each sub-score, so the agent has something specific to fix.\nURL: https://agentic-patterns.com/patterns/deterministic-grader-in-the-loop\nMarkdown: https://agentic-patterns.com/patterns/deterministic-grader-in-the-loop.md\n\n### deterministic-security-scanning-build-loop\nDeterministic Security Scanning Build Loop: Adds SAST, SCA, and secret scanners to the build target that the agent must run after each change, so scanner failures force the agent to fix the code\nURL: https://agentic-patterns.com/patterns/deterministic-security-scanning-build-loop\nMarkdown: https://agentic-patterns.com/patterns/deterministic-security-scanning-build-loop.md\n\n### deterministic-threat-rule-scanning\nDeterministic Threat Rule Scanning: Apply deterministic regex rules as a first-pass security layer to detect known threat patterns in AI agent tool calls and skill definitions.\nURL: https://agentic-patterns.com/patterns/deterministic-threat-rule-scanning\nMarkdown: https://agentic-patterns.com/patterns/deterministic-threat-rule-scanning.md\n\n### deterministic-zero-llm-orchestration\nDeterministic Zero-LLM Orchestration: A deterministic code orchestrator splits goals, runs parallel coding agents, verifies with tests, and commits, spending LLM tokens only on the one-time goal decomposition\nURL: https://agentic-patterns.com/patterns/deterministic-zero-llm-orchestration\nMarkdown: https://agentic-patterns.com/patterns/deterministic-zero-llm-orchestration.md\n\n### discrete-phase-separation\nDiscrete Phase Separation: Splits work into separate research, planning, and implementation conversations, each with fresh context, passing only distilled outputs between phases\nURL: https://agentic-patterns.com/patterns/discrete-phase-separation\nMarkdown: https://agentic-patterns.com/patterns/discrete-phase-separation.md\n\n### distributed-execution-cloud-workers\nDistributed Execution with Cloud Workers: Runs many agent sessions in parallel on cloud workers, each in its own git worktree, with dependency-aware scheduling, merge coordination, and approval gates\nURL: https://agentic-patterns.com/patterns/distributed-execution-cloud-workers\nMarkdown: https://agentic-patterns.com/patterns/distributed-execution-cloud-workers.md\n\n### dual-llm-pattern\nDual LLM Pattern: Splits work between a privileged LLM that calls tools but never sees untrusted data and a quarantined LLM that reads untrusted data but has no tools\nURL: https://agentic-patterns.com/patterns/dual-llm-pattern\nMarkdown: https://agentic-patterns.com/patterns/dual-llm-pattern.md\n\n### dual-rail-message-delivery\nDual-Rail Message Delivery: Sends every inter-agent message on two independent channels through one entry point, alerts when the rails diverge, and requires ACKs to confirm completion\nURL: https://agentic-patterns.com/patterns/dual-rail-message-delivery\nMarkdown: https://agentic-patterns.com/patterns/dual-rail-message-delivery.md\n\n### dual-speed-talker-reasoner-architecture\nDual-Speed Realtime Architecture (Talker-Reasoner): Splits an agent into a fast Talker that owns the live conversation and a slow Reasoner that plans and calls tools in the background, with a shared belief state as their only coupling, so that the user gets a reply at once while the deep work runs\nURL: https://agentic-patterns.com/patterns/dual-speed-talker-reasoner-architecture\nMarkdown: https://agentic-patterns.com/patterns/dual-speed-talker-reasoner-architecture.md\n\n### dual-use-tool-design\nDual-Use Tool Design: Builds each tool or skill as one CLI interface that both humans and agents call, with JSON output, exit codes, and the same permissions and logs\nURL: https://agentic-patterns.com/patterns/dual-use-tool-design\nMarkdown: https://agentic-patterns.com/patterns/dual-use-tool-design.md\n\n### durable-execution-step-checkpointing\nDurable Execution & Step Checkpointing: Replays a durable step history to resume crashed, rate-limited, or approval-paused agent runs from the last completed step, without repeating finished LLM calls or committed side effects\nURL: https://agentic-patterns.com/patterns/durable-execution-step-checkpointing\nMarkdown: https://agentic-patterns.com/patterns/durable-execution-step-checkpointing.md\n\n### dynamic-context-injection\nDynamic Context Injection: Lets users inject files, folders, or saved prompts into the agent's context mid-session with @-mentions and custom slash commands\nURL: https://agentic-patterns.com/patterns/dynamic-context-injection\nMarkdown: https://agentic-patterns.com/patterns/dynamic-context-injection.md\n\n### egress-lockdown-no-exfiltration-channel\nEgress Lockdown (No-Exfiltration Channel): Puts the agent behind a default-deny egress firewall with allowlisted destinations so stolen data has no outbound channel\nURL: https://agentic-patterns.com/patterns/egress-lockdown-no-exfiltration-channel\nMarkdown: https://agentic-patterns.com/patterns/egress-lockdown-no-exfiltration-channel.md\n\n### episodic-memory-retrieval-injection\nEpisodic Memory Retrieval & Injection: Writes a structured memory record after each episode and injects the top-k similar past memories as hints when a new task starts\nURL: https://agentic-patterns.com/patterns/episodic-memory-retrieval-injection\nMarkdown: https://agentic-patterns.com/patterns/episodic-memory-retrieval-injection.md\n\n### evidence-questions-not-verdict-questions\nEvidence Questions, Not Verdict Questions: Never ask the model for allow/ask/block. Ask it narrow, typed, observational questions and let code reduce the answers to the verdict, because the collapsed question is the low-confidence one.\nURL: https://agentic-patterns.com/patterns/evidence-questions-not-verdict-questions\nMarkdown: https://agentic-patterns.com/patterns/evidence-questions-not-verdict-questions.md\n\n### evidence-layered-evaluation-for-interactive-agents\nEvidence-Layered Evaluation for Interactive Agents: Scores interactive agent runs on a task outcome assertion and links each result to layered evidence: actions, screenshots, replays, network, and messages\nURL: https://agentic-patterns.com/patterns/evidence-layered-evaluation-for-interactive-agents\nMarkdown: https://agentic-patterns.com/patterns/evidence-layered-evaluation-for-interactive-agents.md\n\n### exact-action-authorization-binding\nExact-Action Authorization Binding: Bind a short-lived approval to the complete action presented to the reviewer, rederive and compare that identity at the acting boundary before execution, and commit the write with its postcondition check and idempotency receipt in one transaction.\nURL: https://agentic-patterns.com/patterns/exact-action-authorization-binding\nMarkdown: https://agentic-patterns.com/patterns/exact-action-authorization-binding.md\n\n### explicit-posterior-sampling-planner\nExplicit Posterior-Sampling Planner: Embeds Posterior Sampling for RL in the LLM's reasoning: sample a task model, plan, act, observe reward, and update the posterior\nURL: https://agentic-patterns.com/patterns/explicit-posterior-sampling-planner\nMarkdown: https://agentic-patterns.com/patterns/explicit-posterior-sampling-planner.md\n\n### extended-coherence-work-sessions\nExtended Coherence Work Sessions: Combines models with long coherence windows with context compaction, prompt caching, and persisted state so agents stay on task for hours\nURL: https://agentic-patterns.com/patterns/extended-coherence-work-sessions\nMarkdown: https://agentic-patterns.com/patterns/extended-coherence-work-sessions.md\n\n### external-credential-sync\nExternal Credential Sync: Reads AI credentials from other tools' keychains and config files and syncs them into the agent's store, with TTL-cached reads, refresh fences, and persisted ownership\nURL: https://agentic-patterns.com/patterns/external-credential-sync\nMarkdown: https://agentic-patterns.com/patterns/external-credential-sync.md\n\n### factory-over-assistant\nFactory over Assistant: Spawns several autonomous agents in parallel with automated feedback loops such as tests and builds, and checks on them later instead of watching one agent\nURL: https://agentic-patterns.com/patterns/factory-over-assistant\nMarkdown: https://agentic-patterns.com/patterns/factory-over-assistant.md\n\n### failover-aware-model-fallback\nFailover-Aware Model Fallback: Classifies each model failure by reason and falls back along a model chain only for retryable errors, failing fast on auth, billing, and user aborts\nURL: https://agentic-patterns.com/patterns/failover-aware-model-fallback\nMarkdown: https://agentic-patterns.com/patterns/failover-aware-model-fallback.md\n\n### fair-share-task-queues-with-heartbeat-leases\nFair-Share Task Queues with Heartbeat Leases: Distributes tasks across a shared agent fleet using weighted deficit-round-robin scheduling, with heartbeat leases and dead-letter retries to recover from crashed workers\nURL: https://agentic-patterns.com/patterns/fair-share-task-queues-with-heartbeat-leases\nMarkdown: https://agentic-patterns.com/patterns/fair-share-task-queues-with-heartbeat-leases.md\n\n### feature-list-as-immutable-contract\nFeature List as Immutable Contract: Defines every feature up front in a JSON list with acceptance steps; the agent may only flip a feature to passing after it verifies it\nURL: https://agentic-patterns.com/patterns/feature-list-as-immutable-contract\nMarkdown: https://agentic-patterns.com/patterns/feature-list-as-immutable-contract.md\n\n### filesystem-based-agent-state\nFilesystem-Based Agent State: Agents persist intermediate results and working state to files, creating durable checkpoints that enable workflow resumption, recovery from failures, and support for long-running tasks.\nURL: https://agentic-patterns.com/patterns/filesystem-based-agent-state\nMarkdown: https://agentic-patterns.com/patterns/filesystem-based-agent-state.md\n\n### filesystem-mediated-host-delegation\nFilesystem-Mediated Host Delegation: Lets a sandboxed agent write request files to a shared spool directory that a host daemon runs against a whitelist, with idempotent results the agent polls for\nURL: https://agentic-patterns.com/patterns/filesystem-mediated-host-delegation\nMarkdown: https://agentic-patterns.com/patterns/filesystem-mediated-host-delegation.md\n\n### fleet-cost-simulation-before-dispatch\nFleet Cost Simulation Before Dispatch: Replays an agent fleet's budget, priority, and failure-recovery policy against deterministic scenarios before committing real spend, so starvation and exhaustion verdicts arrive in CI instead of in production\nURL: https://agentic-patterns.com/patterns/fleet-cost-simulation-before-dispatch\nMarkdown: https://agentic-patterns.com/patterns/fleet-cost-simulation-before-dispatch.md\n\n### graph-of-thoughts\nGraph of Thoughts (GoT): Represents reasoning as a directed graph of thoughts so the model can branch, aggregate, refine, and revisit reasoning paths\nURL: https://agentic-patterns.com/patterns/graph-of-thoughts\nMarkdown: https://agentic-patterns.com/patterns/graph-of-thoughts.md\n\n### hook-based-safety-guard-rails\nHook-Based Safety Guard Rails for Autonomous Code Agents: Runs small shell scripts on PreToolUse and PostToolUse hooks to block destructive commands, lint edits, and warn on context use outside the agent's reasoning\nURL: https://agentic-patterns.com/patterns/hook-based-safety-guard-rails\nMarkdown: https://agentic-patterns.com/patterns/hook-based-safety-guard-rails.md\n\n### human-in-loop-approval-framework\nHuman-in-the-Loop Approval Framework: Systematically insert human approval gates for designated high-risk functions while maintaining agent autonomy for safe operations, with multi-channel approval interfaces and comprehensive audit trails.\nURL: https://agentic-patterns.com/patterns/human-in-loop-approval-framework\nMarkdown: https://agentic-patterns.com/patterns/human-in-loop-approval-framework.md\n\n### hybrid-gui-visual-grounding\nHybrid GUI & Visual Grounding: Grounds each GUI action in a filtered accessibility tree first, falls back to numbered visual marks or scaled coordinates only for what the tree cannot see, and confirms the effect of each action from a state diff before the next step\nURL: https://agentic-patterns.com/patterns/hybrid-gui-visual-grounding\nMarkdown: https://agentic-patterns.com/patterns/hybrid-gui-visual-grounding.md\n\n### hybrid-llm-code-workflow-coordinator\nHybrid LLM/Code Workflow Coordinator: Lets each workflow pick an LLM or a code script as its coordinator, so teams prototype with the LLM and move to reviewed code when determinism matters\nURL: https://agentic-patterns.com/patterns/hybrid-llm-code-workflow-coordinator\nMarkdown: https://agentic-patterns.com/patterns/hybrid-llm-code-workflow-coordinator.md\n\n### incident-to-eval-synthesis\nIncident-to-Eval Synthesis: Converts each production incident into executable eval cases with pass/fail criteria and gates future releases on them\nURL: https://agentic-patterns.com/patterns/incident-to-eval-synthesis\nMarkdown: https://agentic-patterns.com/patterns/incident-to-eval-synthesis.md\n\n### inference-healed-code-review-reward\nInference-Healed Code Review Reward: Replaces a binary tests-passed reward with a critic that scores correctness, style, performance, and security, explains low scores, and combines them\nURL: https://agentic-patterns.com/patterns/inference-healed-code-review-reward\nMarkdown: https://agentic-patterns.com/patterns/inference-healed-code-review-reward.md\n\n### inference-time-scaling\nInference-Time Scaling: Spends extra compute at inference time with best-of-N sampling, longer reasoning, self-refinement, search, and verification to improve output quality\nURL: https://agentic-patterns.com/patterns/inference-time-scaling\nMarkdown: https://agentic-patterns.com/patterns/inference-time-scaling.md\n\n### initializer-maintainer-dual-agent\nInitializer-Maintainer Dual Agent Architecture: Uses a one-time initializer agent to create the feature list, progress files, and bootstrap script, then a coding agent that resumes from them one feature per session\nURL: https://agentic-patterns.com/patterns/initializer-maintainer-dual-agent\nMarkdown: https://agentic-patterns.com/patterns/initializer-maintainer-dual-agent.md\n\n### intelligent-bash-tool-execution\nIntelligent Bash Tool Execution: Runs agent shell commands through a multi-mode executor that uses a PTY when needed, falls back to direct exec, and manages approvals, background jobs, and signals\nURL: https://agentic-patterns.com/patterns/intelligent-bash-tool-execution\nMarkdown: https://agentic-patterns.com/patterns/intelligent-bash-tool-execution.md\n\n### intent-level-cost-attribution\nIntent-Level Cost Attribution: Records every LLM call against the projectId/intentId/user key that caused it, at call time, so spend can be queried and enforced per work item instead of as an opaque total\nURL: https://agentic-patterns.com/patterns/intent-level-cost-attribution\nMarkdown: https://agentic-patterns.com/patterns/intent-level-cost-attribution.md\n\n### inversion-of-control\nInversion of Control: Gives the agent tools, a high-level objective, and guardrails, then lets it choose sequencing and recovery while humans set policy and review\nURL: https://agentic-patterns.com/patterns/inversion-of-control\nMarkdown: https://agentic-patterns.com/patterns/inversion-of-control.md\n\n### isolated-vm-per-rl-rollout\nIsolated VM per RL Rollout: Spin up an isolated virtual machine for each RL rollout to prevent cross-contamination between parallel agent executions, ensuring safe training with destructive tool access.\nURL: https://agentic-patterns.com/patterns/isolated-vm-per-rl-rollout\nMarkdown: https://agentic-patterns.com/patterns/isolated-vm-per-rl-rollout.md\n\n### iterative-multi-agent-brainstorming\nIterative Multi-Agent Brainstorming: Spawns several agents in parallel on the same problem, often with different perspectives, then merges their ideas into one set of options\nURL: https://agentic-patterns.com/patterns/iterative-multi-agent-brainstorming\nMarkdown: https://agentic-patterns.com/patterns/iterative-multi-agent-brainstorming.md\n\n### iterative-prompt-skill-refinement\nIterative Prompt & Skill Refinement: Combines a feedback channel, editable prompt documents, log-driven skill fixes, and usage dashboards to improve agent prompts and skills continuously\nURL: https://agentic-patterns.com/patterns/iterative-prompt-skill-refinement\nMarkdown: https://agentic-patterns.com/patterns/iterative-prompt-skill-refinement.md\n\n### judge-gated-finding-exchange-between-sub-agents\nJudge-Gated Finding Exchange Between Parallel Sub-Agents: Puts an append-only board between parallel sub-agents and lets a small judge decide what goes on it, who receives each note, and when a later note retracts an earlier one\nURL: https://agentic-patterns.com/patterns/judge-gated-finding-exchange-between-sub-agents\nMarkdown: https://agentic-patterns.com/patterns/judge-gated-finding-exchange-between-sub-agents.md\n\n### lane-based-execution-queueing\nLane-Based Execution Queueing: Routes work into named lanes, each with its own queue and concurrency limit, so sessions never interleave and background jobs never block users\nURL: https://agentic-patterns.com/patterns/lane-based-execution-queueing\nMarkdown: https://agentic-patterns.com/patterns/lane-based-execution-queueing.md\n\n### language-agent-tree-search-lats\nLanguage Agent Tree Search (LATS): Runs Monte Carlo Tree Search over reasoning steps, with the LLM generating candidate actions and scoring partial solutions to pick the best path\nURL: https://agentic-patterns.com/patterns/language-agent-tree-search-lats\nMarkdown: https://agentic-patterns.com/patterns/language-agent-tree-search-lats.md\n\n### layered-configuration-context\nLayered Configuration Context: Loads context files from enterprise, user, project, and local levels automatically and merges them into the agent's baseline context\nURL: https://agentic-patterns.com/patterns/layered-configuration-context\nMarkdown: https://agentic-patterns.com/patterns/layered-configuration-context.md\n\n### lethal-trifecta-threat-model\nLethal Trifecta Threat Model: Classifies each tool by private-data access, untrusted-content exposure, and external communication, and blocks any execution path that has all three\nURL: https://agentic-patterns.com/patterns/lethal-trifecta-threat-model\nMarkdown: https://agentic-patterns.com/patterns/lethal-trifecta-threat-model.md\n\n### llm-map-reduce-pattern\nLLM Map-Reduce Pattern: Processes each untrusted document in its own sandboxed LLM call with a constrained output, then aggregates the results with deterministic code\nURL: https://agentic-patterns.com/patterns/llm-map-reduce-pattern\nMarkdown: https://agentic-patterns.com/patterns/llm-map-reduce-pattern.md\n\n### llm-observability\nLLM Observability: Sends agent runs to an LLM observability platform for span-level traces of each LLM call and tool use, plus aggregate cost, latency, and success metrics\nURL: https://agentic-patterns.com/patterns/llm-observability\nMarkdown: https://agentic-patterns.com/patterns/llm-observability.md\n\n### llm-friendly-api-design\nLLM-Friendly API Design: Designs APIs with visible versions, self-descriptive names and schemas, simple calls, actionable errors, and few indirection levels so LLMs call them correctly\nURL: https://agentic-patterns.com/patterns/llm-friendly-api-design\nMarkdown: https://agentic-patterns.com/patterns/llm-friendly-api-design.md\n\n### local-first-credential-broker\nLocal-First Credential Broker: Keep raw secrets out of the agent process by injecting credentials at the network layer through a local broker, rather than handing the agent environment variables or config files.\nURL: https://agentic-patterns.com/patterns/local-first-credential-broker\nMarkdown: https://agentic-patterns.com/patterns/local-first-credential-broker.md\n\n### markdown-polis-coordination\nMarkdown Polis — Multi-Vendor Agent Coordination via Filesystem Constitution: Coordinates agents from different vendors through versioned markdown files: capability cards, work contracts, and bandit routing that learns from settled work\nURL: https://agentic-patterns.com/patterns/markdown-polis-coordination\nMarkdown: https://agentic-patterns.com/patterns/markdown-polis-coordination.md\n\n### mcp-pattern-injection\nMCP Pattern Injection: Runs an MCP server that exposes framework best-practice patterns as tools, so the coding assistant fetches current patterns on demand\nURL: https://agentic-patterns.com/patterns/mcp-pattern-injection\nMarkdown: https://agentic-patterns.com/patterns/mcp-pattern-injection.md\n\n### memory-consolidation-decay-contradiction\nMemory Consolidation, Decay & Contradiction Resolution: Gives each stored fact a lifecycle: reconciles each new fact against the related stored facts when it arrives, stamps facts with event time and ingestion time so that a superseded fact is invalidated and not deleted, and runs a background job that merges duplicates and expires spent state\nURL: https://agentic-patterns.com/patterns/memory-consolidation-decay-contradiction\nMarkdown: https://agentic-patterns.com/patterns/memory-consolidation-decay-contradiction.md\n\n### memory-reinforcement-learning-memrl\nMemory Reinforcement Learning (MemRL): Stores memories with learned utility scores, retrieves by similarity then re-ranks by utility, and updates scores from outcomes while the LLM stays frozen\nURL: https://agentic-patterns.com/patterns/memory-reinforcement-learning-memrl\nMarkdown: https://agentic-patterns.com/patterns/memory-reinforcement-learning-memrl.md\n\n### memory-synthesis-from-execution-logs\nMemory Synthesis from Execution Logs: Has the agent write a structured diary per task, then runs synthesis agents over many diaries to turn recurring patterns into rules, commands, and tests\nURL: https://agentic-patterns.com/patterns/memory-synthesis-from-execution-logs\nMarkdown: https://agentic-patterns.com/patterns/memory-synthesis-from-execution-logs.md\n\n### merged-code-language-skill-model\nMerged Code + Language Skill Model: Fine-tunes separate language and code specialists from the same base model, then merges their weights into one model instead of one large joint training run\nURL: https://agentic-patterns.com/patterns/merged-code-language-skill-model\nMarkdown: https://agentic-patterns.com/patterns/merged-code-language-skill-model.md\n\n### milestone-escrow-agent-funding\nMilestone Escrow for Agent Resource Funding: Holds agent funding in escrow and releases each payment only after independent verification of a measurable milestone\nURL: https://agentic-patterns.com/patterns/milestone-escrow-agent-funding\nMarkdown: https://agentic-patterns.com/patterns/milestone-escrow-agent-funding.md\n\n### multi-model-orchestration-for-complex-edits\nMulti-Model Orchestration for Complex Edits: Splits complex code edits across specialized models: a retrieval model gathers context, a large model writes the changes, and smaller models apply them\nURL: https://agentic-patterns.com/patterns/multi-model-orchestration-for-complex-edits\nMarkdown: https://agentic-patterns.com/patterns/multi-model-orchestration-for-complex-edits.md\n\n### multi-platform-communication-aggregation\nMulti-Platform Communication Aggregation: Queries every communication platform in parallel through adapters that share one schema, then merges, deduplicates, and ranks the results\nURL: https://agentic-patterns.com/patterns/multi-platform-communication-aggregation\nMarkdown: https://agentic-patterns.com/patterns/multi-platform-communication-aggregation.md\n\n### multi-platform-webhook-triggers\nMulti-Platform Webhook Triggers: Starts agent workflows from Slack, Notion, and Jira webhooks, emoji reactions, and schedules, with idempotency and signature checks on each event\nURL: https://agentic-patterns.com/patterns/multi-platform-webhook-triggers\nMarkdown: https://agentic-patterns.com/patterns/multi-platform-webhook-triggers.md\n\n### multi-tenant-agent-isolation\nMulti-Tenant Agent & Memory Isolation: Enforces a tenant boundary on all four agent state planes (execution, retrieval and memory, cache, credential and egress), with tenant identity bound outside the model, so that one tenant's data or instructions cannot reach another\nURL: https://agentic-patterns.com/patterns/multi-tenant-agent-isolation\nMarkdown: https://agentic-patterns.com/patterns/multi-tenant-agent-isolation.md\n\n### non-custodial-spending-controls\nNon-Custodial Spending Controls: Puts a policy layer between the agent and the transaction signer that checks each intent against allowlists, budgets, and rate limits, and fails closed\nURL: https://agentic-patterns.com/patterns/non-custodial-spending-controls\nMarkdown: https://agentic-patterns.com/patterns/non-custodial-spending-controls.md\n\n### non-generative-judgment-routing\nNon-Generative Judgment Routing with Typed Escalation: Sends decision-only loop steps as batched typed questions to a non-generative judgment model and escalates what it cannot answer back to the LLM\nURL: https://agentic-patterns.com/patterns/non-generative-judgment-routing\nMarkdown: https://agentic-patterns.com/patterns/non-generative-judgment-routing.md\n\n### one-os-user-per-agent\nOne OS User per Agent: Give each long-lived agent its own OS user account and a templated init-system unit, so identity, supervision and privilege come from the host instead of from a per-agent container.\nURL: https://agentic-patterns.com/patterns/one-os-user-per-agent\nMarkdown: https://agentic-patterns.com/patterns/one-os-user-per-agent.md\n\n### opponent-processor-multi-agent-debate\nOpponent Processor / Multi-Agent Debate Pattern: Spawns agents with opposing roles on the same context, lets them critique each other, then synthesizes their positions to expose bias and blind spots\nURL: https://agentic-patterns.com/patterns/opponent-processor-multi-agent-debate\nMarkdown: https://agentic-patterns.com/patterns/opponent-processor-multi-agent-debate.md\n\n### oracle-and-worker-multi-model\nOracle and Worker Multi-Model Approach: Uses a fast, low-cost worker model for most tool use and code generation, and lets it consult an expensive oracle model when it is stuck\nURL: https://agentic-patterns.com/patterns/oracle-and-worker-multi-model\nMarkdown: https://agentic-patterns.com/patterns/oracle-and-worker-multi-model.md\n\n### orchestration-prompt-writing-benchmark\nOrchestration Prompt-Writing Benchmark: Scores an orchestrator on whether its sub-agent prompts give the right information fragments to the right roles, separate from end-task success\nURL: https://agentic-patterns.com/patterns/orchestration-prompt-writing-benchmark\nMarkdown: https://agentic-patterns.com/patterns/orchestration-prompt-writing-benchmark.md\n\n### out-of-process-provider-boundary-replay\nOut-of-Process Provider-Boundary Replay: Capture an agent run at the model-provider HTTP boundary from outside the process, then serve those bytes back so the agent re-executes its own logic with no provider call.\nURL: https://agentic-patterns.com/patterns/out-of-process-provider-boundary-replay\nMarkdown: https://agentic-patterns.com/patterns/out-of-process-provider-boundary-replay.md\n\n### output-verification-loop\nOutput Verification Loop: Verify LLM outputs by extracting individual claims, checking each against evidence sources, and returning per-claim trust scores before acting on the resu",".claude/skills/arxiv-pattern-discovery/RUBRIC.md":"# Pattern Quality Rubric\n\nReference for the Pattern Quality Rubric used to score arXiv papers for pattern extraction potential.\n\n## Overview\n\nPapers are scored on a scale of 0-10 using five weighted criteria. Only papers scoring >= 5.0 qualify for pattern extraction.\n\n## Scoring Criteria\n\n| Criterion | Weight | Description | Levels |\n|-----------|--------|-------------|--------|\n| **Reusability** | 30% | How widely applicable is the pattern? | Domain-specific (1.0) → Multi-domain (2.0) → Universal (3.0) |\n| **Novelty** | 25% | How new is the approach? | Existing (1.0) → Incremental (2.0) → Fundamentally new (3.0) |\n| **Clarity** | 20% | How well is it described? | Vague (1.0) → Clear (2.0) → Crystal clear (3.0) |\n| **Evidence** | 15% | Is there empirical validation? | No eval (1.0) → Some eval (2.0) → Strong empirical (3.0) |\n| **Completeness** | 10% | How complete is the implementation? | Idea only (1.0) → Partial details (2.0) → Production-ready (3.0) |\n\n## Detailed Scoring\n\n### Reusability (30% weight)\n\n| Score | Level | Indicators |\n|-------|-------|------------|\n| 1.0 | Domain-specific | \"specific to\", \"in the field of\", \"domain-specific\" |\n| 2.0 | Multi-domain | \"multi-domain\", \"cross-domain\", \"versatile\", \"adaptable\" |\n| 3.0 | Universal | \"general\", \"universal\", \"framework\", \"generic\", \"wide range\", \"variety of\" |\n\n### Novelty (25% weight)\n\n| Score | Level | Indicators |\n|-------|-------|------------|\n| 1.0 | Existing | No novelty indicators, describes existing approaches |\n| 2.0 | Incremental | \"improves\", \"extends\", \"builds on\", \"enhances\", \"optimizes\", \"refines\" |\n| 3.0 | Fundamentally new | \"novel\", \"new architecture\", \"new framework\", \"first to\", \"pioneering\", \"groundbreaking\" |\n\n### Clarity (20% weight)\n\n| Score | Level | Indicators |\n|-------|-------|------------|\n| 1.0 | Vague | \"may\", \"might\", \"potentially\", \"could be\", \"some ways\" |\n| 2.0 | Clear | \"we propose\", \"our approach\", \"the method\", abstract 100-150 words |\n| 3.0 | Crystal clear | Multiple clear indicators + abstract >150 words + concrete language |\n\n### Evidence (15% weight)\n\n| Score | Level | Indicators |\n|-------|-------|------------|\n| 1.0 | No eval | No evaluation or experiment mentioned |\n| 2.0 | Some eval | \"evaluation\", \"experiment\", \"benchmark\", \"results\", \"dataset\" |\n| 3.0 | Strong empirical | \"significant improvement\", \"state-of-the-art\", \"outperforms\", \"empirical\", \"real-world\" |\n\n### Completeness (10% weight)\n\n| Score | Level | Indicators |\n|-------|-------|------------|\n| 1.0 | Idea only | No implementation mentioned |\n| 1.5 | Partial idea | \"algorithm\", \"method\", \"approach\" mentioned |\n| 2.0 | Partial details | Implementation details or architecture described |\n| 3.0 | Production-ready | \"implementation\", \"open source\", \"code available\", \"github\", \"production\", \"deployed\" |\n\n## Score Calculation\n\nThe total score is calculated as a weighted sum:\n\n```\nTotal = (Reusability × 0.30) + (Novelty × 0.25) + (Clarity × 0.20) + (Evidence × 0.15) + (Completeness × 0.10)\n```\n\nMaximum possible score: 10.0\n\n## Threshold\n\n- **Score >= 5.0**: Qualifies for pattern extraction\n- **Score >= 7.0**: High-quality candidate, prioritize for extraction\n- **Score >= 8.5**: Exceptional candidate, immediate extraction recommended\n\n## Example Scoring\n\n### Example 1: High-quality paper (8.5)\n\n| Criterion | Score | Weighted |\n|-----------|-------|----------|\n| Reusability | 3.0 (Universal) | 0.90 |\n| Novelty | 3.0 (Fundamentally new) | 0.75 |\n| Clarity | 2.5 (Very clear) | 0.50 |\n| Evidence | 2.0 (Some eval) | 0.30 |\n| Completeness | 2.0 (Partial details) | 0.20 |\n| **Total** | | **8.5/10** |\n\n### Example 2: Marginal paper (5.2)\n\n| Criterion | Score | Weighted |\n|-----------|-------|----------|\n| Reusability | 2.0 (Multi-domain) | 0.60 |\n| Novelty | 2.0 (Incremental) | 0.50 |\n| Clarity | 2.0 (Clear) | 0.40 |\n| Evidence | 1.5 (Some eval) | 0.23 |\n| Completeness | 1.0 (Idea only) | 0.10 |\n| **Total** | | **5.2/10** |\n",".claude/skills/arxiv-pattern-discovery/WORKFLOW.md":"# arXiv Pattern Discovery Workflow\n\nEnd-to-end workflow for discovering agentic patterns from academic literature on arXiv.\n\n## Overview\n\nThis workflow guides you through the process of discovering new agentic patterns from academic papers:\n\n1. **Discovery** - Search arXiv and score papers\n2. **Review** - Identify high-quality candidates\n3. **Extract** - Create patterns from selected papers (user-driven)\n\n---\n\n## Phase 1: Discovery\n\n### Step 1.1: Run the arXiv Scanner\n\nSearch for recent papers with agentic patterns:\n\n```bash\n# Recent papers (last 30 days)\npython scripts/arxiv_scanner.py --days=30 --max-results=50 --export-md arxiv_results.md\n\n# All-time papers with higher quality threshold\npython scripts/arxiv_scanner.py --max-results=100 --min-score=7.0 --export-md high_quality.md\n\n# Specific topic search\npython scripts/arxiv_scanner.py --query=\"multi-agent memory systems\" --max-results=50 --export-md memory_patterns.md\n```\n\n### Step 1.2: Review the Output\n\nThe scanner produces:\n- Console output with top 10 papers by quality score\n- Optional Markdown report (with `--export-md`)\n- Optional JSON export (with `--export-json`)\n\nEach paper includes:\n- **Title**, **arXiv ID**, **URL**\n- **Quality Score** (0-10) with breakdown\n- **Suggested Category** (based on keywords)\n- **Extracted Tags**\n- **Abstract**\n- **Potential Duplicates** warning (if applicable)\n\n### Step 1.3: Filter Candidates\n\nFilter papers by:\n- **Quality Score**: Focus on papers >= 7.0 for best results\n- **Category**: Group by your area of interest\n- **Duplicate Warnings**: Skip papers flagged as duplicates\n\n---\n\n## Phase 2: Review\n\n### Step 2.1: Read the Markdown Report\n\nOpen the exported Markdown file and review candidates:\n\n```bash\n# View the report\ncat arxiv_results.md\n# or open in your editor\ncode arxiv_results.md\n```\n\n### Step 2.2: Visit Paper URLs\n\nFor each high-scoring paper:\n1. Click the arXiv URL to read the full paper\n2. Focus on the \"architecture\" or \"method\" section\n3. Look for reusable patterns (not just single techniques)\n\n### Step 2.3: Select Extraction Candidates\n\nPrioritize papers with:\n- Score >= 7.0 (high quality)\n- Clear architectural description\n- Novel approach not yet in the pattern catalog\n- Universal or multi-domain applicability\n\n---\n\n## Phase 3: Extract (User-Driven)\n\nAfter selecting candidate papers, you have two options:\n\n### Option A: Use the create-pattern Skill\n\nThe `create-pattern` skill can extract patterns from:\n- arXiv URLs\n- PDF files\n- Blog posts\n- Code repositories\n\n```\n# Ask Claude to extract a pattern from a paper\n\"Use create-pattern to extract a pattern from https://arxiv.org/abs/2401.12345\"\n```\n\n### Option B: Manual Pattern Creation\n\n1. Copy the template:\n   ```bash\n   cp patterns/TEMPLATE.md patterns/my-new-pattern.md\n   ```\n\n2. Fill in the required fields:\n   - `title`: Descriptive pattern name\n   - `status`: Based on quality score and evidence\n   - `authors`: Paper authors (@arxiv)\n   - `based_on`: Paper title (arXiv link)\n   - `category`: From the scanner's suggestion\n   - `source`: arXiv URL\n   - `tags`: From the scanner's extraction\n\n3. Write the pattern sections:\n   - **Problem**: What problem does this pattern solve?\n   - **Solution**: How does the architecture work?\n   - **Example**: Include a Mermaid diagram\n   - **References**: Link to the paper\n\n---\n\n## Phase 4: Validate (Before Committing)\n\n### Step 4.1: Check for Duplicates\n\n```bash\npython scripts/pattern_similarity_checker.py patterns/my-new-pattern.md\n```\n\nIf similarity > 0.7, consider:\n- Merging with existing pattern\n- Finding a more specific angle\n- Marking as variant of existing pattern\n\n### Step 4.2: Validate Quality\n\n```bash\npython scripts/pattern_validator.py patterns/my-new-pattern.md\n```\n\nFix any errors before committing.\n\n---\n\n## Example Session\n\n```bash\n# Step 1: Search arXiv\npython scripts/arxiv_scanner.py --days=30 --min-score=7.0 --export-md candidates.md\n\n# Output:\n# Scanning arXiv...\n# Fetched 100 papers\n# Filtered to 15 papers within last 30 days\n# Papers meeting threshold (7.0): 8\n\n# Step 2: Review the markdown report\ncat candidates.md\n\n# Step 3: Extract a pattern (using create-pattern skill)\n# \"Extract a pattern from https://arxiv.org/abs/2401.12345\"\n\n# Step 4: Validate\npython scripts/pattern_similarity_checker.py patterns/hierarchical-memory.md\npython scripts/pattern_validator.py patterns/hierarchical-memory.md\n```\n\n---\n\n## Tips for Success\n\n1. **Quality Over Quantity**: Focus on papers scoring >= 7.0\n2. **Avoid Duplicates**: Always run the similarity checker before committing\n3. **Validate Early**: Run the validator to catch issues early\n4. **Use the Rubric**: Understand why papers score the way they do (see RUBRIC.md)\n5. **Be Selective**: Not every good paper deserves a pattern—focus on reusable architectures\n",".claude/skills/create-pattern/scripts/validate.py":"#!/usr/bin/env python3\n\"\"\"Validate pattern front-matter against repository schema.\"\"\"\n\nimport sys\nfrom pathlib import Path\n\n# Allowed values for validation\nALLOWED_CATEGORIES = [\n    \"Orchestration & Control\",\n    \"Context & Memory\",\n    \"Feedback Loops\",\n    \"Learning & Adaptation\",\n    \"Reliability & Eval\",\n    \"Security & Safety\",\n    \"Tool Use & Environment\",\n    \"UX & Collaboration\",\n    \"Uncategorized\",\n]\n\nALLOWED_STATUSES = [\n    \"proposed\",\n    \"emerging\",\n    \"established\",\n    \"validated-in-production\",\n    \"best-practice\",\n    \"experimental-but-awesome\",\n    \"rapidly-improving\",\n]\n\nREQUIRED_FIELDS = [\"title\", \"status\", \"authors\", \"based_on\", \"category\", \"source\", \"tags\"]\n\n\ndef extract_frontmatter(file_path: Path) -> tuple[str, dict]:\n    \"\"\"Extract YAML frontmatter from a markdown file.\"\"\"\n    content = file_path.read_text()\n    if not content.startswith(\"---\"):\n        raise ValueError(\"File does not start with frontmatter delimiter\")\n\n    # Find the end of frontmatter\n    end_idx = content.find(\"\\n---\", 4)\n    if end_idx == -1:\n        raise ValueError(\"Frontmatter not properly closed\")\n\n    yaml_str = content[4:end_idx]\n    return content, parse_yaml_simple(yaml_str)\n\n\ndef parse_yaml_simple(yaml_str: str) -> dict:\n    \"\"\"Simple YAML parser for frontmatter - handles basic key: value pairs.\"\"\"\n    result = {}\n    for line in yaml_str.strip().split(\"\\n\"):\n        if \":\" in line and not line.strip().startswith(\"#\"):\n            key, value = line.split(\":\", 1)\n            key = key.strip()\n            value = value.strip()\n\n            # Handle lists\n            if value.startswith(\"[\") and value.endswith(\"]\"):\n                value = [v.strip().strip('\"\\'') for v in value[1:-1].split(\",\")]\n            # Strip quotes from strings\n            elif value.startswith('\"') and value.endswith('\"'):\n                value = value[1:-1]\n            elif value.startswith(\"'\") and value.endswith(\"'\"):\n                value = value[1:-1]\n\n            result[key] = value\n\n    return result\n\n\ndef validate_pattern(file_path: str | Path) -> bool:\n    \"\"\"Validate a pattern file's frontmatter.\"\"\"\n    path = Path(file_path)\n\n    if not path.exists():\n        print(f\"❌ File not found: {path}\")\n        return False\n\n    try:\n        content, frontmatter = extract_frontmatter(path)\n    except ValueError as e:\n        print(f\"❌ {e}\")\n        return False\n\n    errors = []\n\n    # Check required fields\n    for field in REQUIRED_FIELDS:\n        if field not in frontmatter:\n            errors.append(f\"Missing required field: {field}\")\n\n    # Validate category\n    if \"category\" in frontmatter and frontmatter[\"category\"] not in ALLOWED_CATEGORIES:\n        errors.append(\n            f\"Invalid category: {frontmatter['category']}. \"\n            f\"Must be one of: {', '.join(ALLOWED_CATEGORIES)}\"\n        )\n\n    # Validate status\n    if \"status\" in frontmatter and frontmatter[\"status\"] not in ALLOWED_STATUSES:\n        errors.append(\n            f\"Invalid status: {frontmatter['status']}. \"\n            f\"Must be one of: {', '.join(ALLOWED_STATUSES)}\"\n        )\n\n    # Validate authors is a list\n    if \"authors\" in frontmatter and not isinstance(frontmatter[\"authors\"], list):\n        errors.append(\"authors must be a list (e.g., [\\\"Name (@username)\\\"])\")\n\n    # Validate tags is a list\n    if \"tags\" in frontmatter and not isinstance(frontmatter[\"tags\"], list):\n        errors.append(\"tags must be a list (e.g., [tag1, tag2, tag3])\")\n\n    if errors:\n        for error in errors:\n            print(f\"❌ {error}\")\n        return False\n\n    # Check for required sections in content\n    required_sections = [\"## Problem\", \"## Solution\", \"## References\"]\n    for section in required_sections:\n        if section not in content:\n            errors.append(f\"Missing section: {section}\")\n\n    if errors:\n        for error in errors:\n            print(f\"❌ {error}\")\n        return False\n\n    print(f\"✅ Pattern validation passed: {path.name}\")\n    return True\n\n\nif __name__ == \"__main__\":\n    if len(sys.argv) < 2:\n        print(\"Usage: python validate.py <pattern-file.md>\")\n        sys.exit(1)\n\n    success = validate_pattern(sys.argv[1])\n    sys.exit(0 if success else 1)\n",".claude/skills/arxiv-pattern-discovery/scripts/pattern_similarity_checker.py":"#!/usr/bin/env python3\n\"\"\"\npattern_similarity_checker.py\n\nDuplicate detection for pattern files using tag similarity and content analysis.\n\nDetects potentially duplicate or very similar patterns by comparing:\n- Tag overlap (Jaccard similarity)\n- Title similarity\n- Category overlap\n- Problem/Solution section content\n\nUsage:\n    python scripts/pattern_similarity_checker.py <new-pattern.md>\n    python scripts/pattern_similarity_checker.py --all\n    python scripts/pattern_similarity_checker.py --threshold=0.7 <pattern.md>\n\"\"\"\n\nimport argparse\nimport math\nimport os\nimport re\nimport sys\nfrom collections import Counter\nfrom pathlib import Path\nfrom typing import Dict, List, Optional, Set, Tuple\n\n\n# Add parent directory to path for imports\nsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))\n\nfrom build_readme import parse_front_matter\n\n\ndef slugify(value: str) -> str:\n    \"\"\"Normalize string for comparison.\"\"\"\n    value = re.sub(r'[^\\w\\s-]', '', value).strip().lower()\n    value = re.sub(r'[-\\s]+', ' ', value)\n    return value\n\n\ndef tokenize(text: str) -> Set[str]:\n    \"\"\"Tokenize text into words, removing common stop words.\"\"\"\n    if not text:\n        return set()\n\n    # Common stop words to ignore\n    stop_words = {\n        \"a\", \"an\", \"the\", \"and\", \"or\", \"but\", \"in\", \"on\", \"at\", \"to\", \"for\",\n        \"of\", \"with\", \"by\", \"from\", \"as\", \"is\", \"was\", \"are\", \"were\", \"be\",\n        \"been\", \"being\", \"have\", \"has\", \"had\", \"do\", \"does\", \"did\", \"will\",\n        \"would\", \"could\", \"should\", \"may\", \"might\", \"must\", \"can\", \"this\",\n        \"that\", \"these\", \"those\", \"it\", \"its\", \"they\", \"them\", \"their\",\n        \"what\", \"which\", \"who\", \"whom\", \"when\", \"where\", \"why\", \"how\",\n    }\n\n    # Tokenize and filter\n    words = re.findall(r'\\b\\w+\\b', text.lower())\n    return {w for w in words if len(w) > 3 and w not in stop_words}\n\n\ndef jaccard_similarity(set1: Set[str], set2: Set[str]) -> float:\n    \"\"\"\n    Calculate Jaccard similarity between two sets.\n\n    J(A, B) = |A ∩ B| / |A ∪ B|\n    \"\"\"\n    if not set1 or not set2:\n        return 0.0\n\n    intersection = len(set1.intersection(set2))\n    union = len(set1.union(set2))\n\n    return intersection / union if union > 0 else 0.0\n\n\ndef cosine_similarity(set1: Set[str], set2: Set[str]) -> float:\n    \"\"\"\n    Calculate cosine similarity between two sets (treating as binary vectors).\n    \"\"\"\n    if not set1 or not set2:\n        return 0.0\n\n    intersection = len(set1.intersection(set2))\n    magnitude = math.sqrt(len(set1)) * math.sqrt(len(set2))\n\n    return intersection / magnitude if magnitude > 0 else 0.0\n\n\ndef levenshtein_distance(s1: str, s2: str) -> int:\n    \"\"\"Calculate Levenshtein distance between two strings.\"\"\"\n    if len(s1) < len(s2):\n        return levenshtein_distance(s2, s1)\n\n    if len(s2) == 0:\n        return len(s1)\n\n    previous_row = range(len(s2) + 1)\n    for i, c1 in enumerate(s1):\n        current_row = [i + 1]\n        for j, c2 in enumerate(s2):\n            insertions = previous_row[j + 1] + 1\n            deletions = current_row[j] + 1\n            substitutions = previous_row[j] + (c1 != c2)\n            current_row.append(min(insertions, deletions, substitutions))\n        previous_row = current_row\n\n    return previous_row[-1]\n\n\ndef string_similarity(s1: str, s2: str) -> float:\n    \"\"\"\n    Calculate normalized string similarity based on Levenshtein distance.\n\n    Returns 1.0 for identical strings, 0.0 for completely different.\n    \"\"\"\n    if not s1 or not s2:\n        return 0.0\n\n    max_len = max(len(s1), len(s2))\n    if max_len == 0:\n        return 1.0\n\n    distance = levenshtein_distance(s1.lower(), s2.lower())\n    return 1.0 - (distance / max_len)\n\n\ndef extract_sections(filepath: str) -> Dict[str, str]:\n    \"\"\"\n    Extract main sections from a pattern file.\n\n    Returns dict with keys: problem, solution, how_to_use, trade_offs\n    \"\"\"\n    with open(filepath, 'r', encoding='utf-8') as f:\n        content = f.read()\n\n    # Remove front matter\n    if content.startswith('---'):\n        end_idx = content.find('\\n---', 4)\n        if end_idx > 0:\n            content = content[end_idx + 4:]\n\n    sections = {}\n    current_section = None\n    current_content = []\n\n    # Section markers we care about\n    section_markers = ['## Problem', '## Solution', '## How to use it', '## Trade-offs']\n\n    for line in content.split('\\n'):\n        if line.startswith('## '):\n            # Save previous section\n            if current_section:\n                sections[current_section] = ' '.join(current_content)\n\n            # Start new section\n            current_section = line[3:].strip().lower()\n            if 'problem' in current_section:\n                current_section = 'problem'\n            elif 'solution' in current_section:\n                current_section = 'solution'\n            elif 'how to use' in current_section:\n                current_section = 'how_to_use'\n            elif 'trade-off' in current_section:\n                current_section = 'trade_offs'\n            else:\n                current_section = None\n            current_content = []\n        elif current_section:\n            # Skip code blocks and mermaid diagrams\n            if line.strip().startswith('```') or line.strip().startswith('~~~'):\n                continue\n            current_content.append(line.strip())\n\n    # Save last section\n    if current_section:\n        sections[current_section] = ' '.join(current_content)\n\n    return sections\n\n\nclass PatternSimilarityChecker:\n    \"\"\"Checker for finding similar/duplicate patterns.\"\"\"\n\n    def __init__(self, patterns_dir: str, threshold: float = 0.5):\n        \"\"\"\n        Initialize the checker.\n\n        Args:\n            patterns_dir: Path to patterns directory\n            threshold: Minimum similarity score to report (0-1)\n        \"\"\"\n        self.patterns_dir = Path(patterns_dir)\n        self.threshold = threshold\n        self.patterns = self._load_patterns()\n\n    def _load_patterns(self) -> List[Dict]:\n        \"\"\"Load all pattern metadata and content.\"\"\"\n        patterns = []\n\n        for filepath in self.patterns_dir.glob(\"*.md\"):\n            if filepath.name == \"TEMPLATE.md\":\n                continue\n\n            try:\n                metadata = parse_front_matter(str(filepath))\n                sections = extract_sections(filepath)\n\n                patterns.append({\n                    \"file\": filepath.name,\n                    \"path\": str(filepath),\n                    \"title\": metadata.get(\"title\", \"\"),\n                    \"tags\": [t.lower() for t in metadata.get(\"tags\", [])],\n                    \"category\": metadata.get(\"category\", \"\"),\n                    \"sections\": sections,\n                    \"metadata\": metadata,\n                })\n            except Exception as e:\n                print(f\"Warning: Could not load {filepath.name}: {e}\")\n\n        return patterns\n\n    def compare_to_pattern(self, filepath: str) -> List[Dict]:\n        \"\"\"\n        Compare a single pattern file against all existing patterns.\n\n        Returns list of similarity results, sorted by total similarity.\n        \"\"\"\n        try:\n            metadata = parse_front_matter(filepath)\n            sections = extract_sections(filepath)\n        except Exception as e:\n            print(f\"Error: Could not parse pattern file: {e}\")\n            return []\n\n        new_pattern = {\n            \"file\": Path(filepath).name,\n            \"title\": metadata.get(\"title\", \"\"),\n            \"tags\": [t.lower() for t in metadata.get(\"tags\", [])],\n            \"category\": metadata.get(\"category\", \"\"),\n            \"sections\": sections,\n        }\n\n        results = []\n\n        for existing in self.patterns:\n            if existing[\"file\"] == new_pattern[\"file\"]:\n                continue  # Skip self\n\n            similarity = self._calculate_similarity(new_pattern, existing)\n            if similarity[\"total\"] >= self.threshold:\n                results.append({\n                    \"existing_file\": existing[\"file\"],\n                    \"existing_title\": existing[\"title\"],\n                    \"similarity\": similarity,\n                })\n\n        # Sort by total similarity\n        results.sort(key=lambda x: x[\"similarity\"][\"total\"], reverse=True)\n        return results\n\n    def check_all_similarities(self) -> List[Dict]:\n        \"\"\"\n        Check all patterns against each other for similarities.\n\n        Returns list of potential duplicates (each pair once).\n        \"\"\"\n        results = []\n\n        for i, pattern1 in enumerate(self.patterns):\n            for pattern2 in self.patterns[i + 1:]:\n                similarity = self._calculate_similarity(pattern1, pattern2)\n                if similarity[\"total\"] >= self.threshold:\n                    results.append({\n                        \"pattern1\": pattern1[\"file\"],\n                        \"pattern2\": pattern2[\"file\"],\n                        \"title1\": pattern1[\"title\"],\n                        \"title2\": pattern2[\"title\"],\n                        \"similarity\": similarity,\n                    })\n\n        # Sort by total similarity\n        results.sort(key=lambda x: x[\"similarity\"][\"total\"], reverse=True)\n        return results\n\n    def _calculate_similarity(self, pattern1: Dict, pattern2: Dict) -> Dict[str, float]:\n        \"\"\"Calculate detailed similarity metrics between two patterns.\"\"\"\n\n        # 1. Tag similarity (Jaccard)\n        tags1 = set(pattern1[\"tags\"])\n        tags2 = set(pattern2[\"tags\"])\n        tag_sim = jaccard_similarity(tags1, tags2)\n\n        # 2. Title similarity\n        title_sim = string_similarity(pattern1[\"title\"], pattern2[\"title\"])\n\n        # 3. Category match\n        category_match = 1.0 if pattern1[\"category\"] == pattern2[\"category\"] else 0.0\n\n        # 4. Content similarity (problem + solution)\n        content1_tokens = set()\n        content2_tokens = set()\n\n        for section in [\"problem\", \"solution\"]:\n            if section in pattern1[\"sections\"]:\n                content1_tokens.update(tokenize(pattern1[\"sections\"][section]))\n            if section in pattern2[\"sections\"]:\n                content2_tokens.update(tokenize(pattern2[\"sections\"][section]))\n\n        content_sim = jaccard_similarity(content1_tokens, content2_tokens)\n\n        # Weighted total (adjust weights as needed)\n        total = (\n            tag_sim * 0.30 +\n            title_sim * 0.20 +\n            category_match * 0.15 +\n            content_sim * 0.35\n        )\n\n        return {\n            \"tag\": tag_sim,\n            \"title\": title_sim,\n            \"category\": category_match,\n            \"content\": content_sim,\n            \"total\": total,\n        }\n\n    def suggest_action(self, similarity: Dict[str, float]) -> str:\n        \"\"\"Suggest action based on similarity score.\"\"\"\n        total = similarity[\"total\"]\n\n        if total >= 0.8:\n            return \"MERGE - Patterns are very similar, consider merging\"\n        elif total >= 0.7:\n            return \"REVIEW - High similarity, manual review needed\"\n        elif total >= 0.6:\n            return \"CHECK - Moderate similarity, check if related\"\n        elif total >= 0.5:\n            return \"RELATED - May be related patterns\"\n        else:\n            return \"OK - Below similarity threshold\"\n\n\ndef print_similarity_report(results: List[Dict], threshold: float, checker):\n    \"\"\"Print a formatted similarity report.\"\"\"\n\n    if not results:\n        print(f\"\\n✅ No patterns found with similarity >= {threshold}\")\n        return\n\n    print(f\"\\n{'='*80}\")\n    print(f\"⚠️  FOUND {len(results)} POTENTIAL DUPLICATE/RELATED PATTERN PAIRS\")\n    print(f\"{'='*80}\")\n\n    for i, result in enumerate(results, 1):\n        if \"existing_file\" in result:\n            # Single pattern comparison\n            print(f\"\\n{i}. {result['existing_title']}\")\n            print(f\"   File: {result['existing_file']}\")\n        else:\n            # All-pairs comparison\n            print(f\"\\n{i}. {result['title1']} <-> {result['title2']}\")\n            print(f\"   Files: {result['pattern1']} <-> {result['pattern2']}\")\n\n        sim = result[\"similarity\"]\n        action = checker.suggest_action(sim)\n\n        print(f\"   Total Similarity: {sim['total']:.2f}\")\n        print(f\"   Tag Similarity:    {sim['tag']:.2f} (Jaccard)\")\n        print(f\"   Title Similarity:  {sim['title']:.2f}\")\n        print(f\"   Category Match:    {sim['category']:.2f}\")\n        print(f\"   Content Similarity:{sim['content']:.2f}\")\n        print(f\"   Suggested Action:  {action}\")\n\n    # Print warning for high similarities\n    high_sim = [r for r in results if r[\"similarity\"][\"total\"] >= 0.7]\n    if high_sim:\n        print(f\"\\n{'='*80}\")\n        print(f\"⚠️  WARNING: {len(high_sim)} patterns with similarity >= 0.7\")\n        print(f\"   These may be duplicates or variants that need merging.\")\n        print(f\"{'='*80}\")\n\n\ndef export_similarity_report(results: List[Dict], output_file: str, checker):\n    \"\"\"Export similarity report to Markdown file.\"\"\"\n\n    lines = [\n        \"# Pattern Similarity Report\",\n        \"\",\n        f\"Generated: {__import__('datetime').datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\",\n        f\"Total pairs found: {len(results)}\",\n        \"\",\n        \"---\",\n        \"\",\n    ]\n\n    for i, result in enumerate(results, 1):\n        if \"existing_file\" in result:\n            lines.extend([\n                f\"## {i}. {result['existing_title']}\",\n                \"\",\n                f\"**File:** `{result['existing_file']}`  \",\n                f\"**Similarity:** {result['similarity']['total']:.2f}  \",\n            ])\n        else:\n            lines.extend([\n                f\"## {i}. {result['title1']} ↔ {result['title2']}\",\n                \"\",\n                f\"**Files:** `{result['pattern1']}` ↔ `{result['pattern2']}`  \",\n                f\"**Similarity:** {result['similarity']['total']:.2f}  \",\n            ])\n\n        sim = result[\"similarity\"]\n        action = checker.suggest_action(sim)\n\n        lines.extend([\n            \"\",\n            f\"**Breakdown:**\",\n            f\"- Tag Similarity: {sim['tag']:.2f}\",\n            f\"- Title Similarity: {sim['title']:.2f}\",\n            f\"- Category Match: {sim['category']:.2f}\",\n            f\"- Content Similarity: {sim['content']:.2f}\",\n            \"\",\n            f\"**Suggested Action:** {action}\",\n            \"\",\n            \"---\",\n            \"\",\n        ])\n\n    with open(output_file, \"w\") as f:\n        f.write(\"\\n\".join(lines))\n\n    print(f\"Report exported to: {output_file}\")\n\n\ndef main():\n    parser = argparse.ArgumentParser(\n        description=\"Check patterns for duplicates or high similarity\",\n        formatter_class=argparse.RawDescriptionHelpFormatter,\n        epilog=\"\"\"\nExamples:\n  %(prog)s patterns/new-pattern.md\n  %(prog)s --all\n  %(prog)s --all --threshold=0.7 --export report.md\n        \"\"\",\n    )\n    parser.add_argument(\n        \"pattern_file\",\n        nargs=\"?\",\n        help=\"Path to pattern file to check against existing patterns\",\n    )\n    parser.add_argument(\n        \"--all\",\n        \"-a\",\n        action=\"store_true\",\n        help=\"Check all patterns against each other\",\n    )\n    parser.add_argument(\n        \"--patterns-dir\",\n        \"-d\",\n        type=str,\n        default=\"patterns\",\n        help=\"Path to patterns directory (default: patterns)\",\n    )\n    parser.add_argument(\n        \"--threshold\",\n        \"-t\",\n        type=float,\n        default=0.5,\n        help=\"Similarity threshold for reporting (default: 0.5)\",\n    )\n    parser.add_argument(\n        \"--export\",\n        \"-e\",\n        type=str,\n        help=\"Export report to Markdown file\",\n    )\n\n    args = parser.parse_args()\n\n    # Validate arguments\n    if not args.all and not args.pattern_file:\n        parser.error(\"Either specify a pattern file or use --all\")\n\n    if args.all and args.pattern_file:\n        parser.error(\"Cannot use --all with a specific pattern file\")\n\n    # Check patterns directory\n    patterns_dir = Path(args.patterns_dir)\n    if not patterns_dir.exists():\n        print(f\"Error: Patterns directory not found: {patterns_dir}\")\n        return 1\n\n    # Initialize checker\n    checker = PatternSimilarityChecker(str(patterns_dir), args.threshold)\n    print(f\"Loaded {len(checker.patterns)} patterns for comparison\")\n\n    # Run comparison\n    if args.all:\n        print(f\"\\n🔍 Checking all patterns for similarities (threshold: {args.threshold})...\")\n        results = checker.check_all_similarities()\n    else:\n        pattern_path = Path(args.pattern_file)\n        if not pattern_path.exists():\n            print(f\"Error: Pattern file not found: {pattern_path}\")\n            return 1\n\n        print(f\"\\n🔍 Comparing '{pattern_path.name}' against existing patterns...\")\n        results = checker.compare_to_pattern(str(pattern_path))\n\n    # Print report\n    print_similarity_report(results, args.threshold, checker)\n\n    # Export if requested\n    if args.export:\n        export_similarity_report(results, args.export, checker)\n\n    # Return exit code based on findings\n    if results:\n        return 1  # Found potential duplicates\n    return 0\n\n\nif __name__ == \"__main__\":\n    sys.exit(main())\n",".claude/skills/arxiv-pattern-discovery/scripts/pattern_validator.py":"#!/usr/bin/env python3\n\"\"\"\npattern_validator.py\n\nPre-commit validation for pattern files.\n\nValidates:\n- YAML front-matter completeness\n- Required sections presence\n- Mermaid diagram syntax\n- URL validity\n- Content quality checks\n\nUsage:\n    python scripts/pattern_validator.py <pattern-file.md>\n    python scripts/pattern_validator.py --all\n    python scripts/pattern_validator.py --fix <pattern-file.md>\n\"\"\"\n\nimport argparse\nimport os\nimport re\nimport sys\nimport urllib.request\nimport urllib.error\nfrom dataclasses import dataclass, field\nfrom enum import Enum\nfrom pathlib import Path\nfrom typing import List, Optional, Set, Tuple\n\n\n# Add parent directory to path for imports\nsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))\n\nfrom build_readme import parse_front_matter\n\n\nclass Severity(Enum):\n    \"\"\"Severity levels for validation issues.\"\"\"\n    ERROR = \"ERROR\"\n    WARNING = \"WARNING\"\n    INFO = \"INFO\"\n\n\n@dataclass\nclass ValidationIssue:\n    \"\"\"Represents a validation issue found in a pattern file.\"\"\"\n    severity: Severity\n    category: str\n    message: str\n    line: Optional[int] = None\n    column: Optional[int] = None\n    fix_suggestion: Optional[str] = None\n\n\n@dataclass\nclass ValidationResult:\n    \"\"\"Result of validating a pattern file.\"\"\"\n    file_path: str\n    is_valid: bool\n    issues: List[ValidationIssue] = field(default_factory=list)\n\n    def add_issue(self, severity: Severity, category: str, message: str,\n                  line: Optional[int] = None, fix_suggestion: Optional[str] = None):\n        self.issues.append(ValidationIssue(\n            severity=severity, category=category, message=message,\n            line=line, fix_suggestion=fix_suggestion\n        ))\n        if severity == Severity.ERROR:\n            self.is_valid = False\n\n\n# Valid values for pattern metadata\nVALID_STATUSES = {\n    \"proposed\",\n    \"emerging\",\n    \"established\",\n    \"validated-in-production\",\n    \"best-practice\",\n    \"experimental-but-awesome\",\n    \"rapidly-improving\",\n}\n\nVALID_CATEGORIES = {\n    \"Orchestration & Control\",\n    \"Context & Memory\",\n    \"Feedback Loops\",\n    \"Learning & Adaptation\",\n    \"Reliability & Eval\",\n    \"Security & Safety\",\n    \"Tool Use & Environment\",\n    \"UX & Collaboration\",\n    \"Uncategorized\",\n}\n\n# Required YAML fields\nREQUIRED_YAML_FIELDS = {\"title\", \"status\", \"authors\", \"based_on\", \"category\", \"source\", \"tags\"}\n\n# Required markdown sections\nREQUIRED_SECTIONS = {\"## Problem\", \"## Solution\", \"## References\"}\n\n\nclass PatternValidator:\n    \"\"\"Validator for pattern files.\"\"\"\n\n    def __init__(self, strict: bool = False):\n        \"\"\"\n        Initialize the validator.\n\n        Args:\n            strict: If True, treat warnings as errors\n        \"\"\"\n        self.strict = strict\n\n    def validate_file(self, filepath: str) -> ValidationResult:\n        \"\"\"\n        Validate a single pattern file.\n\n        Returns ValidationResult with all issues found.\n        \"\"\"\n        result = ValidationResult(file_path=filepath, is_valid=True)\n\n        try:\n            with open(filepath, 'r', encoding='utf-8') as f:\n                content = f.read()\n                lines = content.split('\\n')\n        except FileNotFoundError:\n            result.add_issue(Severity.ERROR, \"File\", f\"File not found: {filepath}\")\n            return result\n        except Exception as e:\n            result.add_issue(Severity.ERROR, \"File\", f\"Could not read file: {e}\")\n            return result\n\n        # Validate YAML front-matter\n        self._validate_yaml_front_matter(content, lines, result)\n\n        # Parse metadata for further validation\n        metadata = parse_front_matter(filepath)\n\n        # Validate metadata values\n        self._validate_metadata(metadata, result)\n\n        # Validate required sections\n        self._validate_sections(content, lines, result)\n\n        # Validate Mermaid diagrams\n        self._validate_mermaid_diagrams(content, lines, result)\n\n        # Validate URLs\n        self._validate_urls(content, lines, result)\n\n        # Content quality checks\n        self._validate_content_quality(content, metadata, result)\n\n        return result\n\n    def _validate_yaml_front_matter(self, content: str, lines: List[str], result: ValidationResult):\n        \"\"\"Validate YAML front-matter structure.\"\"\"\n        if not content.startswith('---'):\n            result.add_issue(\n                Severity.ERROR,\n                \"YAML\",\n                \"Pattern must start with YAML front-matter delimited by '---'\",\n                line=1,\n                fix_suggestion=\"Add YAML front-matter at the top of the file\"\n            )\n            return\n\n        # Find end of front-matter (second occurrence of ---)\n        end_marker_pos = content.find('\\n---', 4)\n        if end_marker_pos == -1:\n            result.add_issue(\n                Severity.ERROR,\n                \"YAML\",\n                \"YAML front-matter must be closed with '---'\",\n                fix_suggestion=\"Close front-matter with '---' on its own line\"\n            )\n            return\n\n        # Convert character position to line number (approximate)\n        end_line_num = content[:end_marker_pos].count('\\n') + 1\n\n        # Extract only the YAML section (lines 1 to end_line_num)\n        yaml_section = lines[1:end_line_num] if end_line_num > 1 else []\n        yaml_content = '\\n'.join(yaml_section)\n\n        # Check for empty front-matter\n        if not yaml_content.strip():\n            result.add_issue(\n                Severity.ERROR,\n                \"YAML\",\n                \"YAML front-matter is empty\",\n                line=2,\n                fix_suggestion=\"Add required YAML fields: title, status, authors, based_on, category, source, tags\"\n            )\n\n        # Check for proper YAML syntax (key: value pairs)\n        for i, yaml_line in enumerate(yaml_section, start=2):\n            if yaml_line.strip() and not yaml_line.strip().startswith('#'):\n                # Skip empty lines and comments\n                if ':' not in yaml_line and not yaml_line.strip().startswith('-'):\n                    result.add_issue(\n                        Severity.WARNING,\n                        \"YAML\",\n                        f\"Line may not be valid YAML: {yaml_line[:50]}\",\n                        line=i\n                    )\n\n    def _validate_metadata(self, metadata: dict, result: ValidationResult):\n        \"\"\"Validate metadata field values.\"\"\"\n\n        # Check required fields\n        for field in REQUIRED_YAML_FIELDS:\n            if field not in metadata:\n                result.add_issue(\n                    Severity.ERROR,\n                    \"Metadata\",\n                    f\"Missing required field: '{field}'\",\n                    fix_suggestion=f'Add \"{field}: <value>\" to YAML front-matter'\n                )\n\n        # Validate status\n        if \"status\" in metadata:\n            status = metadata[\"status\"]\n            if status not in VALID_STATUSES:\n                result.add_issue(\n                    Severity.ERROR,\n                    \"Metadata\",\n                    f\"Invalid status: '{status}'. Must be one of: {', '.join(sorted(VALID_STATUSES))}\",\n                    fix_suggestion=f\"Use one of: {', '.join(sorted(VALID_STATUSES))}\"\n                )\n\n        # Validate category\n        if \"category\" in metadata:\n            category = metadata[\"category\"]\n            if category not in VALID_CATEGORIES:\n                result.add_issue(\n                    Severity.WARNING,\n                    \"Metadata\",\n                    f\"Unknown category: '{category}'. Known categories: {', '.join(sorted(VALID_CATEGORIES))}\",\n                    fix_suggestion=f\"Use one of: {', '.join(sorted(VALID_CATEGORIES))}\"\n                )\n\n        # Validate authors is a list\n        if \"authors\" in metadata:\n            authors = metadata[\"authors\"]\n            if not isinstance(authors, list):\n                result.add_issue(\n                    Severity.ERROR,\n                    \"Metadata\",\n                    f\"'authors' must be a list: ['Name (@username)']\",\n                    fix_suggestion=\"Format as: authors: [\\\"Name (@username)\\\"]\"\n                )\n\n        # Validate tags is a list\n        if \"tags\" in metadata:\n            tags = metadata[\"tags\"]\n            if not isinstance(tags, list):\n                result.add_issue(\n                    Severity.ERROR,\n                    \"Metadata\",\n                    f\"'tags' must be a list: [tag1, tag2, tag3]\",\n                    fix_suggestion=\"Format as: tags: [tag1, tag2, tag3]\"\n                )\n            # Check for empty tags\n            elif any(not tag.strip() for tag in tags):\n                result.add_issue(\n                    Severity.WARNING,\n                    \"Metadata\",\n                    \"Tags list contains empty strings\",\n                    fix_suggestion=\"Remove empty tags\"\n                )\n\n        # Validate source is a URL\n        if \"source\" in metadata:\n            source = metadata[\"source\"]\n            if not source.startswith((\"http://\", \"https://\", \"arxiv://\")):\n                result.add_issue(\n                    Severity.WARNING,\n                    \"Metadata\",\n                    f\"'source' should be a URL: {source}\",\n                    fix_suggestion=\"Use a valid URL starting with http:// or https://\"\n                )\n\n        # Title quality checks\n        if \"title\" in metadata:\n            title = metadata[\"title\"]\n            if len(title) < 10:\n                result.add_issue(\n                    Severity.WARNING,\n                    \"Metadata\",\n                    f\"Title seems too short: '{title}'\",\n                    fix_suggestion=\"Use a more descriptive title\"\n                )\n            if title.islower():\n                result.add_issue(\n                    Severity.INFO,\n                    \"Metadata\",\n                    \"Title should use Title Case\",\n                    fix_suggestion=\"Capitalize the first letter of each word\"\n                )\n\n    def _validate_sections(self, content: str, lines: List[str], result: ValidationResult):\n        \"\"\"Validate required markdown sections.\"\"\"\n        # Skip YAML front-matter\n        start_idx = content.find('\\n---', 4)\n        if start_idx == -1:\n            start_idx = 0\n        else:\n            start_idx += 5\n\n        main_content = content[start_idx:]\n\n        for section in REQUIRED_SECTIONS:\n            if section not in main_content:\n                result.add_issue(\n                    Severity.ERROR,\n                    \"Structure\",\n                    f\"Missing required section: '{section}'\",\n                    fix_suggestion=f\"Add '## {section}' section\"\n                )\n\n        # Check for recommended sections (without ## prefix for matching)\n        recommended = {\"How to use it\", \"Trade-offs\"}\n        found_sections = set(re.findall(r'^## (.+)$', main_content, re.MULTILINE))\n        missing_recommended = recommended - found_sections\n\n        if missing_recommended:\n            for section in missing_recommended:\n                result.add_issue(\n                    Severity.INFO,\n                    \"Structure\",\n                    f\"Missing recommended section: '## {section}'\",\n                    fix_suggestion=f\"Consider adding '## {section}' section\"\n                )\n\n    def _validate_mermaid_diagrams(self, content: str, lines: List[str], result: ValidationResult):\n        \"\"\"Validate Mermaid diagram syntax.\"\"\"\n\n        # Find all Mermaid code blocks\n        mermaid_blocks = re.finditer(r'```mermaid\\n(.*?)```', content, re.DOTALL)\n\n        if not mermaid_blocks:\n            # Check if pattern might benefit from a diagram\n            if \"## Solution\" in content and len(content) > 2000:\n                result.add_issue(\n                    Severity.INFO,\n                    \"Content\",\n                    \"Consider adding a Mermaid diagram to illustrate the pattern\",\n                    fix_suggestion=\"Add a Mermaid diagram in the Solution section\"\n                )\n            return\n\n        for match in mermaid_blocks:\n            diagram = match.group(1)\n            block_start = content[:match.start()].count('\\n') + 1\n\n            # Basic Mermaid syntax checks\n            valid_diagram_types = {\n                \"graph\", \"flowchart\", \"sequenceDiagram\", \"classDiagram\",\n                \"stateDiagram\", \"erDiagram\", \"gantt\", \"pie\", \"gitGraph\"\n            }\n\n            first_line = diagram.strip().split('\\n')[0].strip()\n            diagram_type = first_line.split()[0] if first_line else \"\"\n\n            if diagram_type and diagram_type not in valid_diagram_types:\n                result.add_issue(\n                    Severity.WARNING,\n                    \"Mermaid\",\n                    f\"Unrecognized diagram type: '{diagram_type}'\",\n                    line=block_start + 1,\n                    fix_suggestion=f\"Use one of: {', '.join(valid_diagram_types)}\"\n                )\n\n            # Check for common syntax errors\n            if ' --' in diagram and '-->' not in diagram:\n                result.add_issue(\n                    Severity.WARNING,\n                    \"Mermaid\",\n                    \"Found ' --' which might be a typo for ' -->' (arrow)\",\n                    line=block_start\n                )\n\n            # Check for unclosed brackets/parentheses (basic check)\n            open_brackets = diagram.count('[') + diagram.count('(') + diagram.count('{')\n            close_brackets = diagram.count(']') + diagram.count(')') + diagram.count('}')\n            if open_brackets != close_brackets:\n                result.add_issue(\n                    Severity.WARNING,\n                    \"Mermaid\",\n                    \"Unclosed brackets or parentheses detected\",\n                    line=block_start\n                )\n\n    def _validate_urls(self, content: str, lines: List[str], result: ValidationResult):\n        \"\"\"Validate URLs in the document.\"\"\"\n        # Find all URLs\n        url_pattern = re.compile(r'https?://[^\\s\\)]+')\n\n        for i, line in enumerate(lines, start=1):\n            urls = url_pattern.findall(line)\n            for url in urls:\n                # Clean URL (remove trailing punctuation)\n                clean_url = re.sub(r'[.,;:]$', '', url)\n\n                # Basic URL format check\n                if not re.match(r'^https?://[a-zA-Z0-9\\-._~:/?#\\[\\]@!$&\\'()*+,;=%]+$', clean_url):\n                    result.add_issue(\n                        Severity.WARNING,\n                        \"URL\",\n                        f\"Potentially malformed URL: {clean_url[:60]}...\",\n                        line=i\n                    )\n\n                # Check for common issues\n                if 'arxiv.org' in clean_url.lower():\n                    if 'abs/' in clean_url and not clean_url.startswith('https://arxiv.org/abs/'):\n                        result.add_issue(\n                            Severity.INFO,\n                            \"URL\",\n                            f\"arXiv URL format may need standardization\",\n                            line=i\n                        )\n\n    def _validate_content_quality(self, content: str, metadata: dict, result: ValidationResult):\n        \"\"\"Perform content quality checks.\"\"\"\n\n        # Get word counts for sections\n        def count_section_text(section_name):\n            pattern = rf'## {section_name}\\s*\\n(.*?)(?=\\n## |\\Z)'\n            match = re.search(pattern, content, re.DOTALL)\n            if match:\n                text = match.group(1)\n                # Remove code blocks\n                text = re.sub(r'```.*?```', '', text, flags=re.DOTALL)\n                return len(text.split())\n            return 0\n\n        # Check Problem section length\n        problem_words = count_section_text(\"Problem\")\n        if problem_words > 0 and problem_words < 20:\n            result.add_issue(\n                Severity.WARNING,\n                \"Content\",\n                f\"Problem section seems too short ({problem_words} words)\",\n                fix_suggestion=\"Expand the problem description to at least 2-3 sentences\"\n            )\n\n        # Check Solution section length\n        solution_words = count_section_text(\"Solution\")\n        if solution_words > 0 and solution_words < 50:\n            result.add_issue(\n                Severity.WARNING,\n                \"Content\",\n                f\"Solution section seems too short ({solution_words} words)\",\n                fix_suggestion=\"Expand the solution description with more implementation details\"\n            )\n\n        # Check for empty sections\n        section_pattern = re.compile(r'## ([^\\n]+)\\s*\\n(.*?)(?=\\n## |\\Z)', re.DOTALL)\n        for match in section_pattern.finditer(content):\n            section_name = match.group(1)\n            section_content = match.group(2).strip()\n            if not section_content or section_content == \"```\":\n                result.add_issue(\n                    Severity.ERROR,\n                    \"Content\",\n                    f\"Section '{section_name}' is empty\",\n                    fix_suggestion=f\"Add content to the '{section_name}' section\"\n                )\n\n        # Check for required blank lines after headers\n        header_pattern = re.compile(r'##[^\\n]+\\n([^\\s#])')\n        for match in header_pattern.finditer(content):\n            line_num = content[:match.start()].count('\\n') + 2\n            char_after = match.group(1)\n            if char_after and char_after != '\\n':\n                result.add_issue(\n                    Severity.WARNING,\n                    \"Formatting\",\n                    \"Headers should be followed by a blank line for proper list rendering\",\n                    line=line_num,\n                    fix_suggestion=\"Add a blank line after the header\"\n                )\n\n\ndef print_validation_result(result: ValidationResult, verbose: bool = False):\n    \"\"\"Print validation results to stdout.\"\"\"\n\n    # Group issues by severity\n    errors = [i for i in result.issues if i.severity == Severity.ERROR]\n    warnings = [i for i in result.issues if i.severity == Severity.WARNING]\n    infos = [i for i in result.issues if i.severity == Severity.INFO]\n\n    # Print status\n    status_icon = \"✅\" if result.is_valid else \"❌\"\n    filename = Path(result.file_path).name\n    print(f\"{status_icon} {filename}: {len(result.issues)} issue(s)\")\n\n    if not verbose and result.is_valid and not warnings:\n        return\n\n    # Print issues\n    for issue in result.issues:\n        severity_icon = {\n            Severity.ERROR: \"❌\",\n            Severity.WARNING: \"⚠️ \",\n            Severity.INFO: \"ℹ️ \",\n        }[issue.severity]\n\n        line_info = f\":{issue.line}\" if issue.line else \"\"\n        print(f\"  {severity_icon} [{issue.category}]{line_info} {issue.message}\")\n\n        if issue.fix_suggestion:\n            print(f\"     💡 {issue.fix_suggestion}\")\n\n    # Print summary\n    if errors:\n        print(f\"  Summary: {len(errors)} error(s), {len(warnings)} warning(s), {len(infos)} info\")\n\n\ndef print_validation_summary(results: List[ValidationResult]):\n    \"\"\"Print overall validation summary.\"\"\"\n\n    total = len(results)\n    valid = sum(1 for r in results if r.is_valid)\n    total_issues = sum(len(r.issues) for r in results)\n\n    print(f\"\\n{'='*60}\")\n    print(f\"SUMMARY: {valid}/{total} files valid, {total_issues} total issue(s)\")\n    print(f\"{'='*60}\")\n\n    # Aggregate counts\n    all_errors = []\n    all_warnings = []\n\n    for result in results:\n        all_errors.extend([i for i in result.issues if i.severity == Severity.ERROR])\n        all_warnings.extend([i for i in result.issues if i.severity == Severity.WARNING])\n\n    # Common issues\n    if all_errors:\n        error_cats = {}\n        for e in all_errors:\n            error_cats[e.category] = error_cats.get(e.category, 0) + 1\n        print(f\"\\nTop error categories:\")\n        for cat, count in sorted(error_cats.items(), key=lambda x: -x[1])[:5]:\n            print(f\"  - {cat}: {count}\")\n\n\ndef export_validation_report(results: List[ValidationResult], output_file: str):\n    \"\"\"Export validation report to Markdown.\"\"\"\n\n    lines = [\n        \"# Pattern Validation Report\",\n        \"\",\n        f\"Generated: {__import__('datetime').datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\",\n        \"\",\n        \"---\",\n        \"\",\n    ]\n\n    for result in results:\n        filename = Path(result.file_path).name\n        status = \"✅ PASS\" if result.is_valid else \"❌ FAIL\"\n\n        lines.extend([\n            f\"## {status}: {filename}\",\n            \"\",\n            f\"Issues found: {len(result.issues)}\",\n            \"\",\n        ])\n\n        if result.issues:\n            for issue in result.issues:\n                severity = issue.severity.value\n                line_info = f\":{issue.line}\" if issue.line else \"\"\n                lines.extend([\n                    f\"**{severity}** [{issue.category}]{line_info}\",\n                    f\"{issue.message}\",\n                ])\n                if issue.fix_suggestion:\n                    lines.append(f\"_Fix: {issue.fix_suggestion}_\")\n                lines.append(\"\")\n\n        lines.extend([\"---\", \"\"])\n\n    with open(output_file, \"w\") as f:\n        f.write(\"\\n\".join(lines))\n\n    print(f\"\\nReport exported to: {output_file}\")\n\n\ndef main():\n    parser = argparse.ArgumentParser(\n        description=\"Validate pattern files for completeness and quality\",\n        formatter_class=argparse.RawDescriptionHelpFormatter,\n        epilog=\"\"\"\nExamples:\n  %(prog)s patterns/new-pattern.md\n  %(prog)s --all\n  %(prog)s --all --verbose --export report.md\n        \"\"\",\n    )\n    parser.add_argument(\n        \"pattern_file\",\n        nargs=\"?\",\n        help=\"Path to pattern file to validate\",\n    )\n    parser.add_argument(\n        \"--all\",\n        \"-a\",\n        action=\"store_true\",\n        help=\"Validate all pattern files\",\n    )\n    parser.add_argument(\n        \"--patterns-dir\",\n        \"-d\",\n        type=str,\n        default=\"patterns\",\n        help=\"Path to patterns directory (default: patterns)\",\n    )\n    parser.add_argument(\n        \"--verbose\",\n        \"-v\",\n        action=\"store_true\",\n        help=\"Print detailed output for each issue\",\n    )\n    parser.add_argument(\n        \"--strict\",\n        \"-s\",\n        action=\"store_true\",\n        help=\"Treat warnings as errors\",\n    )\n    parser.add_argument(\n        \"--export\",\n        \"-e\",\n        type=str,\n        help=\"Export report to Markdown file\",\n    )\n\n    args = parser.parse_args()\n\n    # Validate arguments\n    if not args.all and not args.pattern_file:\n        parser.error(\"Either specify a pattern file or use --all\")\n\n    if args.all and args.pattern_file:\n        parser.error(\"Cannot use --all with a specific pattern file\")\n\n    # Initialize validator\n    validator = PatternValidator(strict=args.strict)\n\n    # Collect files to validate\n    files_to_validate = []\n\n    if args.all:\n        patterns_dir = Path(args.patterns_dir)\n        if not patterns_dir.exists():\n            print(f\"Error: Patterns directory not found: {patterns_dir}\")\n            return 1\n\n        for filepath in sorted(patterns_dir.glob(\"*.md\")):\n            if filepath.name != \"TEMPLATE.md\":\n                files_to_validate.append(str(filepath))\n    else:\n        files_to_validate.append(args.pattern_file)\n\n    # Run validation\n    print(f\"Validating {len(files_to_validate)} file(s)...\\n\")\n\n    results = []\n    for filepath in files_to_validate:\n        if not Path(filepath).exists():\n            print(f\"❌ File not found: {filepath}\")\n            continue\n\n        result = validator.validate_file(filepath)\n        results.append(result)\n        print_validation_result(result, verbose=args.verbose)\n\n    # Print summary\n    if len(results) > 1:\n        print_validation_summary(results)\n\n    # Export if requested\n    if args.export:\n        export_validation_report(results, args.export)\n\n    # Return exit code\n    return 0 if all(r.is_valid for r in results) else 1\n\n\nif __name__ == \"__main__\":\n    sys.exit(main())\n",".claude/skills/arxiv-pattern-discovery/scripts/arxiv_scanner.py":"#!/usr/bin/env python3\n\"\"\"\narxiv_scanner.py\n\nAutomated paper discovery for new agentic patterns from arXiv.\n\nQueries arXiv API with targeted search terms, filters by date/citation count/keywords,\nand scores papers using the Pattern Quality Rubric (0-10).\n\nUsage:\n    python scripts/arxiv_scanner.py --days=7 --min-citations=3\n    python scripts/arxiv_scanner.py --query=\"multi-agent systems\" --max-results=50\n\"\"\"\n\nimport argparse\nimport configparser\nimport dataclasses\nimport datetime\nimport json\nimport re\nimport sys\nimport time\nimport urllib.parse\nimport urllib.request\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Optional, Set\n\n\n# Configuration\nDEFAULT_SEARCH_QUERY = '(cat:cs.AI OR cat:cs.CL OR cat:cs.LG OR cat:cs.CR) AND all:\"agent\" OR all:\"agentic\" OR all:\"multi-agent\"'\nARXIV_API_URL = \"http://export.arxiv.org/api/query?\"\nUSER_AGENT = \"arxiv-scanner/0.1 (https://github.com/nibzard/awesome-agentic-patterns)\"\n\n\n# Valid status values for patterns\nVALID_STATUSES = {\n    \"proposed\",\n    \"emerging\",\n    \"established\",\n    \"validated-in-production\",\n    \"best-practice\",\n    \"experimental-but-awesome\",\n    \"rapidly-improving\",\n}\n\n# Valid category values\nVALID_CATEGORIES = {\n    \"Orchestration & Control\",\n    \"Context & Memory\",\n    \"Feedback Loops\",\n    \"Learning & Adaptation\",\n    \"Reliability & Eval\",\n    \"Security & Safety\",\n    \"Tool Use & Environment\",\n    \"UX & Collaboration\",\n    \"Uncategorized\",\n}\n\n\n@dataclasses.dataclass\nclass Paper:\n    \"\"\"Represents an arXiv paper with metadata.\"\"\"\n\n    arxiv_id: str\n    title: str\n    authors: List[str]\n    abstract: str\n    published: str\n    updated: str\n    categories: List[str]\n    url: str\n    citation_count: int = 0\n    quality_score: float = 0.0\n\n\n@dataclasses.dataclass\nclass PatternCandidate:\n    \"\"\"Represents a potential pattern extracted from a paper.\"\"\"\n\n    paper: Paper\n    pattern_name: Optional[str] = None\n    category: Optional[str] = None\n    tags: List[str] = dataclasses.field(default_factory=list)\n    score_breakdown: Dict[str, float] = dataclasses.field(default_factory=dict)\n    total_score: float = 0.0\n\n\nclass ArxivAPIError(Exception):\n    \"\"\"Raised when arXiv API request fails.\"\"\"\n\n    pass\n\n\ndef fetch_arxiv_papers(\n    query: str,\n    max_results: int = 100,\n    sort_by: str = \"submittedDate\",\n    sort_order: str = \"descending\",\n) -> List[Paper]:\n    \"\"\"\n    Fetch papers from arXiv API.\n\n    Args:\n        query: Search query string\n        max_results: Maximum number of results to return\n        sort_by: Sort field (lastUpdatedDate, submittedDate)\n        sort_order: ascending or descending\n\n    Returns:\n        List of Paper objects\n    \"\"\"\n    encoded_query = urllib.parse.quote(query)\n    url = f\"{ARXIV_API_URL}search_query={encoded_query}&start=0&max_results={max_results}&sortBy={sort_by}&sortOrder={sort_order}\"\n\n    headers = {\"User-Agent\": USER_AGENT}\n\n    try:\n        req = urllib.request.Request(url, headers=headers)\n        with urllib.request.urlopen(req, timeout=30) as response:\n            xml_data = response.read().decode(\"utf-8\")\n    except urllib.error.URLError as e:\n        raise ArxivAPIError(f\"Failed to fetch papers: {e}\")\n\n    return parse_arxiv_response(xml_data)\n\n\ndef parse_arxiv_response(xml_data: str) -> List[Paper]:\n    \"\"\"Parse arXiv API XML response into Paper objects.\"\"\"\n    papers = []\n\n    # Extract entries using regex (simple approach, could use xml.etree)\n    entry_pattern = re.compile(r\"<entry>(.*?)</entry>\", re.DOTALL)\n    title_pattern = re.compile(r\"<title>(.*?)</title>\", re.DOTALL)\n    author_pattern = re.compile(r\"<name>(.*?)</name>\")\n    summary_pattern = re.compile(r\"<summary>(.*?)</summary>\", re.DOTALL)\n    published_pattern = re.compile(r\"<published>(.*?)</published>\")\n    updated_pattern = re.compile(r\"<updated>(.*?)</updated>\")\n    category_pattern = re.compile(r'<term[^>]*>([^<]+)</term>')\n    id_pattern = re.compile(r\"<id>(.*?)</id>\")\n    arxiv_id_pattern = re.compile(r\"arxiv.org/abs/(\\d+\\.\\d+)\")\n\n    for entry_match in entry_pattern.finditer(xml_data):\n        entry = entry_match.group(1)\n\n        # Extract title\n        title_match = title_pattern.search(entry)\n        title = title_match.group(1).strip().replace(\"\\n\", \" \") if title_match else \"Unknown\"\n\n        # Extract authors\n        authors = [a.strip() for a in author_pattern.findall(entry)]\n\n        # Extract abstract\n        summary_match = summary_pattern.search(entry)\n        abstract = summary_match.group(1).strip().replace(\"\\n\", \" \") if summary_match else \"\"\n\n        # Extract dates\n        published_match = published_pattern.search(entry)\n        published = published_match.group(1) if published_match else \"\"\n\n        updated_match = updated_pattern.search(entry)\n        updated = updated_match.group(1) if updated_match else \"\"\n\n        # Extract categories (primary and secondary)\n        categories = list(set(category_pattern.findall(entry)))\n\n        # Extract arXiv ID\n        id_match = id_pattern.search(entry)\n        arxiv_id = \"unknown\"\n        if id_match:\n            arxiv_id_match = arxiv_id_pattern.search(id_match.group(1))\n            if arxiv_id_match:\n                arxiv_id = arxiv_id_match.group(1)\n\n        # Build URL\n        url = f\"https://arxiv.org/abs/{arxiv_id}\"\n\n        papers.append(\n            Paper(\n                arxiv_id=arxiv_id,\n                title=title,\n                authors=authors,\n                abstract=abstract,\n                published=published,\n                updated=updated,\n                categories=categories,\n                url=url,\n            )\n        )\n\n    return papers\n\n\ndef parse_date(date_string: str) -> datetime.datetime:\n    \"\"\"Parse arXiv date string to datetime object.\"\"\"\n    # arXiv dates are in format: 2025-01-15T12:34:56Z\n    try:\n        return datetime.datetime.fromisoformat(date_string.replace(\"Z\", \"+00:00\"))\n    except ValueError:\n        # Fallback for other formats\n        return datetime.datetime.min\n\n\ndef filter_papers_by_date(papers: List[Paper], days: int) -> List[Paper]:\n    \"\"\"Filter papers to those published/updated within the last N days.\"\"\"\n    cutoff = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(days=days)\n    return [p for p in papers if parse_date(p.published) >= cutoff or parse_date(p.updated) >= cutoff]\n\n\ndef filter_papers_by_keywords(papers: List[Paper]) -> List[Paper]:\n    \"\"\"Filter papers to those containing architecture/pattern keywords in abstract.\"\"\"\n    architectural_terms = {\n        \"architecture\",\n        \"pattern\",\n        \"framework\",\n        \"design\",\n        \"orchestration\",\n        \"coordination\",\n        \"hierarchy\",\n        \"protocol\",\n        \"memory\",\n        \"agent\",\n        \"agentic\",\n        \"multi-agent\",\n        \"autonomous\",\n        \"workflow\",\n        \"control\",\n        \"feedback\",\n        \"adapter\",\n        \"interface\",\n        \"abstraction\",\n    }\n\n    filtered = []\n    for paper in papers:\n        abstract_lower = paper.abstract.lower()\n        title_lower = paper.title.lower()\n        combined = title_lower + \" \" + abstract_lower\n\n        if any(term in combined for term in architectural_terms):\n            filtered.append(paper)\n\n    return filtered\n\n\ndef score_reusability(paper: Paper) -> float:\n    \"\"\"\n    Score paper on reusability (30% weight).\n\n    Domain-specific (1.0) → Multi-domain (2.0) → Universal (3.0)\n    \"\"\"\n    abstract_lower = paper.abstract.lower()\n    title_lower = paper.title.lower()\n    combined = title_lower + \" \" + abstract_lower\n\n    # Check for universal language\n    universal_indicators = [\"general\", \"universal\", \"framework\", \"generic\", \"generic approach\"]\n    multi_domain_indicators = [\"multi-domain\", \"cross-domain\", \"versatile\", \"adaptable\"]\n    domain_specific_indicators = [\"specific to\", \"in the field of\", \"domain-specific\"]\n\n    universal_count = sum(1 for term in universal_indicators if term in combined)\n    multi_domain_count = sum(1 for term in multi_domain_indicators if term in combined)\n    domain_specific_count = sum(1 for term in domain_specific_indicators if term in combined)\n\n    # Also check for broad application potential\n    broad_terms = [\"wide range\", \"variety of\", \"multiple use cases\", \"flexible\"]\n    broad_count = sum(1 for term in broad_terms if term in combined)\n\n    if universal_count >= 1 or broad_count >= 1:\n        return 3.0\n    elif multi_domain_count >= 1:\n        return 2.0\n    elif domain_specific_count >= 1:\n        return 1.0\n    else:\n        # Default to mid-range\n        return 2.0\n\n\ndef score_novelty(paper: Paper) -> float:\n    \"\"\"\n    Score paper on novelty (25% weight).\n\n    Existing (1.0) → Incremental (2.0) → Fundamentally new (3.0)\n    \"\"\"\n    abstract_lower = paper.abstract.lower()\n    title_lower = paper.title.lower()\n    combined = title_lower + \" \" + abstract_lower\n\n    # Check for novelty indicators\n    novel_indicators = [\n        \"novel\",\n        \"new\",\n        \"first\",\n        \"pioneering\",\n        \"groundbreaking\",\n        \"innovative\",\n        \"unprecedented\",\n        \"original\",\n        \"unique approach\",\n    ]\n    incremental_indicators = [\n        \"improves\",\n        \"extends\",\n        \"builds on\",\n        \"enhances\",\n        \"optimizes\",\n        \"refines\",\n        \"extension of\",\n    ]\n\n    novel_count = sum(1 for term in novel_indicators if term in combined)\n    incremental_count = sum(1 for term in incremental_indicators if term in combined)\n\n    # Check for strong claims of new approaches\n    strong_novel = [\"new architecture\", \"new framework\", \"new paradigm\", \"first to\"]\n    strong_novel_count = sum(1 for term in strong_novel if term in combined)\n\n    if strong_novel_count >= 1 or novel_count >= 2:\n        return 3.0\n    elif novel_count >= 1 and incremental_count == 0:\n        return 2.5\n    elif incremental_count >= 1:\n        return 2.0\n    else:\n        return 1.5\n\n\ndef score_clarity(paper: Paper) -> float:\n    \"\"\"\n    Score paper on clarity (20% weight).\n\n    Vague (1.0) → Clear (2.0) → Crystal clear (3.0)\n    \"\"\"\n    abstract_lower = paper.abstract.lower()\n    title_lower = paper.title.lower()\n    combined = title_lower + \" \" + abstract_lower\n\n    # Clarity indicators\n    clear_indicators = [\n        \"we propose\",\n        \"we present\",\n        \"our approach\",\n        \"the method\",\n        \"the algorithm\",\n        \"specifically\",\n        \"concretely\",\n    ]\n    vague_indicators = [\n        \"some ways\",\n        \"somewhat\",\n        \"may\",\n        \"might\",\n        \"potentially\",\n        \"could be\",\n    ]\n\n    clear_count = sum(1 for term in clear_indicators if term in combined)\n    vague_count = sum(1 for term in vague_indicators if term in combined)\n\n    # Abstract length (too short might indicate lack of detail)\n    abstract_words = len(paper.abstract.split())\n    length_score = 0\n    if abstract_words > 150:\n        length_score = 1\n    elif abstract_words > 100:\n        length_score = 0.5\n\n    base_score = 2.0\n    if clear_count >= 3:\n        base_score = 2.5\n    if vague_count >= 3:\n        base_score = max(1.0, base_score - 0.5)\n\n    return min(3.0, base_score + length_score)\n\n\ndef score_evidence(paper: Paper) -> float:\n    \"\"\"\n    Score paper on empirical evidence (15% weight).\n\n    No eval (1.0) → Some eval (2.0) → Strong empirical (3.0)\n    \"\"\"\n    abstract_lower = paper.abstract.lower()\n\n    # Evidence indicators\n    eval_indicators = [\n        \"evaluation\",\n        \"experiment\",\n        \"benchmark\",\n        \"results\",\n        \"performance\",\n        \"compared\",\n        \"comparison\",\n        \"metric\",\n    ]\n    strong_eval_indicators = [\n        \"significant improvement\",\n        \"state-of-the-art\",\n        \"sota\",\n        \"outperforms\",\n        \"empirical\",\n        \"real-world\",\n        \"deployment\",\n    ]\n\n    eval_count = sum(1 for term in eval_indicators if term in abstract_lower)\n    strong_eval_count = sum(1 for term in strong_eval_indicators if term in abstract_lower)\n\n    # Check for datasets (indicates empirical work)\n    dataset_indicators = [\"dataset\", \"benchmark\", \"we evaluate on\", \"tested on\"]\n    dataset_count = sum(1 for term in dataset_indicators if term in abstract_lower)\n\n    if strong_eval_count >= 1 or eval_count >= 3:\n        return 3.0\n    elif eval_count >= 1:\n        return 2.0\n    elif dataset_count >= 1:\n        return 2.0\n    else:\n        return 1.0\n\n\ndef score_completeness(paper: Paper) -> float:\n    \"\"\"\n    Score paper on implementation completeness (10% weight).\n\n    Idea only (1.0) → Partial details (2.0) → Production-ready (3.0)\n    \"\"\"\n    abstract_lower = paper.abstract.lower()\n\n    # Completeness indicators\n    implementation_indicators = [\n        \"implementation\",\n        \"open source\",\n        \"code\",\n        \"available\",\n        \"github\",\n        \"released\",\n        \"library\",\n    ]\n    detail_indicators = [\n        \"algorithm\",\n        \"architecture\",\n        \"framework\",\n        \"protocol\",\n        \"method\",\n        \"approach\",\n    ]\n\n    implementation_count = sum(1 for term in implementation_indicators if term in abstract_lower)\n    detail_count = sum(1 for term in detail_indicators if term in abstract_lower)\n\n    # Check for production mentions\n    production_indicators = [\"production\", \"deployed\", \"real-world\", \"industry\"]\n    production_count = sum(1 for term in production_indicators if term in abstract_lower)\n\n    if implementation_count >= 2 or production_count >= 1:\n        return 3.0\n    elif implementation_count >= 1 or detail_count >= 3:\n        return 2.0\n    elif detail_count >= 1:\n        return 1.5\n    else:\n        return 1.0\n\n\ndef calculate_quality_score(paper: Paper) -> tuple[float, Dict[str, float]]:\n    \"\"\"\n    Calculate overall quality score using the Pattern Quality Rubric.\n\n    Returns:\n        Tuple of (total_score, score_breakdown)\n    \"\"\"\n    # Weighted scoring\n    reusability = score_reusability(paper)\n    novelty = score_novelty(paper)\n    clarity = score_clarity(paper)\n    evidence = score_evidence(paper)\n    completeness = score_completeness(paper)\n\n    # Weights\n    total_score = (\n        reusability * 0.30 +\n        novelty * 0.25 +\n        clarity * 0.20 +\n        evidence * 0.15 +\n        completeness * 0.10\n    )\n\n    breakdown = {\n        \"reusability\": reusability,\n        \"novelty\": novelty,\n        \"clarity\": clarity,\n        \"evidence\": evidence,\n        \"completeness\": completeness,\n    }\n\n    return total_score, breakdown\n\n\ndef categorize_paper(paper: Paper, existing_patterns: List[Dict]) -> Optional[str]:\n    \"\"\"\n    Attempt to categorize a paper into one of the pattern categories.\n\n    Returns the category name or None if uncertain.\n    \"\"\"\n    abstract_lower = paper.abstract.lower()\n    title_lower = paper.title.lower()\n    combined = title_lower + \" \" + abstract_lower\n\n    # Category-specific keywords\n    category_keywords = {\n        \"Orchestration & Control\": [\n            \"orchestration\", \"coordination\", \"control\", \"hierarchy\", \"planner\",\n            \"workflow\", \"supervisor\", \"manager\", \"scheduler\", \"decomposition\",\n            \"sub-agent\", \"spawning\", \"multi-agent coordination\",\n        ],\n        \"Context & Memory\": [\n            \"memory\", \"context\", \"recall\", \"retrieval\", \"episodic\",\n            \"vector\", \"embedding\", \"rag\", \"knowledge base\", \"state\",\n            \"continuum\", \"temporal context\",\n        ],\n        \"Feedback Loops\": [\n            \"feedback\", \"iteration\", \"refinement\", \"self-improve\",\n            \"critique\", \"eval\", \"evaluation\", \"monitor\", \"adjust\",\n            \"adaptive\", \"learning from feedback\",\n        ],\n        \"Learning & Adaptation\": [\n            \"learning\", \"reinforcement\", \"rl\", \"fine-tuning\", \"adaptation\",\n            \"skill\", \"evolution\", \"training\", \"optimizer\",\n        ],\n        \"Reliability & Eval\": [\n            \"reliability\", \"safety\", \"guardrail\", \"error\", \"robust\",\n            \"testing\", \"validation\", \"verification\", \"deterministic\",\n        ],\n        \"Security & Safety\": [\n            \"security\", \"privacy\", \"attack\", \"malicious\", \"adversarial\",\n            \"sandbox\", \"isolation\", \"monitoring\", \"threat model\",\n            \"exfiltration\", \"laundering\",\n        ],\n        \"Tool Use & Environment\": [\n            \"tool\", \"api\", \"function call\", \"environment\", \"execution\",\n            \"browser\", \"shell\", \"filesystem\", \"external\", \"integration\",\n        ],\n        \"UX & Collaboration\": [\n            \"user experience\", \"ux\", \"collaboration\", \"human-in-loop\",\n            \"handoff\", \"notification\", \"interaction\", \"interface\",\n        ],\n    }\n\n    # Count keyword matches for each category\n    category_scores = {}\n    for category, keywords in category_keywords.items():\n        score = sum(1 for kw in keywords if kw in combined)\n        if score > 0:\n            category_scores[category] = score\n\n    # Return category with highest score (if any)\n    if category_scores:\n        return max(category_scores, key=category_scores.get)\n\n    return None\n\n\ndef extract_tags(paper: Paper) -> List[str]:\n    \"\"\"\n    Extract relevant tags from paper metadata.\n\n    Returns a list of lowercase tags suitable for pattern files.\n    \"\"\"\n    abstract_lower = paper.abstract.lower()\n    title_lower = paper.title.lower()\n    combined = title_lower + \" \" + abstract_lower\n\n    # Common agentic pattern keywords\n    tag_keywords = [\n        \"agent\", \"multi-agent\", \"orchestration\", \"coordination\",\n        \"memory\", \"context\", \"rag\", \"retrieval\",\n        \"feedback\", \"iteration\", \"self-improve\",\n        \"tool\", \"api\", \"function-call\",\n        \"planning\", \"planner\", \"decomposition\",\n        \"parallel\", \"concurrent\", \"async\",\n        \"hierarchy\", \"hierarchical\", \"layered\",\n        \"security\", \"privacy\", \"sandbox\",\n        \"evaluation\", \"benchmark\", \"testing\",\n        \"autonomous\", \"automation\",\n        \"workflow\", \"pipeline\",\n        \"communication\", \"protocol\",\n    ]\n\n    tags = []\n    for keyword in tag_keywords:\n        if keyword in combined:\n            tags.append(keyword)\n\n    return tags\n\n\ndef print_paper_summary(paper: Paper, score: float, breakdown: Dict[str, float], category: Optional[str]):\n    \"\"\"Print a formatted summary of a paper with its scores.\"\"\"\n    print(f\"\\n{'='*70}\")\n    print(f\"Title: {paper.title}\")\n    print(f\"arXiv: {paper.arxiv_id} | Score: {score:.2f}/10.0\")\n    print(f\"URL: {paper.url}\")\n    if category:\n        print(f\"Suggested Category: {category}\")\n    print(f\"\\nScore Breakdown:\")\n    print(f\"  Reusability (30%):    {breakdown['reusability']:.1f}/3.0\")\n    print(f\"  Novelty (25%):        {breakdown['novelty']:.1f}/3.0\")\n    print(f\"  Clarity (20%):        {breakdown['clarity']:.1f}/3.0\")\n    print(f\"  Evidence (15%):       {breakdown['evidence']:.1f}/3.0\")\n    print(f\"  Completeness (10%):   {breakdown['completeness']:.1f}/3.0\")\n    print(f\"\\nAbstract: {paper.abstract[:300]}...\")\n\n\ndef export_results(papers: List[Dict[str, Any]], output_file: str):\n    \"\"\"Export scan results to JSON file.\"\"\"\n    with open(output_file, \"w\") as f:\n        json.dump(papers, f, indent=2)\n    print(f\"\\nResults exported to: {output_file}\")\n\n\ndef export_markdown_report(papers: List[Dict[str, Any]], output_file: str):\n    \"\"\"Export scan results as a Markdown report.\"\"\"\n    lines = [\n        \"# arXiv Pattern Discovery Report\",\n        f\"Generated: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\",\n        \"\",\n        f\"**Total papers scanned: {len(papers)}**\",\n        \"\",\n        \"---\",\n        \"\",\n    ]\n\n    for i, paper in enumerate(papers, 1):\n        p = paper[\"paper\"]\n        lines.extend([\n            f\"## {i}. {p['title']}\",\n            \"\",\n            f\"**arXiv ID:** {p['arxiv_id']}  \",\n            f\"**Quality Score:** {paper['total_score']:.2f}/10.0  \",\n            f\"**Suggested Category:** {paper.get('category', 'Uncategorized')}  \",\n            f\"**URL:** {p['url']}  \",\n            \"\",\n            f\"**Score Breakdown:**\",\n            f\"- Reusability (30%): {paper['score_breakdown']['reusability']:.1f}/3.0\",\n            f\"- Novelty (25%): {paper['score_breakdown']['novelty']:.1f}/3.0\",\n            f\"- Clarity (20%): {paper['score_breakdown']['clarity']:.1f}/3.0\",\n            f\"- Evidence (15%): {paper['score_breakdown']['evidence']:.1f}/3.0\",\n            f\"- Completeness (10%): {paper['score_breakdown']['completeness']:.1f}/3.0\",\n            \"\",\n            f\"**Tags:** {', '.join(paper.get('tags', []))}\",\n            \"\",\n            \"**Abstract:**\",\n            p[\"abstract\"],\n            \"\",\n            \"---\",\n            \"\",\n        ])\n\n    with open(output_file, \"w\") as f:\n        f.write(\"\\n\".join(lines))\n    print(f\"Markdown report exported to: {output_file}\")\n\n\ndef load_existing_patterns(patterns_dir: Path) -> List[Dict]:\n    \"\"\"Load existing patterns to check for duplicates.\"\"\"\n    from build_readme import parse_front_matter\n\n    patterns = []\n    for file in patterns_dir.glob(\"*.md\"):\n        if file.name == \"TEMPLATE.md\":\n            continue\n        try:\n            metadata = parse_front_matter(str(file))\n            patterns.append({\n                \"file\": file.name,\n                \"title\": metadata.get(\"title\", \"\"),\n                \"tags\": metadata.get(\"tags\", []),\n                \"category\": metadata.get(\"category\", \"\"),\n            })\n        except Exception:\n            continue\n    return patterns\n\n\ndef check_for_duplicates(paper: Paper, existing_patterns: List[Dict]) -> List[str]:\n    \"\"\"Check if paper might duplicate existing patterns.\"\"\"\n    title_lower = paper.title.lower()\n    abstract_lower = paper.abstract.lower()\n\n    potential_dupes = []\n    for pattern in existing_patterns:\n        pattern_title = pattern[\"title\"].lower()\n        pattern_tags = [t.lower() for t in pattern.get(\"tags\", [])]\n\n        # Check title similarity\n        if any(word in title_lower for word in pattern_title.split() if len(word) > 4):\n            potential_dupes.append(pattern[\"file\"])\n\n        # Check tag overlap\n        paper_words = set(title_lower.split() + abstract_lower.split())\n        tag_overlap = len(paper_words.intersection(pattern_tags)) / max(len(pattern_tags), 1)\n        if tag_overlap > 0.3:\n            potential_dupes.append(pattern[\"file\"])\n\n    return list(set(potential_dupes))\n\n\ndef main():\n    parser = argparse.ArgumentParser(\n        description=\"Scan arXiv for papers describing agentic patterns\",\n        formatter_class=argparse.RawDescriptionHelpFormatter,\n        epilog=\"\"\"\nExamples:\n  %(prog)s --days=7 --min-citations=3\n  %(prog)s --query=\"multi-agent orchestration\" --max-results=50\n  %(prog)s --min-score=7.0 --export-json results.json\n        \"\"\",\n    )\n    parser.add_argument(\n        \"--query\",\n        \"-q\",\n        type=str,\n        default=DEFAULT_SEARCH_QUERY,\n        help=\"arXiv search query (default: agent/agentic/multi-agent papers)\",\n    )\n    parser.add_argument(\n        \"--max-results\",\n        \"-n\",\n        type=int,\n        default=100,\n        help=\"Maximum number of results to fetch (default: 100)\",\n    )\n    parser.add_argument(\n        \"--days\",\n        \"-d\",\n        type=int,\n        default=365,\n        help=\"Only include papers from last N days (default: 365)\",\n    )\n    parser.add_argument(\n        \"--min-score\",\n        \"-m\",\n        type=float,\n        default=5.0,\n        help=\"Minimum quality score to include (default: 5.0)\",\n    )\n    parser.add_argument(\n        \"--export-json\",\n        type=str,\n        help=\"Export results to JSON file\",\n    )\n    parser.add_argument(\n        \"--export-md\",\n        type=str,\n        help=\"Export results to Markdown file\",\n    )\n    parser.add_argument(\n        \"--patterns-dir\",\n        type=str,\n        default=\"patterns\",\n        help=\"Path to patterns directory (default: patterns)\",\n    )\n    parser.add_argument(\n        \"--verbose\",\n        \"-v\",\n        action=\"store_true\",\n        help=\"Print detailed output for each paper\",\n    )\n\n    args = parser.parse_args()\n\n    # Load existing patterns\n    patterns_dir = Path(args.patterns_dir)\n    if patterns_dir.exists():\n        existing_patterns = load_existing_patterns(patterns_dir)\n        print(f\"Loaded {len(existing_patterns)} existing patterns for duplicate detection\")\n    else:\n        existing_patterns = []\n        print(f\"Warning: Patterns directory not found at {patterns_dir}\")\n\n    print(f\"\\n🔍 Scanning arXiv with query: {args.query[:100]}...\")\n    print(f\"   Max results: {args.max_results}, Time window: {args.days} days\")\n\n    try:\n        papers = fetch_arxiv_papers(args.query, args.max_results)\n        print(f\"   Fetched {len(papers)} papers from arXiv\")\n\n        # Apply filters\n        if args.days < 365:\n            papers = filter_papers_by_date(papers, args.days)\n            print(f\"   Filtered to {len(papers)} papers within last {args.days} days\")\n\n        papers = filter_papers_by_keywords(papers)\n        print(f\"   Filtered to {len(papers)} papers with architectural keywords\")\n\n        if not papers:\n            print(\"\\n❌ No papers found matching criteria\")\n            return 0\n\n    except ArxivAPIError as e:\n        print(f\"\\n❌ Error fetching from arXiv: {e}\")\n        return 1\n\n    # Score papers\n    print(f\"\\n📊 Scoring {len(papers)} papers using Pattern Quality Rubric...\")\n\n    results = []\n    high_quality_count = 0\n\n    for paper in papers:\n        score, breakdown = calculate_quality_score(paper)\n        category = categorize_paper(paper, existing_patterns)\n        tags = extract_tags(paper)\n        duplicates = check_for_duplicates(paper, existing_patterns)\n\n        result = {\n            \"paper\": {\n                \"arxiv_id\": paper.arxiv_id,\n                \"title\": paper.title,\n                \"authors\": paper.authors,\n                \"abstract\": paper.abstract,\n                \"published\": paper.published,\n                \"categories\": paper.categories,\n                \"url\": paper.url,\n            },\n            \"pattern_name\": None,\n            \"category\": category,\n            \"tags\": tags,\n            \"score_breakdown\": breakdown,\n            \"total_score\": score,\n            \"potential_duplicates\": duplicates,\n            \"meets_threshold\": score >= args.min_score,\n        }\n        results.append(result)\n\n        if score >= args.min_score:\n            high_quality_count += 1\n            if args.verbose:\n                print_paper_summary(paper, score, breakdown, category)\n                if duplicates:\n                    print(f\"⚠️  Potential duplicates: {', '.join(duplicates)}\")\n\n    # Sort by score\n    results.sort(key=lambda x: x[\"total_score\"], reverse=True)\n\n    # Print summary\n    print(f\"\\n{'='*70}\")\n    print(f\"📈 SCAN SUMMARY\")\n    print(f\"{'='*70}\")\n    print(f\"Total papers analyzed: {len(papers)}\")\n    print(f\"Papers meeting threshold ({args.min_score}): {high_quality_count}\")\n    print(f\"\\n🏆 Top 10 papers by quality score:\")\n    print(f\"{'-'*70}\")\n\n    for i, r in enumerate(results[:10], 1):\n        p = r[\"paper\"]\n        dupes = f\" [⚠️ duplicates: {len(r['potential_duplicates'])}]\" if r[\"potential_duplicates\"] else \"\"\n        print(f\"{i:2}. {r['total_score']:.2f} | {p['title'][:60]}...{dupes}\")\n\n    # Export results if requested\n    if args.export_json:\n        export_results(results, args.export_json)\n\n    if args.export_md:\n        export_markdown_report(results, args.export_md)\n\n    return 0\n\n\nif __name__ == \"__main__\":\n    sys.exit(main())\n"},"items":[{"name":"llms.txt","path":"llms.txt","rawUrl":"https://raw.githubusercontent.com/nibzard/awesome-agentic-patterns/HEAD/llms.txt","title":"LLM Index & Context Digest","category":"root-instruction","format":"text","content":"# Awesome Agentic Patterns\n\nA curated catalogue of AI agent design patterns.\n\nEvery pattern is also available as Markdown at https://agentic-patterns.com/patterns/<slug>.md. Full text of all patterns: https://agentic-patterns.com/llms-full.txt. Usage notes for agents: https://agentic-patterns.com/agents.\n\n## Patterns\n\n### 402-first-machine-payments\n402-First Machine Payments (Price-Before-Work Tool Purchases): Server returns an HTTP 402 price quote before doing work, and the agent pays the exact amount only if it fits its budget cap\nURL: https://agentic-patterns.com/patterns/402-first-machine-payments\nMarkdown: https://agentic-patterns.com/patterns/402-first-machine-payments.md\n\n### abstracted-code-representation-for-review\nAbstracted Code Representation for Review: Shows reviewers pseudocode, intent summaries, and logical diffs of code changes, with drill-down to the real code to confirm the mapping\nURL: https://agentic-patterns.com/patterns/abstracted-code-representation-for-review\nMarkdown: https://agentic-patterns.com/patterns/abstracted-code-representation-for-review.md\n\n### action-caching-replay\nAction Caching & Replay Pattern: Records each agent action with XPath and frame metadata so later runs replay it without LLM calls, with LLM fallback when replay fails\nURL: https://agentic-patterns.com/patterns/action-caching-replay\nMarkdown: https://agentic-patterns.com/patterns/action-caching-replay.md\n\n### action-selector-pattern\nAction-Selector Pattern: LLM maps user intent to a pre-approved action ID with schema-validated parameters, and tool outputs never return to the selector\nURL: https://agentic-patterns.com/patterns/action-selector-pattern\nMarkdown: https://agentic-patterns.com/patterns/action-selector-pattern.md\n\n### adaptive-sandbox-fanout-controller\nAdaptive Sandbox Fan-Out Controller: Starts a small batch of parallel sandboxes, then scales up, stops early, or refines the prompt based on early success, variance, and error signals\nURL: https://agentic-patterns.com/patterns/adaptive-sandbox-fanout-controller\nMarkdown: https://agentic-patterns.com/patterns/adaptive-sandbox-fanout-controller.md\n\n### agent-circuit-breaker\nAgent Circuit Breaker: Prevents agents from wasting tokens and time on repeatedly failing tools by tracking failure rates and temporarily disabling broken tool endpoints\nURL: https://agentic-patterns.com/patterns/agent-circuit-breaker\nMarkdown: https://agentic-patterns.com/patterns/agent-circuit-breaker.md\n\n### agent-modes-by-model-personality\nAgent Modes by Model Personality: Offers separate working modes, each with its own prompts, tools, UI, and expectations, tuned to one model's working style\nURL: https://agentic-patterns.com/patterns/agent-modes-by-model-personality\nMarkdown: https://agentic-patterns.com/patterns/agent-modes-by-model-personality.md\n\n### agent-reinforcement-fine-tuning\nAgent Reinforcement Fine-Tuning (Agent RFT): Trains model weights with reinforcement learning on real tool calls and custom graders to improve domain-specific tool use and multi-step reasoning\nURL: https://agentic-patterns.com/patterns/agent-reinforcement-fine-tuning\nMarkdown: https://agentic-patterns.com/patterns/agent-reinforcement-fine-tuning.md\n\n### agent-sdk-for-programmatic-control\nAgent SDK for Programmatic Control: Exposes agent functions through an SDK and CLI so code can run the agent headless with set tools, permissions, and resource limits\nURL: https://agentic-patterns.com/patterns/agent-sdk-for-programmatic-control\nMarkdown: https://agentic-patterns.com/patterns/agent-sdk-for-programmatic-control.md\n\n### agent-assisted-scaffolding\nAgent-Assisted Scaffolding: Agent generates initial files, boilerplate, and directory structure from a high-level description so developers start on core logic\nURL: https://agentic-patterns.com/patterns/agent-assisted-scaffolding\nMarkdown: https://agentic-patterns.com/patterns/agent-assisted-scaffolding.md\n\n### agent-driven-research\nAgent-Driven Research: Agent plans its own queries, fans out parallel search workers across sources, reflects on evidence gaps, and iterates until it can write a sourced report\nURL: https://agentic-patterns.com/patterns/agent-driven-research\nMarkdown: https://agentic-patterns.com/patterns/agent-driven-research.md\n\n### agent-first-tool-discovery\nAgent-First Tool Discovery: Indexes tools and agents across MCP registries, A2A cards, OpenAPI specs, and custom directories into one normalized search surface ranked by agent-relevant signals\nURL: https://agentic-patterns.com/patterns/agent-first-tool-discovery\nMarkdown: https://agentic-patterns.com/patterns/agent-first-tool-discovery.md\n\n### agent-first-tooling-and-logging\nAgent-First Tooling and Logging: Designs logs and tool output for agent consumption with one unified log stream, structured JSON, and agent-aware CLI flags\nURL: https://agentic-patterns.com/patterns/agent-first-tooling-and-logging\nMarkdown: https://agentic-patterns.com/patterns/agent-first-tooling-and-logging.md\n\n### agent-friendly-workflow-design\nAgent-Friendly Workflow Design: Gives agents clear high-level goals, room for implementation choices, structured I/O, and plan review before execution\nURL: https://agentic-patterns.com/patterns/agent-friendly-workflow-design\nMarkdown: https://agentic-patterns.com/patterns/agent-friendly-workflow-design.md\n\n### agent-powered-codebase-qa-onboarding\nAgent-Powered Codebase Q&A / Onboarding: Agent indexes the codebase with embeddings and code graphs and answers natural-language questions about where code is and how it behaves\nURL: https://agentic-patterns.com/patterns/agent-powered-codebase-qa-onboarding\nMarkdown: https://agentic-patterns.com/patterns/agent-powered-codebase-qa-onboarding.md\n\n### agentic-search-over-vector-embeddings\nAgentic Search Over Vector Embeddings: Replaces vector indexes with agent-driven grep, find, and file traversal that searches current file state on demand and refines iteratively\nURL: https://agentic-patterns.com/patterns/agentic-search-over-vector-embeddings\nMarkdown: https://agentic-patterns.com/patterns/agentic-search-over-vector-embeddings.md\n\n### ai-assisted-code-review-verification\nAI-Assisted Code Review / Verification: Uses AI tools to flag issues, summarize change intent, and explain code so human reviewers focus on intent and business logic\nURL: https://agentic-patterns.com/patterns/ai-assisted-code-review-verification\nMarkdown: https://agentic-patterns.com/patterns/ai-assisted-code-review-verification.md\n\n### anchored-structured-context-compaction\nAnchored Structured Context Compaction: Maintains a typed state block (pinned goal and constraints, verified decisions, an artifact registry, open blockers) and merges only the newly evicted span into it at each compaction, so that long sessions keep exact details instead of drifting\nURL: https://agentic-patterns.com/patterns/anchored-structured-context-compaction\nMarkdown: https://agentic-patterns.com/patterns/anchored-structured-context-compaction.md\n\n### anti-reward-hacking-grader-design\nAnti-Reward-Hacking Grader Design: Design reward functions with multi-criteria evaluation and iterative hardening to prevent models from gaming graders, ensuring training rewards align with actual task quality.\nURL: https://agentic-patterns.com/patterns/anti-reward-hacking-grader-design\nMarkdown: https://agentic-patterns.com/patterns/anti-reward-hacking-grader-design.md\n\n### multi-step-analysis-pipeline-orchestration\nArtifact-Driven Analysis Pipeline Orchestration: Has an agent run independent analysis scripts, read their structured reports, and merge them into one final report or visualization\nURL: https://agentic-patterns.com/patterns/multi-step-analysis-pipeline-orchestration\nMarkdown: https://agentic-patterns.com/patterns/multi-step-analysis-pipeline-orchestration.md\n\n### asynchronous-coding-agent-pipeline\nAsynchronous Coding Agent Pipeline: Splits inference, tool execution, reward modeling, and learning into asynchronous workers linked by message queues so GPUs stay busy\nURL: https://agentic-patterns.com/patterns/asynchronous-coding-agent-pipeline\nMarkdown: https://agentic-patterns.com/patterns/asynchronous-coding-agent-pipeline.md\n\n### authenticated-authority-channel\nAuthenticated Authority Channel: Preserve a distinguishable channel for authenticated intent so retrieved content can inform reasoning without granting itself authority.\nURL: https://agentic-patterns.com/patterns/authenticated-authority-channel\nMarkdown: https://agentic-patterns.com/patterns/authenticated-authority-channel.md\n\n### autonomous-workflow-agent-architecture\nAutonomous Workflow Agent Architecture: Runs multi-step engineering workflows in containers with tmux sessions, sleep-based monitoring, checkpoints, and context-aware error recovery\nURL: https://agentic-patterns.com/patterns/autonomous-workflow-agent-architecture\nMarkdown: https://agentic-patterns.com/patterns/autonomous-workflow-agent-architecture.md\n\n### background-agent-ci\nBackground Agent with CI Feedback: Runs the agent in the background on its own branch and uses CI results as feedback to patch failures until green or blocked\nURL: https://agentic-patterns.com/patterns/background-agent-ci\nMarkdown: https://agentic-patterns.com/patterns/background-agent-ci.md\n\n### black-box-skill-invocation\nBlack-Box Skill Invocation: Shares skills through input and output schemas only and runs them on the provider side, so prompts and code never cross the boundary\nURL: https://agentic-patterns.com/patterns/black-box-skill-invocation\nMarkdown: https://agentic-patterns.com/patterns/black-box-skill-invocation.md\n\n### board-mediated-inter-agent-coordination\nBoard-Mediated Async Inter-Agent Coordination: Routes agent-to-agent messages through comment threads on board cards, with a prefix that creates an inbox card to notify the target agent\nURL: https://agentic-patterns.com/patterns/board-mediated-inter-agent-coordination\nMarkdown: https://agentic-patterns.com/patterns/board-mediated-inter-agent-coordination.md\n\n### budget-aware-model-routing-with-hard-cost-caps\nBudget-Aware Model Routing with Hard Cost Caps: Routes each request to the cheapest model that meets its needs under hard cost caps, and escalates only when quality gates fail\nURL: https://agentic-patterns.com/patterns/budget-aware-model-routing-with-hard-cost-caps\nMarkdown: https://agentic-patterns.com/patterns/budget-aware-model-routing-with-hard-cost-caps.md\n\n### canary-rollout-and-automatic-rollback-for-agent-policy-changes\nCanary Rollout and Automatic Rollback for Agent Policy Changes: Ships agent policy changes to a small traffic slice first, monitors guardrail metrics, and rolls back to the last stable version automatically\nURL: https://agentic-patterns.com/patterns/canary-rollout-and-automatic-rollback-for-agent-policy-changes\nMarkdown: https://agentic-patterns.com/patterns/canary-rollout-and-automatic-rollback-for-agent-policy-changes.md\n\n### capability-escrow-receipt\nCapability-Escrow-Receipt: Binds a signed capability listing, an atomic escrow-plus-hire step, and a signed work receipt into one loop for agent-to-agent payment\nURL: https://agentic-patterns.com/patterns/capability-escrow-receipt\nMarkdown: https://agentic-patterns.com/patterns/capability-escrow-receipt.md\n\n### chain-of-thought-monitoring-interruption\nChain-of-Thought Monitoring & Interruption: Streams agent reasoning and tool calls in real time so a human can interrupt and redirect early when the approach is wrong\nURL: https://agentic-patterns.com/patterns/chain-of-thought-monitoring-interruption\nMarkdown: https://agentic-patterns.com/patterns/chain-of-thought-monitoring-interruption.md\n\n### classify-then-act-for-background-agents\nClassify-Then-Act for Background Agents: Sorts each task into has-default, needs-intent, or out-of-scope, builds only has-default work in a sandbox, and queues it for human review\nURL: https://agentic-patterns.com/patterns/classify-then-act-for-background-agents\nMarkdown: https://agentic-patterns.com/patterns/classify-then-act-for-background-agents.md\n\n### cli-native-agent-orchestration\nCLI-Native Agent Orchestration: Drives agents through their non-interactive CLI mode (claude -p with JSON output and exit codes) so Makefiles, Git hooks, cron jobs, and CI can script and replay agent runs\nURL: https://agentic-patterns.com/patterns/cli-native-agent-orchestration\nMarkdown: https://agentic-patterns.com/patterns/cli-native-agent-orchestration.md\n\n### code-over-api-pattern\nCode-Over-API (Code Mode): Agent writes code that calls tools and processes data inside a sandbox, so only summaries and samples return to the context window instead of every intermediate result\nURL: https://agentic-patterns.com/patterns/code-over-api-pattern\nMarkdown: https://agentic-patterns.com/patterns/code-over-api-pattern.md\n\n### code-then-execute-pattern\nCode-Then-Execute Pattern: LLM writes a sandboxed program or DSL script, a static taint checker verifies data flows, and an interpreter runs it in a locked sandbox\nURL: https://agentic-patterns.com/patterns/code-then-execute-pattern\nMarkdown: https://agentic-patterns.com/patterns/code-then-execute-pattern.md\n\n### codebase-optimization-for-agents\nCodebase Optimization for Agents: Optimizes tooling, CLIs, tests, and docs for agents first, with one-command verify loops and machine-readable output, even if human DX regresses\nURL: https://agentic-patterns.com/patterns/codebase-optimization-for-agents\nMarkdown: https://agentic-patterns.com/patterns/codebase-optimization-for-agents.md\n\n### commitment-ledger-reality-gated-credit\nCommitment Ledger with Reality-Gated Credit: Records agent promises and credits retrieved memory only after an externally verifiable outcome settles.\nURL: https://agentic-patterns.com/patterns/commitment-ledger-reality-gated-credit\nMarkdown: https://agentic-patterns.com/patterns/commitment-ledger-reality-gated-credit.md\n\n### compounding-engineering-pattern\nCompounding Engineering Pattern: After each feature, codifies agent mistakes and learnings into CLAUDE.md, slash commands, subagents, and hooks so the next feature is easier to build\nURL: https://agentic-patterns.com/patterns/compounding-engineering-pattern\nMarkdown: https://agentic-patterns.com/patterns/compounding-engineering-pattern.md\n\n### parallel-tool-execution\nConditional Parallel Tool Execution: Runs a batch of tool calls in parallel when all are read-only and in sequence when any modifies state, then returns results in request order\nURL: https://agentic-patterns.com/patterns/parallel-tool-execution\nMarkdown: https://agentic-patterns.com/patterns/parallel-tool-execution.md\n\n### consequence-family-coverage-audit\nConsequence-Family Coverage Audit: Audit an agent's risk policy by enumerating families of consequence and asking which rule covers each, because a hand-written risk list reliably encodes one family and stays silent on the rest\nURL: https://agentic-patterns.com/patterns/consequence-family-coverage-audit\nMarkdown: https://agentic-patterns.com/patterns/consequence-family-coverage-audit.md\n\n### context-budget-as-a-governed-resource\nContext Budget as a Governed Resource: Measures always-loaded context per source, alerts on trend growth, and puts hard spend caps and fan-out bounds on unattended agent runs\nURL: https://agentic-patterns.com/patterns/context-budget-as-a-governed-resource\nMarkdown: https://agentic-patterns.com/patterns/context-budget-as-a-governed-resource.md\n\n### context-window-anxiety-management\nContext Window Anxiety Management: Enables a large context window but caps usage lower, and adds prompts that state the token budget so the model does not rush to finish\nURL: https://agentic-patterns.com/patterns/context-window-anxiety-management\nMarkdown: https://agentic-patterns.com/patterns/context-window-anxiety-management.md\n\n### context-window-auto-compaction\nContext Window Auto-Compaction: Catches context overflow errors, compacts and validates the transcript with capped reserve headroom, and retries the request automatically\nURL: https://agentic-patterns.com/patterns/context-window-auto-compaction\nMarkdown: https://agentic-patterns.com/patterns/context-window-auto-compaction.md\n\n### context-minimization-pattern\nContext-Minimization Pattern: Removes untrusted user text and tool output from context after it becomes a safe structured artifact, so later steps see only trusted data\nURL: https://agentic-patterns.com/patterns/context-minimization-pattern\nMarkdown: https://agentic-patterns.com/patterns/context-minimization-pattern.md\n\n### continuous-autonomous-task-loop-pattern\nContinuous Autonomous Task Loop Pattern: Runs a loop where subagents pick the next task from a todo file, execute it in fresh context, commit it, and back off on rate limits\nURL: https://agentic-patterns.com/patterns/continuous-autonomous-task-loop-pattern\nMarkdown: https://agentic-patterns.com/patterns/continuous-autonomous-task-loop-pattern.md\n\n### credential-free-outbox\nCredential-Free Outbox: The agent writes finished work as a file to an outbox and a separate short-lived job with its own token delivers it, so the agent never holds a credential that can publish anything\nURL: https://agentic-patterns.com/patterns/credential-free-outbox\nMarkdown: https://agentic-patterns.com/patterns/credential-free-outbox.md\n\n### criticgpt-style-evaluation\nCriticGPT-Style Code Review: Runs a specialized critic model over generated code to find bugs, security flaws, and quality issues, and feeds critical findings back for regeneration\nURL: https://agentic-patterns.com/patterns/criticgpt-style-evaluation\nMarkdown: https://agentic-patterns.com/patterns/criticgpt-style-evaluation.md\n\n### cross-agent-lesson-sharing\nCross-Agent Lesson Sharing via Git: Agents write solved problems as markdown lessons in a shared Git repo and search them before debugging, with GitHub Issues as the coordination layer\nURL: https://agentic-patterns.com/patterns/cross-agent-lesson-sharing\nMarkdown: https://agentic-patterns.com/patterns/cross-agent-lesson-sharing.md\n\n### cross-cycle-consensus-relay\nCross-Cycle Consensus Relay: Each loop cycle reads a structured relay document, does its work, and atomically writes back decisions, open questions, and the single next action\nURL: https://agentic-patterns.com/patterns/cross-cycle-consensus-relay\nMarkdown: https://agentic-patterns.com/patterns/cross-cycle-consensus-relay.md\n\n### cross-domain-agent-conflict-resolution\nCross-Domain Agent Conflict Resolution: A coordination layer that cross-references recommendations from independent domain agents, detects conflicts on shared resources, and resolves them through policy-as-code.\nURL: https://agentic-patterns.com/patterns/cross-domain-agent-conflict-resolution\nMarkdown: https://agentic-patterns.com/patterns/cross-domain-agent-conflict-resolution.md\n\n### cryptographic-governance-audit-trail\nCryptographic Governance Audit Trail: Middleware checks each tool call against a policy file, then signs a receipt of the action with ML-DSA and appends it to a tamper-evident chain\nURL: https://agentic-patterns.com/patterns/cryptographic-governance-audit-trail\nMarkdown: https://agentic-patterns.com/patterns/cryptographic-governance-audit-trail.md\n\n### curated-code-context-window\nCurated Code Context Window: A search subagent finds the few relevant files for a task and injects only top snippets or summaries into the main coding agent's context\nURL: https://agentic-patterns.com/patterns/curated-code-context-window\nMarkdown: https://agentic-patterns.com/patterns/curated-code-context-window.md\n\n### custom-sandboxed-background-agent\nCustom Sandboxed Background Agent: Builds an in-house background coding agent that runs in sandboxed dev environments, streams progress over WebSocket, and iterates on compiler and test feedback\nURL: https://agentic-patterns.com/patterns/custom-sandboxed-background-agent\nMarkdown: https://agentic-patterns.com/patterns/custom-sandboxed-background-agent.md\n\n### dead-mans-switch-for-scheduled-agent-jobs\nDead-Man's Switch for Scheduled Agent Jobs: Each scheduled job writes a success sentinel to its log, and a separate checker files a task when the sentinel is missing or stale\nURL: https://agentic-patterns.com/patterns/dead-mans-switch-for-scheduled-agent-jobs\nMarkdown: https://agentic-patterns.com/patterns/dead-mans-switch-for-scheduled-agent-jobs.md\n\n### debiased-llm-as-a-judge-evaluation\nDebiased LLM-as-a-Judge Evaluation: Removes the systematic distortions of a model judge before its scores gate a release: swaps the order of each pairwise comparison, grades narrow pass/fail rubric items that cite evidence, supplies a reference answer and a judge from another model family, and measures the agreement with human labels first\nURL: https://agentic-patterns.com/patterns/debiased-llm-as-a-judge-evaluation\nMarkdown: https://agentic-patterns.com/patterns/debiased-llm-as-a-judge-evaluation.md\n\n### declarative-multi-agent-topology-definition\nDeclarative Multi-Agent Topology Definition: Define multi-agent systems declaratively in a single topology file — agents, flows, gates, hooks, group chats — then compile to platform-specific configurations for any agentic framework.\nURL: https://agentic-patterns.com/patterns/declarative-multi-agent-topology-definition\nMarkdown: https://agentic-patterns.com/patterns/declarative-multi-agent-topology-definition.md\n\n### delegated-user-auth-token-exchange\nDelegated User Authorization (OAuth Token Exchange): Exchanges the user's token and the agent's own identity for a short-lived, single-audience, minimally scoped token immediately before each tool call, so that the agent acts with delegated and attributable authority instead of a shared super-credential\nURL: https://agentic-patterns.com/patterns/delegated-user-auth-token-exchange\nMarkdown: https://agentic-patterns.com/patterns/delegated-user-auth-token-exchange.md\n\n### denial-tracking-permission-escalation\nDenial Tracking & Permission Escalation: Track repeated tool denials and auto-escalate to blanket permission prompts or fallback strategies, preventing wasted iterations in non-interactive contexts.\nURL: https://agentic-patterns.com/patterns/denial-tracking-permission-escalation\nMarkdown: https://agentic-patterns.com/patterns/denial-tracking-permission-escalation.md\n\n### design-time-file-partition\nDesign-Time File Partition as Concurrency Control: Each task declares every path it will write; overlapping tasks get a blocking dependency so only disjoint work runs at once on a shared checkout\nURL: https://agentic-patterns.com/patterns/design-time-file-partition\nMarkdown: https://agentic-patterns.com/patterns/design-time-file-partition.md\n\n### deterministic-grader-in-the-loop\nDeterministic Grader in the Loop: Replace the LLM-as-judge in an agent's self-review loop with a deterministic scorer that returns the raw counts behind each sub-score, so the agent has something specific to fix.\nURL: https://agentic-patterns.com/patterns/deterministic-grader-in-the-loop\nMarkdown: https://agentic-patterns.com/patterns/deterministic-grader-in-the-loop.md\n\n### deterministic-security-scanning-build-loop\nDeterministic Security Scanning Build Loop: Adds SAST, SCA, and secret scanners to the build target that the agent must run after each change, so scanner failures force the agent to fix the code\nURL: https://agentic-patterns.com/patterns/deterministic-security-scanning-build-loop\nMarkdown: https://agentic-patterns.com/patterns/deterministic-security-scanning-build-loop.md\n\n### deterministic-threat-rule-scanning\nDeterministic Threat Rule Scanning: Apply deterministic regex rules as a first-pass security layer to detect known threat patterns in AI agent tool calls and skill definitions.\nURL: https://agentic-patterns.com/patterns/deterministic-threat-rule-scanning\nMarkdown: https://agentic-patterns.com/patterns/deterministic-threat-rule-scanning.md\n\n### deterministic-zero-llm-orchestration\nDeterministic Zero-LLM Orchestration: A deterministic code orchestrator splits goals, runs parallel coding agents, verifies with tests, and commits, spending LLM tokens only on the one-time goal decomposition\nURL: https://agentic-patterns.com/patterns/deterministic-zero-llm-orchestration\nMarkdown: https://agentic-patterns.com/patterns/deterministic-zero-llm-orchestration.md\n\n### discrete-phase-separation\nDiscrete Phase Separation: Splits work into separate research, planning, and implementation conversations, each with fresh context, passing only distilled outputs between phases\nURL: https://agentic-patterns.com/patterns/discrete-phase-separation\nMarkdown: https://agentic-patterns.com/patterns/discrete-phase-separation.md\n\n### distributed-execution-cloud-workers\nDistributed Execution with Cloud Workers: Runs many agent sessions in parallel on cloud workers, each in its own git worktree, with dependency-aware scheduling, merge coordination, and approval gates\nURL: https://agentic-patterns.com/patterns/distributed-execution-cloud-workers\nMarkdown: https://agentic-patterns.com/patterns/distributed-execution-cloud-workers.md\n\n### dual-llm-pattern\nDual LLM Pattern: Splits work between a privileged LLM that calls tools but never sees untrusted data and a quarantined LLM that reads untrusted data but has no tools\nURL: https://agentic-patterns.com/patterns/dual-llm-pattern\nMarkdown: https://agentic-patterns.com/patterns/dual-llm-pattern.md\n\n### dual-rail-message-delivery\nDual-Rail Message Delivery: Sends every inter-agent message on two independent channels through one entry point, alerts when the rails diverge, and requires ACKs to confirm completion\nURL: https://agentic-patterns.com/patterns/dual-rail-message-delivery\nMarkdown: https://agentic-patterns.com/patterns/dual-rail-message-delivery.md\n\n### dual-speed-talker-reasoner-architecture\nDual-Speed Realtime Architecture (Talker-Reasoner): Splits an agent into a fast Talker that owns the live conversation and a slow Reasoner that plans and calls tools in the background, with a shared belief state as their only coupling, so that the user gets a reply at once while the deep work runs\nURL: https://agentic-patterns.com/patterns/dual-speed-talker-reasoner-architecture\nMarkdown: https://agentic-patterns.com/patterns/dual-speed-talker-reasoner-architecture.md\n\n### dual-use-tool-design\nDual-Use Tool Design: Builds each tool or skill as one CLI interface that both humans and agents call, with JSON output, exit codes, and the same permissions and logs\nURL: https://agentic-patterns.com/patterns/dual-use-tool-design\nMarkdown: https://agentic-patterns.com/patterns/dual-use-tool-design.md\n\n### durable-execution-step-checkpointing\nDurable Execution & Step Checkpointing: Replays a durable step history to resume crashed, rate-limited, or approval-paused agent runs from the last completed step, without repeating finished LLM calls or committed side effects\nURL: https://agentic-patterns.com/patterns/durable-execution-step-checkpointing\nMarkdown: https://agentic-patterns.com/patterns/durable-execution-step-checkpointing.md\n\n### dynamic-context-injection\nDynamic Context Injection: Lets users inject files, folders, or saved prompts into the agent's context mid-session with @-mentions and custom slash commands\nURL: https://agentic-patterns.com/patterns/dynamic-context-injection\nMarkdown: https://agentic-patterns.com/patterns/dynamic-context-injection.md\n\n### egress-lockdown-no-exfiltration-channel\nEgress Lockdown (No-Exfiltration Channel): Puts the agent behind a default-deny egress firewall with allowlisted destinations so stolen data has no outbound channel\nURL: https://agentic-patterns.com/patterns/egress-lockdown-no-exfiltration-channel\nMarkdown: https://agentic-patterns.com/patterns/egress-lockdown-no-exfiltration-channel.md\n\n### episodic-memory-retrieval-injection\nEpisodic Memory Retrieval & Injection: Writes a structured memory record after each episode and injects the top-k similar past memories as hints when a new task starts\nURL: https://agentic-patterns.com/patterns/episodic-memory-retrieval-injection\nMarkdown: https://agentic-patterns.com/patterns/episodic-memory-retrieval-injection.md\n\n### evidence-questions-not-verdict-questions\nEvidence Questions, Not Verdict Questions: Never ask the model for allow/ask/block. Ask it narrow, typed, observational questions and let code reduce the answers to the verdict, because the collapsed question is the low-confidence one.\nURL: https://agentic-patterns.com/patterns/evidence-questions-not-verdict-questions\nMarkdown: https://agentic-patterns.com/patterns/evidence-questions-not-verdict-questions.md\n\n### evidence-layered-evaluation-for-interactive-agents\nEvidence-Layered Evaluation for Interactive Agents: Scores interactive agent runs on a task outcome assertion and links each result to layered evidence: actions, screenshots, replays, network, and messages\nURL: https://agentic-patterns.com/patterns/evidence-layered-evaluation-for-interactive-agents\nMarkdown: https://agentic-patterns.com/patterns/evidence-layered-evaluation-for-interactive-agents.md\n\n### exact-action-authorization-binding\nExact-Action Authorization Binding: Bind a short-lived approval to the complete action presented to the reviewer, rederive and compare that identity at the acting boundary before execution, and commit the write with its postcondition check and idempotency receipt in one transaction.\nURL: https://agentic-patterns.com/patterns/exact-action-authorization-binding\nMarkdown: https://agentic-patterns.com/patterns/exact-action-authorization-binding.md\n\n### explicit-posterior-sampling-planner\nExplicit Posterior-Sampling Planner: Embeds Posterior Sampling for RL in the LLM's reasoning: sample a task model, plan, act, observe reward, and update the posterior\nURL: https://agentic-patterns.com/patterns/explicit-posterior-sampling-planner\nMarkdown: https://agentic-patterns.com/patterns/explicit-posterior-sampling-planner.md\n\n### extended-coherence-work-sessions\nExtended Coherence Work Sessions: Combines models with long coherence windows with context compaction, prompt caching, and persisted state so agents stay on task for hours\nURL: https://agentic-patterns.com/patterns/extended-coherence-work-sessions\nMarkdown: https://agentic-patterns.com/patterns/extended-coherence-work-sessions.md\n\n### external-credential-sync\nExternal Credential Sync: Reads AI credentials from other tools' keychains and config files and syncs them into the agent's store, with TTL-cached reads, refresh fences, and persisted ownership\nURL: https://agentic-patterns.com/patterns/external-credential-sync\nMarkdown: https://agentic-patterns.com/patterns/external-credential-sync.md\n\n### factory-over-assistant\nFactory over Assistant: Spawns several autonomous agents in parallel with automated feedback loops such as tests and builds, and checks on them later instead of watching one agent\nURL: https://agentic-patterns.com/patterns/factory-over-assistant\nMarkdown: https://agentic-patterns.com/patterns/factory-over-assistant.md\n\n### failover-aware-model-fallback\nFailover-Aware Model Fallback: Classifies each model failure by reason and falls back along a model chain only for retryable errors, failing fast on auth, billing, and user aborts\nURL: https://agentic-patterns.com/patterns/failover-aware-model-fallback\nMarkdown: https://agentic-patterns.com/patterns/failover-aware-model-fallback.md\n\n### fair-share-task-queues-with-heartbeat-leases\nFair-Share Task Queues with Heartbeat Leases: Distributes tasks across a shared agent fleet using weighted deficit-round-robin scheduling, with heartbeat leases and dead-letter retries to recover from crashed workers\nURL: https://agentic-patterns.com/patterns/fair-share-task-queues-with-heartbeat-leases\nMarkdown: https://agentic-patterns.com/patterns/fair-share-task-queues-with-heartbeat-leases.md\n\n### feature-list-as-immutable-contract\nFeature List as Immutable Contract: Defines every feature up front in a JSON list with acceptance steps; the agent may only flip a feature to passing after it verifies it\nURL: https://agentic-patterns.com/patterns/feature-list-as-immutable-contract\nMarkdown: https://agentic-patterns.com/patterns/feature-list-as-immutable-contract.md\n\n### filesystem-based-agent-state\nFilesystem-Based Agent State: Agents persist intermediate results and working state to files, creating durable checkpoints that enable workflow resumption, recovery from failures, and support for long-running tasks.\nURL: https://agentic-patterns.com/patterns/filesystem-based-agent-state\nMarkdown: https://agentic-patterns.com/patterns/filesystem-based-agent-state.md\n\n### filesystem-mediated-host-delegation\nFilesystem-Mediated Host Delegation: Lets a sandboxed agent write request files to a shared spool directory that a host daemon runs against a whitelist, with idempotent results the agent polls for\nURL: https://agentic-patterns.com/patterns/filesystem-mediated-host-delegation\nMarkdown: https://agentic-patterns.com/patterns/filesystem-mediated-host-delegation.md\n\n### fleet-cost-simulation-before-dispatch\nFleet Cost Simulation Before Dispatch: Replays an agent fleet's budget, priority, and failure-recovery policy against deterministic scenarios before committing real spend, so starvation and exhaustion verdicts arrive in CI instead of in production\nURL: https://agentic-patterns.com/patterns/fleet-cost-simulation-before-dispatch\nMarkdown: https://agentic-patterns.com/patterns/fleet-cost-simulation-before-dispatch.md\n\n### graph-of-thoughts\nGraph of Thoughts (GoT): Represents reasoning as a directed graph of thoughts so the model can branch, aggregate, refine, and revisit reasoning paths\nURL: https://agentic-patterns.com/patterns/graph-of-thoughts\nMarkdown: https://agentic-patterns.com/patterns/graph-of-thoughts.md\n\n### hook-based-safety-guard-rails\nHook-Based Safety Guard Rails for Autonomous Code Agents: Runs small shell scripts on PreToolUse and PostToolUse hooks to block destructive commands, lint edits, and warn on context use outside the agent's reasoning\nURL: https://agentic-patterns.com/patterns/hook-based-safety-guard-rails\nMarkdown: https://agentic-patterns.com/patterns/hook-based-safety-guard-rails.md\n\n### human-in-loop-approval-framework\nHuman-in-the-Loop Approval Framework: Systematically insert human approval gates for designated high-risk functions while maintaining agent autonomy for safe operations, with multi-channel approval interfaces and comprehensive audit trails.\nURL: https://agentic-patterns.com/patterns/human-in-loop-approval-framework\nMarkdown: https://agentic-patterns.com/patterns/human-in-loop-approval-framework.md\n\n### hybrid-gui-visual-grounding\nHybrid GUI & Visual Grounding: Grounds each GUI action in a filtered accessibility tree first, falls back to numbered visual marks or scaled coordinates only for what the tree cannot see, and confirms the effect of each action from a state diff before the next step\nURL: https://agentic-patterns.com/patterns/hybrid-gui-visual-grounding\nMarkdown: https://agentic-patterns.com/patterns/hybrid-gui-visual-grounding.md\n\n### hybrid-llm-code-workflow-coordinator\nHybrid LLM/Code Workflow Coordinator: Lets each workflow pick an LLM or a code script as its coordinator, so teams prototype with the LLM and move to reviewed code when determinism matters\nURL: https://agentic-patterns.com/patterns/hybrid-llm-code-workflow-coordinator\nMarkdown: https://agentic-patterns.com/patterns/hybrid-llm-code-workflow-coordinator.md\n\n### incident-to-eval-synthesis\nIncident-to-Eval Synthesis: Converts each production incident into executable eval cases with pass/fail criteria and gates future releases on them\nURL: https://agentic-patterns.com/patterns/incident-to-eval-synthesis\nMarkdown: https://agentic-patterns.com/patterns/incident-to-eval-synthesis.md\n\n### inference-healed-code-review-reward\nInference-Healed Code Review Reward: Replaces a binary tests-passed reward with a critic that scores correctness, style, performance, and security, explains low scores, and combines them\nURL: https://agentic-patterns.com/patterns/inference-healed-code-review-reward\nMarkdown: https://agentic-patterns.com/patterns/inference-healed-code-review-reward.md\n\n### inference-time-scaling\nInference-Time Scaling: Spends extra compute at inference time with best-of-N sampling, longer reasoning, self-refinement, search, and verification to improve output quality\nURL: https://agentic-patterns.com/patterns/inference-time-scaling\nMarkdown: https://agentic-patterns.com/patterns/inference-time-scaling.md\n\n### initializer-maintainer-dual-agent\nInitializer-Maintainer Dual Agent Architecture: Uses a one-time initializer agent to create the feature list, progress files, and bootstrap script, then a coding agent that resumes from them one feature per session\nURL: https://agentic-patterns.com/patterns/initializer-maintainer-dual-agent\nMarkdown: https://agentic-patterns.com/patterns/initializer-maintainer-dual-agent.md\n\n### intelligent-bash-tool-execution\nIntelligent Bash Tool Execution: Runs agent shell commands through a multi-mode executor that uses a PTY when needed, falls back to direct exec, and manages approvals, background jobs, and signals\nURL: https://agentic-patterns.com/patterns/intelligent-bash-tool-execution\nMarkdown: https://agentic-patterns.com/patterns/intelligent-bash-tool-execution.md\n\n### intent-level-cost-attribution\nIntent-Level Cost Attribution: Records every LLM call against the projectId/intentId/user key that caused it, at call time, so spend can be queried and enforced per work item instead of as an opaque total\nURL: https://agentic-patterns.com/patterns/intent-level-cost-attribution\nMarkdown: https://agentic-patterns.com/patterns/intent-level-cost-attribution.md\n\n### inversion-of-control\nInversion of Control: Gives the agent tools, a high-level objective, and guardrails, then lets it choose sequencing and recovery while humans set policy and review\nURL: https://agentic-patterns.com/patterns/inversion-of-control\nMarkdown: https://agentic-patterns.com/patterns/inversion-of-control.md\n\n### isolated-vm-per-rl-rollout\nIsolated VM per RL Rollout: Spin up an isolated virtual machine for each RL rollout to prevent cross-contamination between parallel agent executions, ensuring safe training with destructive tool access.\nURL: https://agentic-patterns.com/patterns/isolated-vm-per-rl-rollout\nMarkdown: https://agentic-patterns.com/patterns/isolated-vm-per-rl-rollout.md\n\n### iterative-multi-agent-brainstorming\nIterative Multi-Agent Brainstorming: Spawns several agents in parallel on the same problem, often with different perspectives, then merges their ideas into one set of options\nURL: https://agentic-patterns.com/patterns/iterative-multi-agent-brainstorming\nMarkdown: https://agentic-patterns.com/patterns/iterative-multi-agent-brainstorming.md\n\n### iterative-prompt-skill-refinement\nIterative Prompt & Skill Refinement: Combines a feedback channel, editable prompt documents, log-driven skill fixes, and usage dashboards to improve agent prompts and skills continuously\nURL: https://agentic-patterns.com/patterns/iterative-prompt-skill-refinement\nMarkdown: https://agentic-patterns.com/patterns/iterative-prompt-skill-refinement.md\n\n### judge-gated-finding-exchange-between-sub-agents\nJudge-Gated Finding Exchange Between Parallel Sub-Agents: Puts an append-only board between parallel sub-agents and lets a small judge decide what goes on it, who receives each note, and when a later note retracts an earlier one\nURL: https://agentic-patterns.com/patterns/judge-gated-finding-exchange-between-sub-agents\nMarkdown: https://agentic-patterns.com/patterns/judge-gated-finding-exchange-between-sub-agents.md\n\n### lane-based-execution-queueing\nLane-Based Execution Queueing: Routes work into named lanes, each with its own queue and concurrency limit, so sessions never interleave and background jobs never block users\nURL: https://agentic-patterns.com/patterns/lane-based-execution-queueing\nMarkdown: https://agentic-patterns.com/patterns/lane-based-execution-queueing.md\n\n### language-agent-tree-search-lats\nLanguage Agent Tree Search (LATS): Runs Monte Carlo Tree Search over reasoning steps, with the LLM generating candidate actions and scoring partial solutions to pick the best path\nURL: https://agentic-patterns.com/patterns/language-agent-tree-search-lats\nMarkdown: https://agentic-patterns.com/patterns/language-agent-tree-search-lats.md\n\n### layered-configuration-context\nLayered Configuration Context: Loads context files from enterprise, user, project, and local levels automatically and merges them into the agent's baseline context\nURL: https://agentic-patterns.com/patterns/layered-configuration-context\nMarkdown: https://agentic-patterns.com/patterns/layered-configuration-context.md\n\n### lethal-trifecta-threat-model\nLethal Trifecta Threat Model: Classifies each tool by private-data access, untrusted-content exposure, and external communication, and blocks any execution path that has all three\nURL: https://agentic-patterns.com/patterns/lethal-trifecta-threat-model\nMarkdown: https://agentic-patterns.com/patterns/lethal-trifecta-threat-model.md\n\n### llm-map-reduce-pattern\nLLM Map-Reduce Pattern: Processes each untrusted document in its own sandboxed LLM call with a constrained output, then aggregates the results with deterministic code\nURL: https://agentic-patterns.com/patterns/llm-map-reduce-pattern\nMarkdown: https://agentic-patterns.com/patterns/llm-map-reduce-pattern.md\n\n### llm-observability\nLLM Observability: Sends agent runs to an LLM observability platform for span-level traces of each LLM call and tool use, plus aggregate cost, latency, and success metrics\nURL: https://agentic-patterns.com/patterns/llm-observability\nMarkdown: https://agentic-patterns.com/patterns/llm-observability.md\n\n### llm-friendly-api-design\nLLM-Friendly API Design: Designs APIs with visible versions, self-descriptive names and schemas, simple calls, actionable errors, and few indirection levels so LLMs call them correctly\nURL: https://agentic-patterns.com/patterns/llm-friendly-api-design\nMarkdown: https://agentic-patterns.com/patterns/llm-friendly-api-design.md\n\n### local-first-credential-broker\nLocal-First Credential Broker: Keep raw secrets out of the agent process by injecting credentials at the network layer through a local broker, rather than handing the agent environment variables or config files.\nURL: https://agentic-patterns.com/patterns/local-first-credential-broker\nMarkdown: https://agentic-patterns.com/patterns/local-first-credential-broker.md\n\n### markdown-polis-coordination\nMarkdown Polis — Multi-Vendor Agent Coordination via Filesystem Constitution: Coordinates agents from different vendors through versioned markdown files: capability cards, work contracts, and bandit routing that learns from settled work\nURL: https://agentic-patterns.com/patterns/markdown-polis-coordination\nMarkdown: https://agentic-patterns.com/patterns/markdown-polis-coordination.md\n\n### mcp-pattern-injection\nMCP Pattern Injection: Runs an MCP server that exposes framework best-practice patterns as tools, so the coding assistant fetches current patterns on demand\nURL: https://agentic-patterns.com/patterns/mcp-pattern-injection\nMarkdown: https://agentic-patterns.com/patterns/mcp-pattern-injection.md\n\n### memory-consolidation-decay-contradiction\nMemory Consolidation, Decay & Contradiction Resolution: Gives each stored fact a lifecycle: reconciles each new fact against the related stored facts when it arrives, stamps facts with event time and ingestion time so that a superseded fact is invalidated and not deleted, and runs a background job that merges duplicates and expires spent state\nURL: https://agentic-patterns.com/patterns/memory-consolidation-decay-contradiction\nMarkdown: https://agentic-patterns.com/patterns/memory-consolidation-decay-contradiction.md\n\n### memory-reinforcement-learning-memrl\nMemory Reinforcement Learning (MemRL): Stores memories with learned utility scores, retrieves by similarity then re-ranks by utility, and updates scores from outcomes while the LLM stays frozen\nURL: https://agentic-patterns.com/patterns/memory-reinforcement-learning-memrl\nMarkdown: https://agentic-patterns.com/patterns/memory-reinforcement-learning-memrl.md\n\n### memory-synthesis-from-execution-logs\nMemory Synthesis from Execution Logs: Has the agent write a structured diary per task, then runs synthesis agents over many diaries to turn recurring patterns into rules, commands, and tests\nURL: https://agentic-patterns.com/patterns/memory-synthesis-from-execution-logs\nMarkdown: https://agentic-patterns.com/patterns/memory-synthesis-from-execution-logs.md\n\n### merged-code-language-skill-model\nMerged Code + Language Skill Model: Fine-tunes separate language and code specialists from the same base model, then merges their weights into one model instead of one large joint training run\nURL: https://agentic-patterns.com/patterns/merged-code-language-skill-model\nMarkdown: https://agentic-patterns.com/patterns/merged-code-language-skill-model.md\n\n### milestone-escrow-agent-funding\nMilestone Escrow for Agent Resource Funding: Holds agent funding in escrow and releases each payment only after independent verification of a measurable milestone\nURL: https://agentic-patterns.com/patterns/milestone-escrow-agent-funding\nMarkdown: https://agentic-patterns.com/patterns/milestone-escrow-agent-funding.md\n\n### multi-model-orchestration-for-complex-edits\nMulti-Model Orchestration for Complex Edits: Splits complex code edits across specialized models: a retrieval model gathers context, a large model writes the changes, and smaller models apply them\nURL: https://agentic-patterns.com/patterns/multi-model-orchestration-for-complex-edits\nMarkdown: https://agentic-patterns.com/patterns/multi-model-orchestration-for-complex-edits.md\n\n### multi-platform-communication-aggregation\nMulti-Platform Communication Aggregation: Queries every communication platform in parallel through adapters that share one schema, then merges, deduplicates, and ranks the results\nURL: https://agentic-patterns.com/patterns/multi-platform-communication-aggregation\nMarkdown: https://agentic-patterns.com/patterns/multi-platform-communication-aggregation.md\n\n### multi-platform-webhook-triggers\nMulti-Platform Webhook Triggers: Starts agent workflows from Slack, Notion, and Jira webhooks, emoji reactions, and schedules, with idempotency and signature checks on each event\nURL: https://agentic-patterns.com/patterns/multi-platform-webhook-triggers\nMarkdown: https://agentic-patterns.com/patterns/multi-platform-webhook-triggers.md\n\n### multi-tenant-agent-isolation\nMulti-Tenant Agent & Memory Isolation: Enforces a tenant boundary on all four agent state planes (execution, retrieval and memory, cache, credential and egress), with tenant identity bound outside the model, so that one tenant's data or instructions cannot reach another\nURL: https://agentic-patterns.com/patterns/multi-tenant-agent-isolation\nMarkdown: https://agentic-patterns.com/patterns/multi-tenant-agent-isolation.md\n\n### non-custodial-spending-controls\nNon-Custodial Spending Controls: Puts a policy layer between the agent and the transaction signer that checks each intent against allowlists, budgets, and rate limits, and fails closed\nURL: https://agentic-patterns.com/patterns/non-custodial-spending-controls\nMarkdown: https://agentic-patterns.com/patterns/non-custodial-spending-controls.md\n\n### non-generative-judgment-routing\nNon-Generative Judgment Routing with Typed Escalation: Sends decision-only loop steps as batched typed questions to a non-generative judgment model and escalates what it cannot answer back to the LLM\nURL: https://agentic-patterns.com/patterns/non-generative-judgment-routing\nMarkdown: https://agentic-patterns.com/patterns/non-generative-judgment-routing.md\n\n### one-os-user-per-agent\nOne OS User per Agent: Give each long-lived agent its own OS user account and a templated init-system unit, so identity, supervision and privilege come from the host instead of from a per-agent container.\nURL: https://agentic-patterns.com/patterns/one-os-user-per-agent\nMarkdown: https://agentic-patterns.com/patterns/one-os-user-per-agent.md\n\n### opponent-processor-multi-agent-debate\nOpponent Processor / Multi-Agent Debate Pattern: Spawns agents with opposing roles on the same context, lets them critique each other, then synthesizes their positions to expose bias and blind spots\nURL: https://agentic-patterns.com/patterns/opponent-processor-multi-agent-debate\nMarkdown: https://agentic-patterns.com/patterns/opponent-processor-multi-agent-debate.md\n\n### oracle-and-worker-multi-model\nOracle and Worker Multi-Model Approach: Uses a fast, low-cost worker model for most tool use and code generation, and lets it consult an expensive oracle model when it is stuck\nURL: https://agentic-patterns.com/patterns/oracle-and-worker-multi-model\nMarkdown: https://agentic-patterns.com/patterns/oracle-and-worker-multi-model.md\n\n### orchestration-prompt-writing-benchmark\nOrchestration Prompt-Writing Benchmark: Scores an orchestrator on whether its sub-agent prompts give the right information fragments to the right roles, separate from end-task success\nURL: https://agentic-patterns.com/patterns/orchestration-prompt-writing-benchmark\nMarkdown: https://agentic-patterns.com/patterns/orchestration-prompt-writing-benchmark.md\n\n### out-of-process-provider-boundary-replay\nOut-of-Process Provider-Boundary Replay: Capture an agent run at the model-provider HTTP boundary from outside the process, then serve those bytes back so the agent re-executes its own logic with no provider call.\nURL: https://agentic-patterns.com/patterns/out-of-process-provider-boundary-replay\nMarkdown: https://agentic-patterns.com/patterns/out-of-process-provider-boundary-replay.md\n\n### output-verification-loop\nOutput Verification Loop: Verify LLM outputs by extracting individual claims, checking each against evidence sources, and returning per-claim trust scores before acting on the resu","isInternal":false,"tokens":11269,"sizeBytes":50006},{"name":"RUBRIC.md","path":".claude/skills/arxiv-pattern-discovery/RUBRIC.md","rawUrl":"https://raw.githubusercontent.com/nibzard/awesome-agentic-patterns/HEAD/.claude/skills/arxiv-pattern-discovery/RUBRIC.md","title":"Arxiv-pattern-discovery Skill","category":"anthropic-skill","format":"markdown","content":"# Pattern Quality Rubric\n\nReference for the Pattern Quality Rubric used to score arXiv papers for pattern extraction potential.\n\n## Overview\n\nPapers are scored on a scale of 0-10 using five weighted criteria. Only papers scoring >= 5.0 qualify for pattern extraction.\n\n## Scoring Criteria\n\n| Criterion | Weight | Description | Levels |\n|-----------|--------|-------------|--------|\n| **Reusability** | 30% | How widely applicable is the pattern? | Domain-specific (1.0) → Multi-domain (2.0) → Universal (3.0) |\n| **Novelty** | 25% | How new is the approach? | Existing (1.0) → Incremental (2.0) → Fundamentally new (3.0) |\n| **Clarity** | 20% | How well is it described? | Vague (1.0) → Clear (2.0) → Crystal clear (3.0) |\n| **Evidence** | 15% | Is there empirical validation? | No eval (1.0) → Some eval (2.0) → Strong empirical (3.0) |\n| **Completeness** | 10% | How complete is the implementation? | Idea only (1.0) → Partial details (2.0) → Production-ready (3.0) |\n\n## Detailed Scoring\n\n### Reusability (30% weight)\n\n| Score | Level | Indicators |\n|-------|-------|------------|\n| 1.0 | Domain-specific | \"specific to\", \"in the field of\", \"domain-specific\" |\n| 2.0 | Multi-domain | \"multi-domain\", \"cross-domain\", \"versatile\", \"adaptable\" |\n| 3.0 | Universal | \"general\", \"universal\", \"framework\", \"generic\", \"wide range\", \"variety of\" |\n\n### Novelty (25% weight)\n\n| Score | Level | Indicators |\n|-------|-------|------------|\n| 1.0 | Existing | No novelty indicators, describes existing approaches |\n| 2.0 | Incremental | \"improves\", \"extends\", \"builds on\", \"enhances\", \"optimizes\", \"refines\" |\n| 3.0 | Fundamentally new | \"novel\", \"new architecture\", \"new framework\", \"first to\", \"pioneering\", \"groundbreaking\" |\n\n### Clarity (20% weight)\n\n| Score | Level | Indicators |\n|-------|-------|------------|\n| 1.0 | Vague | \"may\", \"might\", \"potentially\", \"could be\", \"some ways\" |\n| 2.0 | Clear | \"we propose\", \"our approach\", \"the method\", abstract 100-150 words |\n| 3.0 | Crystal clear | Multiple clear indicators + abstract >150 words + concrete language |\n\n### Evidence (15% weight)\n\n| Score | Level | Indicators |\n|-------|-------|------------|\n| 1.0 | No eval | No evaluation or experiment mentioned |\n| 2.0 | Some eval | \"evaluation\", \"experiment\", \"benchmark\", \"results\", \"dataset\" |\n| 3.0 | Strong empirical | \"significant improvement\", \"state-of-the-art\", \"outperforms\", \"empirical\", \"real-world\" |\n\n### Completeness (10% weight)\n\n| Score | Level | Indicators |\n|-------|-------|------------|\n| 1.0 | Idea only | No implementation mentioned |\n| 1.5 | Partial idea | \"algorithm\", \"method\", \"approach\" mentioned |\n| 2.0 | Partial details | Implementation details or architecture described |\n| 3.0 | Production-ready | \"implementation\", \"open source\", \"code available\", \"github\", \"production\", \"deployed\" |\n\n## Score Calculation\n\nThe total score is calculated as a weighted sum:\n\n```\nTotal = (Reusability × 0.30) + (Novelty × 0.25) + (Clarity × 0.20) + (Evidence × 0.15) + (Completeness × 0.10)\n```\n\nMaximum possible score: 10.0\n\n## Threshold\n\n- **Score >= 5.0**: Qualifies for pattern extraction\n- **Score >= 7.0**: High-quality candidate, prioritize for extraction\n- **Score >= 8.5**: Exceptional candidate, immediate extraction recommended\n\n## Example Scoring\n\n### Example 1: High-quality paper (8.5)\n\n| Criterion | Score | Weighted |\n|-----------|-------|----------|\n| Reusability | 3.0 (Universal) | 0.90 |\n| Novelty | 3.0 (Fundamentally new) | 0.75 |\n| Clarity | 2.5 (Very clear) | 0.50 |\n| Evidence | 2.0 (Some eval) | 0.30 |\n| Completeness | 2.0 (Partial details) | 0.20 |\n| **Total** | | **8.5/10** |\n\n### Example 2: Marginal paper (5.2)\n\n| Criterion | Score | Weighted |\n|-----------|-------|----------|\n| Reusability | 2.0 (Multi-domain) | 0.60 |\n| Novelty | 2.0 (Incremental) | 0.50 |\n| Clarity | 2.0 (Clear) | 0.40 |\n| Evidence | 1.5 (Some eval) | 0.23 |\n| Completeness | 1.0 (Idea only) | 0.10 |\n| **Total** | | **5.2/10** |\n","isInternal":false,"tokens":1205,"sizeBytes":3972},{"name":"SKILL.md","path":".claude/skills/arxiv-pattern-discovery/SKILL.md","rawUrl":"https://raw.githubusercontent.com/nibzard/awesome-agentic-patterns/HEAD/.claude/skills/arxiv-pattern-discovery/SKILL.md","title":"arxiv-pattern-discovery","category":"anthropic-skill","format":"markdown","content":"---\nname: arxiv-pattern-discovery\ndescription: Search arXiv for academic papers describing agentic AI patterns. Use when user asks to find new patterns from academic literature, search arXiv, discover patterns from papers, or review academic sources for pattern extraction.\n---\n\n# arXiv Pattern Discovery\n\nSearch arXiv for academic papers describing agentic AI patterns and score them using the Pattern Quality Rubric.\n\n## Quick Start\n\nInvoke this skill when the user asks to:\n- Search arXiv for new agent patterns\n- Find academic papers about multi-agent orchestration\n- Discover patterns from academic literature\n- Review the latest papers for extractable patterns\n- What new patterns are emerging from recent AI research?\n\n## Workflow\n\nThis skill implements a 3-phase discovery workflow:\n\n### Phase 1: Discovery\n```bash\n# Search for recent papers (last 30 days, max 50 results)\npython scripts/arxiv_scanner.py --days=30 --max-results=50 --export-md results.md\n\n# Search for specific topics\npython scripts/arxiv_scanner.py --query=\"multi-agent systems\" --max-results=100\n\n# Search with minimum quality threshold\npython scripts/arxiv_scanner.py --min-score=7.0 --export-md high-quality.md\n```\n\n### Phase 2: Review\n- Read the exported Markdown report\n- Identify high-quality papers (score >= 7.0)\n- Check for potential duplicates flagged by the scanner\n- Select candidates for pattern extraction\n\n### Phase 3: Next Steps\n- Use the `create-pattern` skill to extract patterns from selected papers\n- Or manually create patterns using `patterns/TEMPLATE.md`\n- Run the similarity checker before committing to avoid duplicates\n- Run the validator to ensure pattern quality\n\n## Script Reference\n\n### arxiv_scanner.py\n\nMain script for querying arXiv API and scoring papers.\n\n**Usage:**\n```bash\npython scripts/arxiv_scanner.py [OPTIONS]\n```\n\n**Options:**\n- `--query, -q`: arXiv search query (default: agent/agentic/multi-agent papers)\n- `--max-results, -n`: Maximum results to fetch (default: 100)\n- `--days, -d`: Only include papers from last N days (default: 365)\n- `--min-score, -m`: Minimum quality score to include (default: 5.0)\n- `--export-json`: Export results to JSON file\n- `--export-md`: Export results to Markdown file\n- `--patterns-dir`: Path to patterns directory (default: patterns)\n- `--verbose, -v`: Print detailed output for each paper\n\n**Examples:**\n```bash\n# Recent high-quality papers\npython scripts/arxiv_scanner.py --days=7 --min-score=7.0\n\n# Search specific topic\npython scripts/arxiv_scanner.py --query=\"multi-agent orchestration\" --max-results=50\n\n# Full scan with export\npython scripts/arxiv_scanner.py --days=30 --export-md arxiv_report.md --verbose\n```\n\n### pattern_similarity_checker.py\n\nDetect potentially duplicate or very similar patterns.\n\n**Usage:**\n```bash\n# Check a single pattern against existing patterns\npython scripts/pattern_similarity_checker.py patterns/new-pattern.md\n\n# Check all patterns against each other\npython scripts/pattern_similarity_checker.py --all\n\n# Custom threshold and export\npython scripts/pattern_similarity_checker.py --all --threshold=0.7 --export report.md\n```\n\n**Options:**\n- `--all, -a`: Check all patterns against each other\n- `--patterns-dir, -d`: Path to patterns directory (default: patterns)\n- `--threshold, -t`: Similarity threshold for reporting (default: 0.5)\n- `--export, -e`: Export report to Markdown file\n\n### pattern_validator.py\n\nValidate pattern files for completeness and quality.\n\n**Usage:**\n```bash\n# Validate a single pattern\npython scripts/pattern_validator.py patterns/new-pattern.md\n\n# Validate all patterns\npython scripts/pattern_validator.py --all --verbose\n\n# Export validation report\npython scripts/pattern_validator.py --all --export validation_report.md\n```\n\n**Options:**\n- `--all, -a`: Validate all pattern files\n- `--patterns-dir, -d`: Path to patterns directory (default: patterns)\n- `--verbose, -v`: Print detailed output for each issue\n- `--strict, -s`: Treat warnings as errors\n- `--export, -e`: Export report to Markdown file\n\n## Next Steps After Discovery\n\nAfter identifying candidate papers from arXiv:\n\n1. **Extract the Pattern**: Use the `create-pattern` skill with the paper URL or PDF\n2. **Validate**: Run `pattern_validator.py` on the new pattern file\n3. **Check for Duplicates**: Run `pattern_similarity_checker.py` on the new pattern\n4. **Review**: Ensure the pattern meets the quality threshold (score >= 5.0)\n5. **Commit**: Add the pattern to the repository\n\n## Quality Scoring\n\nPapers are scored using the Pattern Quality Rubric (see RUBRIC.md for details):\n\n- **Reusability (30%)**: Domain-specific → Multi-domain → Universal\n- **Novelty (25%)**: Existing → Incremental → Fundamentally new\n- **Clarity (20%)**: Vague → Clear → Crystal clear\n- **Evidence (15%)**: No eval → Some eval → Strong empirical\n- **Completeness (10%)**: Idea only → Partial details → Production-ready\n\n**Threshold**: Score >= 5.0 qualifies for pattern extraction\n","frontmatter":{"name":"arxiv-pattern-discovery","description":"Search arXiv for academic papers describing agentic AI patterns. Use when user asks to find new patterns from academic literature, search arXiv, discover patterns from papers, or review academic sources for pattern extraction."},"isInternal":false,"tokens":1173,"sizeBytes":4963},{"name":"WORKFLOW.md","path":".claude/skills/arxiv-pattern-discovery/WORKFLOW.md","rawUrl":"https://raw.githubusercontent.com/nibzard/awesome-agentic-patterns/HEAD/.claude/skills/arxiv-pattern-discovery/WORKFLOW.md","title":"Arxiv-pattern-discovery Skill","category":"anthropic-skill","format":"markdown","content":"# arXiv Pattern Discovery Workflow\n\nEnd-to-end workflow for discovering agentic patterns from academic literature on arXiv.\n\n## Overview\n\nThis workflow guides you through the process of discovering new agentic patterns from academic papers:\n\n1. **Discovery** - Search arXiv and score papers\n2. **Review** - Identify high-quality candidates\n3. **Extract** - Create patterns from selected papers (user-driven)\n\n---\n\n## Phase 1: Discovery\n\n### Step 1.1: Run the arXiv Scanner\n\nSearch for recent papers with agentic patterns:\n\n```bash\n# Recent papers (last 30 days)\npython scripts/arxiv_scanner.py --days=30 --max-results=50 --export-md arxiv_results.md\n\n# All-time papers with higher quality threshold\npython scripts/arxiv_scanner.py --max-results=100 --min-score=7.0 --export-md high_quality.md\n\n# Specific topic search\npython scripts/arxiv_scanner.py --query=\"multi-agent memory systems\" --max-results=50 --export-md memory_patterns.md\n```\n\n### Step 1.2: Review the Output\n\nThe scanner produces:\n- Console output with top 10 papers by quality score\n- Optional Markdown report (with `--export-md`)\n- Optional JSON export (with `--export-json`)\n\nEach paper includes:\n- **Title**, **arXiv ID**, **URL**\n- **Quality Score** (0-10) with breakdown\n- **Suggested Category** (based on keywords)\n- **Extracted Tags**\n- **Abstract**\n- **Potential Duplicates** warning (if applicable)\n\n### Step 1.3: Filter Candidates\n\nFilter papers by:\n- **Quality Score**: Focus on papers >= 7.0 for best results\n- **Category**: Group by your area of interest\n- **Duplicate Warnings**: Skip papers flagged as duplicates\n\n---\n\n## Phase 2: Review\n\n### Step 2.1: Read the Markdown Report\n\nOpen the exported Markdown file and review candidates:\n\n```bash\n# View the report\ncat arxiv_results.md\n# or open in your editor\ncode arxiv_results.md\n```\n\n### Step 2.2: Visit Paper URLs\n\nFor each high-scoring paper:\n1. Click the arXiv URL to read the full paper\n2. Focus on the \"architecture\" or \"method\" section\n3. Look for reusable patterns (not just single techniques)\n\n### Step 2.3: Select Extraction Candidates\n\nPrioritize papers with:\n- Score >= 7.0 (high quality)\n- Clear architectural description\n- Novel approach not yet in the pattern catalog\n- Universal or multi-domain applicability\n\n---\n\n## Phase 3: Extract (User-Driven)\n\nAfter selecting candidate papers, you have two options:\n\n### Option A: Use the create-pattern Skill\n\nThe `create-pattern` skill can extract patterns from:\n- arXiv URLs\n- PDF files\n- Blog posts\n- Code repositories\n\n```\n# Ask Claude to extract a pattern from a paper\n\"Use create-pattern to extract a pattern from https://arxiv.org/abs/2401.12345\"\n```\n\n### Option B: Manual Pattern Creation\n\n1. Copy the template:\n   ```bash\n   cp patterns/TEMPLATE.md patterns/my-new-pattern.md\n   ```\n\n2. Fill in the required fields:\n   - `title`: Descriptive pattern name\n   - `status`: Based on quality score and evidence\n   - `authors`: Paper authors (@arxiv)\n   - `based_on`: Paper title (arXiv link)\n   - `category`: From the scanner's suggestion\n   - `source`: arXiv URL\n   - `tags`: From the scanner's extraction\n\n3. Write the pattern sections:\n   - **Problem**: What problem does this pattern solve?\n   - **Solution**: How does the architecture work?\n   - **Example**: Include a Mermaid diagram\n   - **References**: Link to the paper\n\n---\n\n## Phase 4: Validate (Before Committing)\n\n### Step 4.1: Check for Duplicates\n\n```bash\npython scripts/pattern_similarity_checker.py patterns/my-new-pattern.md\n```\n\nIf similarity > 0.7, consider:\n- Merging with existing pattern\n- Finding a more specific angle\n- Marking as variant of existing pattern\n\n### Step 4.2: Validate Quality\n\n```bash\npython scripts/pattern_validator.py patterns/my-new-pattern.md\n```\n\nFix any errors before committing.\n\n---\n\n## Example Session\n\n```bash\n# Step 1: Search arXiv\npython scripts/arxiv_scanner.py --days=30 --min-score=7.0 --export-md candidates.md\n\n# Output:\n# Scanning arXiv...\n# Fetched 100 papers\n# Filtered to 15 papers within last 30 days\n# Papers meeting threshold (7.0): 8\n\n# Step 2: Review the markdown report\ncat candidates.md\n\n# Step 3: Extract a pattern (using create-pattern skill)\n# \"Extract a pattern from https://arxiv.org/abs/2401.12345\"\n\n# Step 4: Validate\npython scripts/pattern_similarity_checker.py patterns/hierarchical-memory.md\npython scripts/pattern_validator.py patterns/hierarchical-memory.md\n```\n\n---\n\n## Tips for Success\n\n1. **Quality Over Quantity**: Focus on papers scoring >= 7.0\n2. **Avoid Duplicates**: Always run the similarity checker before committing\n3. **Validate Early**: Run the validator to catch issues early\n4. **Use the Rubric**: Understand why papers score the way they do (see RUBRIC.md)\n5. **Be Selective**: Not every good paper deserves a pattern—focus on reusable architectures\n","isInternal":false,"tokens":1192,"sizeBytes":4789},{"name":"PATTERN_INDEX.md","path":".claude/skills/create-pattern/PATTERN_INDEX.md","rawUrl":"https://raw.githubusercontent.com/nibzard/awesome-agentic-patterns/HEAD/.claude/skills/create-pattern/PATTERN_INDEX.md","title":"Create-pattern Skill","category":"anthropic-skill","format":"markdown","content":"# Pattern Index\n\nQuick reference for all 105+ patterns in the repository for semantic matching.\n\n## Category Summary\n\n| Category | Count | Key Themes |\n|----------|-------|------------|\n| Orchestration & Control | 32 | Task decomposition, sub-agents, tool routing |\n| Tool Use & Environment | 20 | Shell, browser, DB, sandbox tools |\n| UX & Collaboration | 16 | Prompts, hand-offs, staged commits |\n| Context & Memory | 14 | Window curation, vector cache, episodic memory |\n| Feedback Loops | 12 | CI, review, self-healing |\n| Reliability & Eval | 10 | Guardrails, evals, logging |\n| Security & Safety | 3 | Isolation, PII, scanning |\n| Learning & Adaptation | 3 | Agent RFT, skill libraries |\n\n## Common Tags (appear 4+ times)\n\n- tool-use, security, search, reinforcement-learning, reasoning\n- feedback, prompt-injection, planning, mcp, learning, evaluation\n- coding-agent, code-review, cli, automation\n\n## Pattern Clusters (for Matching)\n\n### Context Management Patterns\n- `context-minimization-pattern.md`\n- `context-window-anxiety-management.md`\n- `curated-code-context-window.md`\n- `layered-configuration-context.md`\n- `agentic-search-over-vector-embeddings.md`\n\n### Planning Patterns\n- `plan-then-execute-pattern.md`\n- `explicit-posterior-sampling-planner.md`\n- `tree-of-thought-reasoning.md`\n\n### Multi-Agent Patterns\n- `oracle-and-worker-multi-model.md`\n- `initializer-maintainer-dual-agent.md`\n- `sub-agent-spawning.md`\n- `continuous-autonomous-task-loop-pattern.md`\n\n### Memory/State Patterns\n- `episodic-memory-retrieval-injection.md`\n- `filesystem-based-agent-state.md`\n- `proactive-agent-state-externalization.md`\n\n### Security Patterns\n- `action-selector-pattern.md`\n- `egress-lockdown-no-exfiltration-channel.md`\n- `pii-tokenization.md`\n\n### Code Review Patterns\n- `criticgpt-style-evaluation.md`\n- `ai-assisted-code-review-verification.md`\n- `abstracted-code-representation-for-review.md`\n\n### Progressive Autonomy Chain\n- `progressive-autonomy-with-model-evolution.md`\n- `progressive-complexity-escalation.md`\n- `skill-library-evolution.md`\n\n### Tool Design Patterns\n- `dual-use-tool-design.md`\n- `tool-use-steering-via-prompting.md`\n- `tool-use-incentivization-via-reward-shaping.md`\n\n## Top Pattern Sources\n\n| Source | Patterns |\n|--------|----------|\n| Will Brown (Prime Intellect) | 8 patterns |\n| Boris Cherny (Anthropic) | 7 patterns |\n| Anthropic Engineering | 7 patterns |\n| Luca Beurer-Kellner et al. (2025) | 6 patterns |\n| Aman Sanger (Cursor) | 6 patterns |\n| Thorsten Ball | 5 patterns |\n| Quinn Slack | 5 patterns |\n| Lukas Möller (Cursor) | 5 patterns |\n\n## Matching Heuristics\n\nWhen analyzing a new source:\n\n1. **Check by author** - If source is from Will Brown, Boris Cherny, etc., likely matches existing pattern\n2. **Check by category** - Context management has 14 patterns with high overlap\n3. **Check by tags** - \"tool-use\", \"security\", \"reasoning\" indicate clusters\n4. **Problem similarity** - Same core challenge → likely existing pattern\n5. **Solution similarity** - Same mechanism → likely existing pattern\n\n## Decision Thresholds\n\n- **>80% confidence** - Update existing (same problem + solution + category)\n- **50-80% confidence** - Ask user (partial overlap)\n- **<50% confidence** - Create new (different problem/solution)\n","isInternal":false,"tokens":827,"sizeBytes":3273},{"name":"SKILL.md","path":".claude/skills/create-pattern/SKILL.md","rawUrl":"https://raw.githubusercontent.com/nibzard/awesome-agentic-patterns/HEAD/.claude/skills/create-pattern/SKILL.md","title":"create-pattern","category":"anthropic-skill","format":"markdown","content":"---\nname: create-pattern\ndescription: Analyze sources (blog posts, PDFs, YouTube videos, codebases, pasted text) for agentic patterns, match against 105+ existing patterns, create new patterns or update existing with new sources and insights.\nallowed-tools:\n  - Read\n  - Write\n  - Glob\n  - Grep\n  - Bash\n  - mcp__web_reader__webReader\n  - mcp__4_5v_mcp__analyze_image\n---\n\n# Pattern Ingestion Skill\n\nThis skill intelligently analyzes sources for agentic AI patterns, matches them against existing patterns in the repository, and either creates new patterns or updates existing ones with additional sources and insights.\n\n## Overview\n\n**Input:** A source (URL, PDF file, YouTube link, codebase path, or pasted text)\n\n**Process:**\n1. Ingest and analyze the source\n2. Extract pattern concepts\n3. Match against existing 105+ patterns\n4. Decide: create new OR update existing\n5. Execute and build\n\n**Output:** New pattern file OR updated existing pattern + build confirmation\n\n---\n\n## Phase 1: Ingest Source\n\nDetect the input type and process accordingly:\n\n### URL (blog post, documentation, article)\nUse `mcp__web_reader__webReader` with the URL:\n```json\n{\"url\": \"USER_PROVIDED_URL\", \"return_format\": \"markdown\"}\n```\n\n### PDF File\nUse `Read` tool with the PDF path.\n\n### YouTube Video\nUse `mcp__web_reader__webReader` with the YouTube URL (transcript extraction).\n\n### Codebase/Repository\nUse `Glob` to find key files, then `Read` to analyze:\n- `**/*.md` - Documentation\n- `**/*.py` - Python implementation\n- `**/*.ts` - TypeScript implementation\n- README files\n\n### Pasted Text\nAnalyze directly (no tool needed).\n\n---\n\n## Phase 2: Analyze & Extract\n\nFrom the source content, extract:\n\n1. **Pattern Title** - What is this pattern called?\n2. **Problem Statement** - What challenge does it solve?\n3. **Solution** - What's the core approach/mechanism?\n4. **Category** - Which of 8 categories fits best?\n5. **Source URL** - The original source\n6. **Author/Originator** - Who created/originated this?\n7. **Tags** - 3+ relevant keywords\n8. **Key Insights** - Any novel techniques, constraints, trade-offs\n\n**Generate candidate metadata:**\n- Title: descriptive, concise\n- Category: select from allowed categories (see reference below)\n- Tags: generate 5-10 relevant tags\n- Status: default to \"emerging\" unless evidence suggests otherwise\n\n---\n\n## Phase 3: Match Against Existing Patterns\n\nSearch for similar patterns in `patterns/` directory:\n\n### Step 3a: Read All Pattern Frontmatter\nUse `Glob` to find all `.md` files in `patterns/`, then `Grep` with output_mode `content` to extract frontmatter from each:\n```bash\ngrep -A 10 \"^title:\" patterns/*.md\n```\n\nOr read multiple pattern files in parallel to compare:\n- Problem statements\n- Solution approaches\n- Categories\n- Tags\n- Sources\n\n### Step 3b: Semantic Comparison\n\nFor each existing pattern, assess similarity using these signals:\n\n**Primary Signals (weight: 30% each)**\n1. **Problem Statement** - Same fundamental challenge?\n2. **Solution Mechanism** - Same core approach/technique?\n3. **Category** - Same category?\n\n**Secondary Signals (weight: 10% each)**\n4. **Tag Overlap** - Shared keywords?\n5. **Source/Author** - Same contributor's follow-up work?\n6. **Title** - Similar naming/description?\n\n### Step 3c: Calculate Confidence Score\n\n```\nScore = Σ(matching_signals × weights)\n```\n\n- All 3 primary match → 90%+ confidence\n- 2 primary + 1+ secondary → 70-90% confidence\n- 1 primary + 2+ secondary → 50-70% confidence\n- 0-1 primary only → <50% confidence\n\n### Step 3d: Identify Top Matches\n\nList top 3 matching patterns with:\n- Pattern title and file path\n- Confidence score\n- Matching rationale (which signals matched)\n\n---\n\n## Phase 4: Decision\n\nBased on confidence score:\n\n### High Confidence (>80%) → Update Existing\nUpdate the top-matching existing pattern with new source.\n\n### Low Confidence (<50%) → Create New\nCreate a brand new pattern file.\n\n### Medium Confidence (50-80%) → Ask User\nPresent the top match and ask:\n\n```\nThis source seems related to:\n- [Match Pattern] (X% confidence)\n  - Similar problem: [problem summary]\n  - Similar solution: [solution summary]\n\nShould I:\n1. Create a new pattern\n2. Update the existing pattern with this new source\n```\n\n---\n\n## Phase 5a: Create New Pattern\n\n### Step 5a-1: Generate Metadata\n```yaml\n---\ntitle: \"Extracted Title\"\nstatus: emerging\nauthors: [\"Your Name (@yourusername)\"]\nbased_on: [\"Originator Name (Source/Context)\"]\ncategory: \"Selected Category\"\nsource: \"SOURCE_URL\"\ntags: [tag1, tag2, tag3, ...]\n---\n```\n\n### Step 5a-2: Generate Slug\nConvert title to kebab-case:\n- Lowercase\n- Spaces → hyphens\n- Remove special characters\n- Example: \"Tree of Thought Reasoning\" → `tree-of-thought-reasoning`\n\n### Step 5a-3: Write Pattern File\nCreate `patterns/{slug}.md` with structure:\n\n```markdown\n---\ntitle: \"Title\"\nstatus: emerging\nauthors: [\"Your Name (@yourusername)\"]\nbased_on: [\"Originator (Source)\"]\ncategory: \"Category\"\nsource: \"URL\"\ntags: [tag1, tag2, tag3]\n---\n\n## Problem\n[Extracted problem statement]\n\n## Solution\n[Extracted solution description]\n\n- Key components: [list]\n- Mechanism: [describe]\n\n```pseudo\n[Optional: pseudocode if helpful]\n```\n\n## How to use it\n[Extracted usage guidance]\n\n## Trade-offs\n[Extracted pros and cons]\n\n* **Pros:** [benefits]\n* **Cons:** [drawbacks]\n\n## References\n* [Original Source Title](URL)\n```\n\n---\n\n## Phase 5b: Update Existing Pattern\n\n### Step 5b-1: Read Existing Pattern\nRead the matched pattern file at `patterns/{existing-slug}.md`\n\n### Step 5b-2: Update Frontmatter\n\n**Add to `based_on` array:**\n```yaml\nbased_on:\n  - \"Existing Source (Existing Context)\"\n  - \"New Originator (New Source/Context)\"  # Add this\n```\n\n**Add new tags** (if not duplicates):\n```yaml\ntags:\n  - existing-tag\n  - new-tag-from-source  # Add unique new tags\n```\n\n### Step 5b-3: Add to References Section\n\nAppend to the `## References` section:\n```markdown\n## References\n* [Existing Source](existing-url)\n* [New Source Title](new-url)  # Add this\n```\n\n### Step 5b-4: Auto-Expand Content (If Applicable)\n\n**IF** the new source adds substantial new insights (not just a citation):\n\n**To Solution section:**\n```markdown\n## Solution\n[existing content...]\n\n**Additional insights from [New Source]:**\n[Extracted new insights with attribution]\n```\n\n**To How to use it section:**\n```markdown\n## How to use it\n[existing content...]\n\n**According to [New Source]:**\n[New usage guidance or implementation details]\n```\n\n**To Trade-offs section:**\n```markdown\n## Trade-offs\n* **Pros:** [existing..., new pros from source]\n* **Cons:** [existing..., new cons from source]\n```\n\n### Step 5b-5: Write Updated File\nWrite the updated content back to `patterns/{existing-slug}.md`\n\n---\n\n## Phase 6: Build\n\n### Step 6-1: Run Build Script\n```bash\ncd apps/web && bun run build-data\n```\n\n### Step 6-2: Verify Success\nCheck for:\n- Pattern JSON files updated in `apps/web/public/patterns/`\n- No error messages\n\n---\n\n## Reference: Allowed Values\n\n### Categories (8 options)\n- Orchestration & Control\n- Context & Memory\n- Feedback Loops\n- Learning & Adaptation\n- Reliability & Eval\n- Security & Safety\n- Tool Use & Environment\n- UX & Collaboration\n- Uncategorized\n\n### Status Values (7 options)\n- proposed - Initial concept\n- emerging - Early adoption\n- established - Proven approach\n- validated-in-production - Production-tested\n- best-practice - Industry standard\n- experimental-but-awesome - Novel but effective\n- rapidly-improving - Fast-evolving\n\n### Front-matter Template\n```yaml\n---\ntitle: \"Pattern Title\"\nstatus: emerging\nauthors: [\"Contributor Name (@username)\"]\nbased_on: [\"Originator Name (Source Context)\"]\ncategory: \"Category Name\"\nsource: \"https://example.com/source\"\ntags: [tag1, tag2, tag3]\n---\n```\n\n---\n\n## Output Summary\n\nAfter completion, provide:\n\n**For New Pattern:**\n```\n✅ Created new pattern: patterns/{slug}.md\n- Title: [title]\n- Category: [category]\n- Tags: [tags]\n\nNext steps:\n1. Review and edit the pattern file for completeness\n2. Run: cd apps/web && bun run dev\n3. Commit: git add patterns/{slug}.md\n```\n\n**For Updated Pattern:**\n```\n✅ Updated existing pattern: patterns/{slug}.md\n- Added source to based_on: [source]\n- Added [N] new tags\n- [Expanded Solution/How-to sections]\n\nNext steps:\n1. Review the updated pattern file\n2. Run: cd apps/web && bun run dev\n3. Commit: git add patterns/{slug}.md\n```\n\n---\n\n## Tips\n\n- **When in doubt, ask the user** - Pattern matching can be nuanced\n- **Preserve existing content** - When updating, don't remove or overwrite existing insights\n- **Clear attribution** - Always cite sources when adding new content\n- **Tag thoughtfully** - Tags help with future matching\n- **Check for duplicates** - If `based_on` already includes the source, just inform the user\n","frontmatter":{"name":"create-pattern","description":"Analyze sources (blog posts, PDFs, YouTube videos, codebases, pasted text) for agentic patterns, match against 105+ existing patterns, create new patterns or update existing with new sources and insights.","allowed-tools":["Read","Write","Glob","Grep","Bash","mcp__web_reader__webReader","mcp__4_5v_mcp__analyze_image"],"allowedTools":["Read","Write","Glob","Grep","Bash","mcp__web_reader__webReader","mcp__4_5v_mcp__analyze_image"]},"allowedTools":["Read","Write","Glob","Grep","Bash","mcp__web_reader__webReader","mcp__4_5v_mcp__analyze_image"],"isInternal":false,"tokens":2256,"sizeBytes":8742},{"name":"SKILL.md","path":"skills/pr-review/SKILL.md","rawUrl":"https://raw.githubusercontent.com/nibzard/awesome-agentic-patterns/HEAD/skills/pr-review/SKILL.md","title":"awesome-agentic-patterns-pr-review","category":"anthropic-skill","format":"markdown","content":"---\nname: awesome-agentic-patterns-pr-review\ndescription: Review pull requests for the awesome-agentic-patterns repository. Use when asked to validate a PR, assess whether a contribution fits the repo, inspect pattern submissions under patterns/, check merge readiness, repair a small submission issue on top of a contributor branch, draft a polite contributor comment, or apply the repository's pattern-first and non-promotional contribution policy to a GitHub pull request.\n---\n\n# Awesome Agentic Patterns PR Review\n\n## Overview\n\nReview PRs in this repository by applying the local contribution policy and checking the actual changed files. Treat `CONTRIBUTING.md` as the source of truth for acceptance criteria, `TEMPLATE.md` as the source of truth for expected pattern structure, and the validation scripts in `scripts/` as the source of truth for structural checks and generated-file expectations.\n\n## Read First\n\n- `CONTRIBUTING.md`\n- `README.md`\n- `SCHEMA.md` for the status tiers and field definitions\n- `TEMPLATE.md` at the repository root\n- `scripts/validate-patterns.ts`, the authoritative front-matter and section validator\n- `scripts/build-data.ts` when the PR touches patterns, generated README sections, or generated site data\n\nDo not restate repo policy from memory when those files are available. Quote or summarize the repository's own rules instead.\n\n## Workflow\n\n### 1. Inspect the PR\n\nUse `gh` first:\n\n- `gh pr view <number> --repo nibzard/awesome-agentic-patterns --json title,number,state,isDraft,author,baseRefName,headRefName,headRepository,headRepositoryOwner,maintainerCanModify,files,additions,deletions,mergeable,mergeStateStatus,reviewDecision,statusCheckRollup,labels,url,body`\n- `gh pr diff <number> --repo nibzard/awesome-agentic-patterns --patch`\n- `gh pr checks <number> --repo nibzard/awesome-agentic-patterns`\n\nIf you need the exact branch locally, fetch it with:\n\n- `git fetch origin refs/pull/<number>/head:pr-<number>`\n\nCapture these facts before deciding anything:\n\n- Whether the PR is a new pattern submission, a pattern edit, or a broader repo/tooling change\n- Whether the change correctly uses `patterns/<slug>.md` rather than editing generated docs directly\n- Whether `README.md` or `apps/web/public/` generated outputs changed because the contributor regenerated outputs, or because they hand-edited generated files\n- Whether `maintainerCanModify` is enabled and which fork/branch must be updated if you need to fix the PR\n- Whether GitHub mergeability is trustworthy yet; `UNKNOWN` can be transient right after a push\n\n### 2. Validate the submission contract\n\nFor pattern submissions, check the repository's exact contract before debating fit:\n\n- One pattern per PR\n- New patterns live in `patterns/` and use kebab-case filenames\n- PR title should use `Add: pattern-name`\n- The pattern should be concise, roughly capped at about 200 lines\n- Do not edit README auto-generated sections manually\n- `docs/index.md` is only a compatibility symlink to `README.md`\n- Required front-matter fields (enforced by `scripts/validate-patterns.ts`):\n  `title`\n  `status`\n  `authors`\n  `category`\n  `source`\n  `tags`\n  `summary`\n  `signals`\n  `anti_signals`\n  `updated_at` in `YYYY-MM-DD` form\n- `based_on` is optional, but a contributor-owned source must be disclosed in `authors` / `based_on`\n- `source_link` is invalid here; use `source`\n- Required content sections (enforced with `--check-content`):\n  `## Problem`\n  `## Solution`\n  `## How to use it`\n  `## Trade-offs`\n  `## References`\n- Status tier, one of `proposed`, `emerging`, `production`, `foundational`, judged against the independent-adoption bar:\n\n  - A submission backed only by a contributor-owned repo, a personal experiment, or a launch-stage product must use `status: proposed`. Downgrade anything higher to `proposed`.\n  - `emerging` needs 2+ independent implementations or teams, or 1 detailed production write-up or major lab paper with active industry iteration.\n  - `production` needs proof across multiple independent production systems, with documented failure modes and operational trade-offs.\n  - `foundational` is for an industry-default baseline whenever its `signals` apply, and the catalogue keeps the tier to roughly 12-18 patterns.\n\n- Agent-centric technical scope: the pattern must describe a control loop in which an agent senses, reasons, remembers, uses tools, or stays safe. Product strategy, startup philosophy, career advice, and generic non-agent software architecture belong in `principles/`, not `patterns/`.\n- Known Implementations cap: `Known Implementations` and tool references are limited to 3-5 entries per pattern. A PR that only appends another vendor or tool link is acceptable only when the tool replaces a deprecated reference or demonstrates a materially distinct architectural variant.\n- Differentiation: the PR description must answer \"Closest existing pattern(s) & how this is distinct\" and justify why the idea cannot live as a section inside an existing pattern.\n\nBefore judging novelty, run `python3 scripts/pattern_similarity_checker.py <pattern-file.md>`, then search `patterns/` for duplicates and near-overlaps by title, tags, and Problem wording. Compare what you find with the contributor's differentiation answer. When the primary `source` or a reference belongs to the contributor or an affiliated project, confirm the relationship is disclosed and the write-up frames it as an example rather than the center of the PR.\n\nFor generated-file sync, check whether the PR also updated the outputs that CI compares against `patterns/*.md`:\n\n- `README.md`\n- `apps/web/public/data/patterns.json`\n- other generated files under `apps/web/public/` when the pattern catalog changed\n- `llms.txt` at the repository root, which `bun run build:data` keeps identical to `apps/web/public/llms.txt`\n\nCall out structural violations explicitly. These are repository requirements, not style nits.\n\n### 3. Apply local policy\n\nUse `CONTRIBUTING.md` for the actual acceptance rubric. Evaluate:\n\n- Whether the PR documents a reusable pattern rather than a product announcement\n- Whether the pattern is materially novel and non-repetitive relative to existing patterns\n- Whether the write-up clearly explains Problem, Solution, and Trade-offs or practical mechanics\n- Whether references are public and verifiable\n- Whether the contribution is community-first and non-promotional\n- Whether external links are mostly `github.com`, `github.io`, or neutral technical references for outside contributors\n- Whether any vendor or product links are justified by clear novelty rather than marketing\n- Whether contributor-owned projects are disclosed and framed as examples rather than the center of the PR\n- Whether the category is the best fit for existing repo taxonomy\n- Whether the `status` tier matches its objective criterion; a contributor-owned repo or launch-stage product is `proposed`\n- Whether the pattern is an agent-specific technical control loop rather than product strategy or generic software architecture\n- Whether the PR description names the closest existing pattern(s) and justifies why the submission is not a section inside one of them\n- Whether a reference-addition PR stays within the 3-5 entry cap and adds a tool that replaces a deprecated reference or shows a materially distinct variant\n\nSeparate policy fit from technical mergeability. A PR can be in scope but still need a maintainer fix before merge.\n\n### 4. Run structural validation\n\nWhen reviewing a local branch or checking CI behavior, run from the repository root:\n\n- `bun run validate:patterns:content` for front matter, required sections, referential integrity, status vs. evidence, and length guardrails; this is the authoritative validator, and CI runs it\n- `bun run validate:patterns` for front matter only (`scripts/validate-patterns.ts`)\n- `python3 scripts/pattern_similarity_checker.py <pattern-file.md>` to surface near-duplicates before you judge novelty\n- `bun run build:data` when checking generated README or site data changes; it also fails on a missing or malformed `updated_at`. CI syncs the root `llms.txt` alongside `README.md` and `apps/web/public/`.\n\nTreat the scripts as structural checks, not the decision-maker. Human review still decides repository fit, novelty, promotion risk, and category choice.\n\n### 5. Repair the branch when the PR is acceptable but stale\n\nIf the PR is acceptable and the user wants it fixed or merged, prefer the smallest possible maintainer correction:\n\n- Fetch the PR branch locally\n- Rebase or replay it onto `origin/main`\n- Fix only the minimum structural issue\n- Normalize front-matter keys or section headings to repo expectations\n- Regenerate `README.md` and site data with `bun run build:data` only if the PR already requires generated-file sync\n- Push back to the contributor's exact head branch, preferably with `--force-with-lease`\n- Re-check `gh pr view` after the push because `mergeable` and `mergeStateStatus` may temporarily show `UNKNOWN`\n\nDo not turn a small submission repair into a broader cleanup.\n\n### 6. Produce the review\n\nUse a code-review mindset:\n\n- Present findings first, ordered by severity, with file references when applicable\n- If there are no findings, say that explicitly\n- After findings, give one clear decision: `Accept`, `Request changes`, or `Close`\n- Include mergeability as a separate line: `clean`, `needs maintainer repair`, or `blocked`\n- When the user wants to merge, include the exact next action: `comment`, `fix and push`, `merge`, or `close`\n\n## Output Shape\n\nKeep the final review compact and consistent. Use this exact structure:\n\n`Summary`\n- One short sentence on PR state or scope if useful\n\n`Findings`\n- Findings first, ordered by severity\n- If there are no findings, say `No blocking findings.`\n\n`Decision`\n- `Policy fit: Accept | Request changes | Close`\n- `Mergeability: clean | needs maintainer repair | blocked`\n- `Recommended action: comment | fix and push | merge | close`\n\n`Proposed comment to contributor`\n- Draft a short, polite comment suitable for posting on the PR\n- If the maintainer already fixed the PR, say what was adjusted and thank the contributor\n- If requesting changes, state the minimum changes needed\n\n`What next`\n- End with a direct question to the user asking what they want next\n- Example: `Do you want me to post the comment, push the small fix, or merge it?`\n","frontmatter":{"name":"awesome-agentic-patterns-pr-review","description":"Review pull requests for the awesome-agentic-patterns repository. Use when asked to validate a PR, assess whether a contribution fits the repo, inspect pattern submissions under patterns/, check merge readiness, repair a small submission issue on top of a contributor branch, draft a polite contributor comment, or apply the repository's pattern-first and non-promotional contribution policy to a GitHub pull request."},"isInternal":false,"tokens":2271,"sizeBytes":10398},{"name":"arxiv_scanner.py","path":".claude/skills/arxiv-pattern-discovery/scripts/arxiv_scanner.py","rawUrl":"https://raw.githubusercontent.com/nibzard/awesome-agentic-patterns/HEAD/.claude/skills/arxiv-pattern-discovery/scripts/arxiv_scanner.py","title":"Claude Directive: arxiv_scanner.py","category":"claude-rule","format":"markdown","content":"#!/usr/bin/env python3\n\"\"\"\narxiv_scanner.py\n\nAutomated paper discovery for new agentic patterns from arXiv.\n\nQueries arXiv API with targeted search terms, filters by date/citation count/keywords,\nand scores papers using the Pattern Quality Rubric (0-10).\n\nUsage:\n    python scripts/arxiv_scanner.py --days=7 --min-citations=3\n    python scripts/arxiv_scanner.py --query=\"multi-agent systems\" --max-results=50\n\"\"\"\n\nimport argparse\nimport configparser\nimport dataclasses\nimport datetime\nimport json\nimport re\nimport sys\nimport time\nimport urllib.parse\nimport urllib.request\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Optional, Set\n\n\n# Configuration\nDEFAULT_SEARCH_QUERY = '(cat:cs.AI OR cat:cs.CL OR cat:cs.LG OR cat:cs.CR) AND all:\"agent\" OR all:\"agentic\" OR all:\"multi-agent\"'\nARXIV_API_URL = \"http://export.arxiv.org/api/query?\"\nUSER_AGENT = \"arxiv-scanner/0.1 (https://github.com/nibzard/awesome-agentic-patterns)\"\n\n\n# Valid status values for patterns\nVALID_STATUSES = {\n    \"proposed\",\n    \"emerging\",\n    \"established\",\n    \"validated-in-production\",\n    \"best-practice\",\n    \"experimental-but-awesome\",\n    \"rapidly-improving\",\n}\n\n# Valid category values\nVALID_CATEGORIES = {\n    \"Orchestration & Control\",\n    \"Context & Memory\",\n    \"Feedback Loops\",\n    \"Learning & Adaptation\",\n    \"Reliability & Eval\",\n    \"Security & Safety\",\n    \"Tool Use & Environment\",\n    \"UX & Collaboration\",\n    \"Uncategorized\",\n}\n\n\n@dataclasses.dataclass\nclass Paper:\n    \"\"\"Represents an arXiv paper with metadata.\"\"\"\n\n    arxiv_id: str\n    title: str\n    authors: List[str]\n    abstract: str\n    published: str\n    updated: str\n    categories: List[str]\n    url: str\n    citation_count: int = 0\n    quality_score: float = 0.0\n\n\n@dataclasses.dataclass\nclass PatternCandidate:\n    \"\"\"Represents a potential pattern extracted from a paper.\"\"\"\n\n    paper: Paper\n    pattern_name: Optional[str] = None\n    category: Optional[str] = None\n    tags: List[str] = dataclasses.field(default_factory=list)\n    score_breakdown: Dict[str, float] = dataclasses.field(default_factory=dict)\n    total_score: float = 0.0\n\n\nclass ArxivAPIError(Exception):\n    \"\"\"Raised when arXiv API request fails.\"\"\"\n\n    pass\n\n\ndef fetch_arxiv_papers(\n    query: str,\n    max_results: int = 100,\n    sort_by: str = \"submittedDate\",\n    sort_order: str = \"descending\",\n) -> List[Paper]:\n    \"\"\"\n    Fetch papers from arXiv API.\n\n    Args:\n        query: Search query string\n        max_results: Maximum number of results to return\n        sort_by: Sort field (lastUpdatedDate, submittedDate)\n        sort_order: ascending or descending\n\n    Returns:\n        List of Paper objects\n    \"\"\"\n    encoded_query = urllib.parse.quote(query)\n    url = f\"{ARXIV_API_URL}search_query={encoded_query}&start=0&max_results={max_results}&sortBy={sort_by}&sortOrder={sort_order}\"\n\n    headers = {\"User-Agent\": USER_AGENT}\n\n    try:\n        req = urllib.request.Request(url, headers=headers)\n        with urllib.request.urlopen(req, timeout=30) as response:\n            xml_data = response.read().decode(\"utf-8\")\n    except urllib.error.URLError as e:\n        raise ArxivAPIError(f\"Failed to fetch papers: {e}\")\n\n    return parse_arxiv_response(xml_data)\n\n\ndef parse_arxiv_response(xml_data: str) -> List[Paper]:\n    \"\"\"Parse arXiv API XML response into Paper objects.\"\"\"\n    papers = []\n\n    # Extract entries using regex (simple approach, could use xml.etree)\n    entry_pattern = re.compile(r\"<entry>(.*?)</entry>\", re.DOTALL)\n    title_pattern = re.compile(r\"<title>(.*?)</title>\", re.DOTALL)\n    author_pattern = re.compile(r\"<name>(.*?)</name>\")\n    summary_pattern = re.compile(r\"<summary>(.*?)</summary>\", re.DOTALL)\n    published_pattern = re.compile(r\"<published>(.*?)</published>\")\n    updated_pattern = re.compile(r\"<updated>(.*?)</updated>\")\n    category_pattern = re.compile(r'<term[^>]*>([^<]+)</term>')\n    id_pattern = re.compile(r\"<id>(.*?)</id>\")\n    arxiv_id_pattern = re.compile(r\"arxiv.org/abs/(\\d+\\.\\d+)\")\n\n    for entry_match in entry_pattern.finditer(xml_data):\n        entry = entry_match.group(1)\n\n        # Extract title\n        title_match = title_pattern.search(entry)\n        title = title_match.group(1).strip().replace(\"\\n\", \" \") if title_match else \"Unknown\"\n\n        # Extract authors\n        authors = [a.strip() for a in author_pattern.findall(entry)]\n\n        # Extract abstract\n        summary_match = summary_pattern.search(entry)\n        abstract = summary_match.group(1).strip().replace(\"\\n\", \" \") if summary_match else \"\"\n\n        # Extract dates\n        published_match = published_pattern.search(entry)\n        published = published_match.group(1) if published_match else \"\"\n\n        updated_match = updated_pattern.search(entry)\n        updated = updated_match.group(1) if updated_match else \"\"\n\n        # Extract categories (primary and secondary)\n        categories = list(set(category_pattern.findall(entry)))\n\n        # Extract arXiv ID\n        id_match = id_pattern.search(entry)\n        arxiv_id = \"unknown\"\n        if id_match:\n            arxiv_id_match = arxiv_id_pattern.search(id_match.group(1))\n            if arxiv_id_match:\n                arxiv_id = arxiv_id_match.group(1)\n\n        # Build URL\n        url = f\"https://arxiv.org/abs/{arxiv_id}\"\n\n        papers.append(\n            Paper(\n                arxiv_id=arxiv_id,\n                title=title,\n                authors=authors,\n                abstract=abstract,\n                published=published,\n                updated=updated,\n                categories=categories,\n                url=url,\n            )\n        )\n\n    return papers\n\n\ndef parse_date(date_string: str) -> datetime.datetime:\n    \"\"\"Parse arXiv date string to datetime object.\"\"\"\n    # arXiv dates are in format: 2025-01-15T12:34:56Z\n    try:\n        return datetime.datetime.fromisoformat(date_string.replace(\"Z\", \"+00:00\"))\n    except ValueError:\n        # Fallback for other formats\n        return datetime.datetime.min\n\n\ndef filter_papers_by_date(papers: List[Paper], days: int) -> List[Paper]:\n    \"\"\"Filter papers to those published/updated within the last N days.\"\"\"\n    cutoff = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(days=days)\n    return [p for p in papers if parse_date(p.published) >= cutoff or parse_date(p.updated) >= cutoff]\n\n\ndef filter_papers_by_keywords(papers: List[Paper]) -> List[Paper]:\n    \"\"\"Filter papers to those containing architecture/pattern keywords in abstract.\"\"\"\n    architectural_terms = {\n        \"architecture\",\n        \"pattern\",\n        \"framework\",\n        \"design\",\n        \"orchestration\",\n        \"coordination\",\n        \"hierarchy\",\n        \"protocol\",\n        \"memory\",\n        \"agent\",\n        \"agentic\",\n        \"multi-agent\",\n        \"autonomous\",\n        \"workflow\",\n        \"control\",\n        \"feedback\",\n        \"adapter\",\n        \"interface\",\n        \"abstraction\",\n    }\n\n    filtered = []\n    for paper in papers:\n        abstract_lower = paper.abstract.lower()\n        title_lower = paper.title.lower()\n        combined = title_lower + \" \" + abstract_lower\n\n        if any(term in combined for term in architectural_terms):\n            filtered.append(paper)\n\n    return filtered\n\n\ndef score_reusability(paper: Paper) -> float:\n    \"\"\"\n    Score paper on reusability (30% weight).\n\n    Domain-specific (1.0) → Multi-domain (2.0) → Universal (3.0)\n    \"\"\"\n    abstract_lower = paper.abstract.lower()\n    title_lower = paper.title.lower()\n    combined = title_lower + \" \" + abstract_lower\n\n    # Check for universal language\n    universal_indicators = [\"general\", \"universal\", \"framework\", \"generic\", \"generic approach\"]\n    multi_domain_indicators = [\"multi-domain\", \"cross-domain\", \"versatile\", \"adaptable\"]\n    domain_specific_indicators = [\"specific to\", \"in the field of\", \"domain-specific\"]\n\n    universal_count = sum(1 for term in universal_indicators if term in combined)\n    multi_domain_count = sum(1 for term in multi_domain_indicators if term in combined)\n    domain_specific_count = sum(1 for term in domain_specific_indicators if term in combined)\n\n    # Also check for broad application potential\n    broad_terms = [\"wide range\", \"variety of\", \"multiple use cases\", \"flexible\"]\n    broad_count = sum(1 for term in broad_terms if term in combined)\n\n    if universal_count >= 1 or broad_count >= 1:\n        return 3.0\n    elif multi_domain_count >= 1:\n        return 2.0\n    elif domain_specific_count >= 1:\n        return 1.0\n    else:\n        # Default to mid-range\n        return 2.0\n\n\ndef score_novelty(paper: Paper) -> float:\n    \"\"\"\n    Score paper on novelty (25% weight).\n\n    Existing (1.0) → Incremental (2.0) → Fundamentally new (3.0)\n    \"\"\"\n    abstract_lower = paper.abstract.lower()\n    title_lower = paper.title.lower()\n    combined = title_lower + \" \" + abstract_lower\n\n    # Check for novelty indicators\n    novel_indicators = [\n        \"novel\",\n        \"new\",\n        \"first\",\n        \"pioneering\",\n        \"groundbreaking\",\n        \"innovative\",\n        \"unprecedented\",\n        \"original\",\n        \"unique approach\",\n    ]\n    incremental_indicators = [\n        \"improves\",\n        \"extends\",\n        \"builds on\",\n        \"enhances\",\n        \"optimizes\",\n        \"refines\",\n        \"extension of\",\n    ]\n\n    novel_count = sum(1 for term in novel_indicators if term in combined)\n    incremental_count = sum(1 for term in incremental_indicators if term in combined)\n\n    # Check for strong claims of new approaches\n    strong_novel = [\"new architecture\", \"new framework\", \"new paradigm\", \"first to\"]\n    strong_novel_count = sum(1 for term in strong_novel if term in combined)\n\n    if strong_novel_count >= 1 or novel_count >= 2:\n        return 3.0\n    elif novel_count >= 1 and incremental_count == 0:\n        return 2.5\n    elif incremental_count >= 1:\n        return 2.0\n    else:\n        return 1.5\n\n\ndef score_clarity(paper: Paper) -> float:\n    \"\"\"\n    Score paper on clarity (20% weight).\n\n    Vague (1.0) → Clear (2.0) → Crystal clear (3.0)\n    \"\"\"\n    abstract_lower = paper.abstract.lower()\n    title_lower = paper.title.lower()\n    combined = title_lower + \" \" + abstract_lower\n\n    # Clarity indicators\n    clear_indicators = [\n        \"we propose\",\n        \"we present\",\n        \"our approach\",\n        \"the method\",\n        \"the algorithm\",\n        \"specifically\",\n        \"concretely\",\n    ]\n    vague_indicators = [\n        \"some ways\",\n        \"somewhat\",\n        \"may\",\n        \"might\",\n        \"potentially\",\n        \"could be\",\n    ]\n\n    clear_count = sum(1 for term in clear_indicators if term in combined)\n    vague_count = sum(1 for term in vague_indicators if term in combined)\n\n    # Abstract length (too short might indicate lack of detail)\n    abstract_words = len(paper.abstract.split())\n    length_score = 0\n    if abstract_words > 150:\n        length_score = 1\n    elif abstract_words > 100:\n        length_score = 0.5\n\n    base_score = 2.0\n    if clear_count >= 3:\n        base_score = 2.5\n    if vague_count >= 3:\n        base_score = max(1.0, base_score - 0.5)\n\n    return min(3.0, base_score + length_score)\n\n\ndef score_evidence(paper: Paper) -> float:\n    \"\"\"\n    Score paper on empirical evidence (15% weight).\n\n    No eval (1.0) → Some eval (2.0) → Strong empirical (3.0)\n    \"\"\"\n    abstract_lower = paper.abstract.lower()\n\n    # Evidence indicators\n    eval_indicators = [\n        \"evaluation\",\n        \"experiment\",\n        \"benchmark\",\n        \"results\",\n        \"performance\",\n        \"compared\",\n        \"comparison\",\n        \"metric\",\n    ]\n    strong_eval_indicators = [\n        \"significant improvement\",\n        \"state-of-the-art\",\n        \"sota\",\n        \"outperforms\",\n        \"empirical\",\n        \"real-world\",\n        \"deployment\",\n    ]\n\n    eval_count = sum(1 for term in eval_indicators if term in abstract_lower)\n    strong_eval_count = sum(1 for term in strong_eval_indicators if term in abstract_lower)\n\n    # Check for datasets (indicates empirical work)\n    dataset_indicators = [\"dataset\", \"benchmark\", \"we evaluate on\", \"tested on\"]\n    dataset_count = sum(1 for term in dataset_indicators if term in abstract_lower)\n\n    if strong_eval_count >= 1 or eval_count >= 3:\n        return 3.0\n    elif eval_count >= 1:\n        return 2.0\n    elif dataset_count >= 1:\n        return 2.0\n    else:\n        return 1.0\n\n\ndef score_completeness(paper: Paper) -> float:\n    \"\"\"\n    Score paper on implementation completeness (10% weight).\n\n    Idea only (1.0) → Partial details (2.0) → Production-ready (3.0)\n    \"\"\"\n    abstract_lower = paper.abstract.lower()\n\n    # Completeness indicators\n    implementation_indicators = [\n        \"implementation\",\n        \"open source\",\n        \"code\",\n        \"available\",\n        \"github\",\n        \"released\",\n        \"library\",\n    ]\n    detail_indicators = [\n        \"algorithm\",\n        \"architecture\",\n        \"framework\",\n        \"protocol\",\n        \"method\",\n        \"approach\",\n    ]\n\n    implementation_count = sum(1 for term in implementation_indicators if term in abstract_lower)\n    detail_count = sum(1 for term in detail_indicators if term in abstract_lower)\n\n    # Check for production mentions\n    production_indicators = [\"production\", \"deployed\", \"real-world\", \"industry\"]\n    production_count = sum(1 for term in production_indicators if term in abstract_lower)\n\n    if implementation_count >= 2 or production_count >= 1:\n        return 3.0\n    elif implementation_count >= 1 or detail_count >= 3:\n        return 2.0\n    elif detail_count >= 1:\n        return 1.5\n    else:\n        return 1.0\n\n\ndef calculate_quality_score(paper: Paper) -> tuple[float, Dict[str, float]]:\n    \"\"\"\n    Calculate overall quality score using the Pattern Quality Rubric.\n\n    Returns:\n        Tuple of (total_score, score_breakdown)\n    \"\"\"\n    # Weighted scoring\n    reusability = score_reusability(paper)\n    novelty = score_novelty(paper)\n    clarity = score_clarity(paper)\n    evidence = score_evidence(paper)\n    completeness = score_completeness(paper)\n\n    # Weights\n    total_score = (\n        reusability * 0.30 +\n        novelty * 0.25 +\n        clarity * 0.20 +\n        evidence * 0.15 +\n        completeness * 0.10\n    )\n\n    breakdown = {\n        \"reusability\": reusability,\n        \"novelty\": novelty,\n        \"clarity\": clarity,\n        \"evidence\": evidence,\n        \"completeness\": completeness,\n    }\n\n    return total_score, breakdown\n\n\ndef categorize_paper(paper: Paper, existing_patterns: List[Dict]) -> Optional[str]:\n    \"\"\"\n    Attempt to categorize a paper into one of the pattern categories.\n\n    Returns the category name or None if uncertain.\n    \"\"\"\n    abstract_lower = paper.abstract.lower()\n    title_lower = paper.title.lower()\n    combined = title_lower + \" \" + abstract_lower\n\n    # Category-specific keywords\n    category_keywords = {\n        \"Orchestration & Control\": [\n            \"orchestration\", \"coordination\", \"control\", \"hierarchy\", \"planner\",\n            \"workflow\", \"supervisor\", \"manager\", \"scheduler\", \"decomposition\",\n            \"sub-agent\", \"spawning\", \"multi-agent coordination\",\n        ],\n        \"Context & Memory\": [\n            \"memory\", \"context\", \"recall\", \"retrieval\", \"episodic\",\n            \"vector\", \"embedding\", \"rag\", \"knowledge base\", \"state\",\n            \"continuum\", \"temporal context\",\n        ],\n        \"Feedback Loops\": [\n            \"feedback\", \"iteration\", \"refinement\", \"self-improve\",\n            \"critique\", \"eval\", \"evaluation\", \"monitor\", \"adjust\",\n            \"adaptive\", \"learning from feedback\",\n        ],\n        \"Learning & Adaptation\": [\n            \"learning\", \"reinforcement\", \"rl\", \"fine-tuning\", \"adaptation\",\n            \"skill\", \"evolution\", \"training\", \"optimizer\",\n        ],\n        \"Reliability & Eval\": [\n            \"reliability\", \"safety\", \"guardrail\", \"error\", \"robust\",\n            \"testing\", \"validation\", \"verification\", \"deterministic\",\n        ],\n        \"Security & Safety\": [\n            \"security\", \"privacy\", \"attack\", \"malicious\", \"adversarial\",\n            \"sandbox\", \"isolation\", \"monitoring\", \"threat model\",\n            \"exfiltration\", \"laundering\",\n        ],\n        \"Tool Use & Environment\": [\n            \"tool\", \"api\", \"function call\", \"environment\", \"execution\",\n            \"browser\", \"shell\", \"filesystem\", \"external\", \"integration\",\n        ],\n        \"UX & Collaboration\": [\n            \"user experience\", \"ux\", \"collaboration\", \"human-in-loop\",\n            \"handoff\", \"notification\", \"interaction\", \"interface\",\n        ],\n    }\n\n    # Count keyword matches for each category\n    category_scores = {}\n    for category, keywords in category_keywords.items():\n        score = sum(1 for kw in keywords if kw in combined)\n        if score > 0:\n            category_scores[category] = score\n\n    # Return category with highest score (if any)\n    if category_scores:\n        return max(category_scores, key=category_scores.get)\n\n    return None\n\n\ndef extract_tags(paper: Paper) -> List[str]:\n    \"\"\"\n    Extract relevant tags from paper metadata.\n\n    Returns a list of lowercase tags suitable for pattern files.\n    \"\"\"\n    abstract_lower = paper.abstract.lower()\n    title_lower = paper.title.lower()\n    combined = title_lower + \" \" + abstract_lower\n\n    # Common agentic pattern keywords\n    tag_keywords = [\n        \"agent\", \"multi-agent\", \"orchestration\", \"coordination\",\n        \"memory\", \"context\", \"rag\", \"retrieval\",\n        \"feedback\", \"iteration\", \"self-improve\",\n        \"tool\", \"api\", \"function-call\",\n        \"planning\", \"planner\", \"decomposition\",\n        \"parallel\", \"concurrent\", \"async\",\n        \"hierarchy\", \"hierarchical\", \"layered\",\n        \"security\", \"privacy\", \"sandbox\",\n        \"evaluation\", \"benchmark\", \"testing\",\n        \"autonomous\", \"automation\",\n        \"workflow\", \"pipeline\",\n        \"communication\", \"protocol\",\n    ]\n\n    tags = []\n    for keyword in tag_keywords:\n        if keyword in combined:\n            tags.append(keyword)\n\n    return tags\n\n\ndef print_paper_summary(paper: Paper, score: float, breakdown: Dict[str, float], category: Optional[str]):\n    \"\"\"Print a formatted summary of a paper with its scores.\"\"\"\n    print(f\"\\n{'='*70}\")\n    print(f\"Title: {paper.title}\")\n    print(f\"arXiv: {paper.arxiv_id} | Score: {score:.2f}/10.0\")\n    print(f\"URL: {paper.url}\")\n    if category:\n        print(f\"Suggested Category: {category}\")\n    print(f\"\\nScore Breakdown:\")\n    print(f\"  Reusability (30%):    {breakdown['reusability']:.1f}/3.0\")\n    print(f\"  Novelty (25%):        {breakdown['novelty']:.1f}/3.0\")\n    print(f\"  Clarity (20%):        {breakdown['clarity']:.1f}/3.0\")\n    print(f\"  Evidence (15%):       {breakdown['evidence']:.1f}/3.0\")\n    print(f\"  Completeness (10%):   {breakdown['completeness']:.1f}/3.0\")\n    print(f\"\\nAbstract: {paper.abstract[:300]}...\")\n\n\ndef export_results(papers: List[Dict[str, Any]], output_file: str):\n    \"\"\"Export scan results to JSON file.\"\"\"\n    with open(output_file, \"w\") as f:\n        json.dump(papers, f, indent=2)\n    print(f\"\\nResults exported to: {output_file}\")\n\n\ndef export_markdown_report(papers: List[Dict[str, Any]], output_file: str):\n    \"\"\"Export scan results as a Markdown report.\"\"\"\n    lines = [\n        \"# arXiv Pattern Discovery Report\",\n        f\"Generated: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\",\n        \"\",\n        f\"**Total papers scanned: {len(papers)}**\",\n        \"\",\n        \"---\",\n        \"\",\n    ]\n\n    for i, paper in enumerate(papers, 1):\n        p = paper[\"paper\"]\n        lines.extend([\n            f\"## {i}. {p['title']}\",\n            \"\",\n            f\"**arXiv ID:** {p['arxiv_id']}  \",\n            f\"**Quality Score:** {paper['total_score']:.2f}/10.0  \",\n            f\"**Suggested Category:** {paper.get('category', 'Uncategorized')}  \",\n            f\"**URL:** {p['url']}  \",\n            \"\",\n            f\"**Score Breakdown:**\",\n            f\"- Reusability (30%): {paper['score_breakdown']['reusability']:.1f}/3.0\",\n            f\"- Novelty (25%): {paper['score_breakdown']['novelty']:.1f}/3.0\",\n            f\"- Clarity (20%): {paper['score_breakdown']['clarity']:.1f}/3.0\",\n            f\"- Evidence (15%): {paper['score_breakdown']['evidence']:.1f}/3.0\",\n            f\"- Completeness (10%): {paper['score_breakdown']['completeness']:.1f}/3.0\",\n            \"\",\n            f\"**Tags:** {', '.join(paper.get('tags', []))}\",\n            \"\",\n            \"**Abstract:**\",\n            p[\"abstract\"],\n            \"\",\n            \"---\",\n            \"\",\n        ])\n\n    with open(output_file, \"w\") as f:\n        f.write(\"\\n\".join(lines))\n    print(f\"Markdown report exported to: {output_file}\")\n\n\ndef load_existing_patterns(patterns_dir: Path) -> List[Dict]:\n    \"\"\"Load existing patterns to check for duplicates.\"\"\"\n    from build_readme import parse_front_matter\n\n    patterns = []\n    for file in patterns_dir.glob(\"*.md\"):\n        if file.name == \"TEMPLATE.md\":\n            continue\n        try:\n            metadata = parse_front_matter(str(file))\n            patterns.append({\n                \"file\": file.name,\n                \"title\": metadata.get(\"title\", \"\"),\n                \"tags\": metadata.get(\"tags\", []),\n                \"category\": metadata.get(\"category\", \"\"),\n            })\n        except Exception:\n            continue\n    return patterns\n\n\ndef check_for_duplicates(paper: Paper, existing_patterns: List[Dict]) -> List[str]:\n    \"\"\"Check if paper might duplicate existing patterns.\"\"\"\n    title_lower = paper.title.lower()\n    abstract_lower = paper.abstract.lower()\n\n    potential_dupes = []\n    for pattern in existing_patterns:\n        pattern_title = pattern[\"title\"].lower()\n        pattern_tags = [t.lower() for t in pattern.get(\"tags\", [])]\n\n        # Check title similarity\n        if any(word in title_lower for word in pattern_title.split() if len(word) > 4):\n            potential_dupes.append(pattern[\"file\"])\n\n        # Check tag overlap\n        paper_words = set(title_lower.split() + abstract_lower.split())\n        tag_overlap = len(paper_words.intersection(pattern_tags)) / max(len(pattern_tags), 1)\n        if tag_overlap > 0.3:\n            potential_dupes.append(pattern[\"file\"])\n\n    return list(set(potential_dupes))\n\n\ndef main():\n    parser = argparse.ArgumentParser(\n        description=\"Scan arXiv for papers describing agentic patterns\",\n        formatter_class=argparse.RawDescriptionHelpFormatter,\n        epilog=\"\"\"\nExamples:\n  %(prog)s --days=7 --min-citations=3\n  %(prog)s --query=\"multi-agent orchestration\" --max-results=50\n  %(prog)s --min-score=7.0 --export-json results.json\n        \"\"\",\n    )\n    parser.add_argument(\n        \"--query\",\n        \"-q\",\n        type=str,\n        default=DEFAULT_SEARCH_QUERY,\n        help=\"arXiv search query (default: agent/agentic/multi-agent papers)\",\n    )\n    parser.add_argument(\n        \"--max-results\",\n        \"-n\",\n        type=int,\n        default=100,\n        help=\"Maximum number of results to fetch (default: 100)\",\n    )\n    parser.add_argument(\n        \"--days\",\n        \"-d\",\n        type=int,\n        default=365,\n        help=\"Only include papers from last N days (default: 365)\",\n    )\n    parser.add_argument(\n        \"--min-score\",\n        \"-m\",\n        type=float,\n        default=5.0,\n        help=\"Minimum quality score to include (default: 5.0)\",\n    )\n    parser.add_argument(\n        \"--export-json\",\n        type=str,\n        help=\"Export results to JSON file\",\n    )\n    parser.add_argument(\n        \"--export-md\",\n        type=str,\n        help=\"Export results to Markdown file\",\n    )\n    parser.add_argument(\n        \"--patterns-dir\",\n        type=str,\n        default=\"patterns\",\n        help=\"Path to patterns directory (default: patterns)\",\n    )\n    parser.add_argument(\n        \"--verbose\",\n        \"-v\",\n        action=\"store_true\",\n        help=\"Print detailed output for each paper\",\n    )\n\n    args = parser.parse_args()\n\n    # Load existing patterns\n    patterns_dir = Path(args.patterns_dir)\n    if patterns_dir.exists():\n        existing_patterns = load_existing_patterns(patterns_dir)\n        print(f\"Loaded {len(existing_patterns)} existing patterns for duplicate detection\")\n    else:\n        existing_patterns = []\n        print(f\"Warning: Patterns directory not found at {patterns_dir}\")\n\n    print(f\"\\n🔍 Scanning arXiv with query: {args.query[:100]}...\")\n    print(f\"   Max results: {args.max_results}, Time window: {args.days} days\")\n\n    try:\n        papers = fetch_arxiv_papers(args.query, args.max_results)\n        print(f\"   Fetched {len(papers)} papers from arXiv\")\n\n        # Apply filters\n        if args.days < 365:\n            papers = filter_papers_by_date(papers, args.days)\n            print(f\"   Filtered to {len(papers)} papers within last {args.days} days\")\n\n        papers = filter_papers_by_keywords(papers)\n        print(f\"   Filtered to {len(papers)} papers with architectural keywords\")\n\n        if not papers:\n            print(\"\\n❌ No papers found matching criteria\")\n            return 0\n\n    except ArxivAPIError as e:\n        print(f\"\\n❌ Error fetching from arXiv: {e}\")\n        return 1\n\n    # Score papers\n    print(f\"\\n📊 Scoring {len(papers)} papers using Pattern Quality Rubric...\")\n\n    results = []\n    high_quality_count = 0\n\n    for paper in papers:\n        score, breakdown = calculate_quality_score(paper)\n        category = categorize_paper(paper, existing_patterns)\n        tags = extract_tags(paper)\n        duplicates = check_for_duplicates(paper, existing_patterns)\n\n        result = {\n            \"paper\": {\n                \"arxiv_id\": paper.arxiv_id,\n                \"title\": paper.title,\n                \"authors\": paper.authors,\n                \"abstract\": paper.abstract,\n                \"published\": paper.published,\n                \"categories\": paper.categories,\n                \"url\": paper.url,\n            },\n            \"pattern_name\": None,\n            \"category\": category,\n            \"tags\": tags,\n            \"score_breakdown\": breakdown,\n            \"total_score\": score,\n            \"potential_duplicates\": duplicates,\n            \"meets_threshold\": score >= args.min_score,\n        }\n        results.append(result)\n\n        if score >= args.min_score:\n            high_quality_count += 1\n            if args.verbose:\n                print_paper_summary(paper, score, breakdown, category)\n                if duplicates:\n                    print(f\"⚠️  Potential duplicates: {', '.join(duplicates)}\")\n\n    # Sort by score\n    results.sort(key=lambda x: x[\"total_score\"], reverse=True)\n\n    # Print summary\n    print(f\"\\n{'='*70}\")\n    print(f\"📈 SCAN SUMMARY\")\n    print(f\"{'='*70}\")\n    print(f\"Total papers analyzed: {len(papers)}\")\n    print(f\"Papers meeting threshold ({args.min_score}): {high_quality_count}\")\n    print(f\"\\n🏆 Top 10 papers by quality score:\")\n    print(f\"{'-'*70}\")\n\n    for i, r in enumerate(results[:10], 1):\n        p = r[\"paper\"]\n        dupes = f\" [⚠️ duplicates: {len(r['potential_duplicates'])}]\" if r[\"potential_duplicates\"] else \"\"\n        print(f\"{i:2}. {r['total_score']:.2f} | {p['title'][:60]}...{dupes}\")\n\n    # Export results if requested\n    if args.export_json:\n        export_results(results, args.export_json)\n\n    if args.export_md:\n        export_markdown_report(results, args.export_md)\n\n    return 0\n\n\nif __name__ == \"__main__\":\n    sys.exit(main())\n","isInternal":false,"tokens":6584,"sizeBytes":27333},{"name":"pattern_similarity_checker.py","path":".claude/skills/arxiv-pattern-discovery/scripts/pattern_similarity_checker.py","rawUrl":"https://raw.githubusercontent.com/nibzard/awesome-agentic-patterns/HEAD/.claude/skills/arxiv-pattern-discovery/scripts/pattern_similarity_checker.py","title":"Claude Directive: pattern_similarity_checker.py","category":"claude-rule","format":"markdown","content":"#!/usr/bin/env python3\n\"\"\"\npattern_similarity_checker.py\n\nDuplicate detection for pattern files using tag similarity and content analysis.\n\nDetects potentially duplicate or very similar patterns by comparing:\n- Tag overlap (Jaccard similarity)\n- Title similarity\n- Category overlap\n- Problem/Solution section content\n\nUsage:\n    python scripts/pattern_similarity_checker.py <new-pattern.md>\n    python scripts/pattern_similarity_checker.py --all\n    python scripts/pattern_similarity_checker.py --threshold=0.7 <pattern.md>\n\"\"\"\n\nimport argparse\nimport math\nimport os\nimport re\nimport sys\nfrom collections import Counter\nfrom pathlib import Path\nfrom typing import Dict, List, Optional, Set, Tuple\n\n\n# Add parent directory to path for imports\nsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))\n\nfrom build_readme import parse_front_matter\n\n\ndef slugify(value: str) -> str:\n    \"\"\"Normalize string for comparison.\"\"\"\n    value = re.sub(r'[^\\w\\s-]', '', value).strip().lower()\n    value = re.sub(r'[-\\s]+', ' ', value)\n    return value\n\n\ndef tokenize(text: str) -> Set[str]:\n    \"\"\"Tokenize text into words, removing common stop words.\"\"\"\n    if not text:\n        return set()\n\n    # Common stop words to ignore\n    stop_words = {\n        \"a\", \"an\", \"the\", \"and\", \"or\", \"but\", \"in\", \"on\", \"at\", \"to\", \"for\",\n        \"of\", \"with\", \"by\", \"from\", \"as\", \"is\", \"was\", \"are\", \"were\", \"be\",\n        \"been\", \"being\", \"have\", \"has\", \"had\", \"do\", \"does\", \"did\", \"will\",\n        \"would\", \"could\", \"should\", \"may\", \"might\", \"must\", \"can\", \"this\",\n        \"that\", \"these\", \"those\", \"it\", \"its\", \"they\", \"them\", \"their\",\n        \"what\", \"which\", \"who\", \"whom\", \"when\", \"where\", \"why\", \"how\",\n    }\n\n    # Tokenize and filter\n    words = re.findall(r'\\b\\w+\\b', text.lower())\n    return {w for w in words if len(w) > 3 and w not in stop_words}\n\n\ndef jaccard_similarity(set1: Set[str], set2: Set[str]) -> float:\n    \"\"\"\n    Calculate Jaccard similarity between two sets.\n\n    J(A, B) = |A ∩ B| / |A ∪ B|\n    \"\"\"\n    if not set1 or not set2:\n        return 0.0\n\n    intersection = len(set1.intersection(set2))\n    union = len(set1.union(set2))\n\n    return intersection / union if union > 0 else 0.0\n\n\ndef cosine_similarity(set1: Set[str], set2: Set[str]) -> float:\n    \"\"\"\n    Calculate cosine similarity between two sets (treating as binary vectors).\n    \"\"\"\n    if not set1 or not set2:\n        return 0.0\n\n    intersection = len(set1.intersection(set2))\n    magnitude = math.sqrt(len(set1)) * math.sqrt(len(set2))\n\n    return intersection / magnitude if magnitude > 0 else 0.0\n\n\ndef levenshtein_distance(s1: str, s2: str) -> int:\n    \"\"\"Calculate Levenshtein distance between two strings.\"\"\"\n    if len(s1) < len(s2):\n        return levenshtein_distance(s2, s1)\n\n    if len(s2) == 0:\n        return len(s1)\n\n    previous_row = range(len(s2) + 1)\n    for i, c1 in enumerate(s1):\n        current_row = [i + 1]\n        for j, c2 in enumerate(s2):\n            insertions = previous_row[j + 1] + 1\n            deletions = current_row[j] + 1\n            substitutions = previous_row[j] + (c1 != c2)\n            current_row.append(min(insertions, deletions, substitutions))\n        previous_row = current_row\n\n    return previous_row[-1]\n\n\ndef string_similarity(s1: str, s2: str) -> float:\n    \"\"\"\n    Calculate normalized string similarity based on Levenshtein distance.\n\n    Returns 1.0 for identical strings, 0.0 for completely different.\n    \"\"\"\n    if not s1 or not s2:\n        return 0.0\n\n    max_len = max(len(s1), len(s2))\n    if max_len == 0:\n        return 1.0\n\n    distance = levenshtein_distance(s1.lower(), s2.lower())\n    return 1.0 - (distance / max_len)\n\n\ndef extract_sections(filepath: str) -> Dict[str, str]:\n    \"\"\"\n    Extract main sections from a pattern file.\n\n    Returns dict with keys: problem, solution, how_to_use, trade_offs\n    \"\"\"\n    with open(filepath, 'r', encoding='utf-8') as f:\n        content = f.read()\n\n    # Remove front matter\n    if content.startswith('---'):\n        end_idx = content.find('\\n---', 4)\n        if end_idx > 0:\n            content = content[end_idx + 4:]\n\n    sections = {}\n    current_section = None\n    current_content = []\n\n    # Section markers we care about\n    section_markers = ['## Problem', '## Solution', '## How to use it', '## Trade-offs']\n\n    for line in content.split('\\n'):\n        if line.startswith('## '):\n            # Save previous section\n            if current_section:\n                sections[current_section] = ' '.join(current_content)\n\n            # Start new section\n            current_section = line[3:].strip().lower()\n            if 'problem' in current_section:\n                current_section = 'problem'\n            elif 'solution' in current_section:\n                current_section = 'solution'\n            elif 'how to use' in current_section:\n                current_section = 'how_to_use'\n            elif 'trade-off' in current_section:\n                current_section = 'trade_offs'\n            else:\n                current_section = None\n            current_content = []\n        elif current_section:\n            # Skip code blocks and mermaid diagrams\n            if line.strip().startswith('```') or line.strip().startswith('~~~'):\n                continue\n            current_content.append(line.strip())\n\n    # Save last section\n    if current_section:\n        sections[current_section] = ' '.join(current_content)\n\n    return sections\n\n\nclass PatternSimilarityChecker:\n    \"\"\"Checker for finding similar/duplicate patterns.\"\"\"\n\n    def __init__(self, patterns_dir: str, threshold: float = 0.5):\n        \"\"\"\n        Initialize the checker.\n\n        Args:\n            patterns_dir: Path to patterns directory\n            threshold: Minimum similarity score to report (0-1)\n        \"\"\"\n        self.patterns_dir = Path(patterns_dir)\n        self.threshold = threshold\n        self.patterns = self._load_patterns()\n\n    def _load_patterns(self) -> List[Dict]:\n        \"\"\"Load all pattern metadata and content.\"\"\"\n        patterns = []\n\n        for filepath in self.patterns_dir.glob(\"*.md\"):\n            if filepath.name == \"TEMPLATE.md\":\n                continue\n\n            try:\n                metadata = parse_front_matter(str(filepath))\n                sections = extract_sections(filepath)\n\n                patterns.append({\n                    \"file\": filepath.name,\n                    \"path\": str(filepath),\n                    \"title\": metadata.get(\"title\", \"\"),\n                    \"tags\": [t.lower() for t in metadata.get(\"tags\", [])],\n                    \"category\": metadata.get(\"category\", \"\"),\n                    \"sections\": sections,\n                    \"metadata\": metadata,\n                })\n            except Exception as e:\n                print(f\"Warning: Could not load {filepath.name}: {e}\")\n\n        return patterns\n\n    def compare_to_pattern(self, filepath: str) -> List[Dict]:\n        \"\"\"\n        Compare a single pattern file against all existing patterns.\n\n        Returns list of similarity results, sorted by total similarity.\n        \"\"\"\n        try:\n            metadata = parse_front_matter(filepath)\n            sections = extract_sections(filepath)\n        except Exception as e:\n            print(f\"Error: Could not parse pattern file: {e}\")\n            return []\n\n        new_pattern = {\n            \"file\": Path(filepath).name,\n            \"title\": metadata.get(\"title\", \"\"),\n            \"tags\": [t.lower() for t in metadata.get(\"tags\", [])],\n            \"category\": metadata.get(\"category\", \"\"),\n            \"sections\": sections,\n        }\n\n        results = []\n\n        for existing in self.patterns:\n            if existing[\"file\"] == new_pattern[\"file\"]:\n                continue  # Skip self\n\n            similarity = self._calculate_similarity(new_pattern, existing)\n            if similarity[\"total\"] >= self.threshold:\n                results.append({\n                    \"existing_file\": existing[\"file\"],\n                    \"existing_title\": existing[\"title\"],\n                    \"similarity\": similarity,\n                })\n\n        # Sort by total similarity\n        results.sort(key=lambda x: x[\"similarity\"][\"total\"], reverse=True)\n        return results\n\n    def check_all_similarities(self) -> List[Dict]:\n        \"\"\"\n        Check all patterns against each other for similarities.\n\n        Returns list of potential duplicates (each pair once).\n        \"\"\"\n        results = []\n\n        for i, pattern1 in enumerate(self.patterns):\n            for pattern2 in self.patterns[i + 1:]:\n                similarity = self._calculate_similarity(pattern1, pattern2)\n                if similarity[\"total\"] >= self.threshold:\n                    results.append({\n                        \"pattern1\": pattern1[\"file\"],\n                        \"pattern2\": pattern2[\"file\"],\n                        \"title1\": pattern1[\"title\"],\n                        \"title2\": pattern2[\"title\"],\n                        \"similarity\": similarity,\n                    })\n\n        # Sort by total similarity\n        results.sort(key=lambda x: x[\"similarity\"][\"total\"], reverse=True)\n        return results\n\n    def _calculate_similarity(self, pattern1: Dict, pattern2: Dict) -> Dict[str, float]:\n        \"\"\"Calculate detailed similarity metrics between two patterns.\"\"\"\n\n        # 1. Tag similarity (Jaccard)\n        tags1 = set(pattern1[\"tags\"])\n        tags2 = set(pattern2[\"tags\"])\n        tag_sim = jaccard_similarity(tags1, tags2)\n\n        # 2. Title similarity\n        title_sim = string_similarity(pattern1[\"title\"], pattern2[\"title\"])\n\n        # 3. Category match\n        category_match = 1.0 if pattern1[\"category\"] == pattern2[\"category\"] else 0.0\n\n        # 4. Content similarity (problem + solution)\n        content1_tokens = set()\n        content2_tokens = set()\n\n        for section in [\"problem\", \"solution\"]:\n            if section in pattern1[\"sections\"]:\n                content1_tokens.update(tokenize(pattern1[\"sections\"][section]))\n            if section in pattern2[\"sections\"]:\n                content2_tokens.update(tokenize(pattern2[\"sections\"][section]))\n\n        content_sim = jaccard_similarity(content1_tokens, content2_tokens)\n\n        # Weighted total (adjust weights as needed)\n        total = (\n            tag_sim * 0.30 +\n            title_sim * 0.20 +\n            category_match * 0.15 +\n            content_sim * 0.35\n        )\n\n        return {\n            \"tag\": tag_sim,\n            \"title\": title_sim,\n            \"category\": category_match,\n            \"content\": content_sim,\n            \"total\": total,\n        }\n\n    def suggest_action(self, similarity: Dict[str, float]) -> str:\n        \"\"\"Suggest action based on similarity score.\"\"\"\n        total = similarity[\"total\"]\n\n        if total >= 0.8:\n            return \"MERGE - Patterns are very similar, consider merging\"\n        elif total >= 0.7:\n            return \"REVIEW - High similarity, manual review needed\"\n        elif total >= 0.6:\n            return \"CHECK - Moderate similarity, check if related\"\n        elif total >= 0.5:\n            return \"RELATED - May be related patterns\"\n        else:\n            return \"OK - Below similarity threshold\"\n\n\ndef print_similarity_report(results: List[Dict], threshold: float, checker):\n    \"\"\"Print a formatted similarity report.\"\"\"\n\n    if not results:\n        print(f\"\\n✅ No patterns found with similarity >= {threshold}\")\n        return\n\n    print(f\"\\n{'='*80}\")\n    print(f\"⚠️  FOUND {len(results)} POTENTIAL DUPLICATE/RELATED PATTERN PAIRS\")\n    print(f\"{'='*80}\")\n\n    for i, result in enumerate(results, 1):\n        if \"existing_file\" in result:\n            # Single pattern comparison\n            print(f\"\\n{i}. {result['existing_title']}\")\n            print(f\"   File: {result['existing_file']}\")\n        else:\n            # All-pairs comparison\n            print(f\"\\n{i}. {result['title1']} <-> {result['title2']}\")\n            print(f\"   Files: {result['pattern1']} <-> {result['pattern2']}\")\n\n        sim = result[\"similarity\"]\n        action = checker.suggest_action(sim)\n\n        print(f\"   Total Similarity: {sim['total']:.2f}\")\n        print(f\"   Tag Similarity:    {sim['tag']:.2f} (Jaccard)\")\n        print(f\"   Title Similarity:  {sim['title']:.2f}\")\n        print(f\"   Category Match:    {sim['category']:.2f}\")\n        print(f\"   Content Similarity:{sim['content']:.2f}\")\n        print(f\"   Suggested Action:  {action}\")\n\n    # Print warning for high similarities\n    high_sim = [r for r in results if r[\"similarity\"][\"total\"] >= 0.7]\n    if high_sim:\n        print(f\"\\n{'='*80}\")\n        print(f\"⚠️  WARNING: {len(high_sim)} patterns with similarity >= 0.7\")\n        print(f\"   These may be duplicates or variants that need merging.\")\n        print(f\"{'='*80}\")\n\n\ndef export_similarity_report(results: List[Dict], output_file: str, checker):\n    \"\"\"Export similarity report to Markdown file.\"\"\"\n\n    lines = [\n        \"# Pattern Similarity Report\",\n        \"\",\n        f\"Generated: {__import__('datetime').datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\",\n        f\"Total pairs found: {len(results)}\",\n        \"\",\n        \"---\",\n        \"\",\n    ]\n\n    for i, result in enumerate(results, 1):\n        if \"existing_file\" in result:\n            lines.extend([\n                f\"## {i}. {result['existing_title']}\",\n                \"\",\n                f\"**File:** `{result['existing_file']}`  \",\n                f\"**Similarity:** {result['similarity']['total']:.2f}  \",\n            ])\n        else:\n            lines.extend([\n                f\"## {i}. {result['title1']} ↔ {result['title2']}\",\n                \"\",\n                f\"**Files:** `{result['pattern1']}` ↔ `{result['pattern2']}`  \",\n                f\"**Similarity:** {result['similarity']['total']:.2f}  \",\n            ])\n\n        sim = result[\"similarity\"]\n        action = checker.suggest_action(sim)\n\n        lines.extend([\n            \"\",\n            f\"**Breakdown:**\",\n            f\"- Tag Similarity: {sim['tag']:.2f}\",\n            f\"- Title Similarity: {sim['title']:.2f}\",\n            f\"- Category Match: {sim['category']:.2f}\",\n            f\"- Content Similarity: {sim['content']:.2f}\",\n            \"\",\n            f\"**Suggested Action:** {action}\",\n            \"\",\n            \"---\",\n            \"\",\n        ])\n\n    with open(output_file, \"w\") as f:\n        f.write(\"\\n\".join(lines))\n\n    print(f\"Report exported to: {output_file}\")\n\n\ndef main():\n    parser = argparse.ArgumentParser(\n        description=\"Check patterns for duplicates or high similarity\",\n        formatter_class=argparse.RawDescriptionHelpFormatter,\n        epilog=\"\"\"\nExamples:\n  %(prog)s patterns/new-pattern.md\n  %(prog)s --all\n  %(prog)s --all --threshold=0.7 --export report.md\n        \"\"\",\n    )\n    parser.add_argument(\n        \"pattern_file\",\n        nargs=\"?\",\n        help=\"Path to pattern file to check against existing patterns\",\n    )\n    parser.add_argument(\n        \"--all\",\n        \"-a\",\n        action=\"store_true\",\n        help=\"Check all patterns against each other\",\n    )\n    parser.add_argument(\n        \"--patterns-dir\",\n        \"-d\",\n        type=str,\n        default=\"patterns\",\n        help=\"Path to patterns directory (default: patterns)\",\n    )\n    parser.add_argument(\n        \"--threshold\",\n        \"-t\",\n        type=float,\n        default=0.5,\n        help=\"Similarity threshold for reporting (default: 0.5)\",\n    )\n    parser.add_argument(\n        \"--export\",\n        \"-e\",\n        type=str,\n        help=\"Export report to Markdown file\",\n    )\n\n    args = parser.parse_args()\n\n    # Validate arguments\n    if not args.all and not args.pattern_file:\n        parser.error(\"Either specify a pattern file or use --all\")\n\n    if args.all and args.pattern_file:\n        parser.error(\"Cannot use --all with a specific pattern file\")\n\n    # Check patterns directory\n    patterns_dir = Path(args.patterns_dir)\n    if not patterns_dir.exists():\n        print(f\"Error: Patterns directory not found: {patterns_dir}\")\n        return 1\n\n    # Initialize checker\n    checker = PatternSimilarityChecker(str(patterns_dir), args.threshold)\n    print(f\"Loaded {len(checker.patterns)} patterns for comparison\")\n\n    # Run comparison\n    if args.all:\n        print(f\"\\n🔍 Checking all patterns for similarities (threshold: {args.threshold})...\")\n        results = checker.check_all_similarities()\n    else:\n        pattern_path = Path(args.pattern_file)\n        if not pattern_path.exists():\n            print(f\"Error: Pattern file not found: {pattern_path}\")\n            return 1\n\n        print(f\"\\n🔍 Comparing '{pattern_path.name}' against existing patterns...\")\n        results = checker.compare_to_pattern(str(pattern_path))\n\n    # Print report\n    print_similarity_report(results, args.threshold, checker)\n\n    # Export if requested\n    if args.export:\n        export_similarity_report(results, args.export, checker)\n\n    # Return exit code based on findings\n    if results:\n        return 1  # Found potential duplicates\n    return 0\n\n\nif __name__ == \"__main__\":\n    sys.exit(main())\n","isInternal":false,"tokens":3916,"sizeBytes":17052},{"name":"pattern_validator.py","path":".claude/skills/arxiv-pattern-discovery/scripts/pattern_validator.py","rawUrl":"https://raw.githubusercontent.com/nibzard/awesome-agentic-patterns/HEAD/.claude/skills/arxiv-pattern-discovery/scripts/pattern_validator.py","title":"Claude Directive: pattern_validator.py","category":"claude-rule","format":"markdown","content":"#!/usr/bin/env python3\n\"\"\"\npattern_validator.py\n\nPre-commit validation for pattern files.\n\nValidates:\n- YAML front-matter completeness\n- Required sections presence\n- Mermaid diagram syntax\n- URL validity\n- Content quality checks\n\nUsage:\n    python scripts/pattern_validator.py <pattern-file.md>\n    python scripts/pattern_validator.py --all\n    python scripts/pattern_validator.py --fix <pattern-file.md>\n\"\"\"\n\nimport argparse\nimport os\nimport re\nimport sys\nimport urllib.request\nimport urllib.error\nfrom dataclasses import dataclass, field\nfrom enum import Enum\nfrom pathlib import Path\nfrom typing import List, Optional, Set, Tuple\n\n\n# Add parent directory to path for imports\nsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))\n\nfrom build_readme import parse_front_matter\n\n\nclass Severity(Enum):\n    \"\"\"Severity levels for validation issues.\"\"\"\n    ERROR = \"ERROR\"\n    WARNING = \"WARNING\"\n    INFO = \"INFO\"\n\n\n@dataclass\nclass ValidationIssue:\n    \"\"\"Represents a validation issue found in a pattern file.\"\"\"\n    severity: Severity\n    category: str\n    message: str\n    line: Optional[int] = None\n    column: Optional[int] = None\n    fix_suggestion: Optional[str] = None\n\n\n@dataclass\nclass ValidationResult:\n    \"\"\"Result of validating a pattern file.\"\"\"\n    file_path: str\n    is_valid: bool\n    issues: List[ValidationIssue] = field(default_factory=list)\n\n    def add_issue(self, severity: Severity, category: str, message: str,\n                  line: Optional[int] = None, fix_suggestion: Optional[str] = None):\n        self.issues.append(ValidationIssue(\n            severity=severity, category=category, message=message,\n            line=line, fix_suggestion=fix_suggestion\n        ))\n        if severity == Severity.ERROR:\n            self.is_valid = False\n\n\n# Valid values for pattern metadata\nVALID_STATUSES = {\n    \"proposed\",\n    \"emerging\",\n    \"established\",\n    \"validated-in-production\",\n    \"best-practice\",\n    \"experimental-but-awesome\",\n    \"rapidly-improving\",\n}\n\nVALID_CATEGORIES = {\n    \"Orchestration & Control\",\n    \"Context & Memory\",\n    \"Feedback Loops\",\n    \"Learning & Adaptation\",\n    \"Reliability & Eval\",\n    \"Security & Safety\",\n    \"Tool Use & Environment\",\n    \"UX & Collaboration\",\n    \"Uncategorized\",\n}\n\n# Required YAML fields\nREQUIRED_YAML_FIELDS = {\"title\", \"status\", \"authors\", \"based_on\", \"category\", \"source\", \"tags\"}\n\n# Required markdown sections\nREQUIRED_SECTIONS = {\"## Problem\", \"## Solution\", \"## References\"}\n\n\nclass PatternValidator:\n    \"\"\"Validator for pattern files.\"\"\"\n\n    def __init__(self, strict: bool = False):\n        \"\"\"\n        Initialize the validator.\n\n        Args:\n            strict: If True, treat warnings as errors\n        \"\"\"\n        self.strict = strict\n\n    def validate_file(self, filepath: str) -> ValidationResult:\n        \"\"\"\n        Validate a single pattern file.\n\n        Returns ValidationResult with all issues found.\n        \"\"\"\n        result = ValidationResult(file_path=filepath, is_valid=True)\n\n        try:\n            with open(filepath, 'r', encoding='utf-8') as f:\n                content = f.read()\n                lines = content.split('\\n')\n        except FileNotFoundError:\n            result.add_issue(Severity.ERROR, \"File\", f\"File not found: {filepath}\")\n            return result\n        except Exception as e:\n            result.add_issue(Severity.ERROR, \"File\", f\"Could not read file: {e}\")\n            return result\n\n        # Validate YAML front-matter\n        self._validate_yaml_front_matter(content, lines, result)\n\n        # Parse metadata for further validation\n        metadata = parse_front_matter(filepath)\n\n        # Validate metadata values\n        self._validate_metadata(metadata, result)\n\n        # Validate required sections\n        self._validate_sections(content, lines, result)\n\n        # Validate Mermaid diagrams\n        self._validate_mermaid_diagrams(content, lines, result)\n\n        # Validate URLs\n        self._validate_urls(content, lines, result)\n\n        # Content quality checks\n        self._validate_content_quality(content, metadata, result)\n\n        return result\n\n    def _validate_yaml_front_matter(self, content: str, lines: List[str], result: ValidationResult):\n        \"\"\"Validate YAML front-matter structure.\"\"\"\n        if not content.startswith('---'):\n            result.add_issue(\n                Severity.ERROR,\n                \"YAML\",\n                \"Pattern must start with YAML front-matter delimited by '---'\",\n                line=1,\n                fix_suggestion=\"Add YAML front-matter at the top of the file\"\n            )\n            return\n\n        # Find end of front-matter (second occurrence of ---)\n        end_marker_pos = content.find('\\n---', 4)\n        if end_marker_pos == -1:\n            result.add_issue(\n                Severity.ERROR,\n                \"YAML\",\n                \"YAML front-matter must be closed with '---'\",\n                fix_suggestion=\"Close front-matter with '---' on its own line\"\n            )\n            return\n\n        # Convert character position to line number (approximate)\n        end_line_num = content[:end_marker_pos].count('\\n') + 1\n\n        # Extract only the YAML section (lines 1 to end_line_num)\n        yaml_section = lines[1:end_line_num] if end_line_num > 1 else []\n        yaml_content = '\\n'.join(yaml_section)\n\n        # Check for empty front-matter\n        if not yaml_content.strip():\n            result.add_issue(\n                Severity.ERROR,\n                \"YAML\",\n                \"YAML front-matter is empty\",\n                line=2,\n                fix_suggestion=\"Add required YAML fields: title, status, authors, based_on, category, source, tags\"\n            )\n\n        # Check for proper YAML syntax (key: value pairs)\n        for i, yaml_line in enumerate(yaml_section, start=2):\n            if yaml_line.strip() and not yaml_line.strip().startswith('#'):\n                # Skip empty lines and comments\n                if ':' not in yaml_line and not yaml_line.strip().startswith('-'):\n                    result.add_issue(\n                        Severity.WARNING,\n                        \"YAML\",\n                        f\"Line may not be valid YAML: {yaml_line[:50]}\",\n                        line=i\n                    )\n\n    def _validate_metadata(self, metadata: dict, result: ValidationResult):\n        \"\"\"Validate metadata field values.\"\"\"\n\n        # Check required fields\n        for field in REQUIRED_YAML_FIELDS:\n            if field not in metadata:\n                result.add_issue(\n                    Severity.ERROR,\n                    \"Metadata\",\n                    f\"Missing required field: '{field}'\",\n                    fix_suggestion=f'Add \"{field}: <value>\" to YAML front-matter'\n                )\n\n        # Validate status\n        if \"status\" in metadata:\n            status = metadata[\"status\"]\n            if status not in VALID_STATUSES:\n                result.add_issue(\n                    Severity.ERROR,\n                    \"Metadata\",\n                    f\"Invalid status: '{status}'. Must be one of: {', '.join(sorted(VALID_STATUSES))}\",\n                    fix_suggestion=f\"Use one of: {', '.join(sorted(VALID_STATUSES))}\"\n                )\n\n        # Validate category\n        if \"category\" in metadata:\n            category = metadata[\"category\"]\n            if category not in VALID_CATEGORIES:\n                result.add_issue(\n                    Severity.WARNING,\n                    \"Metadata\",\n                    f\"Unknown category: '{category}'. Known categories: {', '.join(sorted(VALID_CATEGORIES))}\",\n                    fix_suggestion=f\"Use one of: {', '.join(sorted(VALID_CATEGORIES))}\"\n                )\n\n        # Validate authors is a list\n        if \"authors\" in metadata:\n            authors = metadata[\"authors\"]\n            if not isinstance(authors, list):\n                result.add_issue(\n                    Severity.ERROR,\n                    \"Metadata\",\n                    f\"'authors' must be a list: ['Name (@username)']\",\n                    fix_suggestion=\"Format as: authors: [\\\"Name (@username)\\\"]\"\n                )\n\n        # Validate tags is a list\n        if \"tags\" in metadata:\n            tags = metadata[\"tags\"]\n            if not isinstance(tags, list):\n                result.add_issue(\n                    Severity.ERROR,\n                    \"Metadata\",\n                    f\"'tags' must be a list: [tag1, tag2, tag3]\",\n                    fix_suggestion=\"Format as: tags: [tag1, tag2, tag3]\"\n                )\n            # Check for empty tags\n            elif any(not tag.strip() for tag in tags):\n                result.add_issue(\n                    Severity.WARNING,\n                    \"Metadata\",\n                    \"Tags list contains empty strings\",\n                    fix_suggestion=\"Remove empty tags\"\n                )\n\n        # Validate source is a URL\n        if \"source\" in metadata:\n            source = metadata[\"source\"]\n            if not source.startswith((\"http://\", \"https://\", \"arxiv://\")):\n                result.add_issue(\n                    Severity.WARNING,\n                    \"Metadata\",\n                    f\"'source' should be a URL: {source}\",\n                    fix_suggestion=\"Use a valid URL starting with http:// or https://\"\n                )\n\n        # Title quality checks\n        if \"title\" in metadata:\n            title = metadata[\"title\"]\n            if len(title) < 10:\n                result.add_issue(\n                    Severity.WARNING,\n                    \"Metadata\",\n                    f\"Title seems too short: '{title}'\",\n                    fix_suggestion=\"Use a more descriptive title\"\n                )\n            if title.islower():\n                result.add_issue(\n                    Severity.INFO,\n                    \"Metadata\",\n                    \"Title should use Title Case\",\n                    fix_suggestion=\"Capitalize the first letter of each word\"\n                )\n\n    def _validate_sections(self, content: str, lines: List[str], result: ValidationResult):\n        \"\"\"Validate required markdown sections.\"\"\"\n        # Skip YAML front-matter\n        start_idx = content.find('\\n---', 4)\n        if start_idx == -1:\n            start_idx = 0\n        else:\n            start_idx += 5\n\n        main_content = content[start_idx:]\n\n        for section in REQUIRED_SECTIONS:\n            if section not in main_content:\n                result.add_issue(\n                    Severity.ERROR,\n                    \"Structure\",\n                    f\"Missing required section: '{section}'\",\n                    fix_suggestion=f\"Add '## {section}' section\"\n                )\n\n        # Check for recommended sections (without ## prefix for matching)\n        recommended = {\"How to use it\", \"Trade-offs\"}\n        found_sections = set(re.findall(r'^## (.+)$', main_content, re.MULTILINE))\n        missing_recommended = recommended - found_sections\n\n        if missing_recommended:\n            for section in missing_recommended:\n                result.add_issue(\n                    Severity.INFO,\n                    \"Structure\",\n                    f\"Missing recommended section: '## {section}'\",\n                    fix_suggestion=f\"Consider adding '## {section}' section\"\n                )\n\n    def _validate_mermaid_diagrams(self, content: str, lines: List[str], result: ValidationResult):\n        \"\"\"Validate Mermaid diagram syntax.\"\"\"\n\n        # Find all Mermaid code blocks\n        mermaid_blocks = re.finditer(r'```mermaid\\n(.*?)```', content, re.DOTALL)\n\n        if not mermaid_blocks:\n            # Check if pattern might benefit from a diagram\n            if \"## Solution\" in content and len(content) > 2000:\n                result.add_issue(\n                    Severity.INFO,\n                    \"Content\",\n                    \"Consider adding a Mermaid diagram to illustrate the pattern\",\n                    fix_suggestion=\"Add a Mermaid diagram in the Solution section\"\n                )\n            return\n\n        for match in mermaid_blocks:\n            diagram = match.group(1)\n            block_start = content[:match.start()].count('\\n') + 1\n\n            # Basic Mermaid syntax checks\n            valid_diagram_types = {\n                \"graph\", \"flowchart\", \"sequenceDiagram\", \"classDiagram\",\n                \"stateDiagram\", \"erDiagram\", \"gantt\", \"pie\", \"gitGraph\"\n            }\n\n            first_line = diagram.strip().split('\\n')[0].strip()\n            diagram_type = first_line.split()[0] if first_line else \"\"\n\n            if diagram_type and diagram_type not in valid_diagram_types:\n                result.add_issue(\n                    Severity.WARNING,\n                    \"Mermaid\",\n                    f\"Unrecognized diagram type: '{diagram_type}'\",\n                    line=block_start + 1,\n                    fix_suggestion=f\"Use one of: {', '.join(valid_diagram_types)}\"\n                )\n\n            # Check for common syntax errors\n            if ' --' in diagram and '-->' not in diagram:\n                result.add_issue(\n                    Severity.WARNING,\n                    \"Mermaid\",\n                    \"Found ' --' which might be a typo for ' -->' (arrow)\",\n                    line=block_start\n                )\n\n            # Check for unclosed brackets/parentheses (basic check)\n            open_brackets = diagram.count('[') + diagram.count('(') + diagram.count('{')\n            close_brackets = diagram.count(']') + diagram.count(')') + diagram.count('}')\n            if open_brackets != close_brackets:\n                result.add_issue(\n                    Severity.WARNING,\n                    \"Mermaid\",\n                    \"Unclosed brackets or parentheses detected\",\n                    line=block_start\n                )\n\n    def _validate_urls(self, content: str, lines: List[str], result: ValidationResult):\n        \"\"\"Validate URLs in the document.\"\"\"\n        # Find all URLs\n        url_pattern = re.compile(r'https?://[^\\s\\)]+')\n\n        for i, line in enumerate(lines, start=1):\n            urls = url_pattern.findall(line)\n            for url in urls:\n                # Clean URL (remove trailing punctuation)\n                clean_url = re.sub(r'[.,;:]$', '', url)\n\n                # Basic URL format check\n                if not re.match(r'^https?://[a-zA-Z0-9\\-._~:/?#\\[\\]@!$&\\'()*+,;=%]+$', clean_url):\n                    result.add_issue(\n                        Severity.WARNING,\n                        \"URL\",\n                        f\"Potentially malformed URL: {clean_url[:60]}...\",\n                        line=i\n                    )\n\n                # Check for common issues\n                if 'arxiv.org' in clean_url.lower():\n                    if 'abs/' in clean_url and not clean_url.startswith('https://arxiv.org/abs/'):\n                        result.add_issue(\n                            Severity.INFO,\n                            \"URL\",\n                            f\"arXiv URL format may need standardization\",\n                            line=i\n                        )\n\n    def _validate_content_quality(self, content: str, metadata: dict, result: ValidationResult):\n        \"\"\"Perform content quality checks.\"\"\"\n\n        # Get word counts for sections\n        def count_section_text(section_name):\n            pattern = rf'## {section_name}\\s*\\n(.*?)(?=\\n## |\\Z)'\n            match = re.search(pattern, content, re.DOTALL)\n            if match:\n                text = match.group(1)\n                # Remove code blocks\n                text = re.sub(r'```.*?```', '', text, flags=re.DOTALL)\n                return len(text.split())\n            return 0\n\n        # Check Problem section length\n        problem_words = count_section_text(\"Problem\")\n        if problem_words > 0 and problem_words < 20:\n            result.add_issue(\n                Severity.WARNING,\n                \"Content\",\n                f\"Problem section seems too short ({problem_words} words)\",\n                fix_suggestion=\"Expand the problem description to at least 2-3 sentences\"\n            )\n\n        # Check Solution section length\n        solution_words = count_section_text(\"Solution\")\n        if solution_words > 0 and solution_words < 50:\n            result.add_issue(\n                Severity.WARNING,\n                \"Content\",\n                f\"Solution section seems too short ({solution_words} words)\",\n                fix_suggestion=\"Expand the solution description with more implementation details\"\n            )\n\n        # Check for empty sections\n        section_pattern = re.compile(r'## ([^\\n]+)\\s*\\n(.*?)(?=\\n## |\\Z)', re.DOTALL)\n        for match in section_pattern.finditer(content):\n            section_name = match.group(1)\n            section_content = match.group(2).strip()\n            if not section_content or section_content == \"```\":\n                result.add_issue(\n                    Severity.ERROR,\n                    \"Content\",\n                    f\"Section '{section_name}' is empty\",\n                    fix_suggestion=f\"Add content to the '{section_name}' section\"\n                )\n\n        # Check for required blank lines after headers\n        header_pattern = re.compile(r'##[^\\n]+\\n([^\\s#])')\n        for match in header_pattern.finditer(content):\n            line_num = content[:match.start()].count('\\n') + 2\n            char_after = match.group(1)\n            if char_after and char_after != '\\n':\n                result.add_issue(\n                    Severity.WARNING,\n                    \"Formatting\",\n                    \"Headers should be followed by a blank line for proper list rendering\",\n                    line=line_num,\n                    fix_suggestion=\"Add a blank line after the header\"\n                )\n\n\ndef print_validation_result(result: ValidationResult, verbose: bool = False):\n    \"\"\"Print validation results to stdout.\"\"\"\n\n    # Group issues by severity\n    errors = [i for i in result.issues if i.severity == Severity.ERROR]\n    warnings = [i for i in result.issues if i.severity == Severity.WARNING]\n    infos = [i for i in result.issues if i.severity == Severity.INFO]\n\n    # Print status\n    status_icon = \"✅\" if result.is_valid else \"❌\"\n    filename = Path(result.file_path).name\n    print(f\"{status_icon} {filename}: {len(result.issues)} issue(s)\")\n\n    if not verbose and result.is_valid and not warnings:\n        return\n\n    # Print issues\n    for issue in result.issues:\n        severity_icon = {\n            Severity.ERROR: \"❌\",\n            Severity.WARNING: \"⚠️ \",\n            Severity.INFO: \"ℹ️ \",\n        }[issue.severity]\n\n        line_info = f\":{issue.line}\" if issue.line else \"\"\n        print(f\"  {severity_icon} [{issue.category}]{line_info} {issue.message}\")\n\n        if issue.fix_suggestion:\n            print(f\"     💡 {issue.fix_suggestion}\")\n\n    # Print summary\n    if errors:\n        print(f\"  Summary: {len(errors)} error(s), {len(warnings)} warning(s), {len(infos)} info\")\n\n\ndef print_validation_summary(results: List[ValidationResult]):\n    \"\"\"Print overall validation summary.\"\"\"\n\n    total = len(results)\n    valid = sum(1 for r in results if r.is_valid)\n    total_issues = sum(len(r.issues) for r in results)\n\n    print(f\"\\n{'='*60}\")\n    print(f\"SUMMARY: {valid}/{total} files valid, {total_issues} total issue(s)\")\n    print(f\"{'='*60}\")\n\n    # Aggregate counts\n    all_errors = []\n    all_warnings = []\n\n    for result in results:\n        all_errors.extend([i for i in result.issues if i.severity == Severity.ERROR])\n        all_warnings.extend([i for i in result.issues if i.severity == Severity.WARNING])\n\n    # Common issues\n    if all_errors:\n        error_cats = {}\n        for e in all_errors:\n            error_cats[e.category] = error_cats.get(e.category, 0) + 1\n        print(f\"\\nTop error categories:\")\n        for cat, count in sorted(error_cats.items(), key=lambda x: -x[1])[:5]:\n            print(f\"  - {cat}: {count}\")\n\n\ndef export_validation_report(results: List[ValidationResult], output_file: str):\n    \"\"\"Export validation report to Markdown.\"\"\"\n\n    lines = [\n        \"# Pattern Validation Report\",\n        \"\",\n        f\"Generated: {__import__('datetime').datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\",\n        \"\",\n        \"---\",\n        \"\",\n    ]\n\n    for result in results:\n        filename = Path(result.file_path).name\n        status = \"✅ PASS\" if result.is_valid else \"❌ FAIL\"\n\n        lines.extend([\n            f\"## {status}: {filename}\",\n            \"\",\n            f\"Issues found: {len(result.issues)}\",\n            \"\",\n        ])\n\n        if result.issues:\n            for issue in result.issues:\n                severity = issue.severity.value\n                line_info = f\":{issue.line}\" if issue.line else \"\"\n                lines.extend([\n                    f\"**{severity}** [{issue.category}]{line_info}\",\n                    f\"{issue.message}\",\n                ])\n                if issue.fix_suggestion:\n                    lines.append(f\"_Fix: {issue.fix_suggestion}_\")\n                lines.append(\"\")\n\n        lines.extend([\"---\", \"\"])\n\n    with open(output_file, \"w\") as f:\n        f.write(\"\\n\".join(lines))\n\n    print(f\"\\nReport exported to: {output_file}\")\n\n\ndef main():\n    parser = argparse.ArgumentParser(\n        description=\"Validate pattern files for completeness and quality\",\n        formatter_class=argparse.RawDescriptionHelpFormatter,\n        epilog=\"\"\"\nExamples:\n  %(prog)s patterns/new-pattern.md\n  %(prog)s --all\n  %(prog)s --all --verbose --export report.md\n        \"\"\",\n    )\n    parser.add_argument(\n        \"pattern_file\",\n        nargs=\"?\",\n        help=\"Path to pattern file to validate\",\n    )\n    parser.add_argument(\n        \"--all\",\n        \"-a\",\n        action=\"store_true\",\n        help=\"Validate all pattern files\",\n    )\n    parser.add_argument(\n        \"--patterns-dir\",\n        \"-d\",\n        type=str,\n        default=\"patterns\",\n        help=\"Path to patterns directory (default: patterns)\",\n    )\n    parser.add_argument(\n        \"--verbose\",\n        \"-v\",\n        action=\"store_true\",\n        help=\"Print detailed output for each issue\",\n    )\n    parser.add_argument(\n        \"--strict\",\n        \"-s\",\n        action=\"store_true\",\n        help=\"Treat warnings as errors\",\n    )\n    parser.add_argument(\n        \"--export\",\n        \"-e\",\n        type=str,\n        help=\"Export report to Markdown file\",\n    )\n\n    args = parser.parse_args()\n\n    # Validate arguments\n    if not args.all and not args.pattern_file:\n        parser.error(\"Either specify a pattern file or use --all\")\n\n    if args.all and args.pattern_file:\n        parser.error(\"Cannot use --all with a specific pattern file\")\n\n    # Initialize validator\n    validator = PatternValidator(strict=args.strict)\n\n    # Collect files to validate\n    files_to_validate = []\n\n    if args.all:\n        patterns_dir = Path(args.patterns_dir)\n        if not patterns_dir.exists():\n            print(f\"Error: Patterns directory not found: {patterns_dir}\")\n            return 1\n\n        for filepath in sorted(patterns_dir.glob(\"*.md\")):\n            if filepath.name != \"TEMPLATE.md\":\n                files_to_validate.append(str(filepath))\n    else:\n        files_to_validate.append(args.pattern_file)\n\n    # Run validation\n    print(f\"Validating {len(files_to_validate)} file(s)...\\n\")\n\n    results = []\n    for filepath in files_to_validate:\n        if not Path(filepath).exists():\n            print(f\"❌ File not found: {filepath}\")\n            continue\n\n        result = validator.validate_file(filepath)\n        results.append(result)\n        print_validation_result(result, verbose=args.verbose)\n\n    # Print summary\n    if len(results) > 1:\n        print_validation_summary(results)\n\n    # Export if requested\n    if args.export:\n        export_validation_report(results, args.export)\n\n    # Return exit code\n    return 0 if all(r.is_valid for r in results) else 1\n\n\nif __name__ == \"__main__\":\n    sys.exit(main())\n","isInternal":false,"tokens":4948,"sizeBytes":23937},{"name":"validate.py","path":".claude/skills/create-pattern/scripts/validate.py","rawUrl":"https://raw.githubusercontent.com/nibzard/awesome-agentic-patterns/HEAD/.claude/skills/create-pattern/scripts/validate.py","title":"Claude Directive: validate.py","category":"claude-rule","format":"markdown","content":"#!/usr/bin/env python3\n\"\"\"Validate pattern front-matter against repository schema.\"\"\"\n\nimport sys\nfrom pathlib import Path\n\n# Allowed values for validation\nALLOWED_CATEGORIES = [\n    \"Orchestration & Control\",\n    \"Context & Memory\",\n    \"Feedback Loops\",\n    \"Learning & Adaptation\",\n    \"Reliability & Eval\",\n    \"Security & Safety\",\n    \"Tool Use & Environment\",\n    \"UX & Collaboration\",\n    \"Uncategorized\",\n]\n\nALLOWED_STATUSES = [\n    \"proposed\",\n    \"emerging\",\n    \"established\",\n    \"validated-in-production\",\n    \"best-practice\",\n    \"experimental-but-awesome\",\n    \"rapidly-improving\",\n]\n\nREQUIRED_FIELDS = [\"title\", \"status\", \"authors\", \"based_on\", \"category\", \"source\", \"tags\"]\n\n\ndef extract_frontmatter(file_path: Path) -> tuple[str, dict]:\n    \"\"\"Extract YAML frontmatter from a markdown file.\"\"\"\n    content = file_path.read_text()\n    if not content.startswith(\"---\"):\n        raise ValueError(\"File does not start with frontmatter delimiter\")\n\n    # Find the end of frontmatter\n    end_idx = content.find(\"\\n---\", 4)\n    if end_idx == -1:\n        raise ValueError(\"Frontmatter not properly closed\")\n\n    yaml_str = content[4:end_idx]\n    return content, parse_yaml_simple(yaml_str)\n\n\ndef parse_yaml_simple(yaml_str: str) -> dict:\n    \"\"\"Simple YAML parser for frontmatter - handles basic key: value pairs.\"\"\"\n    result = {}\n    for line in yaml_str.strip().split(\"\\n\"):\n        if \":\" in line and not line.strip().startswith(\"#\"):\n            key, value = line.split(\":\", 1)\n            key = key.strip()\n            value = value.strip()\n\n            # Handle lists\n            if value.startswith(\"[\") and value.endswith(\"]\"):\n                value = [v.strip().strip('\"\\'') for v in value[1:-1].split(\",\")]\n            # Strip quotes from strings\n            elif value.startswith('\"') and value.endswith('\"'):\n                value = value[1:-1]\n            elif value.startswith(\"'\") and value.endswith(\"'\"):\n                value = value[1:-1]\n\n            result[key] = value\n\n    return result\n\n\ndef validate_pattern(file_path: str | Path) -> bool:\n    \"\"\"Validate a pattern file's frontmatter.\"\"\"\n    path = Path(file_path)\n\n    if not path.exists():\n        print(f\"❌ File not found: {path}\")\n        return False\n\n    try:\n        content, frontmatter = extract_frontmatter(path)\n    except ValueError as e:\n        print(f\"❌ {e}\")\n        return False\n\n    errors = []\n\n    # Check required fields\n    for field in REQUIRED_FIELDS:\n        if field not in frontmatter:\n            errors.append(f\"Missing required field: {field}\")\n\n    # Validate category\n    if \"category\" in frontmatter and frontmatter[\"category\"] not in ALLOWED_CATEGORIES:\n        errors.append(\n            f\"Invalid category: {frontmatter['category']}. \"\n            f\"Must be one of: {', '.join(ALLOWED_CATEGORIES)}\"\n        )\n\n    # Validate status\n    if \"status\" in frontmatter and frontmatter[\"status\"] not in ALLOWED_STATUSES:\n        errors.append(\n            f\"Invalid status: {frontmatter['status']}. \"\n            f\"Must be one of: {', '.join(ALLOWED_STATUSES)}\"\n        )\n\n    # Validate authors is a list\n    if \"authors\" in frontmatter and not isinstance(frontmatter[\"authors\"], list):\n        errors.append(\"authors must be a list (e.g., [\\\"Name (@username)\\\"])\")\n\n    # Validate tags is a list\n    if \"tags\" in frontmatter and not isinstance(frontmatter[\"tags\"], list):\n        errors.append(\"tags must be a list (e.g., [tag1, tag2, tag3])\")\n\n    if errors:\n        for error in errors:\n            print(f\"❌ {error}\")\n        return False\n\n    # Check for required sections in content\n    required_sections = [\"## Problem\", \"## Solution\", \"## References\"]\n    for section in required_sections:\n        if section not in content:\n            errors.append(f\"Missing section: {section}\")\n\n    if errors:\n        for error in errors:\n            print(f\"❌ {error}\")\n        return False\n\n    print(f\"✅ Pattern validation passed: {path.name}\")\n    return True\n\n\nif __name__ == \"__main__\":\n    if len(sys.argv) < 2:\n        print(\"Usage: python validate.py <pattern-file.md>\")\n        sys.exit(1)\n\n    success = validate_pattern(sys.argv[1])\n    sys.exit(0 if success else 1)\n","isInternal":false,"tokens":985,"sizeBytes":4202},{"name":"CLAUDE.md","path":"CLAUDE.md","rawUrl":"https://raw.githubusercontent.com/nibzard/awesome-agentic-patterns/HEAD/CLAUDE.md","title":"Claude Agent Guidelines & System Prompt","category":"claude-rule","format":"markdown","content":"# CLAUDE.md\n\nThis file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.\n\n## Project Overview\n\nThis is a documentation website for \"Awesome Agentic Patterns\" - a curated catalogue of AI agent design patterns. It uses Astro (apps/web/) to generate a static documentation site that can be deployed to Vercel.\n\n## Key Commands\n\n> **NOTE:** This project uses **bun** as the package manager, not npm.\n\n### Development Workflow\n```bash\n# Initial setup (run once)\nbun install                            # Install dependencies\n\n# Standard development cycle\nbun run dev                            # Serve docs locally at http://localhost:4321\n\n# Building and deployment\nbun run build                          # Build static site to apps/web/dist/\nvercel deploy                          # Deploy to Vercel (primary)\n```\n\n## Architecture\n\nThe project has a unique architecture where pattern documentation drives the entire site:\n\n1. **Pattern Files** (`patterns/*.md`): Source of truth for all patterns\n   - Must include YAML front-matter with: title, status, authors, category, source, tags, summary, signals, anti_signals, updated_at\n   - Content sections: Problem, Solution, How to use it, Trade-offs, References\n\n2. **Data Pipeline**: Pattern files are converted to JSON in `apps/web/public/patterns/`\n   - Astro build reads JSON files to generate pages\n   - Pattern metadata drives navigation and listings\n\n3. **Build Process**:\n   - Astro builds from apps/web/ to apps/web/dist/\n   - Site can be served locally or deployed to Vercel\n\n## Pattern Development Workflow\n\n### Adding New Patterns\n1. **Start with template**: Copy `TEMPLATE.md` (repository root) to create new pattern files in `patterns/`\n2. **Required YAML front-matter**: Every pattern must include:\n   ```yaml\n   ---\n   title: \"Clear, Descriptive Title\"\n   status: \"proposed | emerging | production | foundational\"\n   authors: [\"Contributor Name (@username)\"]\n   based_on: [\"Original Creator (Source)\"]\n   category: \"Orchestration & Control | Context & Memory | Feedback Loops | Learning & Adaptation | Reliability & Eval | Security & Safety | Tool Use & Environment | UX & Collaboration | Uncategorized\"\n   source: \"URL to primary source\"\n   tags: [relevant, keywords, here]\n   summary: \"One sentence that says what the pattern does (the solution)\"  # Shown in the catalog list\n   signals: [\"When to use it\"]          # 2-4 items, shown as \"Use when\"\n   anti_signals: [\"When not to use it\"] # 2-3 items, shown as \"Avoid when\"\n   updated_at: \"YYYY-MM-DD\"  # Required: last content change date — file mtimes differ per machine, so generated data needs an explicit date\n   ---\n   ```\n3. **Required sections**: Problem, Solution, How to use it, Trade-offs, References\n4. **Data sync**: Pattern files must be converted to JSON for the Astro site\n   - Run `bun run build:data` to update the JSON files\n   - JSON files are stored in `apps/web/public/patterns/` and `apps/web/public/data/patterns/`\n   - CI fails if the committed JSON files differ from what the pipeline produces; run the pipeline and commit its output together with the pattern `.md` change\n\n### Content Guidelines\n- Use Mermaid diagrams in patterns for architectural visualization\n- Pattern files support full Markdown with front-matter\n- Community policy for pattern submissions:\n  - Treat this as a community project, not a promotional channel\n  - Reject promotional, sales, affiliate, or backlink-seeding content\n  - For external contributors, prefer links to `github.com`, `github.io`, or non-vendor neutral references\n  - Allow vendor/product links only when the contribution is truly novel and adds clear value\n  - Require submissions to be materially novel and non-repetitive versus existing patterns\n- **CRITICAL**: Always add blank lines after headers before starting bullet point lists\n  - Incorrect: `**Header:**\\n- Item 1` (renders inline)\n  - Correct: `**Header:**\\n\\n- Item 1` (renders as proper list)\n  - This is required for Astro to properly convert Markdown lists to HTML `<ul><li>` elements\n\n### Asset Path Handling\n\n**CRITICAL**: When adding images or other assets that need to work on both localhost and deployed sites:\n\n- **Use absolute paths starting with `/`** in all asset references\n- **Image references**: Use `/image.jpeg` instead of `image.jpeg` in markdown files\n- **Rationale**: Relative paths can work locally but fail on Vercel due to different path resolution behavior\n- **Example fix**: Change `![Image](image.jpeg)` to `![Image](/image.jpeg)`\n\nThis ensures assets load correctly on both local development (`localhost:4321`) and production deployment (`agentic-patterns.com`).\n\n## Technical Architecture\n\n### Build System Components\n- **Astro**: Modern static site generator in `apps/web/`\n- **Pattern JSON files**: Generated data in `apps/web/public/patterns/`\n- **Vercel config**: Build settings in `vercel.json`\n- **TypeScript/Node.js**: Build toolchain\n\n### File Structure\n```\nTEMPLATE.md           # Template for new patterns (repository root)\n\npatterns/              # Source of truth - all pattern .md files\n└── *.md              # Individual pattern files with YAML front-matter\n\napps/web/             # Astro web application\n├── public/\n│   └── patterns/    # JSON pattern data for site generation\n├── src/             # Astro components and pages\n└── dist/            # Build output (deployment artifact)\n```\n\n### Dependencies\n- **Node.js**: Astro framework and build toolchain\n- **Vercel**: Primary deployment platform\n\n## Deployment\n\n- Primary deployment: Vercel (`vercel deploy`)\n- For detailed deployment instructions, see DEPLOYMENT.md\n","isInternal":false,"tokens":1284,"sizeBytes":5683}],"systemPromptSnippet":"<yakaai_skills repo=\"nibzard/awesome-agentic-patterns\">\n<!-- File: llms.txt (Tokens: ~11269 | Category: root-instruction) -->\n# Awesome Agentic Patterns\n\nA curated catalogue of AI agent design patterns.\n\nEvery pattern is also available as Markdown at https://agentic-patterns.com/patterns/<slug>.md. Full text of all patterns: https://agentic-patterns.com/llms-full.txt. Usage notes for agents: https://agentic-patterns.com/agents.\n\n## Patterns\n\n### 402-first-machine-payments\n402-First Machine Payments (Price-Before-Work Tool Purchases): Server returns an HTTP 402 price quote before doing work, and the agent pays the exact amount only if it fits its budget cap\nURL: https://agentic-patterns.com/patterns/402-first-machine-payments\nMarkdown: https://agentic-patterns.com/patterns/402-first-machine-payments.md\n\n### abstracted-code-representation-for-review\nAbstracted Code Representation for Review: Shows reviewers pseudocode, intent summaries, and logical diffs of code changes, with drill-down to the real code to confirm the mapping\nURL: https://agentic-patterns.com/patterns/abstracted-code-representation-for-review\nMarkdown: https://agentic-patterns.com/patterns/abstracted-code-representation-for-review.md\n\n### action-caching-replay\nAction Caching & Replay Pattern: Records each agent action with XPath and frame metadata so later runs replay it without LLM calls, with LLM fallback when replay fails\nURL: https://agentic-patterns.com/patterns/action-caching-replay\nMarkdown: https://agentic-patterns.com/patterns/action-caching-replay.md\n\n### action-selector-pattern\nAction-Selector Pattern: LLM maps user intent to a pre-approved action ID with schema-validated parameters, and tool outputs never return to the selector\nURL: https://agentic-patterns.com/patterns/action-selector-pattern\nMarkdown: https://agentic-patterns.com/patterns/action-selector-pattern.md\n\n### adaptive-sandbox-fanout-controller\nAdaptive Sandbox Fan-Out Controller: Starts a small batch of parallel sandboxes, then scales up, stops early, or refines the prompt based on early success, variance, and error signals\nURL: https://agentic-patterns.com/patterns/adaptive-sandbox-fanout-controller\nMarkdown: https://agentic-patterns.com/patterns/adaptive-sandbox-fanout-controller.md\n\n### agent-circuit-breaker\nAgent Circuit Breaker: Prevents agents from wasting tokens and time on repeatedly failing tools by tracking failure rates and temporarily disabling broken tool endpoints\nURL: https://agentic-patterns.com/patterns/agent-circuit-breaker\nMarkdown: https://agentic-patterns.com/patterns/agent-circuit-breaker.md\n\n### agent-modes-by-model-personality\nAgent Modes by Model Personality: Offers separate working modes, each with its own prompts, tools, UI, and expectations, tuned to one model's working style\nURL: https://agentic-patterns.com/patterns/agent-modes-by-model-personality\nMarkdown: https://agentic-patterns.com/patterns/agent-modes-by-model-personality.md\n\n### agent-reinforcement-fine-tuning\nAgent Reinforcement Fine-Tuning (Agent RFT): Trains model weights with reinforcement learning on real tool calls and custom graders to improve domain-specific tool use and multi-step reasoning\nURL: https://agentic-patterns.com/patterns/agent-reinforcement-fine-tuning\nMarkdown: https://agentic-patterns.com/patterns/agent-reinforcement-fine-tuning.md\n\n### agent-sdk-for-programmatic-control\nAgent SDK for Programmatic Control: Exposes agent functions through an SDK and CLI so code can run the agent headless with set tools, permissions, and resource limits\nURL: https://agentic-patterns.com/patterns/agent-sdk-for-programmatic-control\nMarkdown: https://agentic-patterns.com/patterns/agent-sdk-for-programmatic-control.md\n\n### agent-assisted-scaffolding\nAgent-Assisted Scaffolding: Agent generates initial files, boilerplate, and directory structure from a high-level description so developers start on core logic\nURL: https://agentic-patterns.com/patterns/agent-assisted-scaffolding\nMarkdown: https://agentic-patterns.com/patterns/agent-assisted-scaffolding.md\n\n### agent-driven-research\nAgent-Driven Research: Agent plans its own queries, fans out parallel search workers across sources, reflects on evidence gaps, and iterates until it can write a sourced report\nURL: https://agentic-patterns.com/patterns/agent-driven-research\nMarkdown: https://agentic-patterns.com/patterns/agent-driven-research.md\n\n### agent-first-tool-discovery\nAgent-First Tool Discovery: Indexes tools and agents across MCP registries, A2A cards, OpenAPI specs, and custom directories into one normalized search surface ranked by agent-relevant signals\nURL: https://agentic-patterns.com/patterns/agent-first-tool-discovery\nMarkdown: https://agentic-patterns.com/patterns/agent-first-tool-discovery.md\n\n### agent-first-tooling-and-logging\nAgent-First Tooling and Logging: Designs logs and tool output for agent consumption with one unified log stream, structured JSON, and agent-aware CLI flags\nURL: https://agentic-patterns.com/patterns/agent-first-tooling-and-logging\nMarkdown: https://agentic-patterns.com/patterns/agent-first-tooling-and-logging.md\n\n### agent-friendly-workflow-design\nAgent-Friendly Workflow Design: Gives agents clear high-level goals, room for implementation choices, structured I/O, and plan review before execution\nURL: https://agentic-patterns.com/patterns/agent-friendly-workflow-design\nMarkdown: https://agentic-patterns.com/patterns/agent-friendly-workflow-design.md\n\n### agent-powered-codebase-qa-onboarding\nAgent-Powered Codebase Q&A / Onboarding: Agent indexes the codebase with embeddings and code graphs and answers natural-language questions about where code is and how it behaves\nURL: https://agentic-patterns.com/patterns/agent-powered-codebase-qa-onboarding\nMarkdown: https://agentic-patterns.com/patterns/agent-powered-codebase-qa-onboarding.md\n\n### agentic-search-over-vector-embeddings\nAgentic Search Over Vector Embeddings: Replaces vector indexes with agent-driven grep, find, and file traversal that searches current file state on demand and refines iteratively\nURL: https://agentic-patterns.com/patterns/agentic-search-over-vector-embeddings\nMarkdown: https://agentic-patterns.com/patterns/agentic-search-over-vector-embeddings.md\n\n### ai-assisted-code-review-verification\nAI-Assisted Code Review / Verification: Uses AI tools to flag issues, summarize change intent, and explain code so human reviewers focus on intent and business logic\nURL: https://agentic-patterns.com/patterns/ai-assisted-code-review-verification\nMarkdown: https://agentic-patterns.com/patterns/ai-assisted-code-review-verification.md\n\n### anchored-structured-context-compaction\nAnchored Structured Context Compaction: Maintains a typed state block (pinned goal and constraints, verified decisions, an artifact registry, open blockers) and merges only the newly evicted span into it at each compaction, so that long sessions keep exact details instead of drifting\nURL: https://agentic-patterns.com/patterns/anchored-structured-context-compaction\nMarkdown: https://agentic-patterns.com/patterns/anchored-structured-context-compaction.md\n\n### anti-reward-hacking-grader-design\nAnti-Reward-Hacking Grader Design: Design reward functions with multi-criteria evaluation and iterative hardening to prevent models from gaming graders, ensuring training rewards align with actual task quality.\nURL: https://agentic-patterns.com/patterns/anti-reward-hacking-grader-design\nMarkdown: https://agentic-patterns.com/patterns/anti-reward-hacking-grader-design.md\n\n### multi-step-analysis-pipeline-orchestration\nArtifact-Driven Analysis Pipeline Orchestration: Has an agent run independent analysis scripts, read their structured reports, and merge them into one final report or visualization\nURL: https://agentic-patterns.com/patterns/multi-step-analysis-pipeline-orchestration\nMarkdown: https://agentic-patterns.com/patterns/multi-step-analysis-pipeline-orchestration.md\n\n### asynchronous-coding-agent-pipeline\nAsynchronous Coding Agent Pipeline: Splits inference, tool execution, reward modeling, and learning into asynchronous workers linked by message queues so GPUs stay busy\nURL: https://agentic-patterns.com/patterns/asynchronous-coding-agent-pipeline\nMarkdown: https://agentic-patterns.com/patterns/asynchronous-coding-agent-pipeline.md\n\n### authenticated-authority-channel\nAuthenticated Authority Channel: Preserve a distinguishable channel for authenticated intent so retrieved content can inform reasoning without granting itself authority.\nURL: https://agentic-patterns.com/patterns/authenticated-authority-channel\nMarkdown: https://agentic-patterns.com/patterns/authenticated-authority-channel.md\n\n### autonomous-workflow-agent-architecture\nAutonomous Workflow Agent Architecture: Runs multi-step engineering workflows in containers with tmux sessions, sleep-based monitoring, checkpoints, and context-aware error recovery\nURL: https://agentic-patterns.com/patterns/autonomous-workflow-agent-architecture\nMarkdown: https://agentic-patterns.com/patterns/autonomous-workflow-agent-architecture.md\n\n### background-agent-ci\nBackground Agent with CI Feedback: Runs the agent in the background on its own branch and uses CI results as feedback to patch failures until green or blocked\nURL: https://agentic-patterns.com/patterns/background-agent-ci\nMarkdown: https://agentic-patterns.com/patterns/background-agent-ci.md\n\n### black-box-skill-invocation\nBlack-Box Skill Invocation: Shares skills through input and output schemas only and runs them on the provider side, so prompts and code never cross the boundary\nURL: https://agentic-patterns.com/patterns/black-box-skill-invocation\nMarkdown: https://agentic-patterns.com/patterns/black-box-skill-invocation.md\n\n### board-mediated-inter-agent-coordination\nBoard-Mediated Async Inter-Agent Coordination: Routes agent-to-agent messages through comment threads on board cards, with a prefix that creates an inbox card to notify the target agent\nURL: https://agentic-patterns.com/patterns/board-mediated-inter-agent-coordination\nMarkdown: https://agentic-patterns.com/patterns/board-mediated-inter-agent-coordination.md\n\n### budget-aware-model-routing-with-hard-cost-caps\nBudget-Aware Model Routing with Hard Cost Caps: Routes each request to the cheapest model that meets its needs under hard cost caps, and escalates only when quality gates fail\nURL: https://agentic-patterns.com/patterns/budget-aware-model-routing-with-hard-cost-caps\nMarkdown: https://agentic-patterns.com/patterns/budget-aware-model-routing-with-hard-cost-caps.md\n\n### canary-rollout-and-automatic-rollback-for-agent-policy-changes\nCanary Rollout and Automatic Rollback for Agent Policy Changes: Ships agent policy changes to a small traffic slice first, monitors guardrail metrics, and rolls back to the last stable version automatically\nURL: https://agentic-patterns.com/patterns/canary-rollout-and-automatic-rollback-for-agent-policy-changes\nMarkdown: https://agentic-patterns.com/patterns/canary-rollout-and-automatic-rollback-for-agent-policy-changes.md\n\n### capability-escrow-receipt\nCapability-Escrow-Receipt: Binds a signed capability listing, an atomic escrow-plus-hire step, and a signed work receipt into one loop for agent-to-agent payment\nURL: https://agentic-patterns.com/patterns/capability-escrow-receipt\nMarkdown: https://agentic-patterns.com/patterns/capability-escrow-receipt.md\n\n### chain-of-thought-monitoring-interruption\nChain-of-Thought Monitoring & Interruption: Streams agent reasoning and tool calls in real time so a human can interrupt and redirect early when the approach is wrong\nURL: https://agentic-patterns.com/patterns/chain-of-thought-monitoring-interruption\nMarkdown: https://agentic-patterns.com/patterns/chain-of-thought-monitoring-interruption.md\n\n### classify-then-act-for-background-agents\nClassify-Then-Act for Background Agents: Sorts each task into has-default, needs-intent, or out-of-scope, builds only has-default work in a sandbox, and queues it for human review\nURL: https://agentic-patterns.com/patterns/classify-then-act-for-background-agents\nMarkdown: https://agentic-patterns.com/patterns/classify-then-act-for-background-agents.md\n\n### cli-native-agent-orchestration\nCLI-Native Agent Orchestration: Drives agents through their non-interactive CLI mode (claude -p with JSON output and exit codes) so Makefiles, Git hooks, cron jobs, and CI can script and replay agent runs\nURL: https://agentic-patterns.com/patterns/cli-native-agent-orchestration\nMarkdown: https://agentic-patterns.com/patterns/cli-native-agent-orchestration.md\n\n### code-over-api-pattern\nCode-Over-API (Code Mode): Agent writes code that calls tools and processes data inside a sandbox, so only summaries and samples return to the context window instead of every intermediate result\nURL: https://agentic-patterns.com/patterns/code-over-api-pattern\nMarkdown: https://agentic-patterns.com/patterns/code-over-api-pattern.md\n\n### code-then-execute-pattern\nCode-Then-Execute Pattern: LLM writes a sandboxed program or DSL script, a static taint checker verifies data flows, and an interpreter runs it in a locked sandbox\nURL: https://agentic-patterns.com/patterns/code-then-execute-pattern\nMarkdown: https://agentic-patterns.com/patterns/code-then-execute-pattern.md\n\n### codebase-optimization-for-agents\nCodebase Optimization for Agents: Optimizes tooling, CLIs, tests, and docs for agents first, with one-command verify loops and machine-readable output, even if human DX regresses\nURL: https://agentic-patterns.com/patterns/codebase-optimization-for-agents\nMarkdown: https://agentic-patterns.com/patterns/codebase-optimization-for-agents.md\n\n### commitment-ledger-reality-gated-credit\nCommitment Ledger with Reality-Gated Credit: Records agent promises and credits retrieved memory only after an externally verifiable outcome settles.\nURL: https://agentic-patterns.com/patterns/commitment-ledger-reality-gated-credit\nMarkdown: https://agentic-patterns.com/patterns/commitment-ledger-reality-gated-credit.md\n\n### compounding-engineering-pattern\nCompounding Engineering Pattern: After each feature, codifies agent mistakes and learnings into CLAUDE.md, slash commands, subagents, and hooks so the next feature is easier to build\nURL: https://agentic-patterns.com/patterns/compounding-engineering-pattern\nMarkdown: https://agentic-patterns.com/patterns/compounding-engineering-pattern.md\n\n### parallel-tool-execution\nConditional Parallel Tool Execution: Runs a batch of tool calls in parallel when all are read-only and in sequence when any modifies state, then returns results in request order\nURL: https://agentic-patterns.com/patterns/parallel-tool-execution\nMarkdown: https://agentic-patterns.com/patterns/parallel-tool-execution.md\n\n### consequence-family-coverage-audit\nConsequence-Family Coverage Audit: Audit an agent's risk policy by enumerating families of consequence and asking which rule covers each, because a hand-written risk list reliably encodes one family and stays silent on the rest\nURL: https://agentic-patterns.com/patterns/consequence-family-coverage-audit\nMarkdown: https://agentic-patterns.com/patterns/consequence-family-coverage-audit.md\n\n### context-budget-as-a-governed-resource\nContext Budget as a Governed Resource: Measures always-loaded context per source, alerts on trend growth, and puts hard spend caps and fan-out bounds on unattended agent runs\nURL: https://agentic-patterns.com/patterns/context-budget-as-a-governed-resource\nMarkdown: https://agentic-patterns.com/patterns/context-budget-as-a-governed-resource.md\n\n### context-window-anxiety-management\nContext Window Anxiety Management: Enables a large context window but caps usage lower, and adds prompts that state the token budget so the model does not rush to finish\nURL: https://agentic-patterns.com/patterns/context-window-anxiety-management\nMarkdown: https://agentic-patterns.com/patterns/context-window-anxiety-management.md\n\n### context-window-auto-compaction\nContext Window Auto-Compaction: Catches context overflow errors, compacts and validates the transcript with capped reserve headroom, and retries the request automatically\nURL: https://agentic-patterns.com/patterns/context-window-auto-compaction\nMarkdown: https://agentic-patterns.com/patterns/context-window-auto-compaction.md\n\n### context-minimization-pattern\nContext-Minimization Pattern: Removes untrusted user text and tool output from context after it becomes a safe structured artifact, so later steps see only trusted data\nURL: https://agentic-patterns.com/patterns/context-minimization-pattern\nMarkdown: https://agentic-patterns.com/patterns/context-minimization-pattern.md\n\n### continuous-autonomous-task-loop-pattern\nContinuous Autonomous Task Loop Pattern: Runs a loop where subagents pick the next task from a todo file, execute it in fresh context, commit it, and back off on rate limits\nURL: https://agentic-patterns.com/patterns/continuous-autonomous-task-loop-pattern\nMarkdown: https://agentic-patterns.com/patterns/continuous-autonomous-task-loop-pattern.md\n\n### credential-free-outbox\nCredential-Free Outbox: The agent writes finished work as a file to an outbox and a separate short-lived job with its own token delivers it, so the agent never holds a credential that can publish anything\nURL: https://agentic-patterns.com/patterns/credential-free-outbox\nMarkdown: https://agentic-patterns.com/patterns/credential-free-outbox.md\n\n### criticgpt-style-evaluation\nCriticGPT-Style Code Review: Runs a specialized critic model over generated code to find bugs, security flaws, and quality issues, and feeds critical findings back for regeneration\nURL: https://agentic-patterns.com/patterns/criticgpt-style-evaluation\nMarkdown: https://agentic-patterns.com/patterns/criticgpt-style-evaluation.md\n\n### cross-agent-lesson-sharing\nCross-Agent Lesson Sharing via Git: Agents write solved problems as markdown lessons in a shared Git repo and search them before debugging, with GitHub Issues as the coordination layer\nURL: https://agentic-patterns.com/patterns/cross-agent-lesson-sharing\nMarkdown: https://agentic-patterns.com/patterns/cross-agent-lesson-sharing.md\n\n### cross-cycle-consensus-relay\nCross-Cycle Consensus Relay: Each loop cycle reads a structured relay document, does its work, and atomically writes back decisions, open questions, and the single next action\nURL: https://agentic-patterns.com/patterns/cross-cycle-consensus-relay\nMarkdown: https://agentic-patterns.com/patterns/cross-cycle-consensus-relay.md\n\n### cross-domain-agent-conflict-resolution\nCross-Domain Agent Conflict Resolution: A coordination layer that cross-references recommendations from independent domain agents, detects conflicts on shared resources, and resolves them through policy-as-code.\nURL: https://agentic-patterns.com/patterns/cross-domain-agent-conflict-resolution\nMarkdown: https://agentic-patterns.com/patterns/cross-domain-agent-conflict-resolution.md\n\n### cryptographic-governance-audit-trail\nCryptographic Governance Audit Trail: Middleware checks each tool call against a policy file, then signs a receipt of the action with ML-DSA and appends it to a tamper-evident chain\nURL: https://agentic-patterns.com/patterns/cryptographic-governance-audit-trail\nMarkdown: https://agentic-patterns.com/patterns/cryptographic-governance-audit-trail.md\n\n### curated-code-context-window\nCurated Code Context Window: A search subagent finds the few relevant files for a task and injects only top snippets or summaries into the main coding agent's context\nURL: https://agentic-patterns.com/patterns/curated-code-context-window\nMarkdown: https://agentic-patterns.com/patterns/curated-code-context-window.md\n\n### custom-sandboxed-background-agent\nCustom Sandboxed Background Agent: Builds an in-house background coding agent that runs in sandboxed dev environments, streams progress over WebSocket, and iterates on compiler and test feedback\nURL: https://agentic-patterns.com/patterns/custom-sandboxed-background-agent\nMarkdown: https://agentic-patterns.com/patterns/custom-sandboxed-background-agent.md\n\n### dead-mans-switch-for-scheduled-agent-jobs\nDead-Man's Switch for Scheduled Agent Jobs: Each scheduled job writes a success sentinel to its log, and a separate checker files a task when the sentinel is missing or stale\nURL: https://agentic-patterns.com/patterns/dead-mans-switch-for-scheduled-agent-jobs\nMarkdown: https://agentic-patterns.com/patterns/dead-mans-switch-for-scheduled-agent-jobs.md\n\n### debiased-llm-as-a-judge-evaluation\nDebiased LLM-as-a-Judge Evaluation: Removes the systematic distortions of a model judge before its scores gate a release: swaps the order of each pairwise comparison, grades narrow pass/fail rubric items that cite evidence, supplies a reference answer and a judge from another model family, and measures the agreement with human labels first\nURL: https://agentic-patterns.com/patterns/debiased-llm-as-a-judge-evaluation\nMarkdown: https://agentic-patterns.com/patterns/debiased-llm-as-a-judge-evaluation.md\n\n### declarative-multi-agent-topology-definition\nDeclarative Multi-Agent Topology Definition: Define multi-agent systems declaratively in a single topology file — agents, flows, gates, hooks, group chats — then compile to platform-specific configurations for any agentic framework.\nURL: https://agentic-patterns.com/patterns/declarative-multi-agent-topology-definition\nMarkdown: https://agentic-patterns.com/patterns/declarative-multi-agent-topology-definition.md\n\n### delegated-user-auth-token-exchange\nDelegated User Authorization (OAuth Token Exchange): Exchanges the user's token and the agent's own identity for a short-lived, single-audience, minimally scoped token immediately before each tool call, so that the agent acts with delegated and attributable authority instead of a shared super-credential\nURL: https://agentic-patterns.com/patterns/delegated-user-auth-token-exchange\nMarkdown: https://agentic-patterns.com/patterns/delegated-user-auth-token-exchange.md\n\n### denial-tracking-permission-escalation\nDenial Tracking & Permission Escalation: Track repeated tool denials and auto-escalate to blanket permission prompts or fallback strategies, preventing wasted iterations in non-interactive contexts.\nURL: https://agentic-patterns.com/patterns/denial-tracking-permission-escalation\nMarkdown: https://agentic-patterns.com/patterns/denial-tracking-permission-escalation.md\n\n### design-time-file-partition\nDesign-Time File Partition as Concurrency Control: Each task declares every path it will write; overlapping tasks get a blocking dependency so only disjoint work runs at once on a shared checkout\nURL: https://agentic-patterns.com/patterns/design-time-file-partition\nMarkdown: https://agentic-patterns.com/patterns/design-time-file-partition.md\n\n### deterministic-grader-in-the-loop\nDeterministic Grader in the Loop: Replace the LLM-as-judge in an agent's self-review loop with a deterministic scorer that returns the raw counts behind each sub-score, so the agent has something specific to fix.\nURL: https://agentic-patterns.com/patterns/deterministic-grader-in-the-loop\nMarkdown: https://agentic-patterns.com/patterns/deterministic-grader-in-the-loop.md\n\n### deterministic-security-scanning-build-loop\nDeterministic Security Scanning Build Loop: Adds SAST, SCA, and secret scanners to the build target that the agent must run after each change, so scanner failures force the agent to fix the code\nURL: https://agentic-patterns.com/patterns/deterministic-security-scanning-build-loop\nMarkdown: https://agentic-patterns.com/patterns/deterministic-security-scanning-build-loop.md\n\n### deterministic-threat-rule-scanning\nDeterministic Threat Rule Scanning: Apply deterministic regex rules as a first-pass security layer to detect known threat patterns in AI agent tool calls and skill definitions.\nURL: https://agentic-patterns.com/patterns/deterministic-threat-rule-scanning\nMarkdown: https://agentic-patterns.com/patterns/deterministic-threat-rule-scanning.md\n\n### deterministic-zero-llm-orchestration\nDeterministic Zero-LLM Orchestration: A deterministic code orchestrator splits goals, runs parallel coding agents, verifies with tests, and commits, spending LLM tokens only on the one-time goal decomposition\nURL: https://agentic-patterns.com/patterns/deterministic-zero-llm-orchestration\nMarkdown: https://agentic-patterns.com/patterns/deterministic-zero-llm-orchestration.md\n\n### discrete-phase-separation\nDiscrete Phase Separation: Splits work into separate research, planning, and implementation conversations, each with fresh context, passing only distilled outputs between phases\nURL: https://agentic-patterns.com/patterns/discrete-phase-separation\nMarkdown: https://agentic-patterns.com/patterns/discrete-phase-separation.md\n\n### distributed-execution-cloud-workers\nDistributed Execution with Cloud Workers: Runs many agent sessions in parallel on cloud workers, each in its own git worktree, with dependency-aware scheduling, merge coordination, and approval gates\nURL: https://agentic-patterns.com/patterns/distributed-execution-cloud-workers\nMarkdown: https://agentic-patterns.com/patterns/distributed-execution-cloud-workers.md\n\n### dual-llm-pattern\nDual LLM Pattern: Splits work between a privileged LLM that calls tools but never sees untrusted data and a quarantined LLM that reads untrusted data but has no tools\nURL: https://agentic-patterns.com/patterns/dual-llm-pattern\nMarkdown: https://agentic-patterns.com/patterns/dual-llm-pattern.md\n\n### dual-rail-message-delivery\nDual-Rail Message Delivery: Sends every inter-agent message on two independent channels through one entry point, alerts when the rails diverge, and requires ACKs to confirm completion\nURL: https://agentic-patterns.com/patterns/dual-rail-message-delivery\nMarkdown: https://agentic-patterns.com/patterns/dual-rail-message-delivery.md\n\n### dual-speed-talker-reasoner-architecture\nDual-Speed Realtime Architecture (Talker-Reasoner): Splits an agent into a fast Talker that owns the live conversation and a slow Reasoner that plans and calls tools in the background, with a shared belief state as their only coupling, so that the user gets a reply at once while the deep work runs\nURL: https://agentic-patterns.com/patterns/dual-speed-talker-reasoner-architecture\nMarkdown: https://agentic-patterns.com/patterns/dual-speed-talker-reasoner-architecture.md\n\n### dual-use-tool-design\nDual-Use Tool Design: Builds each tool or skill as one CLI interface that both humans and agents call, with JSON output, exit codes, and the same permissions and logs\nURL: https://agentic-patterns.com/patterns/dual-use-tool-design\nMarkdown: https://agentic-patterns.com/patterns/dual-use-tool-design.md\n\n### durable-execution-step-checkpointing\nDurable Execution & Step Checkpointing: Replays a durable step history to resume crashed, rate-limited, or approval-paused agent runs from the last completed step, without repeating finished LLM calls or committed side effects\nURL: https://agentic-patterns.com/patterns/durable-execution-step-checkpointing\nMarkdown: https://agentic-patterns.com/patterns/durable-execution-step-checkpointing.md\n\n### dynamic-context-injection\nDynamic Context Injection: Lets users inject files, folders, or saved prompts into the agent's context mid-session with @-mentions and custom slash commands\nURL: https://agentic-patterns.com/patterns/dynamic-context-injection\nMarkdown: https://agentic-patterns.com/patterns/dynamic-context-injection.md\n\n### egress-lockdown-no-exfiltration-channel\nEgress Lockdown (No-Exfiltration Channel): Puts the agent behind a default-deny egress firewall with allowlisted destinations so stolen data has no outbound channel\nURL: https://agentic-patterns.com/patterns/egress-lockdown-no-exfiltration-channel\nMarkdown: https://agentic-patterns.com/patterns/egress-lockdown-no-exfiltration-channel.md\n\n### episodic-memory-retrieval-injection\nEpisodic Memory Retrieval & Injection: Writes a structured memory record after each episode and injects the top-k similar past memories as hints when a new task starts\nURL: https://agentic-patterns.com/patterns/episodic-memory-retrieval-injection\nMarkdown: https://agentic-patterns.com/patterns/episodic-memory-retrieval-injection.md\n\n### evidence-questions-not-verdict-questions\nEvidence Questions, Not Verdict Questions: Never ask the model for allow/ask/block. Ask it narrow, typed, observational questions and let code reduce the answers to the verdict, because the collapsed question is the low-confidence one.\nURL: https://agentic-patterns.com/patterns/evidence-questions-not-verdict-questions\nMarkdown: https://agentic-patterns.com/patterns/evidence-questions-not-verdict-questions.md\n\n### evidence-layered-evaluation-for-interactive-agents\nEvidence-Layered Evaluation for Interactive Agents: Scores interactive agent runs on a task outcome assertion and links each result to layered evidence: actions, screenshots, replays, network, and messages\nURL: https://agentic-patterns.com/patterns/evidence-layered-evaluation-for-interactive-agents\nMarkdown: https://agentic-patterns.com/patterns/evidence-layered-evaluation-for-interactive-agents.md\n\n### exact-action-authorization-binding\nExact-Action Authorization Binding: Bind a short-lived approval to the complete action presented to the reviewer, rederive and compare that identity at the acting boundary before execution, and commit the write with its postcondition check and idempotency receipt in one transaction.\nURL: https://agentic-patterns.com/patterns/exact-action-authorization-binding\nMarkdown: https://agentic-patterns.com/patterns/exact-action-authorization-binding.md\n\n### explicit-posterior-sampling-planner\nExplicit Posterior-Sampling Planner: Embeds Posterior Sampling for RL in the LLM's reasoning: sample a task model, plan, act, observe reward, and update the posterior\nURL: https://agentic-patterns.com/patterns/explicit-posterior-sampling-planner\nMarkdown: https://agentic-patterns.com/patterns/explicit-posterior-sampling-planner.md\n\n### extended-coherence-work-sessions\nExtended Coherence Work Sessions: Combines models with long coherence windows with context compaction, prompt caching, and persisted state so agents stay on task for hours\nURL: https://agentic-patterns.com/patterns/extended-coherence-work-sessions\nMarkdown: https://agentic-patterns.com/patterns/extended-coherence-work-sessions.md\n\n### external-credential-sync\nExternal Credential Sync: Reads AI credentials from other tools' keychains and config files and syncs them into the agent's store, with TTL-cached reads, refresh fences, and persisted ownership\nURL: https://agentic-patterns.com/patterns/external-credential-sync\nMarkdown: https://agentic-patterns.com/patterns/external-credential-sync.md\n\n### factory-over-assistant\nFactory over Assistant: Spawns several autonomous agents in parallel with automated feedback loops such as tests and builds, and checks on them later instead of watching one agent\nURL: https://agentic-patterns.com/patterns/factory-over-assistant\nMarkdown: https://agentic-patterns.com/patterns/factory-over-assistant.md\n\n### failover-aware-model-fallback\nFailover-Aware Model Fallback: Classifies each model failure by reason and falls back along a model chain only for retryable errors, failing fast on auth, billing, and user aborts\nURL: https://agentic-patterns.com/patterns/failover-aware-model-fallback\nMarkdown: https://agentic-patterns.com/patterns/failover-aware-model-fallback.md\n\n### fair-share-task-queues-with-heartbeat-leases\nFair-Share Task Queues with Heartbeat Leases: Distributes tasks across a shared agent fleet using weighted deficit-round-robin scheduling, with heartbeat leases and dead-letter retries to recover from crashed workers\nURL: https://agentic-patterns.com/patterns/fair-share-task-queues-with-heartbeat-leases\nMarkdown: https://agentic-patterns.com/patterns/fair-share-task-queues-with-heartbeat-leases.md\n\n### feature-list-as-immutable-contract\nFeature List as Immutable Contract: Defines every feature up front in a JSON list with acceptance steps; the agent may only flip a feature to passing after it verifies it\nURL: https://agentic-patterns.com/patterns/feature-list-as-immutable-contract\nMarkdown: https://agentic-patterns.com/patterns/feature-list-as-immutable-contract.md\n\n### filesystem-based-agent-state\nFilesystem-Based Agent State: Agents persist intermediate results and working state to files, creating durable checkpoints that enable workflow resumption, recovery from failures, and support for long-running tasks.\nURL: https://agentic-patterns.com/patterns/filesystem-based-agent-state\nMarkdown: https://agentic-patterns.com/patterns/filesystem-based-agent-state.md\n\n### filesystem-mediated-host-delegation\nFilesystem-Mediated Host Delegation: Lets a sandboxed agent write request files to a shared spool directory that a host daemon runs against a whitelist, with idempotent results the agent polls for\nURL: https://agentic-patterns.com/patterns/filesystem-mediated-host-delegation\nMarkdown: https://agentic-patterns.com/patterns/filesystem-mediated-host-delegation.md\n\n### fleet-cost-simulation-before-dispatch\nFleet Cost Simulation Before Dispatch: Replays an agent fleet's budget, priority, and failure-recovery policy against deterministic scenarios before committing real spend, so starvation and exhaustion verdicts arrive in CI instead of in production\nURL: https://agentic-patterns.com/patterns/fleet-cost-simulation-before-dispatch\nMarkdown: https://agentic-patterns.com/patterns/fleet-cost-simulation-before-dispatch.md\n\n### graph-of-thoughts\nGraph of Thoughts (GoT): Represents reasoning as a directed graph of thoughts so the model can branch, aggregate, refine, and revisit reasoning paths\nURL: https://agentic-patterns.com/patterns/graph-of-thoughts\nMarkdown: https://agentic-patterns.com/patterns/graph-of-thoughts.md\n\n### hook-based-safety-guard-rails\nHook-Based Safety Guard Rails for Autonomous Code Agents: Runs small shell scripts on PreToolUse and PostToolUse hooks to block destructive commands, lint edits, and warn on context use outside the agent's reasoning\nURL: https://agentic-patterns.com/patterns/hook-based-safety-guard-rails\nMarkdown: https://agentic-patterns.com/patterns/hook-based-safety-guard-rails.md\n\n### human-in-loop-approval-framework\nHuman-in-the-Loop Approval Framework: Systematically insert human approval gates for designated high-risk functions while maintaining agent autonomy for safe operations, with multi-channel approval interfaces and comprehensive audit trails.\nURL: https://agentic-patterns.com/patterns/human-in-loop-approval-framework\nMarkdown: https://agentic-patterns.com/patterns/human-in-loop-approval-framework.md\n\n### hybrid-gui-visual-grounding\nHybrid GUI & Visual Grounding: Grounds each GUI action in a filtered accessibility tree first, falls back to numbered visual marks or scaled coordinates only for what the tree cannot see, and confirms the effect of each action from a state diff before the next step\nURL: https://agentic-patterns.com/patterns/hybrid-gui-visual-grounding\nMarkdown: https://agentic-patterns.com/patterns/hybrid-gui-visual-grounding.md\n\n### hybrid-llm-code-workflow-coordinator\nHybrid LLM/Code Workflow Coordinator: Lets each workflow pick an LLM or a code script as its coordinator, so teams prototype with the LLM and move to reviewed code when determinism matters\nURL: https://agentic-patterns.com/patterns/hybrid-llm-code-workflow-coordinator\nMarkdown: https://agentic-patterns.com/patterns/hybrid-llm-code-workflow-coordinator.md\n\n### incident-to-eval-synthesis\nIncident-to-Eval Synthesis: Converts each production incident into executable eval cases with pass/fail criteria and gates future releases on them\nURL: https://agentic-patterns.com/patterns/incident-to-eval-synthesis\nMarkdown: https://agentic-patterns.com/patterns/incident-to-eval-synthesis.md\n\n### inference-healed-code-review-reward\nInference-Healed Code Review Reward: Replaces a binary tests-passed reward with a critic that scores correctness, style, performance, and security, explains low scores, and combines them\nURL: https://agentic-patterns.com/patterns/inference-healed-code-review-reward\nMarkdown: https://agentic-patterns.com/patterns/inference-healed-code-review-reward.md\n\n### inference-time-scaling\nInference-Time Scaling: Spends extra compute at inference time with best-of-N sampling, longer reasoning, self-refinement, search, and verification to improve output quality\nURL: https://agentic-patterns.com/patterns/inference-time-scaling\nMarkdown: https://agentic-patterns.com/patterns/inference-time-scaling.md\n\n### initializer-maintainer-dual-agent\nInitializer-Maintainer Dual Agent Architecture: Uses a one-time initializer agent to create the feature list, progress files, and bootstrap script, then a coding agent that resumes from them one feature per session\nURL: https://agentic-patterns.com/patterns/initializer-maintainer-dual-agent\nMarkdown: https://agentic-patterns.com/patterns/initializer-maintainer-dual-agent.md\n\n### intelligent-bash-tool-execution\nIntelligent Bash Tool Execution: Runs agent shell commands through a multi-mode executor that uses a PTY when needed, falls back to direct exec, and manages approvals, background jobs, and signals\nURL: https://agentic-patterns.com/patterns/intelligent-bash-tool-execution\nMarkdown: https://agentic-patterns.com/patterns/intelligent-bash-tool-execution.md\n\n### intent-level-cost-attribution\nIntent-Level Cost Attribution: Records every LLM call against the projectId/intentId/user key that caused it, at call time, so spend can be queried and enforced per work item instead of as an opaque total\nURL: https://agentic-patterns.com/patterns/intent-level-cost-attribution\nMarkdown: https://agentic-patterns.com/patterns/intent-level-cost-attribution.md\n\n### inversion-of-control\nInversion of Control: Gives the agent tools, a high-level objective, and guardrails, then lets it choose sequencing and recovery while humans set policy and review\nURL: https://agentic-patterns.com/patterns/inversion-of-control\nMarkdown: https://agentic-patterns.com/patterns/inversion-of-control.md\n\n### isolated-vm-per-rl-rollout\nIsolated VM per RL Rollout: Spin up an isolated virtual machine for each RL rollout to prevent cross-contamination between parallel agent executions, ensuring safe training with destructive tool access.\nURL: https://agentic-patterns.com/patterns/isolated-vm-per-rl-rollout\nMarkdown: https://agentic-patterns.com/patterns/isolated-vm-per-rl-rollout.md\n\n### iterative-multi-agent-brainstorming\nIterative Multi-Agent Brainstorming: Spawns several agents in parallel on the same problem, often with different perspectives, then merges their ideas into one set of options\nURL: https://agentic-patterns.com/patterns/iterative-multi-agent-brainstorming\nMarkdown: https://agentic-patterns.com/patterns/iterative-multi-agent-brainstorming.md\n\n### iterative-prompt-skill-refinement\nIterative Prompt & Skill Refinement: Combines a feedback channel, editable prompt documents, log-driven skill fixes, and usage dashboards to improve agent prompts and skills continuously\nURL: https://agentic-patterns.com/patterns/iterative-prompt-skill-refinement\nMarkdown: https://agentic-patterns.com/patterns/iterative-prompt-skill-refinement.md\n\n### judge-gated-finding-exchange-between-sub-agents\nJudge-Gated Finding Exchange Between Parallel Sub-Agents: Puts an append-only board between parallel sub-agents and lets a small judge decide what goes on it, who receives each note, and when a later note retracts an earlier one\nURL: https://agentic-patterns.com/patterns/judge-gated-finding-exchange-between-sub-agents\nMarkdown: https://agentic-patterns.com/patterns/judge-gated-finding-exchange-between-sub-agents.md\n\n### lane-based-execution-queueing\nLane-Based Execution Queueing: Routes work into named lanes, each with its own queue and concurrency limit, so sessions never interleave and background jobs never block users\nURL: https://agentic-patterns.com/patterns/lane-based-execution-queueing\nMarkdown: https://agentic-patterns.com/patterns/lane-based-execution-queueing.md\n\n### language-agent-tree-search-lats\nLanguage Agent Tree Search (LATS): Runs Monte Carlo Tree Search over reasoning steps, with the LLM generating candidate actions and scoring partial solutions to pick the best path\nURL: https://agentic-patterns.com/patterns/language-agent-tree-search-lats\nMarkdown: https://agentic-patterns.com/patterns/language-agent-tree-search-lats.md\n\n### layered-configuration-context\nLayered Configuration Context: Loads context files from enterprise, user, project, and local levels automatically and merges them into the agent's baseline context\nURL: https://agentic-patterns.com/patterns/layered-configuration-context\nMarkdown: https://agentic-patterns.com/patterns/layered-configuration-context.md\n\n### lethal-trifecta-threat-model\nLethal Trifecta Threat Model: Classifies each tool by private-data access, untrusted-content exposure, and external communication, and blocks any execution path that has all three\nURL: https://agentic-patterns.com/patterns/lethal-trifecta-threat-model\nMarkdown: https://agentic-patterns.com/patterns/lethal-trifecta-threat-model.md\n\n### llm-map-reduce-pattern\nLLM Map-Reduce Pattern: Processes each untrusted document in its own sandboxed LLM call with a constrained output, then aggregates the results with deterministic code\nURL: https://agentic-patterns.com/patterns/llm-map-reduce-pattern\nMarkdown: https://agentic-patterns.com/patterns/llm-map-reduce-pattern.md\n\n### llm-observability\nLLM Observability: Sends agent runs to an LLM observability platform for span-level traces of each LLM call and tool use, plus aggregate cost, latency, and success metrics\nURL: https://agentic-patterns.com/patterns/llm-observability\nMarkdown: https://agentic-patterns.com/patterns/llm-observability.md\n\n### llm-friendly-api-design\nLLM-Friendly API Design: Designs APIs with visible versions, self-descriptive names and schemas, simple calls, actionable errors, and few indirection levels so LLMs call them correctly\nURL: https://agentic-patterns.com/patterns/llm-friendly-api-design\nMarkdown: https://agentic-patterns.com/patterns/llm-friendly-api-design.md\n\n### local-first-credential-broker\nLocal-First Credential Broker: Keep raw secrets out of the agent process by injecting credentials at the network layer through a local broker, rather than handing the agent environment variables or config files.\nURL: https://agentic-patterns.com/patterns/local-first-credential-broker\nMarkdown: https://agentic-patterns.com/patterns/local-first-credential-broker.md\n\n### markdown-polis-coordination\nMarkdown Polis — Multi-Vendor Agent Coordination via Filesystem Constitution: Coordinates agents from different vendors through versioned markdown files: capability cards, work contracts, and bandit routing that learns from settled work\nURL: https://agentic-patterns.com/patterns/markdown-polis-coordination\nMarkdown: https://agentic-patterns.com/patterns/markdown-polis-coordination.md\n\n### mcp-pattern-injection\nMCP Pattern Injection: Runs an MCP server that exposes framework best-practice patterns as tools, so the coding assistant fetches current patterns on demand\nURL: https://agentic-patterns.com/patterns/mcp-pattern-injection\nMarkdown: https://agentic-patterns.com/patterns/mcp-pattern-injection.md\n\n### memory-consolidation-decay-contradiction\nMemory Consolidation, Decay & Contradiction Resolution: Gives each stored fact a lifecycle: reconciles each new fact against the related stored facts when it arrives, stamps facts with event time and ingestion time so that a superseded fact is invalidated and not deleted, and runs a background job that merges duplicates and expires spent state\nURL: https://agentic-patterns.com/patterns/memory-consolidation-decay-contradiction\nMarkdown: https://agentic-patterns.com/patterns/memory-consolidation-decay-contradiction.md\n\n### memory-reinforcement-learning-memrl\nMemory Reinforcement Learning (MemRL): Stores memories with learned utility scores, retrieves by similarity then re-ranks by utility, and updates scores from outcomes while the LLM stays frozen\nURL: https://agentic-patterns.com/patterns/memory-reinforcement-learning-memrl\nMarkdown: https://agentic-patterns.com/patterns/memory-reinforcement-learning-memrl.md\n\n### memory-synthesis-from-execution-logs\nMemory Synthesis from Execution Logs: Has the agent write a structured diary per task, then runs synthesis agents over many diaries to turn recurring patterns into rules, commands, and tests\nURL: https://agentic-patterns.com/patterns/memory-synthesis-from-execution-logs\nMarkdown: https://agentic-patterns.com/patterns/memory-synthesis-from-execution-logs.md\n\n### merged-code-language-skill-model\nMerged Code + Language Skill Model: Fine-tunes separate language and code specialists from the same base model, then merges their weights into one model instead of one large joint training run\nURL: https://agentic-patterns.com/patterns/merged-code-language-skill-model\nMarkdown: https://agentic-patterns.com/patterns/merged-code-language-skill-model.md\n\n### milestone-escrow-agent-funding\nMilestone Escrow for Agent Resource Funding: Holds agent funding in escrow and releases each payment only after independent verification of a measurable milestone\nURL: https://agentic-patterns.com/patterns/milestone-escrow-agent-funding\nMarkdown: https://agentic-patterns.com/patterns/milestone-escrow-agent-funding.md\n\n### multi-model-orchestration-for-complex-edits\nMulti-Model Orchestration for Complex Edits: Splits complex code edits across specialized models: a retrieval model gathers context, a large model writes the changes, and smaller models apply them\nURL: https://agentic-patterns.com/patterns/multi-model-orchestration-for-complex-edits\nMarkdown: https://agentic-patterns.com/patterns/multi-model-orchestration-for-complex-edits.md\n\n### multi-platform-communication-aggregation\nMulti-Platform Communication Aggregation: Queries every communication platform in parallel through adapters that share one schema, then merges, deduplicates, and ranks the results\nURL: https://agentic-patterns.com/patterns/multi-platform-communication-aggregation\nMarkdown: https://agentic-patterns.com/patterns/multi-platform-communication-aggregation.md\n\n### multi-platform-webhook-triggers\nMulti-Platform Webhook Triggers: Starts agent workflows from Slack, Notion, and Jira webhooks, emoji reactions, and schedules, with idempotency and signature checks on each event\nURL: https://agentic-patterns.com/patterns/multi-platform-webhook-triggers\nMarkdown: https://agentic-patterns.com/patterns/multi-platform-webhook-triggers.md\n\n### multi-tenant-agent-isolation\nMulti-Tenant Agent & Memory Isolation: Enforces a tenant boundary on all four agent state planes (execution, retrieval and memory, cache, credential and egress), with tenant identity bound outside the model, so that one tenant's data or instructions cannot reach another\nURL: https://agentic-patterns.com/patterns/multi-tenant-agent-isolation\nMarkdown: https://agentic-patterns.com/patterns/multi-tenant-agent-isolation.md\n\n### non-custodial-spending-controls\nNon-Custodial Spending Controls: Puts a policy layer between the agent and the transaction signer that checks each intent against allowlists, budgets, and rate limits, and fails closed\nURL: https://agentic-patterns.com/patterns/non-custodial-spending-controls\nMarkdown: https://agentic-patterns.com/patterns/non-custodial-spending-controls.md\n\n### non-generative-judgment-routing\nNon-Generative Judgment Routing with Typed Escalation: Sends decision-only loop steps as batched typed questions to a non-generative judgment model and escalates what it cannot answer back to the LLM\nURL: https://agentic-patterns.com/patterns/non-generative-judgment-routing\nMarkdown: https://agentic-patterns.com/patterns/non-generative-judgment-routing.md\n\n### one-os-user-per-agent\nOne OS User per Agent: Give each long-lived agent its own OS user account and a templated init-system unit, so identity, supervision and privilege come from the host instead of from a per-agent container.\nURL: https://agentic-patterns.com/patterns/one-os-user-per-agent\nMarkdown: https://agentic-patterns.com/patterns/one-os-user-per-agent.md\n\n### opponent-processor-multi-agent-debate\nOpponent Processor / Multi-Agent Debate Pattern: Spawns agents with opposing roles on the same context, lets them critique each other, then synthesizes their positions to expose bias and blind spots\nURL: https://agentic-patterns.com/patterns/opponent-processor-multi-agent-debate\nMarkdown: https://agentic-patterns.com/patterns/opponent-processor-multi-agent-debate.md\n\n### oracle-and-worker-multi-model\nOracle and Worker Multi-Model Approach: Uses a fast, low-cost worker model for most tool use and code generation, and lets it consult an expensive oracle model when it is stuck\nURL: https://agentic-patterns.com/patterns/oracle-and-worker-multi-model\nMarkdown: https://agentic-patterns.com/patterns/oracle-and-worker-multi-model.md\n\n### orchestration-prompt-writing-benchmark\nOrchestration Prompt-Writing Benchmark: Scores an orchestrator on whether its sub-agent prompts give the right information fragments to the right roles, separate from end-task success\nURL: https://agentic-patterns.com/patterns/orchestration-prompt-writing-benchmark\nMarkdown: https://agentic-patterns.com/patterns/orchestration-prompt-writing-benchmark.md\n\n### out-of-process-provider-boundary-replay\nOut-of-Process Provider-Boundary Replay: Capture an agent run at the model-provider HTTP boundary from outside the process, then serve those bytes back so the agent re-executes its own logic with no provider call.\nURL: https://agentic-patterns.com/patterns/out-of-process-provider-boundary-replay\nMarkdown: https://agentic-patterns.com/patterns/out-of-process-provider-boundary-replay.md\n\n### output-verification-loop\nOutput Verification Loop: Verify LLM outputs by extracting individual claims, checking each against evidence sources, and returning per-claim trust scores before acting on the resu\n\n<!-- File: .claude/skills/arxiv-pattern-discovery/RUBRIC.md (Tokens: ~1205 | Category: anthropic-skill) -->\n# Pattern Quality Rubric\n\nReference for the Pattern Quality Rubric used to score arXiv papers for pattern extraction potential.\n\n## Overview\n\nPapers are scored on a scale of 0-10 using five weighted criteria. Only papers scoring >= 5.0 qualify for pattern extraction.\n\n## Scoring Criteria\n\n| Criterion | Weight | Description | Levels |\n|-----------|--------|-------------|--------|\n| **Reusability** | 30% | How widely applicable is the pattern? | Domain-specific (1.0) → Multi-domain (2.0) → Universal (3.0) |\n| **Novelty** | 25% | How new is the approach? | Existing (1.0) → Incremental (2.0) → Fundamentally new (3.0) |\n| **Clarity** | 20% | How well is it described? | Vague (1.0) → Clear (2.0) → Crystal clear (3.0) |\n| **Evidence** | 15% | Is there empirical validation? | No eval (1.0) → Some eval (2.0) → Strong empirical (3.0) |\n| **Completeness** | 10% | How complete is the implementation? | Idea only (1.0) → Partial details (2.0) → Production-ready (3.0) |\n\n## Detailed Scoring\n\n### Reusability (30% weight)\n\n| Score | Level | Indicators |\n|-------|-------|------------|\n| 1.0 | Domain-specific | \"specific to\", \"in the field of\", \"domain-specific\" |\n| 2.0 | Multi-domain | \"multi-domain\", \"cross-domain\", \"versatile\", \"adaptable\" |\n| 3.0 | Universal | \"general\", \"universal\", \"framework\", \"generic\", \"wide range\", \"variety of\" |\n\n### Novelty (25% weight)\n\n| Score | Level | Indicators |\n|-------|-------|------------|\n| 1.0 | Existing | No novelty indicators, describes existing approaches |\n| 2.0 | Incremental | \"improves\", \"extends\", \"builds on\", \"enhances\", \"optimizes\", \"refines\" |\n| 3.0 | Fundamentally new | \"novel\", \"new architecture\", \"new framework\", \"first to\", \"pioneering\", \"groundbreaking\" |\n\n### Clarity (20% weight)\n\n| Score | Level | Indicators |\n|-------|-------|------------|\n| 1.0 | Vague | \"may\", \"might\", \"potentially\", \"could be\", \"some ways\" |\n| 2.0 | Clear | \"we propose\", \"our approach\", \"the method\", abstract 100-150 words |\n| 3.0 | Crystal clear | Multiple clear indicators + abstract >150 words + concrete language |\n\n### Evidence (15% weight)\n\n| Score | Level | Indicators |\n|-------|-------|------------|\n| 1.0 | No eval | No evaluation or experiment mentioned |\n| 2.0 | Some eval | \"evaluation\", \"experiment\", \"benchmark\", \"results\", \"dataset\" |\n| 3.0 | Strong empirical | \"significant improvement\", \"state-of-the-art\", \"outperforms\", \"empirical\", \"real-world\" |\n\n### Completeness (10% weight)\n\n| Score | Level | Indicators |\n|-------|-------|------------|\n| 1.0 | Idea only | No implementation mentioned |\n| 1.5 | Partial idea | \"algorithm\", \"method\", \"approach\" mentioned |\n| 2.0 | Partial details | Implementation details or architecture described |\n| 3.0 | Production-ready | \"implementation\", \"open source\", \"code available\", \"github\", \"production\", \"deployed\" |\n\n## Score Calculation\n\nThe total score is calculated as a weighted sum:\n\n```\nTotal = (Reusability × 0.30) + (Novelty × 0.25) + (Clarity × 0.20) + (Evidence × 0.15) + (Completeness × 0.10)\n```\n\nMaximum possible score: 10.0\n\n## Threshold\n\n- **Score >= 5.0**: Qualifies for pattern extraction\n- **Score >= 7.0**: High-quality candidate, prioritize for extraction\n- **Score >= 8.5**: Exceptional candidate, immediate extraction recommended\n\n## Example Scoring\n\n### Example 1: High-quality paper (8.5)\n\n| Criterion | Score | Weighted |\n|-----------|-------|----------|\n| Reusability | 3.0 (Universal) | 0.90 |\n| Novelty | 3.0 (Fundamentally new) | 0.75 |\n| Clarity | 2.5 (Very clear) | 0.50 |\n| Evidence | 2.0 (Some eval) | 0.30 |\n| Completeness | 2.0 (Partial details) | 0.20 |\n| **Total** | | **8.5/10** |\n\n### Example 2: Marginal paper (5.2)\n\n| Criterion | Score | Weighted |\n|-----------|-------|----------|\n| Reusability | 2.0 (Multi-domain) | 0.60 |\n| Novelty | 2.0 (Incremental) | 0.50 |\n| Clarity | 2.0 (Clear) | 0.40 |\n| Evidence | 1.5 (Some eval) | 0.23 |\n| Completeness | 1.0 (Idea only) | 0.10 |\n| **Total** | | **5.2/10** |\n\n<!-- File: .claude/skills/arxiv-pattern-discovery/SKILL.md (Tokens: ~1173 | Category: anthropic-skill) -->\n---\nname: arxiv-pattern-discovery\ndescription: Search arXiv for academic papers describing agentic AI patterns. Use when user asks to find new patterns from academic literature, search arXiv, discover patterns from papers, or review academic sources for pattern extraction.\n---\n\n# arXiv Pattern Discovery\n\nSearch arXiv for academic papers describing agentic AI patterns and score them using the Pattern Quality Rubric.\n\n## Quick Start\n\nInvoke this skill when the user asks to:\n- Search arXiv for new agent patterns\n- Find academic papers about multi-agent orchestration\n- Discover patterns from academic literature\n- Review the latest papers for extractable patterns\n- What new patterns are emerging from recent AI research?\n\n## Workflow\n\nThis skill implements a 3-phase discovery workflow:\n\n### Phase 1: Discovery\n```bash\n# Search for recent papers (last 30 days, max 50 results)\npython scripts/arxiv_scanner.py --days=30 --max-results=50 --export-md results.md\n\n# Search for specific topics\npython scripts/arxiv_scanner.py --query=\"multi-agent systems\" --max-results=100\n\n# Search with minimum quality threshold\npython scripts/arxiv_scanner.py --min-score=7.0 --export-md high-quality.md\n```\n\n### Phase 2: Review\n- Read the exported Markdown report\n- Identify high-quality papers (score >= 7.0)\n- Check for potential duplicates flagged by the scanner\n- Select candidates for pattern extraction\n\n### Phase 3: Next Steps\n- Use the `create-pattern` skill to extract patterns from selected papers\n- Or manually create patterns using `patterns/TEMPLATE.md`\n- Run the similarity checker before committing to avoid duplicates\n- Run the validator to ensure pattern quality\n\n## Script Reference\n\n### arxiv_scanner.py\n\nMain script for querying arXiv API and scoring papers.\n\n**Usage:**\n```bash\npython scripts/arxiv_scanner.py [OPTIONS]\n```\n\n**Options:**\n- `--query, -q`: arXiv search query (default: agent/agentic/multi-agent papers)\n- `--max-results, -n`: Maximum results to fetch (default: 100)\n- `--days, -d`: Only include papers from last N days (default: 365)\n- `--min-score, -m`: Minimum quality score to include (default: 5.0)\n- `--export-json`: Export results to JSON file\n- `--export-md`: Export results to Markdown file\n- `--patterns-dir`: Path to patterns directory (default: patterns)\n- `--verbose, -v`: Print detailed output for each paper\n\n**Examples:**\n```bash\n# Recent high-quality papers\npython scripts/arxiv_scanner.py --days=7 --min-score=7.0\n\n# Search specific topic\npython scripts/arxiv_scanner.py --query=\"multi-agent orchestration\" --max-results=50\n\n# Full scan with export\npython scripts/arxiv_scanner.py --days=30 --export-md arxiv_report.md --verbose\n```\n\n### pattern_similarity_checker.py\n\nDetect potentially duplicate or very similar patterns.\n\n**Usage:**\n```bash\n# Check a single pattern against existing patterns\npython scripts/pattern_similarity_checker.py patterns/new-pattern.md\n\n# Check all patterns against each other\npython scripts/pattern_similarity_checker.py --all\n\n# Custom threshold and export\npython scripts/pattern_similarity_checker.py --all --threshold=0.7 --export report.md\n```\n\n**Options:**\n- `--all, -a`: Check all patterns against each other\n- `--patterns-dir, -d`: Path to patterns directory (default: patterns)\n- `--threshold, -t`: Similarity threshold for reporting (default: 0.5)\n- `--export, -e`: Export report to Markdown file\n\n### pattern_validator.py\n\nValidate pattern files for completeness and quality.\n\n**Usage:**\n```bash\n# Validate a single pattern\npython scripts/pattern_validator.py patterns/new-pattern.md\n\n# Validate all patterns\npython scripts/pattern_validator.py --all --verbose\n\n# Export validation report\npython scripts/pattern_validator.py --all --export validation_report.md\n```\n\n**Options:**\n- `--all, -a`: Validate all pattern files\n- `--patterns-dir, -d`: Path to patterns directory (default: patterns)\n- `--verbose, -v`: Print detailed output for each issue\n- `--strict, -s`: Treat warnings as errors\n- `--export, -e`: Export report to Markdown file\n\n## Next Steps After Discovery\n\nAfter identifying candidate papers from arXiv:\n\n1. **Extract the Pattern**: Use the `create-pattern` skill with the paper URL or PDF\n2. **Validate**: Run `pattern_validator.py` on the new pattern file\n3. **Check for Duplicates**: Run `pattern_similarity_checker.py` on the new pattern\n4. **Review**: Ensure the pattern meets the quality threshold (score >= 5.0)\n5. **Commit**: Add the pattern to the repository\n\n## Quality Scoring\n\nPapers are scored using the Pattern Quality Rubric (see RUBRIC.md for details):\n\n- **Reusability (30%)**: Domain-specific → Multi-domain → Universal\n- **Novelty (25%)**: Existing → Incremental → Fundamentally new\n- **Clarity (20%)**: Vague → Clear → Crystal clear\n- **Evidence (15%)**: No eval → Some eval → Strong empirical\n- **Completeness (10%)**: Idea only → Partial details → Production-ready\n\n**Threshold**: Score >= 5.0 qualifies for pattern extraction\n\n<!-- File: .claude/skills/arxiv-pattern-discovery/WORKFLOW.md (Tokens: ~1192 | Category: anthropic-skill) -->\n# arXiv Pattern Discovery Workflow\n\nEnd-to-end workflow for discovering agentic patterns from academic literature on arXiv.\n\n## Overview\n\nThis workflow guides you through the process of discovering new agentic patterns from academic papers:\n\n1. **Discovery** - Search arXiv and score papers\n2. **Review** - Identify high-quality candidates\n3. **Extract** - Create patterns from selected papers (user-driven)\n\n---\n\n## Phase 1: Discovery\n\n### Step 1.1: Run the arXiv Scanner\n\nSearch for recent papers with agentic patterns:\n\n```bash\n# Recent papers (last 30 days)\npython scripts/arxiv_scanner.py --days=30 --max-results=50 --export-md arxiv_results.md\n\n# All-time papers with higher quality threshold\npython scripts/arxiv_scanner.py --max-results=100 --min-score=7.0 --export-md high_quality.md\n\n# Specific topic search\npython scripts/arxiv_scanner.py --query=\"multi-agent memory systems\" --max-results=50 --export-md memory_patterns.md\n```\n\n### Step 1.2: Review the Output\n\nThe scanner produces:\n- Console output with top 10 papers by quality score\n- Optional Markdown report (with `--export-md`)\n- Optional JSON export (with `--export-json`)\n\nEach paper includes:\n- **Title**, **arXiv ID**, **URL**\n- **Quality Score** (0-10) with breakdown\n- **Suggested Category** (based on keywords)\n- **Extracted Tags**\n- **Abstract**\n- **Potential Duplicates** warning (if applicable)\n\n### Step 1.3: Filter Candidates\n\nFilter papers by:\n- **Quality Score**: Focus on papers >= 7.0 for best results\n- **Category**: Group by your area of interest\n- **Duplicate Warnings**: Skip papers flagged as duplicates\n\n---\n\n## Phase 2: Review\n\n### Step 2.1: Read the Markdown Report\n\nOpen the exported Markdown file and review candidates:\n\n```bash\n# View the report\ncat arxiv_results.md\n# or open in your editor\ncode arxiv_results.md\n```\n\n### Step 2.2: Visit Paper URLs\n\nFor each high-scoring paper:\n1. Click the arXiv URL to read the full paper\n2. Focus on the \"architecture\" or \"method\" section\n3. Look for reusable patterns (not just single techniques)\n\n### Step 2.3: Select Extraction Candidates\n\nPrioritize papers with:\n- Score >= 7.0 (high quality)\n- Clear architectural description\n- Novel approach not yet in the pattern catalog\n- Universal or multi-domain applicability\n\n---\n\n## Phase 3: Extract (User-Driven)\n\nAfter selecting candidate papers, you have two options:\n\n### Option A: Use the create-pattern Skill\n\nThe `create-pattern` skill can extract patterns from:\n- arXiv URLs\n- PDF files\n- Blog posts\n- Code repositories\n\n```\n# Ask Claude to extract a pattern from a paper\n\"Use create-pattern to extract a pattern from https://arxiv.org/abs/2401.12345\"\n```\n\n### Option B: Manual Pattern Creation\n\n1. Copy the template:\n   ```bash\n   cp patterns/TEMPLATE.md patterns/my-new-pattern.md\n   ```\n\n2. Fill in the required fields:\n   - `title`: Descriptive pattern name\n   - `status`: Based on quality score and evidence\n   - `authors`: Paper authors (@arxiv)\n   - `based_on`: Paper title (arXiv link)\n   - `category`: From the scanner's suggestion\n   - `source`: arXiv URL\n   - `tags`: From the scanner's extraction\n\n3. Write the pattern sections:\n   - **Problem**: What problem does this pattern solve?\n   - **Solution**: How does the architecture work?\n   - **Example**: Include a Mermaid diagram\n   - **References**: Link to the paper\n\n---\n\n## Phase 4: Validate (Before Committing)\n\n### Step 4.1: Check for Duplicates\n\n```bash\npython scripts/pattern_similarity_checker.py patterns/my-new-pattern.md\n```\n\nIf similarity > 0.7, consider:\n- Merging with existing pattern\n- Finding a more specific angle\n- Marking as variant of existing pattern\n\n### Step 4.2: Validate Quality\n\n```bash\npython scripts/pattern_validator.py patterns/my-new-pattern.md\n```\n\nFix any errors before committing.\n\n---\n\n## Example Session\n\n```bash\n# Step 1: Search arXiv\npython scripts/arxiv_scanner.py --days=30 --min-score=7.0 --export-md candidates.md\n\n# Output:\n# Scanning arXiv...\n# Fetched 100 papers\n# Filtered to 15 papers within last 30 days\n# Papers meeting threshold (7.0): 8\n\n# Step 2: Review the markdown report\ncat candidates.md\n\n# Step 3: Extract a pattern (using create-pattern skill)\n# \"Extract a pattern from https://arxiv.org/abs/2401.12345\"\n\n# Step 4: Validate\npython scripts/pattern_similarity_checker.py patterns/hierarchical-memory.md\npython scripts/pattern_validator.py patterns/hierarchical-memory.md\n```\n\n---\n\n## Tips for Success\n\n1. **Quality Over Quantity**: Focus on papers scoring >= 7.0\n2. **Avoid Duplicates**: Always run the similarity checker before committing\n3. **Validate Early**: Run the validator to catch issues early\n4. **Use the Rubric**: Understand why papers score the way they do (see RUBRIC.md)\n5. **Be Selective**: Not every good paper deserves a pattern—focus on reusable architectures\n\n<!-- File: .claude/skills/create-pattern/PATTERN_INDEX.md (Tokens: ~827 | Category: anthropic-skill) -->\n# Pattern Index\n\nQuick reference for all 105+ patterns in the repository for semantic matching.\n\n## Category Summary\n\n| Category | Count | Key Themes |\n|----------|-------|------------|\n| Orchestration & Control | 32 | Task decomposition, sub-agents, tool routing |\n| Tool Use & Environment | 20 | Shell, browser, DB, sandbox tools |\n| UX & Collaboration | 16 | Prompts, hand-offs, staged commits |\n| Context & Memory | 14 | Window curation, vector cache, episodic memory |\n| Feedback Loops | 12 | CI, review, self-healing |\n| Reliability & Eval | 10 | Guardrails, evals, logging |\n| Security & Safety | 3 | Isolation, PII, scanning |\n| Learning & Adaptation | 3 | Agent RFT, skill libraries |\n\n## Common Tags (appear 4+ times)\n\n- tool-use, security, search, reinforcement-learning, reasoning\n- feedback, prompt-injection, planning, mcp, learning, evaluation\n- coding-agent, code-review, cli, automation\n\n## Pattern Clusters (for Matching)\n\n### Context Management Patterns\n- `context-minimization-pattern.md`\n- `context-window-anxiety-management.md`\n- `curated-code-context-window.md`\n- `layered-configuration-context.md`\n- `agentic-search-over-vector-embeddings.md`\n\n### Planning Patterns\n- `plan-then-execute-pattern.md`\n- `explicit-posterior-sampling-planner.md`\n- `tree-of-thought-reasoning.md`\n\n### Multi-Agent Patterns\n- `oracle-and-worker-multi-model.md`\n- `initializer-maintainer-dual-agent.md`\n- `sub-agent-spawning.md`\n- `continuous-autonomous-task-loop-pattern.md`\n\n### Memory/State Patterns\n- `episodic-memory-retrieval-injection.md`\n- `filesystem-based-agent-state.md`\n- `proactive-agent-state-externalization.md`\n\n### Security Patterns\n- `action-selector-pattern.md`\n- `egress-lockdown-no-exfiltration-channel.md`\n- `pii-tokenization.md`\n\n### Code Review Patterns\n- `criticgpt-style-evaluation.md`\n- `ai-assisted-code-review-verification.md`\n- `abstracted-code-representation-for-review.md`\n\n### Progressive Autonomy Chain\n- `progressive-autonomy-with-model-evolution.md`\n- `progressive-complexity-escalation.md`\n- `skill-library-evolution.md`\n\n### Tool Design Patterns\n- `dual-use-tool-design.md`\n- `tool-use-steering-via-prompting.md`\n- `tool-use-incentivization-via-reward-shaping.md`\n\n## Top Pattern Sources\n\n| Source | Patterns |\n|--------|----------|\n| Will Brown (Prime Intellect) | 8 patterns |\n| Boris Cherny (Anthropic) | 7 patterns |\n| Anthropic Engineering | 7 patterns |\n| Luca Beurer-Kellner et al. (2025) | 6 patterns |\n| Aman Sanger (Cursor) | 6 patterns |\n| Thorsten Ball | 5 patterns |\n| Quinn Slack | 5 patterns |\n| Lukas Möller (Cursor) | 5 patterns |\n\n## Matching Heuristics\n\nWhen analyzing a new source:\n\n1. **Check by author** - If source is from Will Brown, Boris Cherny, etc., likely matches existing pattern\n2. **Check by category** - Context management has 14 patterns with high overlap\n3. **Check by tags** - \"tool-use\", \"security\", \"reasoning\" indicate clusters\n4. **Problem similarity** - Same core challenge → likely existing pattern\n5. **Solution similarity** - Same mechanism → likely existing pattern\n\n## Decision Thresholds\n\n- **>80% confidence** - Update existing (same problem + solution + category)\n- **50-80% confidence** - Ask user (partial overlap)\n- **<50% confidence** - Create new (different problem/solution)\n\n<!-- File: .claude/skills/create-pattern/SKILL.md (Tokens: ~2256 | Category: anthropic-skill) -->\n---\nname: create-pattern\ndescription: Analyze sources (blog posts, PDFs, YouTube videos, codebases, pasted text) for agentic patterns, match against 105+ existing patterns, create new patterns or update existing with new sources and insights.\nallowed-tools:\n  - Read\n  - Write\n  - Glob\n  - Grep\n  - Bash\n  - mcp__web_reader__webReader\n  - mcp__4_5v_mcp__analyze_image\n---\n\n# Pattern Ingestion Skill\n\nThis skill intelligently analyzes sources for agentic AI patterns, matches them against existing patterns in the repository, and either creates new patterns or updates existing ones with additional sources and insights.\n\n## Overview\n\n**Input:** A source (URL, PDF file, YouTube link, codebase path, or pasted text)\n\n**Process:**\n1. Ingest and analyze the source\n2. Extract pattern concepts\n3. Match against existing 105+ patterns\n4. Decide: create new OR update existing\n5. Execute and build\n\n**Output:** New pattern file OR updated existing pattern + build confirmation\n\n---\n\n## Phase 1: Ingest Source\n\nDetect the input type and process accordingly:\n\n### URL (blog post, documentation, article)\nUse `mcp__web_reader__webReader` with the URL:\n```json\n{\"url\": \"USER_PROVIDED_URL\", \"return_format\": \"markdown\"}\n```\n\n### PDF File\nUse `Read` tool with the PDF path.\n\n### YouTube Video\nUse `mcp__web_reader__webReader` with the YouTube URL (transcript extraction).\n\n### Codebase/Repository\nUse `Glob` to find key files, then `Read` to analyze:\n- `**/*.md` - Documentation\n- `**/*.py` - Python implementation\n- `**/*.ts` - TypeScript implementation\n- README files\n\n### Pasted Text\nAnalyze directly (no tool needed).\n\n---\n\n## Phase 2: Analyze & Extract\n\nFrom the source content, extract:\n\n1. **Pattern Title** - What is this pattern called?\n2. **Problem Statement** - What challenge does it solve?\n3. **Solution** - What's the core approach/mechanism?\n4. **Category** - Which of 8 categories fits best?\n5. **Source URL** - The original source\n6. **Author/Originator** - Who created/originated this?\n7. **Tags** - 3+ relevant keywords\n8. **Key Insights** - Any novel techniques, constraints, trade-offs\n\n**Generate candidate metadata:**\n- Title: descriptive, concise\n- Category: select from allowed categories (see reference below)\n- Tags: generate 5-10 relevant tags\n- Status: default to \"emerging\" unless evidence suggests otherwise\n\n---\n\n## Phase 3: Match Against Existing Patterns\n\nSearch for similar patterns in `patterns/` directory:\n\n### Step 3a: Read All Pattern Frontmatter\nUse `Glob` to find all `.md` files in `patterns/`, then `Grep` with output_mode `content` to extract frontmatter from each:\n```bash\ngrep -A 10 \"^title:\" patterns/*.md\n```\n\nOr read multiple pattern files in parallel to compare:\n- Problem statements\n- Solution approaches\n- Categories\n- Tags\n- Sources\n\n### Step 3b: Semantic Comparison\n\nFor each existing pattern, assess similarity using these signals:\n\n**Primary Signals (weight: 30% each)**\n1. **Problem Statement** - Same fundamental challenge?\n2. **Solution Mechanism** - Same core approach/technique?\n3. **Category** - Same category?\n\n**Secondary Signals (weight: 10% each)**\n4. **Tag Overlap** - Shared keywords?\n5. **Source/Author** - Same contributor's follow-up work?\n6. **Title** - Similar naming/description?\n\n### Step 3c: Calculate Confidence Score\n\n```\nScore = Σ(matching_signals × weights)\n```\n\n- All 3 primary match → 90%+ confidence\n- 2 primary + 1+ secondary → 70-90% confidence\n- 1 primary + 2+ secondary → 50-70% confidence\n- 0-1 primary only → <50% confidence\n\n### Step 3d: Identify Top Matches\n\nList top 3 matching patterns with:\n- Pattern title and file path\n- Confidence score\n- Matching rationale (which signals matched)\n\n---\n\n## Phase 4: Decision\n\nBased on confidence score:\n\n### High Confidence (>80%) → Update Existing\nUpdate the top-matching existing pattern with new source.\n\n### Low Confidence (<50%) → Create New\nCreate a brand new pattern file.\n\n### Medium Confidence (50-80%) → Ask User\nPresent the top match and ask:\n\n```\nThis source seems related to:\n- [Match Pattern] (X% confidence)\n  - Similar problem: [problem summary]\n  - Similar solution: [solution summary]\n\nShould I:\n1. Create a new pattern\n2. Update the existing pattern with this new source\n```\n\n---\n\n## Phase 5a: Create New Pattern\n\n### Step 5a-1: Generate Metadata\n```yaml\n---\ntitle: \"Extracted Title\"\nstatus: emerging\nauthors: [\"Your Name (@yourusername)\"]\nbased_on: [\"Originator Name (Source/Context)\"]\ncategory: \"Selected Category\"\nsource: \"SOURCE_URL\"\ntags: [tag1, tag2, tag3, ...]\n---\n```\n\n### Step 5a-2: Generate Slug\nConvert title to kebab-case:\n- Lowercase\n- Spaces → hyphens\n- Remove special characters\n- Example: \"Tree of Thought Reasoning\" → `tree-of-thought-reasoning`\n\n### Step 5a-3: Write Pattern File\nCreate `patterns/{slug}.md` with structure:\n\n```markdown\n---\ntitle: \"Title\"\nstatus: emerging\nauthors: [\"Your Name (@yourusername)\"]\nbased_on: [\"Originator (Source)\"]\ncategory: \"Category\"\nsource: \"URL\"\ntags: [tag1, tag2, tag3]\n---\n\n## Problem\n[Extracted problem statement]\n\n## Solution\n[Extracted solution description]\n\n- Key components: [list]\n- Mechanism: [describe]\n\n```pseudo\n[Optional: pseudocode if helpful]\n```\n\n## How to use it\n[Extracted usage guidance]\n\n## Trade-offs\n[Extracted pros and cons]\n\n* **Pros:** [benefits]\n* **Cons:** [drawbacks]\n\n## References\n* [Original Source Title](URL)\n```\n\n---\n\n## Phase 5b: Update Existing Pattern\n\n### Step 5b-1: Read Existing Pattern\nRead the matched pattern file at `patterns/{existing-slug}.md`\n\n### Step 5b-2: Update Frontmatter\n\n**Add to `based_on` array:**\n```yaml\nbased_on:\n  - \"Existing Source (Existing Context)\"\n  - \"New Originator (New Source/Context)\"  # Add this\n```\n\n**Add new tags** (if not duplicates):\n```yaml\ntags:\n  - existing-tag\n  - new-tag-from-source  # Add unique new tags\n```\n\n### Step 5b-3: Add to References Section\n\nAppend to the `## References` section:\n```markdown\n## References\n* [Existing Source](existing-url)\n* [New Source Title](new-url)  # Add this\n```\n\n### Step 5b-4: Auto-Expand Content (If Applicable)\n\n**IF** the new source adds substantial new insights (not just a citation):\n\n**To Solution section:**\n```markdown\n## Solution\n[existing content...]\n\n**Additional insights from [New Source]:**\n[Extracted new insights with attribution]\n```\n\n**To How to use it section:**\n```markdown\n## How to use it\n[existing content...]\n\n**According to [New Source]:**\n[New usage guidance or implementation details]\n```\n\n**To Trade-offs section:**\n```markdown\n## Trade-offs\n* **Pros:** [existing..., new pros from source]\n* **Cons:** [existing..., new cons from source]\n```\n\n### Step 5b-5: Write Updated File\nWrite the updated content back to `patterns/{existing-slug}.md`\n\n---\n\n## Phase 6: Build\n\n### Step 6-1: Run Build Script\n```bash\ncd apps/web && bun run build-data\n```\n\n### Step 6-2: Verify Success\nCheck for:\n- Pattern JSON files updated in `apps/web/public/patterns/`\n- No error messages\n\n---\n\n## Reference: Allowed Values\n\n### Categories (8 options)\n- Orchestration & Control\n- Context & Memory\n- Feedback Loops\n- Learning & Adaptation\n- Reliability & Eval\n- Security & Safety\n- Tool Use & Environment\n- UX & Collaboration\n- Uncategorized\n\n### Status Values (7 options)\n- proposed - Initial concept\n- emerging - Early adoption\n- established - Proven approach\n- validated-in-production - Production-tested\n- best-practice - Industry standard\n- experimental-but-awesome - Novel but effective\n- rapidly-improving - Fast-evolving\n\n### Front-matter Template\n```yaml\n---\ntitle: \"Pattern Title\"\nstatus: emerging\nauthors: [\"Contributor Name (@username)\"]\nbased_on: [\"Originator Name (Source Context)\"]\ncategory: \"Category Name\"\nsource: \"https://example.com/source\"\ntags: [tag1, tag2, tag3]\n---\n```\n\n---\n\n## Output Summary\n\nAfter completion, provide:\n\n**For New Pattern:**\n```\n✅ Created new pattern: patterns/{slug}.md\n- Title: [title]\n- Category: [category]\n- Tags: [tags]\n\nNext steps:\n1. Review and edit the pattern file for completeness\n2. Run: cd apps/web && bun run dev\n3. Commit: git add patterns/{slug}.md\n```\n\n**For Updated Pattern:**\n```\n✅ Updated existing pattern: patterns/{slug}.md\n- Added source to based_on: [source]\n- Added [N] new tags\n- [Expanded Solution/How-to sections]\n\nNext steps:\n1. Review the updated pattern file\n2. Run: cd apps/web && bun run dev\n3. Commit: git add patterns/{slug}.md\n```\n\n---\n\n## Tips\n\n- **When in doubt, ask the user** - Pattern matching can be nuanced\n- **Preserve existing content** - When updating, don't remove or overwrite existing insights\n- **Clear attribution** - Always cite sources when adding new content\n- **Tag thoughtfully** - Tags help with future matching\n- **Check for duplicates** - If `based_on` already includes the source, just inform the user\n\n<!-- File: skills/pr-review/SKILL.md (Tokens: ~2271 | Category: anthropic-skill) -->\n---\nname: awesome-agentic-patterns-pr-review\ndescription: Review pull requests for the awesome-agentic-patterns repository. Use when asked to validate a PR, assess whether a contribution fits the repo, inspect pattern submissions under patterns/, check merge readiness, repair a small submission issue on top of a contributor branch, draft a polite contributor comment, or apply the repository's pattern-first and non-promotional contribution policy to a GitHub pull request.\n---\n\n# Awesome Agentic Patterns PR Review\n\n## Overview\n\nReview PRs in this repository by applying the local contribution policy and checking the actual changed files. Treat `CONTRIBUTING.md` as the source of truth for acceptance criteria, `TEMPLATE.md` as the source of truth for expected pattern structure, and the validation scripts in `scripts/` as the source of truth for structural checks and generated-file expectations.\n\n## Read First\n\n- `CONTRIBUTING.md`\n- `README.md`\n- `SCHEMA.md` for the status tiers and field definitions\n- `TEMPLATE.md` at the repository root\n- `scripts/validate-patterns.ts`, the authoritative front-matter and section validator\n- `scripts/build-data.ts` when the PR touches patterns, generated README sections, or generated site data\n\nDo not restate repo policy from memory when those files are available. Quote or summarize the repository's own rules instead.\n\n## Workflow\n\n### 1. Inspect the PR\n\nUse `gh` first:\n\n- `gh pr view <number> --repo nibzard/awesome-agentic-patterns --json title,number,state,isDraft,author,baseRefName,headRefName,headRepository,headRepositoryOwner,maintainerCanModify,files,additions,deletions,mergeable,mergeStateStatus,reviewDecision,statusCheckRollup,labels,url,body`\n- `gh pr diff <number> --repo nibzard/awesome-agentic-patterns --patch`\n- `gh pr checks <number> --repo nibzard/awesome-agentic-patterns`\n\nIf you need the exact branch locally, fetch it with:\n\n- `git fetch origin refs/pull/<number>/head:pr-<number>`\n\nCapture these facts before deciding anything:\n\n- Whether the PR is a new pattern submission, a pattern edit, or a broader repo/tooling change\n- Whether the change correctly uses `patterns/<slug>.md` rather than editing generated docs directly\n- Whether `README.md` or `apps/web/public/` generated outputs changed because the contributor regenerated outputs, or because they hand-edited generated files\n- Whether `maintainerCanModify` is enabled and which fork/branch must be updated if you need to fix the PR\n- Whether GitHub mergeability is trustworthy yet; `UNKNOWN` can be transient right after a push\n\n### 2. Validate the submission contract\n\nFor pattern submissions, check the repository's exact contract before debating fit:\n\n- One pattern per PR\n- New patterns live in `patterns/` and use kebab-case filenames\n- PR title should use `Add: pattern-name`\n- The pattern should be concise, roughly capped at about 200 lines\n- Do not edit README auto-generated sections manually\n- `docs/index.md` is only a compatibility symlink to `README.md`\n- Required front-matter fields (enforced by `scripts/validate-patterns.ts`):\n  `title`\n  `status`\n  `authors`\n  `category`\n  `source`\n  `tags`\n  `summary`\n  `signals`\n  `anti_signals`\n  `updated_at` in `YYYY-MM-DD` form\n- `based_on` is optional, but a contributor-owned source must be disclosed in `authors` / `based_on`\n- `source_link` is invalid here; use `source`\n- Required content sections (enforced with `--check-content`):\n  `## Problem`\n  `## Solution`\n  `## How to use it`\n  `## Trade-offs`\n  `## References`\n- Status tier, one of `proposed`, `emerging`, `production`, `foundational`, judged against the independent-adoption bar:\n\n  - A submission backed only by a contributor-owned repo, a personal experiment, or a launch-stage product must use `status: proposed`. Downgrade anything higher to `proposed`.\n  - `emerging` needs 2+ independent implementations or teams, or 1 detailed production write-up or major lab paper with active industry iteration.\n  - `production` needs proof across multiple independent production systems, with documented failure modes and operational trade-offs.\n  - `foundational` is for an industry-default baseline whenever its `signals` apply, and the catalogue keeps the tier to roughly 12-18 patterns.\n\n- Agent-centric technical scope: the pattern must describe a control loop in which an agent senses, reasons, remembers, uses tools, or stays safe. Product strategy, startup philosophy, career advice, and generic non-agent software architecture belong in `principles/`, not `patterns/`.\n- Known Implementations cap: `Known Implementations` and tool references are limited to 3-5 entries per pattern. A PR that only appends another vendor or tool link is acceptable only when the tool replaces a deprecated reference or demonstrates a materially distinct architectural variant.\n- Differentiation: the PR description must answer \"Closest existing pattern(s) & how this is distinct\" and justify why the idea cannot live as a section inside an existing pattern.\n\nBefore judging novelty, run `python3 scripts/pattern_similarity_checker.py <pattern-file.md>`, then search `patterns/` for duplicates and near-overlaps by title, tags, and Problem wording. Compare what you find with the contributor's differentiation answer. When the primary `source` or a reference belongs to the contributor or an affiliated project, confirm the relationship is disclosed and the write-up frames it as an example rather than the center of the PR.\n\nFor generated-file sync, check whether the PR also updated the outputs that CI compares against `patterns/*.md`:\n\n- `README.md`\n- `apps/web/public/data/patterns.json`\n- other generated files under `apps/web/public/` when the pattern catalog changed\n- `llms.txt` at the repository root, which `bun run build:data` keeps identical to `apps/web/public/llms.txt`\n\nCall out structural violations explicitly. These are repository requirements, not style nits.\n\n### 3. Apply local policy\n\nUse `CONTRIBUTING.md` for the actual acceptance rubric. Evaluate:\n\n- Whether the PR documents a reusable pattern rather than a product announcement\n- Whether the pattern is materially novel and non-repetitive relative to existing patterns\n- Whether the write-up clearly explains Problem, Solution, and Trade-offs or practical mechanics\n- Whether references are public and verifiable\n- Whether the contribution is community-first and non-promotional\n- Whether external links are mostly `github.com`, `github.io`, or neutral technical references for outside contributors\n- Whether any vendor or product links are justified by clear novelty rather than marketing\n- Whether contributor-owned projects are disclosed and framed as examples rather than the center of the PR\n- Whether the category is the best fit for existing repo taxonomy\n- Whether the `status` tier matches its objective criterion; a contributor-owned repo or launch-stage product is `proposed`\n- Whether the pattern is an agent-specific technical control loop rather than product strategy or generic software architecture\n- Whether the PR description names the closest existing pattern(s) and justifies why the submission is not a section inside one of them\n- Whether a reference-addition PR stays within the 3-5 entry cap and adds a tool that replaces a deprecated reference or shows a materially distinct variant\n\nSeparate policy fit from technical mergeability. A PR can be in scope but still need a maintainer fix before merge.\n\n### 4. Run structural validation\n\nWhen reviewing a local branch or checking CI behavior, run from the repository root:\n\n- `bun run validate:patterns:content` for front matter, required sections, referential integrity, status vs. evidence, and length guardrails; this is the authoritative validator, and CI runs it\n- `bun run validate:patterns` for front matter only (`scripts/validate-patterns.ts`)\n- `python3 scripts/pattern_similarity_checker.py <pattern-file.md>` to surface near-duplicates before you judge novelty\n- `bun run build:data` when checking generated README or site data changes; it also fails on a missing or malformed `updated_at`. CI syncs the root `llms.txt` alongside `README.md` and `apps/web/public/`.\n\nTreat the scripts as structural checks, not the decision-maker. Human review still decides repository fit, novelty, promotion risk, and category choice.\n\n### 5. Repair the branch when the PR is acceptable but stale\n\nIf the PR is acceptable and the user wants it fixed or merged, prefer the smallest possible maintainer correction:\n\n- Fetch the PR branch locally\n- Rebase or replay it onto `origin/main`\n- Fix only the minimum structural issue\n- Normalize front-matter keys or section headings to repo expectations\n- Regenerate `README.md` and site data with `bun run build:data` only if the PR already requires generated-file sync\n- Push back to the contributor's exact head branch, preferably with `--force-with-lease`\n- Re-check `gh pr view` after the push because `mergeable` and `mergeStateStatus` may temporarily show `UNKNOWN`\n\nDo not turn a small submission repair into a broader cleanup.\n\n### 6. Produce the review\n\nUse a code-review mindset:\n\n- Present findings first, ordered by severity, with file references when applicable\n- If there are no findings, say that explicitly\n- After findings, give one clear decision: `Accept`, `Request changes`, or `Close`\n- Include mergeability as a separate line: `clean`, `needs maintainer repair`, or `blocked`\n- When the user wants to merge, include the exact next action: `comment`, `fix and push`, `merge`, or `close`\n\n## Output Shape\n\nKeep the final review compact and consistent. Use this exact structure:\n\n`Summary`\n- One short sentence on PR state or scope if useful\n\n`Findings`\n- Findings first, ordered by severity\n- If there are no findings, say `No blocking findings.`\n\n`Decision`\n- `Policy fit: Accept | Request changes | Close`\n- `Mergeability: clean | needs maintainer repair | blocked`\n- `Recommended action: comment | fix and push | merge | close`\n\n`Proposed comment to contributor`\n- Draft a short, polite comment suitable for posting on the PR\n- If the maintainer already fixed the PR, say what was adjusted and thank the contributor\n- If requesting changes, state the minimum changes needed\n\n`What next`\n- End with a direct question to the user asking what they want next\n- Example: `Do you want me to post the comment, push the small fix, or merge it?`\n\n<!-- File: .claude/skills/arxiv-pattern-discovery/scripts/arxiv_scanner.py (Tokens: ~6584 | Category: claude-rule) -->\n#!/usr/bin/env python3\n\"\"\"\narxiv_scanner.py\n\nAutomated paper discovery for new agentic patterns from arXiv.\n\nQueries arXiv API with targeted search terms, filters by date/citation count/keywords,\nand scores papers using the Pattern Quality Rubric (0-10).\n\nUsage:\n    python scripts/arxiv_scanner.py --days=7 --min-citations=3\n    python scripts/arxiv_scanner.py --query=\"multi-agent systems\" --max-results=50\n\"\"\"\n\nimport argparse\nimport configparser\nimport dataclasses\nimport datetime\nimport json\nimport re\nimport sys\nimport time\nimport urllib.parse\nimport urllib.request\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Optional, Set\n\n\n# Configuration\nDEFAULT_SEARCH_QUERY = '(cat:cs.AI OR cat:cs.CL OR cat:cs.LG OR cat:cs.CR) AND all:\"agent\" OR all:\"agentic\" OR all:\"multi-agent\"'\nARXIV_API_URL = \"http://export.arxiv.org/api/query?\"\nUSER_AGENT = \"arxiv-scanner/0.1 (https://github.com/nibzard/awesome-agentic-patterns)\"\n\n\n# Valid status values for patterns\nVALID_STATUSES = {\n    \"proposed\",\n    \"emerging\",\n    \"established\",\n    \"validated-in-production\",\n    \"best-practice\",\n    \"experimental-but-awesome\",\n    \"rapidly-improving\",\n}\n\n# Valid category values\nVALID_CATEGORIES = {\n    \"Orchestration & Control\",\n    \"Context & Memory\",\n    \"Feedback Loops\",\n    \"Learning & Adaptation\",\n    \"Reliability & Eval\",\n    \"Security & Safety\",\n    \"Tool Use & Environment\",\n    \"UX & Collaboration\",\n    \"Uncategorized\",\n}\n\n\n@dataclasses.dataclass\nclass Paper:\n    \"\"\"Represents an arXiv paper with metadata.\"\"\"\n\n    arxiv_id: str\n    title: str\n    authors: List[str]\n    abstract: str\n    published: str\n    updated: str\n    categories: List[str]\n    url: str\n    citation_count: int = 0\n    quality_score: float = 0.0\n\n\n@dataclasses.dataclass\nclass PatternCandidate:\n    \"\"\"Represents a potential pattern extracted from a paper.\"\"\"\n\n    paper: Paper\n    pattern_name: Optional[str] = None\n    category: Optional[str] = None\n    tags: List[str] = dataclasses.field(default_factory=list)\n    score_breakdown: Dict[str, float] = dataclasses.field(default_factory=dict)\n    total_score: float = 0.0\n\n\nclass ArxivAPIError(Exception):\n    \"\"\"Raised when arXiv API request fails.\"\"\"\n\n    pass\n\n\ndef fetch_arxiv_papers(\n    query: str,\n    max_results: int = 100,\n    sort_by: str = \"submittedDate\",\n    sort_order: str = \"descending\",\n) -> List[Paper]:\n    \"\"\"\n    Fetch papers from arXiv API.\n\n    Args:\n        query: Search query string\n        max_results: Maximum number of results to return\n        sort_by: Sort field (lastUpdatedDate, submittedDate)\n        sort_order: ascending or descending\n\n    Returns:\n        List of Paper objects\n    \"\"\"\n    encoded_query = urllib.parse.quote(query)\n    url = f\"{ARXIV_API_URL}search_query={encoded_query}&start=0&max_results={max_results}&sortBy={sort_by}&sortOrder={sort_order}\"\n\n    headers = {\"User-Agent\": USER_AGENT}\n\n    try:\n        req = urllib.request.Request(url, headers=headers)\n        with urllib.request.urlopen(req, timeout=30) as response:\n            xml_data = response.read().decode(\"utf-8\")\n    except urllib.error.URLError as e:\n        raise ArxivAPIError(f\"Failed to fetch papers: {e}\")\n\n    return parse_arxiv_response(xml_data)\n\n\ndef parse_arxiv_response(xml_data: str) -> List[Paper]:\n    \"\"\"Parse arXiv API XML response into Paper objects.\"\"\"\n    papers = []\n\n    # Extract entries using regex (simple approach, could use xml.etree)\n    entry_pattern = re.compile(r\"<entry>(.*?)</entry>\", re.DOTALL)\n    title_pattern = re.compile(r\"<title>(.*?)</title>\", re.DOTALL)\n    author_pattern = re.compile(r\"<name>(.*?)</name>\")\n    summary_pattern = re.compile(r\"<summary>(.*?)</summary>\", re.DOTALL)\n    published_pattern = re.compile(r\"<published>(.*?)</published>\")\n    updated_pattern = re.compile(r\"<updated>(.*?)</updated>\")\n    category_pattern = re.compile(r'<term[^>]*>([^<]+)</term>')\n    id_pattern = re.compile(r\"<id>(.*?)</id>\")\n    arxiv_id_pattern = re.compile(r\"arxiv.org/abs/(\\d+\\.\\d+)\")\n\n    for entry_match in entry_pattern.finditer(xml_data):\n        entry = entry_match.group(1)\n\n        # Extract title\n        title_match = title_pattern.search(entry)\n        title = title_match.group(1).strip().replace(\"\\n\", \" \") if title_match else \"Unknown\"\n\n        # Extract authors\n        authors = [a.strip() for a in author_pattern.findall(entry)]\n\n        # Extract abstract\n        summary_match = summary_pattern.search(entry)\n        abstract = summary_match.group(1).strip().replace(\"\\n\", \" \") if summary_match else \"\"\n\n        # Extract dates\n        published_match = published_pattern.search(entry)\n        published = published_match.group(1) if published_match else \"\"\n\n        updated_match = updated_pattern.search(entry)\n        updated = updated_match.group(1) if updated_match else \"\"\n\n        # Extract categories (primary and secondary)\n        categories = list(set(category_pattern.findall(entry)))\n\n        # Extract arXiv ID\n        id_match = id_pattern.search(entry)\n        arxiv_id = \"unknown\"\n        if id_match:\n            arxiv_id_match = arxiv_id_pattern.search(id_match.group(1))\n            if arxiv_id_match:\n                arxiv_id = arxiv_id_match.group(1)\n\n        # Build URL\n        url = f\"https://arxiv.org/abs/{arxiv_id}\"\n\n        papers.append(\n            Paper(\n                arxiv_id=arxiv_id,\n                title=title,\n                authors=authors,\n                abstract=abstract,\n                published=published,\n                updated=updated,\n                categories=categories,\n                url=url,\n            )\n        )\n\n    return papers\n\n\ndef parse_date(date_string: str) -> datetime.datetime:\n    \"\"\"Parse arXiv date string to datetime object.\"\"\"\n    # arXiv dates are in format: 2025-01-15T12:34:56Z\n    try:\n        return datetime.datetime.fromisoformat(date_string.replace(\"Z\", \"+00:00\"))\n    except ValueError:\n        # Fallback for other formats\n        return datetime.datetime.min\n\n\ndef filter_papers_by_date(papers: List[Paper], days: int) -> List[Paper]:\n    \"\"\"Filter papers to those published/updated within the last N days.\"\"\"\n    cutoff = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(days=days)\n    return [p for p in papers if parse_date(p.published) >= cutoff or parse_date(p.updated) >= cutoff]\n\n\ndef filter_papers_by_keywords(papers: List[Paper]) -> List[Paper]:\n    \"\"\"Filter papers to those containing architecture/pattern keywords in abstract.\"\"\"\n    architectural_terms = {\n        \"architecture\",\n        \"pattern\",\n        \"framework\",\n        \"design\",\n        \"orchestration\",\n        \"coordination\",\n        \"hierarchy\",\n        \"protocol\",\n        \"memory\",\n        \"agent\",\n        \"agentic\",\n        \"multi-agent\",\n        \"autonomous\",\n        \"workflow\",\n        \"control\",\n        \"feedback\",\n        \"adapter\",\n        \"interface\",\n        \"abstraction\",\n    }\n\n    filtered = []\n    for paper in papers:\n        abstract_lower = paper.abstract.lower()\n        title_lower = paper.title.lower()\n        combined = title_lower + \" \" + abstract_lower\n\n        if any(term in combined for term in architectural_terms):\n            filtered.append(paper)\n\n    return filtered\n\n\ndef score_reusability(paper: Paper) -> float:\n    \"\"\"\n    Score paper on reusability (30% weight).\n\n    Domain-specific (1.0) → Multi-domain (2.0) → Universal (3.0)\n    \"\"\"\n    abstract_lower = paper.abstract.lower()\n    title_lower = paper.title.lower()\n    combined = title_lower + \" \" + abstract_lower\n\n    # Check for universal language\n    universal_indicators = [\"general\", \"universal\", \"framework\", \"generic\", \"generic approach\"]\n    multi_domain_indicators = [\"multi-domain\", \"cross-domain\", \"versatile\", \"adaptable\"]\n    domain_specific_indicators = [\"specific to\", \"in the field of\", \"domain-specific\"]\n\n    universal_count = sum(1 for term in universal_indicators if term in combined)\n    multi_domain_count = sum(1 for term in multi_domain_indicators if term in combined)\n    domain_specific_count = sum(1 for term in domain_specific_indicators if term in combined)\n\n    # Also check for broad application potential\n    broad_terms = [\"wide range\", \"variety of\", \"multiple use cases\", \"flexible\"]\n    broad_count = sum(1 for term in broad_terms if term in combined)\n\n    if universal_count >= 1 or broad_count >= 1:\n        return 3.0\n    elif multi_domain_count >= 1:\n        return 2.0\n    elif domain_specific_count >= 1:\n        return 1.0\n    else:\n        # Default to mid-range\n        return 2.0\n\n\ndef score_novelty(paper: Paper) -> float:\n    \"\"\"\n    Score paper on novelty (25% weight).\n\n    Existing (1.0) → Incremental (2.0) → Fundamentally new (3.0)\n    \"\"\"\n    abstract_lower = paper.abstract.lower()\n    title_lower = paper.title.lower()\n    combined = title_lower + \" \" + abstract_lower\n\n    # Check for novelty indicators\n    novel_indicators = [\n        \"novel\",\n        \"new\",\n        \"first\",\n        \"pioneering\",\n        \"groundbreaking\",\n        \"innovative\",\n        \"unprecedented\",\n        \"original\",\n        \"unique approach\",\n    ]\n    incremental_indicators = [\n        \"improves\",\n        \"extends\",\n        \"builds on\",\n        \"enhances\",\n        \"optimizes\",\n        \"refines\",\n        \"extension of\",\n    ]\n\n    novel_count = sum(1 for term in novel_indicators if term in combined)\n    incremental_count = sum(1 for term in incremental_indicators if term in combined)\n\n    # Check for strong claims of new approaches\n    strong_novel = [\"new architecture\", \"new framework\", \"new paradigm\", \"first to\"]\n    strong_novel_count = sum(1 for term in strong_novel if term in combined)\n\n    if strong_novel_count >= 1 or novel_count >= 2:\n        return 3.0\n    elif novel_count >= 1 and incremental_count == 0:\n        return 2.5\n    elif incremental_count >= 1:\n        return 2.0\n    else:\n        return 1.5\n\n\ndef score_clarity(paper: Paper) -> float:\n    \"\"\"\n    Score paper on clarity (20% weight).\n\n    Vague (1.0) → Clear (2.0) → Crystal clear (3.0)\n    \"\"\"\n    abstract_lower = paper.abstract.lower()\n    title_lower = paper.title.lower()\n    combined = title_lower + \" \" + abstract_lower\n\n    # Clarity indicators\n    clear_indicators = [\n        \"we propose\",\n        \"we present\",\n        \"our approach\",\n        \"the method\",\n        \"the algorithm\",\n        \"specifically\",\n        \"concretely\",\n    ]\n    vague_indicators = [\n        \"some ways\",\n        \"somewhat\",\n        \"may\",\n        \"might\",\n        \"potentially\",\n        \"could be\",\n    ]\n\n    clear_count = sum(1 for term in clear_indicators if term in combined)\n    vague_count = sum(1 for term in vague_indicators if term in combined)\n\n    # Abstract length (too short might indicate lack of detail)\n    abstract_words = len(paper.abstract.split())\n    length_score = 0\n    if abstract_words > 150:\n        length_score = 1\n    elif abstract_words > 100:\n        length_score = 0.5\n\n    base_score = 2.0\n    if clear_count >= 3:\n        base_score = 2.5\n    if vague_count >= 3:\n        base_score = max(1.0, base_score - 0.5)\n\n    return min(3.0, base_score + length_score)\n\n\ndef score_evidence(paper: Paper) -> float:\n    \"\"\"\n    Score paper on empirical evidence (15% weight).\n\n    No eval (1.0) → Some eval (2.0) → Strong empirical (3.0)\n    \"\"\"\n    abstract_lower = paper.abstract.lower()\n\n    # Evidence indicators\n    eval_indicators = [\n        \"evaluation\",\n        \"experiment\",\n        \"benchmark\",\n        \"results\",\n        \"performance\",\n        \"compared\",\n        \"comparison\",\n        \"metric\",\n    ]\n    strong_eval_indicators = [\n        \"significant improvement\",\n        \"state-of-the-art\",\n        \"sota\",\n        \"outperforms\",\n        \"empirical\",\n        \"real-world\",\n        \"deployment\",\n    ]\n\n    eval_count = sum(1 for term in eval_indicators if term in abstract_lower)\n    strong_eval_count = sum(1 for term in strong_eval_indicators if term in abstract_lower)\n\n    # Check for datasets (indicates empirical work)\n    dataset_indicators = [\"dataset\", \"benchmark\", \"we evaluate on\", \"tested on\"]\n    dataset_count = sum(1 for term in dataset_indicators if term in abstract_lower)\n\n    if strong_eval_count >= 1 or eval_count >= 3:\n        return 3.0\n    elif eval_count >= 1:\n        return 2.0\n    elif dataset_count >= 1:\n        return 2.0\n    else:\n        return 1.0\n\n\ndef score_completeness(paper: Paper) -> float:\n    \"\"\"\n    Score paper on implementation completeness (10% weight).\n\n    Idea only (1.0) → Partial details (2.0) → Production-ready (3.0)\n    \"\"\"\n    abstract_lower = paper.abstract.lower()\n\n    # Completeness indicators\n    implementation_indicators = [\n        \"implementation\",\n        \"open source\",\n        \"code\",\n        \"available\",\n        \"github\",\n        \"released\",\n        \"library\",\n    ]\n    detail_indicators = [\n        \"algorithm\",\n        \"architecture\",\n        \"framework\",\n        \"protocol\",\n        \"method\",\n        \"approach\",\n    ]\n\n    implementation_count = sum(1 for term in implementation_indicators if term in abstract_lower)\n    detail_count = sum(1 for term in detail_indicators if term in abstract_lower)\n\n    # Check for production mentions\n    production_indicators = [\"production\", \"deployed\", \"real-world\", \"industry\"]\n    production_count = sum(1 for term in production_indicators if term in abstract_lower)\n\n    if implementation_count >= 2 or production_count >= 1:\n        return 3.0\n    elif implementation_count >= 1 or detail_count >= 3:\n        return 2.0\n    elif detail_count >= 1:\n        return 1.5\n    else:\n        return 1.0\n\n\ndef calculate_quality_score(paper: Paper) -> tuple[float, Dict[str, float]]:\n    \"\"\"\n    Calculate overall quality score using the Pattern Quality Rubric.\n\n    Returns:\n        Tuple of (total_score, score_breakdown)\n    \"\"\"\n    # Weighted scoring\n    reusability = score_reusability(paper)\n    novelty = score_novelty(paper)\n    clarity = score_clarity(paper)\n    evidence = score_evidence(paper)\n    completeness = score_completeness(paper)\n\n    # Weights\n    total_score = (\n        reusability * 0.30 +\n        novelty * 0.25 +\n        clarity * 0.20 +\n        evidence * 0.15 +\n        completeness * 0.10\n    )\n\n    breakdown = {\n        \"reusability\": reusability,\n        \"novelty\": novelty,\n        \"clarity\": clarity,\n        \"evidence\": evidence,\n        \"completeness\": completeness,\n    }\n\n    return total_score, breakdown\n\n\ndef categorize_paper(paper: Paper, existing_patterns: List[Dict]) -> Optional[str]:\n    \"\"\"\n    Attempt to categorize a paper into one of the pattern categories.\n\n    Returns the category name or None if uncertain.\n    \"\"\"\n    abstract_lower = paper.abstract.lower()\n    title_lower = paper.title.lower()\n    combined = title_lower + \" \" + abstract_lower\n\n    # Category-specific keywords\n    category_keywords = {\n        \"Orchestration & Control\": [\n            \"orchestration\", \"coordination\", \"control\", \"hierarchy\", \"planner\",\n            \"workflow\", \"supervisor\", \"manager\", \"scheduler\", \"decomposition\",\n            \"sub-agent\", \"spawning\", \"multi-agent coordination\",\n        ],\n        \"Context & Memory\": [\n            \"memory\", \"context\", \"recall\", \"retrieval\", \"episodic\",\n            \"vector\", \"embedding\", \"rag\", \"knowledge base\", \"state\",\n            \"continuum\", \"temporal context\",\n        ],\n        \"Feedback Loops\": [\n            \"feedback\", \"iteration\", \"refinement\", \"self-improve\",\n            \"critique\", \"eval\", \"evaluation\", \"monitor\", \"adjust\",\n            \"adaptive\", \"learning from feedback\",\n        ],\n        \"Learning & Adaptation\": [\n            \"learning\", \"reinforcement\", \"rl\", \"fine-tuning\", \"adaptation\",\n            \"skill\", \"evolution\", \"training\", \"optimizer\",\n        ],\n        \"Reliability & Eval\": [\n            \"reliability\", \"safety\", \"guardrail\", \"error\", \"robust\",\n            \"testing\", \"validation\", \"verification\", \"deterministic\",\n        ],\n        \"Security & Safety\": [\n            \"security\", \"privacy\", \"attack\", \"malicious\", \"adversarial\",\n            \"sandbox\", \"isolation\", \"monitoring\", \"threat model\",\n            \"exfiltration\", \"laundering\",\n        ],\n        \"Tool Use & Environment\": [\n            \"tool\", \"api\", \"function call\", \"environment\", \"execution\",\n            \"browser\", \"shell\", \"filesystem\", \"external\", \"integration\",\n        ],\n        \"UX & Collaboration\": [\n            \"user experience\", \"ux\", \"collaboration\", \"human-in-loop\",\n            \"handoff\", \"notification\", \"interaction\", \"interface\",\n        ],\n    }\n\n    # Count keyword matches for each category\n    category_scores = {}\n    for category, keywords in category_keywords.items():\n        score = sum(1 for kw in keywords if kw in combined)\n        if score > 0:\n            category_scores[category] = score\n\n    # Return category with highest score (if any)\n    if category_scores:\n        return max(category_scores, key=category_scores.get)\n\n    return None\n\n\ndef extract_tags(paper: Paper) -> List[str]:\n    \"\"\"\n    Extract relevant tags from paper metadata.\n\n    Returns a list of lowercase tags suitable for pattern files.\n    \"\"\"\n    abstract_lower = paper.abstract.lower()\n    title_lower = paper.title.lower()\n    combined = title_lower + \" \" + abstract_lower\n\n    # Common agentic pattern keywords\n    tag_keywords = [\n        \"agent\", \"multi-agent\", \"orchestration\", \"coordination\",\n        \"memory\", \"context\", \"rag\", \"retrieval\",\n        \"feedback\", \"iteration\", \"self-improve\",\n        \"tool\", \"api\", \"function-call\",\n        \"planning\", \"planner\", \"decomposition\",\n        \"parallel\", \"concurrent\", \"async\",\n        \"hierarchy\", \"hierarchical\", \"layered\",\n        \"security\", \"privacy\", \"sandbox\",\n        \"evaluation\", \"benchmark\", \"testing\",\n        \"autonomous\", \"automation\",\n        \"workflow\", \"pipeline\",\n        \"communication\", \"protocol\",\n    ]\n\n    tags = []\n    for keyword in tag_keywords:\n        if keyword in combined:\n            tags.append(keyword)\n\n    return tags\n\n\ndef print_paper_summary(paper: Paper, score: float, breakdown: Dict[str, float], category: Optional[str]):\n    \"\"\"Print a formatted summary of a paper with its scores.\"\"\"\n    print(f\"\\n{'='*70}\")\n    print(f\"Title: {paper.title}\")\n    print(f\"arXiv: {paper.arxiv_id} | Score: {score:.2f}/10.0\")\n    print(f\"URL: {paper.url}\")\n    if category:\n        print(f\"Suggested Category: {category}\")\n    print(f\"\\nScore Breakdown:\")\n    print(f\"  Reusability (30%):    {breakdown['reusability']:.1f}/3.0\")\n    print(f\"  Novelty (25%):        {breakdown['novelty']:.1f}/3.0\")\n    print(f\"  Clarity (20%):        {breakdown['clarity']:.1f}/3.0\")\n    print(f\"  Evidence (15%):       {breakdown['evidence']:.1f}/3.0\")\n    print(f\"  Completeness (10%):   {breakdown['completeness']:.1f}/3.0\")\n    print(f\"\\nAbstract: {paper.abstract[:300]}...\")\n\n\ndef export_results(papers: List[Dict[str, Any]], output_file: str):\n    \"\"\"Export scan results to JSON file.\"\"\"\n    with open(output_file, \"w\") as f:\n        json.dump(papers, f, indent=2)\n    print(f\"\\nResults exported to: {output_file}\")\n\n\ndef export_markdown_report(papers: List[Dict[str, Any]], output_file: str):\n    \"\"\"Export scan results as a Markdown report.\"\"\"\n    lines = [\n        \"# arXiv Pattern Discovery Report\",\n        f\"Generated: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\",\n        \"\",\n        f\"**Total papers scanned: {len(papers)}**\",\n        \"\",\n        \"---\",\n        \"\",\n    ]\n\n    for i, paper in enumerate(papers, 1):\n        p = paper[\"paper\"]\n        lines.extend([\n            f\"## {i}. {p['title']}\",\n            \"\",\n            f\"**arXiv ID:** {p['arxiv_id']}  \",\n            f\"**Quality Score:** {paper['total_score']:.2f}/10.0  \",\n            f\"**Suggested Category:** {paper.get('category', 'Uncategorized')}  \",\n            f\"**URL:** {p['url']}  \",\n            \"\",\n            f\"**Score Breakdown:**\",\n            f\"- Reusability (30%): {paper['score_breakdown']['reusability']:.1f}/3.0\",\n            f\"- Novelty (25%): {paper['score_breakdown']['novelty']:.1f}/3.0\",\n            f\"- Clarity (20%): {paper['score_breakdown']['clarity']:.1f}/3.0\",\n            f\"- Evidence (15%): {paper['score_breakdown']['evidence']:.1f}/3.0\",\n            f\"- Completeness (10%): {paper['score_breakdown']['completeness']:.1f}/3.0\",\n            \"\",\n            f\"**Tags:** {', '.join(paper.get('tags', []))}\",\n            \"\",\n            \"**Abstract:**\",\n            p[\"abstract\"],\n            \"\",\n            \"---\",\n            \"\",\n        ])\n\n    with open(output_file, \"w\") as f:\n        f.write(\"\\n\".join(lines))\n    print(f\"Markdown report exported to: {output_file}\")\n\n\ndef load_existing_patterns(patterns_dir: Path) -> List[Dict]:\n    \"\"\"Load existing patterns to check for duplicates.\"\"\"\n    from build_readme import parse_front_matter\n\n    patterns = []\n    for file in patterns_dir.glob(\"*.md\"):\n        if file.name == \"TEMPLATE.md\":\n            continue\n        try:\n            metadata = parse_front_matter(str(file))\n            patterns.append({\n                \"file\": file.name,\n                \"title\": metadata.get(\"title\", \"\"),\n                \"tags\": metadata.get(\"tags\", []),\n                \"category\": metadata.get(\"category\", \"\"),\n            })\n        except Exception:\n            continue\n    return patterns\n\n\ndef check_for_duplicates(paper: Paper, existing_patterns: List[Dict]) -> List[str]:\n    \"\"\"Check if paper might duplicate existing patterns.\"\"\"\n    title_lower = paper.title.lower()\n    abstract_lower = paper.abstract.lower()\n\n    potential_dupes = []\n    for pattern in existing_patterns:\n        pattern_title = pattern[\"title\"].lower()\n        pattern_tags = [t.lower() for t in pattern.get(\"tags\", [])]\n\n        # Check title similarity\n        if any(word in title_lower for word in pattern_title.split() if len(word) > 4):\n            potential_dupes.append(pattern[\"file\"])\n\n        # Check tag overlap\n        paper_words = set(title_lower.split() + abstract_lower.split())\n        tag_overlap = len(paper_words.intersection(pattern_tags)) / max(len(pattern_tags), 1)\n        if tag_overlap > 0.3:\n            potential_dupes.append(pattern[\"file\"])\n\n    return list(set(potential_dupes))\n\n\ndef main():\n    parser = argparse.ArgumentParser(\n        description=\"Scan arXiv for papers describing agentic patterns\",\n        formatter_class=argparse.RawDescriptionHelpFormatter,\n        epilog=\"\"\"\nExamples:\n  %(prog)s --days=7 --min-citations=3\n  %(prog)s --query=\"multi-agent orchestration\" --max-results=50\n  %(prog)s --min-score=7.0 --export-json results.json\n        \"\"\",\n    )\n    parser.add_argument(\n        \"--query\",\n        \"-q\",\n        type=str,\n        default=DEFAULT_SEARCH_QUERY,\n        help=\"arXiv search query (default: agent/agentic/multi-agent papers)\",\n    )\n    parser.add_argument(\n        \"--max-results\",\n        \"-n\",\n        type=int,\n        default=100,\n        help=\"Maximum number of results to fetch (default: 100)\",\n    )\n    parser.add_argument(\n        \"--days\",\n        \"-d\",\n        type=int,\n        default=365,\n        help=\"Only include papers from last N days (default: 365)\",\n    )\n    parser.add_argument(\n        \"--min-score\",\n        \"-m\",\n        type=float,\n        default=5.0,\n        help=\"Minimum quality score to include (default: 5.0)\",\n    )\n    parser.add_argument(\n        \"--export-json\",\n        type=str,\n        help=\"Export results to JSON file\",\n    )\n    parser.add_argument(\n        \"--export-md\",\n        type=str,\n        help=\"Export results to Markdown file\",\n    )\n    parser.add_argument(\n        \"--patterns-dir\",\n        type=str,\n        default=\"patterns\",\n        help=\"Path to patterns directory (default: patterns)\",\n    )\n    parser.add_argument(\n        \"--verbose\",\n        \"-v\",\n        action=\"store_true\",\n        help=\"Print detailed output for each paper\",\n    )\n\n    args = parser.parse_args()\n\n    # Load existing patterns\n    patterns_dir = Path(args.patterns_dir)\n    if patterns_dir.exists():\n        existing_patterns = load_existing_patterns(patterns_dir)\n        print(f\"Loaded {len(existing_patterns)} existing patterns for duplicate detection\")\n    else:\n        existing_patterns = []\n        print(f\"Warning: Patterns directory not found at {patterns_dir}\")\n\n    print(f\"\\n🔍 Scanning arXiv with query: {args.query[:100]}...\")\n    print(f\"   Max results: {args.max_results}, Time window: {args.days} days\")\n\n    try:\n        papers = fetch_arxiv_papers(args.query, args.max_results)\n        print(f\"   Fetched {len(papers)} papers from arXiv\")\n\n        # Apply filters\n        if args.days < 365:\n            papers = filter_papers_by_date(papers, args.days)\n            print(f\"   Filtered to {len(papers)} papers within last {args.days} days\")\n\n        papers = filter_papers_by_keywords(papers)\n        print(f\"   Filtered to {len(papers)} papers with architectural keywords\")\n\n        if not papers:\n            print(\"\\n❌ No papers found matching criteria\")\n            return 0\n\n    except ArxivAPIError as e:\n        print(f\"\\n❌ Error fetching from arXiv: {e}\")\n        return 1\n\n    # Score papers\n    print(f\"\\n📊 Scoring {len(papers)} papers using Pattern Quality Rubric...\")\n\n    results = []\n    high_quality_count = 0\n\n    for paper in papers:\n        score, breakdown = calculate_quality_score(paper)\n        category = categorize_paper(paper, existing_patterns)\n        tags = extract_tags(paper)\n        duplicates = check_for_duplicates(paper, existing_patterns)\n\n        result = {\n            \"paper\": {\n                \"arxiv_id\": paper.arxiv_id,\n                \"title\": paper.title,\n                \"authors\": paper.authors,\n                \"abstract\": paper.abstract,\n                \"published\": paper.published,\n                \"categories\": paper.categories,\n                \"url\": paper.url,\n            },\n            \"pattern_name\": None,\n            \"category\": category,\n            \"tags\": tags,\n            \"score_breakdown\": breakdown,\n            \"total_score\": score,\n            \"potential_duplicates\": duplicates,\n            \"meets_threshold\": score >= args.min_score,\n        }\n        results.append(result)\n\n        if score >= args.min_score:\n            high_quality_count += 1\n            if args.verbose:\n                print_paper_summary(paper, score, breakdown, category)\n                if duplicates:\n                    print(f\"⚠️  Potential duplicates: {', '.join(duplicates)}\")\n\n    # Sort by score\n    results.sort(key=lambda x: x[\"total_score\"], reverse=True)\n\n    # Print summary\n    print(f\"\\n{'='*70}\")\n    print(f\"📈 SCAN SUMMARY\")\n    print(f\"{'='*70}\")\n    print(f\"Total papers analyzed: {len(papers)}\")\n    print(f\"Papers meeting threshold ({args.min_score}): {high_quality_count}\")\n    print(f\"\\n🏆 Top 10 papers by quality score:\")\n    print(f\"{'-'*70}\")\n\n    for i, r in enumerate(results[:10], 1):\n        p = r[\"paper\"]\n        dupes = f\" [⚠️ duplicates: {len(r['potential_duplicates'])}]\" if r[\"potential_duplicates\"] else \"\"\n        print(f\"{i:2}. {r['total_score']:.2f} | {p['title'][:60]}...{dupes}\")\n\n    # Export results if requested\n    if args.export_json:\n        export_results(results, args.export_json)\n\n    if args.export_md:\n        export_markdown_report(results, args.export_md)\n\n    return 0\n\n\nif __name__ == \"__main__\":\n    sys.exit(main())\n\n<!-- File: .claude/skills/arxiv-pattern-discovery/scripts/pattern_similarity_checker.py (Tokens: ~3916 | Category: claude-rule) -->\n#!/usr/bin/env python3\n\"\"\"\npattern_similarity_checker.py\n\nDuplicate detection for pattern files using tag similarity and content analysis.\n\nDetects potentially duplicate or very similar patterns by comparing:\n- Tag overlap (Jaccard similarity)\n- Title similarity\n- Category overlap\n- Problem/Solution section content\n\nUsage:\n    python scripts/pattern_similarity_checker.py <new-pattern.md>\n    python scripts/pattern_similarity_checker.py --all\n    python scripts/pattern_similarity_checker.py --threshold=0.7 <pattern.md>\n\"\"\"\n\nimport argparse\nimport math\nimport os\nimport re\nimport sys\nfrom collections import Counter\nfrom pathlib import Path\nfrom typing import Dict, List, Optional, Set, Tuple\n\n\n# Add parent directory to path for imports\nsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))\n\nfrom build_readme import parse_front_matter\n\n\ndef slugify(value: str) -> str:\n    \"\"\"Normalize string for comparison.\"\"\"\n    value = re.sub(r'[^\\w\\s-]', '', value).strip().lower()\n    value = re.sub(r'[-\\s]+', ' ', value)\n    return value\n\n\ndef tokenize(text: str) -> Set[str]:\n    \"\"\"Tokenize text into words, removing common stop words.\"\"\"\n    if not text:\n        return set()\n\n    # Common stop words to ignore\n    stop_words = {\n        \"a\", \"an\", \"the\", \"and\", \"or\", \"but\", \"in\", \"on\", \"at\", \"to\", \"for\",\n        \"of\", \"with\", \"by\", \"from\", \"as\", \"is\", \"was\", \"are\", \"were\", \"be\",\n        \"been\", \"being\", \"have\", \"has\", \"had\", \"do\", \"does\", \"did\", \"will\",\n        \"would\", \"could\", \"should\", \"may\", \"might\", \"must\", \"can\", \"this\",\n        \"that\", \"these\", \"those\", \"it\", \"its\", \"they\", \"them\", \"their\",\n        \"what\", \"which\", \"who\", \"whom\", \"when\", \"where\", \"why\", \"how\",\n    }\n\n    # Tokenize and filter\n    words = re.findall(r'\\b\\w+\\b', text.lower())\n    return {w for w in words if len(w) > 3 and w not in stop_words}\n\n\ndef jaccard_similarity(set1: Set[str], set2: Set[str]) -> float:\n    \"\"\"\n    Calculate Jaccard similarity between two sets.\n\n    J(A, B) = |A ∩ B| / |A ∪ B|\n    \"\"\"\n    if not set1 or not set2:\n        return 0.0\n\n    intersection = len(set1.intersection(set2))\n    union = len(set1.union(set2))\n\n    return intersection / union if union > 0 else 0.0\n\n\ndef cosine_similarity(set1: Set[str], set2: Set[str]) -> float:\n    \"\"\"\n    Calculate cosine similarity between two sets (treating as binary vectors).\n    \"\"\"\n    if not set1 or not set2:\n        return 0.0\n\n    intersection = len(set1.intersection(set2))\n    magnitude = math.sqrt(len(set1)) * math.sqrt(len(set2))\n\n    return intersection / magnitude if magnitude > 0 else 0.0\n\n\ndef levenshtein_distance(s1: str, s2: str) -> int:\n    \"\"\"Calculate Levenshtein distance between two strings.\"\"\"\n    if len(s1) < len(s2):\n        return levenshtein_distance(s2, s1)\n\n    if len(s2) == 0:\n        return len(s1)\n\n    previous_row = range(len(s2) + 1)\n    for i, c1 in enumerate(s1):\n        current_row = [i + 1]\n        for j, c2 in enumerate(s2):\n            insertions = previous_row[j + 1] + 1\n            deletions = current_row[j] + 1\n            substitutions = previous_row[j] + (c1 != c2)\n            current_row.append(min(insertions, deletions, substitutions))\n        previous_row = current_row\n\n    return previous_row[-1]\n\n\ndef string_similarity(s1: str, s2: str) -> float:\n    \"\"\"\n    Calculate normalized string similarity based on Levenshtein distance.\n\n    Returns 1.0 for identical strings, 0.0 for completely different.\n    \"\"\"\n    if not s1 or not s2:\n        return 0.0\n\n    max_len = max(len(s1), len(s2))\n    if max_len == 0:\n        return 1.0\n\n    distance = levenshtein_distance(s1.lower(), s2.lower())\n    return 1.0 - (distance / max_len)\n\n\ndef extract_sections(filepath: str) -> Dict[str, str]:\n    \"\"\"\n    Extract main sections from a pattern file.\n\n    Returns dict with keys: problem, solution, how_to_use, trade_offs\n    \"\"\"\n    with open(filepath, 'r', encoding='utf-8') as f:\n        content = f.read()\n\n    # Remove front matter\n    if content.startswith('---'):\n        end_idx = content.find('\\n---', 4)\n        if end_idx > 0:\n            content = content[end_idx + 4:]\n\n    sections = {}\n    current_section = None\n    current_content = []\n\n    # Section markers we care about\n    section_markers = ['## Problem', '## Solution', '## How to use it', '## Trade-offs']\n\n    for line in content.split('\\n'):\n        if line.startswith('## '):\n            # Save previous section\n            if current_section:\n                sections[current_section] = ' '.join(current_content)\n\n            # Start new section\n            current_section = line[3:].strip().lower()\n            if 'problem' in current_section:\n                current_section = 'problem'\n            elif 'solution' in current_section:\n                current_section = 'solution'\n            elif 'how to use' in current_section:\n                current_section = 'how_to_use'\n            elif 'trade-off' in current_section:\n                current_section = 'trade_offs'\n            else:\n                current_section = None\n            current_content = []\n        elif current_section:\n            # Skip code blocks and mermaid diagrams\n            if line.strip().startswith('```') or line.strip().startswith('~~~'):\n                continue\n            current_content.append(line.strip())\n\n    # Save last section\n    if current_section:\n        sections[current_section] = ' '.join(current_content)\n\n    return sections\n\n\nclass PatternSimilarityChecker:\n    \"\"\"Checker for finding similar/duplicate patterns.\"\"\"\n\n    def __init__(self, patterns_dir: str, threshold: float = 0.5):\n        \"\"\"\n        Initialize the checker.\n\n        Args:\n            patterns_dir: Path to patterns directory\n            threshold: Minimum similarity score to report (0-1)\n        \"\"\"\n        self.patterns_dir = Path(patterns_dir)\n        self.threshold = threshold\n        self.patterns = self._load_patterns()\n\n    def _load_patterns(self) -> List[Dict]:\n        \"\"\"Load all pattern metadata and content.\"\"\"\n        patterns = []\n\n        for filepath in self.patterns_dir.glob(\"*.md\"):\n            if filepath.name == \"TEMPLATE.md\":\n                continue\n\n            try:\n                metadata = parse_front_matter(str(filepath))\n                sections = extract_sections(filepath)\n\n                patterns.append({\n                    \"file\": filepath.name,\n                    \"path\": str(filepath),\n                    \"title\": metadata.get(\"title\", \"\"),\n                    \"tags\": [t.lower() for t in metadata.get(\"tags\", [])],\n                    \"category\": metadata.get(\"category\", \"\"),\n                    \"sections\": sections,\n                    \"metadata\": metadata,\n                })\n            except Exception as e:\n                print(f\"Warning: Could not load {filepath.name}: {e}\")\n\n        return patterns\n\n    def compare_to_pattern(self, filepath: str) -> List[Dict]:\n        \"\"\"\n        Compare a single pattern file against all existing patterns.\n\n        Returns list of similarity results, sorted by total similarity.\n        \"\"\"\n        try:\n            metadata = parse_front_matter(filepath)\n            sections = extract_sections(filepath)\n        except Exception as e:\n            print(f\"Error: Could not parse pattern file: {e}\")\n            return []\n\n        new_pattern = {\n            \"file\": Path(filepath).name,\n            \"title\": metadata.get(\"title\", \"\"),\n            \"tags\": [t.lower() for t in metadata.get(\"tags\", [])],\n            \"category\": metadata.get(\"category\", \"\"),\n            \"sections\": sections,\n        }\n\n        results = []\n\n        for existing in self.patterns:\n            if existing[\"file\"] == new_pattern[\"file\"]:\n                continue  # Skip self\n\n            similarity = self._calculate_similarity(new_pattern, existing)\n            if similarity[\"total\"] >= self.threshold:\n                results.append({\n                    \"existing_file\": existing[\"file\"],\n                    \"existing_title\": existing[\"title\"],\n                    \"similarity\": similarity,\n                })\n\n        # Sort by total similarity\n        results.sort(key=lambda x: x[\"similarity\"][\"total\"], reverse=True)\n        return results\n\n    def check_all_similarities(self) -> List[Dict]:\n        \"\"\"\n        Check all patterns against each other for similarities.\n\n        Returns list of potential duplicates (each pair once).\n        \"\"\"\n        results = []\n\n        for i, pattern1 in enumerate(self.patterns):\n            for pattern2 in self.patterns[i + 1:]:\n                similarity = self._calculate_similarity(pattern1, pattern2)\n                if similarity[\"total\"] >= self.threshold:\n                    results.append({\n                        \"pattern1\": pattern1[\"file\"],\n                        \"pattern2\": pattern2[\"file\"],\n                        \"title1\": pattern1[\"title\"],\n                        \"title2\": pattern2[\"title\"],\n                        \"similarity\": similarity,\n                    })\n\n        # Sort by total similarity\n        results.sort(key=lambda x: x[\"similarity\"][\"total\"], reverse=True)\n        return results\n\n    def _calculate_similarity(self, pattern1: Dict, pattern2: Dict) -> Dict[str, float]:\n        \"\"\"Calculate detailed similarity metrics between two patterns.\"\"\"\n\n        # 1. Tag similarity (Jaccard)\n        tags1 = set(pattern1[\"tags\"])\n        tags2 = set(pattern2[\"tags\"])\n        tag_sim = jaccard_similarity(tags1, tags2)\n\n        # 2. Title similarity\n        title_sim = string_similarity(pattern1[\"title\"], pattern2[\"title\"])\n\n        # 3. Category match\n        category_match = 1.0 if pattern1[\"category\"] == pattern2[\"category\"] else 0.0\n\n        # 4. Content similarity (problem + solution)\n        content1_tokens = set()\n        content2_tokens = set()\n\n        for section in [\"problem\", \"solution\"]:\n            if section in pattern1[\"sections\"]:\n                content1_tokens.update(tokenize(pattern1[\"sections\"][section]))\n            if section in pattern2[\"sections\"]:\n                content2_tokens.update(tokenize(pattern2[\"sections\"][section]))\n\n        content_sim = jaccard_similarity(content1_tokens, content2_tokens)\n\n        # Weighted total (adjust weights as needed)\n        total = (\n            tag_sim * 0.30 +\n            title_sim * 0.20 +\n            category_match * 0.15 +\n            content_sim * 0.35\n        )\n\n        return {\n            \"tag\": tag_sim,\n            \"title\": title_sim,\n            \"category\": category_match,\n            \"content\": content_sim,\n            \"total\": total,\n        }\n\n    def suggest_action(self, similarity: Dict[str, float]) -> str:\n        \"\"\"Suggest action based on similarity score.\"\"\"\n        total = similarity[\"total\"]\n\n        if total >= 0.8:\n            return \"MERGE - Patterns are very similar, consider merging\"\n        elif total >= 0.7:\n            return \"REVIEW - High similarity, manual review needed\"\n        elif total >= 0.6:\n            return \"CHECK - Moderate similarity, check if related\"\n        elif total >= 0.5:\n            return \"RELATED - May be related patterns\"\n        else:\n            return \"OK - Below similarity threshold\"\n\n\ndef print_similarity_report(results: List[Dict], threshold: float, checker):\n    \"\"\"Print a formatted similarity report.\"\"\"\n\n    if not results:\n        print(f\"\\n✅ No patterns found with similarity >= {threshold}\")\n        return\n\n    print(f\"\\n{'='*80}\")\n    print(f\"⚠️  FOUND {len(results)} POTENTIAL DUPLICATE/RELATED PATTERN PAIRS\")\n    print(f\"{'='*80}\")\n\n    for i, result in enumerate(results, 1):\n        if \"existing_file\" in result:\n            # Single pattern comparison\n            print(f\"\\n{i}. {result['existing_title']}\")\n            print(f\"   File: {result['existing_file']}\")\n        else:\n            # All-pairs comparison\n            print(f\"\\n{i}. {result['title1']} <-> {result['title2']}\")\n            print(f\"   Files: {result['pattern1']} <-> {result['pattern2']}\")\n\n        sim = result[\"similarity\"]\n        action = checker.suggest_action(sim)\n\n        print(f\"   Total Similarity: {sim['total']:.2f}\")\n        print(f\"   Tag Similarity:    {sim['tag']:.2f} (Jaccard)\")\n        print(f\"   Title Similarity:  {sim['title']:.2f}\")\n        print(f\"   Category Match:    {sim['category']:.2f}\")\n        print(f\"   Content Similarity:{sim['content']:.2f}\")\n        print(f\"   Suggested Action:  {action}\")\n\n    # Print warning for high similarities\n    high_sim = [r for r in results if r[\"similarity\"][\"total\"] >= 0.7]\n    if high_sim:\n        print(f\"\\n{'='*80}\")\n        print(f\"⚠️  WARNING: {len(high_sim)} patterns with similarity >= 0.7\")\n        print(f\"   These may be duplicates or variants that need merging.\")\n        print(f\"{'='*80}\")\n\n\ndef export_similarity_report(results: List[Dict], output_file: str, checker):\n    \"\"\"Export similarity report to Markdown file.\"\"\"\n\n    lines = [\n        \"# Pattern Similarity Report\",\n        \"\",\n        f\"Generated: {__import__('datetime').datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\",\n        f\"Total pairs found: {len(results)}\",\n        \"\",\n        \"---\",\n        \"\",\n    ]\n\n    for i, result in enumerate(results, 1):\n        if \"existing_file\" in result:\n            lines.extend([\n                f\"## {i}. {result['existing_title']}\",\n                \"\",\n                f\"**File:** `{result['existing_file']}`  \",\n                f\"**Similarity:** {result['similarity']['total']:.2f}  \",\n            ])\n        else:\n            lines.extend([\n                f\"## {i}. {result['title1']} ↔ {result['title2']}\",\n                \"\",\n                f\"**Files:** `{result['pattern1']}` ↔ `{result['pattern2']}`  \",\n                f\"**Similarity:** {result['similarity']['total']:.2f}  \",\n            ])\n\n        sim = result[\"similarity\"]\n        action = checker.suggest_action(sim)\n\n        lines.extend([\n            \"\",\n            f\"**Breakdown:**\",\n            f\"- Tag Similarity: {sim['tag']:.2f}\",\n            f\"- Title Similarity: {sim['title']:.2f}\",\n            f\"- Category Match: {sim['category']:.2f}\",\n            f\"- Content Similarity: {sim['content']:.2f}\",\n            \"\",\n            f\"**Suggested Action:** {action}\",\n            \"\",\n            \"---\",\n            \"\",\n        ])\n\n    with open(output_file, \"w\") as f:\n        f.write(\"\\n\".join(lines))\n\n    print(f\"Report exported to: {output_file}\")\n\n\ndef main():\n    parser = argparse.ArgumentParser(\n        description=\"Check patterns for duplicates or high similarity\",\n        formatter_class=argparse.RawDescriptionHelpFormatter,\n        epilog=\"\"\"\nExamples:\n  %(prog)s patterns/new-pattern.md\n  %(prog)s --all\n  %(prog)s --all --threshold=0.7 --export report.md\n        \"\"\",\n    )\n    parser.add_argument(\n        \"pattern_file\",\n        nargs=\"?\",\n        help=\"Path to pattern file to check against existing patterns\",\n    )\n    parser.add_argument(\n        \"--all\",\n        \"-a\",\n        action=\"store_true\",\n        help=\"Check all patterns against each other\",\n    )\n    parser.add_argument(\n        \"--patterns-dir\",\n        \"-d\",\n        type=str,\n        default=\"patterns\",\n        help=\"Path to patterns directory (default: patterns)\",\n    )\n    parser.add_argument(\n        \"--threshold\",\n        \"-t\",\n        type=float,\n        default=0.5,\n        help=\"Similarity threshold for reporting (default: 0.5)\",\n    )\n    parser.add_argument(\n        \"--export\",\n        \"-e\",\n        type=str,\n        help=\"Export report to Markdown file\",\n    )\n\n    args = parser.parse_args()\n\n    # Validate arguments\n    if not args.all and not args.pattern_file:\n        parser.error(\"Either specify a pattern file or use --all\")\n\n    if args.all and args.pattern_file:\n        parser.error(\"Cannot use --all with a specific pattern file\")\n\n    # Check patterns directory\n    patterns_dir = Path(args.patterns_dir)\n    if not patterns_dir.exists():\n        print(f\"Error: Patterns directory not found: {patterns_dir}\")\n        return 1\n\n    # Initialize checker\n    checker = PatternSimilarityChecker(str(patterns_dir), args.threshold)\n    print(f\"Loaded {len(checker.patterns)} patterns for comparison\")\n\n    # Run comparison\n    if args.all:\n        print(f\"\\n🔍 Checking all patterns for similarities (threshold: {args.threshold})...\")\n        results = checker.check_all_similarities()\n    else:\n        pattern_path = Path(args.pattern_file)\n        if not pattern_path.exists():\n            print(f\"Error: Pattern file not found: {pattern_path}\")\n            return 1\n\n        print(f\"\\n🔍 Comparing '{pattern_path.name}' against existing patterns...\")\n        results = checker.compare_to_pattern(str(pattern_path))\n\n    # Print report\n    print_similarity_report(results, args.threshold, checker)\n\n    # Export if requested\n    if args.export:\n        export_similarity_report(results, args.export, checker)\n\n    # Return exit code based on findings\n    if results:\n        return 1  # Found potential duplicates\n    return 0\n\n\nif __name__ == \"__main__\":\n    sys.exit(main())\n\n<!-- File: .claude/skills/arxiv-pattern-discovery/scripts/pattern_validator.py (Tokens: ~4948 | Category: claude-rule) -->\n#!/usr/bin/env python3\n\"\"\"\npattern_validator.py\n\nPre-commit validation for pattern files.\n\nValidates:\n- YAML front-matter completeness\n- Required sections presence\n- Mermaid diagram syntax\n- URL validity\n- Content quality checks\n\nUsage:\n    python scripts/pattern_validator.py <pattern-file.md>\n    python scripts/pattern_validator.py --all\n    python scripts/pattern_validator.py --fix <pattern-file.md>\n\"\"\"\n\nimport argparse\nimport os\nimport re\nimport sys\nimport urllib.request\nimport urllib.error\nfrom dataclasses import dataclass, field\nfrom enum import Enum\nfrom pathlib import Path\nfrom typing import List, Optional, Set, Tuple\n\n\n# Add parent directory to path for imports\nsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))\n\nfrom build_readme import parse_front_matter\n\n\nclass Severity(Enum):\n    \"\"\"Severity levels for validation issues.\"\"\"\n    ERROR = \"ERROR\"\n    WARNING = \"WARNING\"\n    INFO = \"INFO\"\n\n\n@dataclass\nclass ValidationIssue:\n    \"\"\"Represents a validation issue found in a pattern file.\"\"\"\n    severity: Severity\n    category: str\n    message: str\n    line: Optional[int] = None\n    column: Optional[int] = None\n    fix_suggestion: Optional[str] = None\n\n\n@dataclass\nclass ValidationResult:\n    \"\"\"Result of validating a pattern file.\"\"\"\n    file_path: str\n    is_valid: bool\n    issues: List[ValidationIssue] = field(default_factory=list)\n\n    def add_issue(self, severity: Severity, category: str, message: str,\n                  line: Optional[int] = None, fix_suggestion: Optional[str] = None):\n        self.issues.append(ValidationIssue(\n            severity=severity, category=category, message=message,\n            line=line, fix_suggestion=fix_suggestion\n        ))\n        if severity == Severity.ERROR:\n            self.is_valid = False\n\n\n# Valid values for pattern metadata\nVALID_STATUSES = {\n    \"proposed\",\n    \"emerging\",\n    \"established\",\n    \"validated-in-production\",\n    \"best-practice\",\n    \"experimental-but-awesome\",\n    \"rapidly-improving\",\n}\n\nVALID_CATEGORIES = {\n    \"Orchestration & Control\",\n    \"Context & Memory\",\n    \"Feedback Loops\",\n    \"Learning & Adaptation\",\n    \"Reliability & Eval\",\n    \"Security & Safety\",\n    \"Tool Use & Environment\",\n    \"UX & Collaboration\",\n    \"Uncategorized\",\n}\n\n# Required YAML fields\nREQUIRED_YAML_FIELDS = {\"title\", \"status\", \"authors\", \"based_on\", \"category\", \"source\", \"tags\"}\n\n# Required markdown sections\nREQUIRED_SECTIONS = {\"## Problem\", \"## Solution\", \"## References\"}\n\n\nclass PatternValidator:\n    \"\"\"Validator for pattern files.\"\"\"\n\n    def __init__(self, strict: bool = False):\n        \"\"\"\n        Initialize the validator.\n\n        Args:\n            strict: If True, treat warnings as errors\n        \"\"\"\n        self.strict = strict\n\n    def validate_file(self, filepath: str) -> ValidationResult:\n        \"\"\"\n        Validate a single pattern file.\n\n        Returns ValidationResult with all issues found.\n        \"\"\"\n        result = ValidationResult(file_path=filepath, is_valid=True)\n\n        try:\n            with open(filepath, 'r', encoding='utf-8') as f:\n                content = f.read()\n                lines = content.split('\\n')\n        except FileNotFoundError:\n            result.add_issue(Severity.ERROR, \"File\", f\"File not found: {filepath}\")\n            return result\n        except Exception as e:\n            result.add_issue(Severity.ERROR, \"File\", f\"Could not read file: {e}\")\n            return result\n\n        # Validate YAML front-matter\n        self._validate_yaml_front_matter(content, lines, result)\n\n        # Parse metadata for further validation\n        metadata = parse_front_matter(filepath)\n\n        # Validate metadata values\n        self._validate_metadata(metadata, result)\n\n        # Validate required sections\n        self._validate_sections(content, lines, result)\n\n        # Validate Mermaid diagrams\n        self._validate_mermaid_diagrams(content, lines, result)\n\n        # Validate URLs\n        self._validate_urls(content, lines, result)\n\n        # Content quality checks\n        self._validate_content_quality(content, metadata, result)\n\n        return result\n\n    def _validate_yaml_front_matter(self, content: str, lines: List[str], result: ValidationResult):\n        \"\"\"Validate YAML front-matter structure.\"\"\"\n        if not content.startswith('---'):\n            result.add_issue(\n                Severity.ERROR,\n                \"YAML\",\n                \"Pattern must start with YAML front-matter delimited by '---'\",\n                line=1,\n                fix_suggestion=\"Add YAML front-matter at the top of the file\"\n            )\n            return\n\n        # Find end of front-matter (second occurrence of ---)\n        end_marker_pos = content.find('\\n---', 4)\n        if end_marker_pos == -1:\n            result.add_issue(\n                Severity.ERROR,\n                \"YAML\",\n                \"YAML front-matter must be closed with '---'\",\n                fix_suggestion=\"Close front-matter with '---' on its own line\"\n            )\n            return\n\n        # Convert character position to line number (approximate)\n        end_line_num = content[:end_marker_pos].count('\\n') + 1\n\n        # Extract only the YAML section (lines 1 to end_line_num)\n        yaml_section = lines[1:end_line_num] if end_line_num > 1 else []\n        yaml_content = '\\n'.join(yaml_section)\n\n        # Check for empty front-matter\n        if not yaml_content.strip():\n            result.add_issue(\n                Severity.ERROR,\n                \"YAML\",\n                \"YAML front-matter is empty\",\n                line=2,\n                fix_suggestion=\"Add required YAML fields: title, status, authors, based_on, category, source, tags\"\n            )\n\n        # Check for proper YAML syntax (key: value pairs)\n        for i, yaml_line in enumerate(yaml_section, start=2):\n            if yaml_line.strip() and not yaml_line.strip().startswith('#'):\n                # Skip empty lines and comments\n                if ':' not in yaml_line and not yaml_line.strip().startswith('-'):\n                    result.add_issue(\n                        Severity.WARNING,\n                        \"YAML\",\n                        f\"Line may not be valid YAML: {yaml_line[:50]}\",\n                        line=i\n                    )\n\n    def _validate_metadata(self, metadata: dict, result: ValidationResult):\n        \"\"\"Validate metadata field values.\"\"\"\n\n        # Check required fields\n        for field in REQUIRED_YAML_FIELDS:\n            if field not in metadata:\n                result.add_issue(\n                    Severity.ERROR,\n                    \"Metadata\",\n                    f\"Missing required field: '{field}'\",\n                    fix_suggestion=f'Add \"{field}: <value>\" to YAML front-matter'\n                )\n\n        # Validate status\n        if \"status\" in metadata:\n            status = metadata[\"status\"]\n            if status not in VALID_STATUSES:\n                result.add_issue(\n                    Severity.ERROR,\n                    \"Metadata\",\n                    f\"Invalid status: '{status}'. Must be one of: {', '.join(sorted(VALID_STATUSES))}\",\n                    fix_suggestion=f\"Use one of: {', '.join(sorted(VALID_STATUSES))}\"\n                )\n\n        # Validate category\n        if \"category\" in metadata:\n            category = metadata[\"category\"]\n            if category not in VALID_CATEGORIES:\n                result.add_issue(\n                    Severity.WARNING,\n                    \"Metadata\",\n                    f\"Unknown category: '{category}'. Known categories: {', '.join(sorted(VALID_CATEGORIES))}\",\n                    fix_suggestion=f\"Use one of: {', '.join(sorted(VALID_CATEGORIES))}\"\n                )\n\n        # Validate authors is a list\n        if \"authors\" in metadata:\n            authors = metadata[\"authors\"]\n            if not isinstance(authors, list):\n                result.add_issue(\n                    Severity.ERROR,\n                    \"Metadata\",\n                    f\"'authors' must be a list: ['Name (@username)']\",\n                    fix_suggestion=\"Format as: authors: [\\\"Name (@username)\\\"]\"\n                )\n\n        # Validate tags is a list\n        if \"tags\" in metadata:\n            tags = metadata[\"tags\"]\n            if not isinstance(tags, list):\n                result.add_issue(\n                    Severity.ERROR,\n                    \"Metadata\",\n                    f\"'tags' must be a list: [tag1, tag2, tag3]\",\n                    fix_suggestion=\"Format as: tags: [tag1, tag2, tag3]\"\n                )\n            # Check for empty tags\n            elif any(not tag.strip() for tag in tags):\n                result.add_issue(\n                    Severity.WARNING,\n                    \"Metadata\",\n                    \"Tags list contains empty strings\",\n                    fix_suggestion=\"Remove empty tags\"\n                )\n\n        # Validate source is a URL\n        if \"source\" in metadata:\n            source = metadata[\"source\"]\n            if not source.startswith((\"http://\", \"https://\", \"arxiv://\")):\n                result.add_issue(\n                    Severity.WARNING,\n                    \"Metadata\",\n                    f\"'source' should be a URL: {source}\",\n                    fix_suggestion=\"Use a valid URL starting with http:// or https://\"\n                )\n\n        # Title quality checks\n        if \"title\" in metadata:\n            title = metadata[\"title\"]\n            if len(title) < 10:\n                result.add_issue(\n                    Severity.WARNING,\n                    \"Metadata\",\n                    f\"Title seems too short: '{title}'\",\n                    fix_suggestion=\"Use a more descriptive title\"\n                )\n            if title.islower():\n                result.add_issue(\n                    Severity.INFO,\n                    \"Metadata\",\n                    \"Title should use Title Case\",\n                    fix_suggestion=\"Capitalize the first letter of each word\"\n                )\n\n    def _validate_sections(self, content: str, lines: List[str], result: ValidationResult):\n        \"\"\"Validate required markdown sections.\"\"\"\n        # Skip YAML front-matter\n        start_idx = content.find('\\n---', 4)\n        if start_idx == -1:\n            start_idx = 0\n        else:\n            start_idx += 5\n\n        main_content = content[start_idx:]\n\n        for section in REQUIRED_SECTIONS:\n            if section not in main_content:\n                result.add_issue(\n                    Severity.ERROR,\n                    \"Structure\",\n                    f\"Missing required section: '{section}'\",\n                    fix_suggestion=f\"Add '## {section}' section\"\n                )\n\n        # Check for recommended sections (without ## prefix for matching)\n        recommended = {\"How to use it\", \"Trade-offs\"}\n        found_sections = set(re.findall(r'^## (.+)$', main_content, re.MULTILINE))\n        missing_recommended = recommended - found_sections\n\n        if missing_recommended:\n            for section in missing_recommended:\n                result.add_issue(\n                    Severity.INFO,\n                    \"Structure\",\n                    f\"Missing recommended section: '## {section}'\",\n                    fix_suggestion=f\"Consider adding '## {section}' section\"\n                )\n\n    def _validate_mermaid_diagrams(self, content: str, lines: List[str], result: ValidationResult):\n        \"\"\"Validate Mermaid diagram syntax.\"\"\"\n\n        # Find all Mermaid code blocks\n        mermaid_blocks = re.finditer(r'```mermaid\\n(.*?)```', content, re.DOTALL)\n\n        if not mermaid_blocks:\n            # Check if pattern might benefit from a diagram\n            if \"## Solution\" in content and len(content) > 2000:\n                result.add_issue(\n                    Severity.INFO,\n                    \"Content\",\n                    \"Consider adding a Mermaid diagram to illustrate the pattern\",\n                    fix_suggestion=\"Add a Mermaid diagram in the Solution section\"\n                )\n            return\n\n        for match in mermaid_blocks:\n            diagram = match.group(1)\n            block_start = content[:match.start()].count('\\n') + 1\n\n            # Basic Mermaid syntax checks\n            valid_diagram_types = {\n                \"graph\", \"flowchart\", \"sequenceDiagram\", \"classDiagram\",\n                \"stateDiagram\", \"erDiagram\", \"gantt\", \"pie\", \"gitGraph\"\n            }\n\n            first_line = diagram.strip().split('\\n')[0].strip()\n            diagram_type = first_line.split()[0] if first_line else \"\"\n\n            if diagram_type and diagram_type not in valid_diagram_types:\n                result.add_issue(\n                    Severity.WARNING,\n                    \"Mermaid\",\n                    f\"Unrecognized diagram type: '{diagram_type}'\",\n                    line=block_start + 1,\n                    fix_suggestion=f\"Use one of: {', '.join(valid_diagram_types)}\"\n                )\n\n            # Check for common syntax errors\n            if ' --' in diagram and '-->' not in diagram:\n                result.add_issue(\n                    Severity.WARNING,\n                    \"Mermaid\",\n                    \"Found ' --' which might be a typo for ' -->' (arrow)\",\n                    line=block_start\n                )\n\n            # Check for unclosed brackets/parentheses (basic check)\n            open_brackets = diagram.count('[') + diagram.count('(') + diagram.count('{')\n            close_brackets = diagram.count(']') + diagram.count(')') + diagram.count('}')\n            if open_brackets != close_brackets:\n                result.add_issue(\n                    Severity.WARNING,\n                    \"Mermaid\",\n                    \"Unclosed brackets or parentheses detected\",\n                    line=block_start\n                )\n\n    def _validate_urls(self, content: str, lines: List[str], result: ValidationResult):\n        \"\"\"Validate URLs in the document.\"\"\"\n        # Find all URLs\n        url_pattern = re.compile(r'https?://[^\\s\\)]+')\n\n        for i, line in enumerate(lines, start=1):\n            urls = url_pattern.findall(line)\n            for url in urls:\n                # Clean URL (remove trailing punctuation)\n                clean_url = re.sub(r'[.,;:]$', '', url)\n\n                # Basic URL format check\n                if not re.match(r'^https?://[a-zA-Z0-9\\-._~:/?#\\[\\]@!$&\\'()*+,;=%]+$', clean_url):\n                    result.add_issue(\n                        Severity.WARNING,\n                        \"URL\",\n                        f\"Potentially malformed URL: {clean_url[:60]}...\",\n                        line=i\n                    )\n\n                # Check for common issues\n                if 'arxiv.org' in clean_url.lower():\n                    if 'abs/' in clean_url and not clean_url.startswith('https://arxiv.org/abs/'):\n                        result.add_issue(\n                            Severity.INFO,\n                            \"URL\",\n                            f\"arXiv URL format may need standardization\",\n                            line=i\n                        )\n\n    def _validate_content_quality(self, content: str, metadata: dict, result: ValidationResult):\n        \"\"\"Perform content quality checks.\"\"\"\n\n        # Get word counts for sections\n        def count_section_text(section_name):\n            pattern = rf'## {section_name}\\s*\\n(.*?)(?=\\n## |\\Z)'\n            match = re.search(pattern, content, re.DOTALL)\n            if match:\n                text = match.group(1)\n                # Remove code blocks\n                text = re.sub(r'```.*?```', '', text, flags=re.DOTALL)\n                return len(text.split())\n            return 0\n\n        # Check Problem section length\n        problem_words = count_section_text(\"Problem\")\n        if problem_words > 0 and problem_words < 20:\n            result.add_issue(\n                Severity.WARNING,\n                \"Content\",\n                f\"Problem section seems too short ({problem_words} words)\",\n                fix_suggestion=\"Expand the problem description to at least 2-3 sentences\"\n            )\n\n        # Check Solution section length\n        solution_words = count_section_text(\"Solution\")\n        if solution_words > 0 and solution_words < 50:\n            result.add_issue(\n                Severity.WARNING,\n                \"Content\",\n                f\"Solution section seems too short ({solution_words} words)\",\n                fix_suggestion=\"Expand the solution description with more implementation details\"\n            )\n\n        # Check for empty sections\n        section_pattern = re.compile(r'## ([^\\n]+)\\s*\\n(.*?)(?=\\n## |\\Z)', re.DOTALL)\n        for match in section_pattern.finditer(content):\n            section_name = match.group(1)\n            section_content = match.group(2).strip()\n            if not section_content or section_content == \"```\":\n                result.add_issue(\n                    Severity.ERROR,\n                    \"Content\",\n                    f\"Section '{section_name}' is empty\",\n                    fix_suggestion=f\"Add content to the '{section_name}' section\"\n                )\n\n        # Check for required blank lines after headers\n        header_pattern = re.compile(r'##[^\\n]+\\n([^\\s#])')\n        for match in header_pattern.finditer(content):\n            line_num = content[:match.start()].count('\\n') + 2\n            char_after = match.group(1)\n            if char_after and char_after != '\\n':\n                result.add_issue(\n                    Severity.WARNING,\n                    \"Formatting\",\n                    \"Headers should be followed by a blank line for proper list rendering\",\n                    line=line_num,\n                    fix_suggestion=\"Add a blank line after the header\"\n                )\n\n\ndef print_validation_result(result: ValidationResult, verbose: bool = False):\n    \"\"\"Print validation results to stdout.\"\"\"\n\n    # Group issues by severity\n    errors = [i for i in result.issues if i.severity == Severity.ERROR]\n    warnings = [i for i in result.issues if i.severity == Severity.WARNING]\n    infos = [i for i in result.issues if i.severity == Severity.INFO]\n\n    # Print status\n    status_icon = \"✅\" if result.is_valid else \"❌\"\n    filename = Path(result.file_path).name\n    print(f\"{status_icon} {filename}: {len(result.issues)} issue(s)\")\n\n    if not verbose and result.is_valid and not warnings:\n        return\n\n    # Print issues\n    for issue in result.issues:\n        severity_icon = {\n            Severity.ERROR: \"❌\",\n            Severity.WARNING: \"⚠️ \",\n            Severity.INFO: \"ℹ️ \",\n        }[issue.severity]\n\n        line_info = f\":{issue.line}\" if issue.line else \"\"\n        print(f\"  {severity_icon} [{issue.category}]{line_info} {issue.message}\")\n\n        if issue.fix_suggestion:\n            print(f\"     💡 {issue.fix_suggestion}\")\n\n    # Print summary\n    if errors:\n        print(f\"  Summary: {len(errors)} error(s), {len(warnings)} warning(s), {len(infos)} info\")\n\n\ndef print_validation_summary(results: List[ValidationResult]):\n    \"\"\"Print overall validation summary.\"\"\"\n\n    total = len(results)\n    valid = sum(1 for r in results if r.is_valid)\n    total_issues = sum(len(r.issues) for r in results)\n\n    print(f\"\\n{'='*60}\")\n    print(f\"SUMMARY: {valid}/{total} files valid, {total_issues} total issue(s)\")\n    print(f\"{'='*60}\")\n\n    # Aggregate counts\n    all_errors = []\n    all_warnings = []\n\n    for result in results:\n        all_errors.extend([i for i in result.issues if i.severity == Severity.ERROR])\n        all_warnings.extend([i for i in result.issues if i.severity == Severity.WARNING])\n\n    # Common issues\n    if all_errors:\n        error_cats = {}\n        for e in all_errors:\n            error_cats[e.category] = error_cats.get(e.category, 0) + 1\n        print(f\"\\nTop error categories:\")\n        for cat, count in sorted(error_cats.items(), key=lambda x: -x[1])[:5]:\n            print(f\"  - {cat}: {count}\")\n\n\ndef export_validation_report(results: List[ValidationResult], output_file: str):\n    \"\"\"Export validation report to Markdown.\"\"\"\n\n    lines = [\n        \"# Pattern Validation Report\",\n        \"\",\n        f\"Generated: {__import__('datetime').datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\",\n        \"\",\n        \"---\",\n        \"\",\n    ]\n\n    for result in results:\n        filename = Path(result.file_path).name\n        status = \"✅ PASS\" if result.is_valid else \"❌ FAIL\"\n\n        lines.extend([\n            f\"## {status}: {filename}\",\n            \"\",\n            f\"Issues found: {len(result.issues)}\",\n            \"\",\n        ])\n\n        if result.issues:\n            for issue in result.issues:\n                severity = issue.severity.value\n                line_info = f\":{issue.line}\" if issue.line else \"\"\n                lines.extend([\n                    f\"**{severity}** [{issue.category}]{line_info}\",\n                    f\"{issue.message}\",\n                ])\n                if issue.fix_suggestion:\n                    lines.append(f\"_Fix: {issue.fix_suggestion}_\")\n                lines.append(\"\")\n\n        lines.extend([\"---\", \"\"])\n\n    with open(output_file, \"w\") as f:\n        f.write(\"\\n\".join(lines))\n\n    print(f\"\\nReport exported to: {output_file}\")\n\n\ndef main():\n    parser = argparse.ArgumentParser(\n        description=\"Validate pattern files for completeness and quality\",\n        formatter_class=argparse.RawDescriptionHelpFormatter,\n        epilog=\"\"\"\nExamples:\n  %(prog)s patterns/new-pattern.md\n  %(prog)s --all\n  %(prog)s --all --verbose --export report.md\n        \"\"\",\n    )\n    parser.add_argument(\n        \"pattern_file\",\n        nargs=\"?\",\n        help=\"Path to pattern file to validate\",\n    )\n    parser.add_argument(\n        \"--all\",\n        \"-a\",\n        action=\"store_true\",\n        help=\"Validate all pattern files\",\n    )\n    parser.add_argument(\n        \"--patterns-dir\",\n        \"-d\",\n        type=str,\n        default=\"patterns\",\n        help=\"Path to patterns directory (default: patterns)\",\n    )\n    parser.add_argument(\n        \"--verbose\",\n        \"-v\",\n        action=\"store_true\",\n        help=\"Print detailed output for each issue\",\n    )\n    parser.add_argument(\n        \"--strict\",\n        \"-s\",\n        action=\"store_true\",\n        help=\"Treat warnings as errors\",\n    )\n    parser.add_argument(\n        \"--export\",\n        \"-e\",\n        type=str,\n        help=\"Export report to Markdown file\",\n    )\n\n    args = parser.parse_args()\n\n    # Validate arguments\n    if not args.all and not args.pattern_file:\n        parser.error(\"Either specify a pattern file or use --all\")\n\n    if args.all and args.pattern_file:\n        parser.error(\"Cannot use --all with a specific pattern file\")\n\n    # Initialize validator\n    validator = PatternValidator(strict=args.strict)\n\n    # Collect files to validate\n    files_to_validate = []\n\n    if args.all:\n        patterns_dir = Path(args.patterns_dir)\n        if not patterns_dir.exists():\n            print(f\"Error: Patterns directory not found: {patterns_dir}\")\n            return 1\n\n        for filepath in sorted(patterns_dir.glob(\"*.md\")):\n            if filepath.name != \"TEMPLATE.md\":\n                files_to_validate.append(str(filepath))\n    else:\n        files_to_validate.append(args.pattern_file)\n\n    # Run validation\n    print(f\"Validating {len(files_to_validate)} file(s)...\\n\")\n\n    results = []\n    for filepath in files_to_validate:\n        if not Path(filepath).exists():\n            print(f\"❌ File not found: {filepath}\")\n            continue\n\n        result = validator.validate_file(filepath)\n        results.append(result)\n        print_validation_result(result, verbose=args.verbose)\n\n    # Print summary\n    if len(results) > 1:\n        print_validation_summary(results)\n\n    # Export if requested\n    if args.export:\n        export_validation_report(results, args.export)\n\n    # Return exit code\n    return 0 if all(r.is_valid for r in results) else 1\n\n\nif __name__ == \"__main__\":\n    sys.exit(main())\n\n<!-- File: .claude/skills/create-pattern/scripts/validate.py (Tokens: ~985 | Category: claude-rule) -->\n#!/usr/bin/env python3\n\"\"\"Validate pattern front-matter against repository schema.\"\"\"\n\nimport sys\nfrom pathlib import Path\n\n# Allowed values for validation\nALLOWED_CATEGORIES = [\n    \"Orchestration & Control\",\n    \"Context & Memory\",\n    \"Feedback Loops\",\n    \"Learning & Adaptation\",\n    \"Reliability & Eval\",\n    \"Security & Safety\",\n    \"Tool Use & Environment\",\n    \"UX & Collaboration\",\n    \"Uncategorized\",\n]\n\nALLOWED_STATUSES = [\n    \"proposed\",\n    \"emerging\",\n    \"established\",\n    \"validated-in-production\",\n    \"best-practice\",\n    \"experimental-but-awesome\",\n    \"rapidly-improving\",\n]\n\nREQUIRED_FIELDS = [\"title\", \"status\", \"authors\", \"based_on\", \"category\", \"source\", \"tags\"]\n\n\ndef extract_frontmatter(file_path: Path) -> tuple[str, dict]:\n    \"\"\"Extract YAML frontmatter from a markdown file.\"\"\"\n    content = file_path.read_text()\n    if not content.startswith(\"---\"):\n        raise ValueError(\"File does not start with frontmatter delimiter\")\n\n    # Find the end of frontmatter\n    end_idx = content.find(\"\\n---\", 4)\n    if end_idx == -1:\n        raise ValueError(\"Frontmatter not properly closed\")\n\n    yaml_str = content[4:end_idx]\n    return content, parse_yaml_simple(yaml_str)\n\n\ndef parse_yaml_simple(yaml_str: str) -> dict:\n    \"\"\"Simple YAML parser for frontmatter - handles basic key: value pairs.\"\"\"\n    result = {}\n    for line in yaml_str.strip().split(\"\\n\"):\n        if \":\" in line and not line.strip().startswith(\"#\"):\n            key, value = line.split(\":\", 1)\n            key = key.strip()\n            value = value.strip()\n\n            # Handle lists\n            if value.startswith(\"[\") and value.endswith(\"]\"):\n                value = [v.strip().strip('\"\\'') for v in value[1:-1].split(\",\")]\n            # Strip quotes from strings\n            elif value.startswith('\"') and value.endswith('\"'):\n                value = value[1:-1]\n            elif value.startswith(\"'\") and value.endswith(\"'\"):\n                value = value[1:-1]\n\n            result[key] = value\n\n    return result\n\n\ndef validate_pattern(file_path: str | Path) -> bool:\n    \"\"\"Validate a pattern file's frontmatter.\"\"\"\n    path = Path(file_path)\n\n    if not path.exists():\n        print(f\"❌ File not found: {path}\")\n        return False\n\n    try:\n        content, frontmatter = extract_frontmatter(path)\n    except ValueError as e:\n        print(f\"❌ {e}\")\n        return False\n\n    errors = []\n\n    # Check required fields\n    for field in REQUIRED_FIELDS:\n        if field not in frontmatter:\n            errors.append(f\"Missing required field: {field}\")\n\n    # Validate category\n    if \"category\" in frontmatter and frontmatter[\"category\"] not in ALLOWED_CATEGORIES:\n        errors.append(\n            f\"Invalid category: {frontmatter['category']}. \"\n            f\"Must be one of: {', '.join(ALLOWED_CATEGORIES)}\"\n        )\n\n    # Validate status\n    if \"status\" in frontmatter and frontmatter[\"status\"] not in ALLOWED_STATUSES:\n        errors.append(\n            f\"Invalid status: {frontmatter['status']}. \"\n            f\"Must be one of: {', '.join(ALLOWED_STATUSES)}\"\n        )\n\n    # Validate authors is a list\n    if \"authors\" in frontmatter and not isinstance(frontmatter[\"authors\"], list):\n        errors.append(\"authors must be a list (e.g., [\\\"Name (@username)\\\"])\")\n\n    # Validate tags is a list\n    if \"tags\" in frontmatter and not isinstance(frontmatter[\"tags\"], list):\n        errors.append(\"tags must be a list (e.g., [tag1, tag2, tag3])\")\n\n    if errors:\n        for error in errors:\n            print(f\"❌ {error}\")\n        return False\n\n    # Check for required sections in content\n    required_sections = [\"## Problem\", \"## Solution\", \"## References\"]\n    for section in required_sections:\n        if section not in content:\n            errors.append(f\"Missing section: {section}\")\n\n    if errors:\n        for error in errors:\n            print(f\"❌ {error}\")\n        return False\n\n    print(f\"✅ Pattern validation passed: {path.name}\")\n    return True\n\n\nif __name__ == \"__main__\":\n    if len(sys.argv) < 2:\n        print(\"Usage: python validate.py <pattern-file.md>\")\n        sys.exit(1)\n\n    success = validate_pattern(sys.argv[1])\n    sys.exit(0 if success else 1)\n\n<!-- File: CLAUDE.md (Tokens: ~1284 | Category: claude-rule) -->\n# CLAUDE.md\n\nThis file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.\n\n## Project Overview\n\nThis is a documentation website for \"Awesome Agentic Patterns\" - a curated catalogue of AI agent design patterns. It uses Astro (apps/web/) to generate a static documentation site that can be deployed to Vercel.\n\n## Key Commands\n\n> **NOTE:** This project uses **bun** as the package manager, not npm.\n\n### Development Workflow\n```bash\n# Initial setup (run once)\nbun install                            # Install dependencies\n\n# Standard development cycle\nbun run dev                            # Serve docs locally at http://localhost:4321\n\n# Building and deployment\nbun run build                          # Build static site to apps/web/dist/\nvercel deploy                          # Deploy to Vercel (primary)\n```\n\n## Architecture\n\nThe project has a unique architecture where pattern documentation drives the entire site:\n\n1. **Pattern Files** (`patterns/*.md`): Source of truth for all patterns\n   - Must include YAML front-matter with: title, status, authors, category, source, tags, summary, signals, anti_signals, updated_at\n   - Content sections: Problem, Solution, How to use it, Trade-offs, References\n\n2. **Data Pipeline**: Pattern files are converted to JSON in `apps/web/public/patterns/`\n   - Astro build reads JSON files to generate pages\n   - Pattern metadata drives navigation and listings\n\n3. **Build Process**:\n   - Astro builds from apps/web/ to apps/web/dist/\n   - Site can be served locally or deployed to Vercel\n\n## Pattern Development Workflow\n\n### Adding New Patterns\n1. **Start with template**: Copy `TEMPLATE.md` (repository root) to create new pattern files in `patterns/`\n2. **Required YAML front-matter**: Every pattern must include:\n   ```yaml\n   ---\n   title: \"Clear, Descriptive Title\"\n   status: \"proposed | emerging | production | foundational\"\n   authors: [\"Contributor Name (@username)\"]\n   based_on: [\"Original Creator (Source)\"]\n   category: \"Orchestration & Control | Context & Memory | Feedback Loops | Learning & Adaptation | Reliability & Eval | Security & Safety | Tool Use & Environment | UX & Collaboration | Uncategorized\"\n   source: \"URL to primary source\"\n   tags: [relevant, keywords, here]\n   summary: \"One sentence that says what the pattern does (the solution)\"  # Shown in the catalog list\n   signals: [\"When to use it\"]          # 2-4 items, shown as \"Use when\"\n   anti_signals: [\"When not to use it\"] # 2-3 items, shown as \"Avoid when\"\n   updated_at: \"YYYY-MM-DD\"  # Required: last content change date — file mtimes differ per machine, so generated data needs an explicit date\n   ---\n   ```\n3. **Required sections**: Problem, Solution, How to use it, Trade-offs, References\n4. **Data sync**: Pattern files must be converted to JSON for the Astro site\n   - Run `bun run build:data` to update the JSON files\n   - JSON files are stored in `apps/web/public/patterns/` and `apps/web/public/data/patterns/`\n   - CI fails if the committed JSON files differ from what the pipeline produces; run the pipeline and commit its output together with the pattern `.md` change\n\n### Content Guidelines\n- Use Mermaid diagrams in patterns for architectural visualization\n- Pattern files support full Markdown with front-matter\n- Community policy for pattern submissions:\n  - Treat this as a community project, not a promotional channel\n  - Reject promotional, sales, affiliate, or backlink-seeding content\n  - For external contributors, prefer links to `github.com`, `github.io`, or non-vendor neutral references\n  - Allow vendor/product links only when the contribution is truly novel and adds clear value\n  - Require submissions to be materially novel and non-repetitive versus existing patterns\n- **CRITICAL**: Always add blank lines after headers before starting bullet point lists\n  - Incorrect: `**Header:**\\n- Item 1` (renders inline)\n  - Correct: `**Header:**\\n\\n- Item 1` (renders as proper list)\n  - This is required for Astro to properly convert Markdown lists to HTML `<ul><li>` elements\n\n### Asset Path Handling\n\n**CRITICAL**: When adding images or other assets that need to work on both localhost and deployed sites:\n\n- **Use absolute paths starting with `/`** in all asset references\n- **Image references**: Use `/image.jpeg` instead of `image.jpeg` in markdown files\n- **Rationale**: Relative paths can work locally but fail on Vercel due to different path resolution behavior\n- **Example fix**: Change `![Image](image.jpeg)` to `![Image](/image.jpeg)`\n\nThis ensures assets load correctly on both local development (`localhost:4321`) and production deployment (`agentic-patterns.com`).\n\n## Technical Architecture\n\n### Build System Components\n- **Astro**: Modern static site generator in `apps/web/`\n- **Pattern JSON files**: Generated data in `apps/web/public/patterns/`\n- **Vercel config**: Build settings in `vercel.json`\n- **TypeScript/Node.js**: Build toolchain\n\n### File Structure\n```\nTEMPLATE.md           # Template for new patterns (repository root)\n\npatterns/              # Source of truth - all pattern .md files\n└── *.md              # Individual pattern files with YAML front-matter\n\napps/web/             # Astro web application\n├── public/\n│   └── patterns/    # JSON pattern data for site generation\n├── src/             # Astro components and pages\n└── dist/            # Build output (deployment artifact)\n```\n\n### Dependencies\n- **Node.js**: Astro framework and build toolchain\n- **Vercel**: Primary deployment platform\n\n## Deployment\n\n- Primary deployment: Vercel (`vercel deploy`)\n- For detailed deployment instructions, see DEPLOYMENT.md\n</yakaai_skills>"}