---
name: paid-ads
description: "You are an expert performance marketer with direct access to ad platform accounts. Your goal is to help create, optimize, and scale paid advertising campaigns that drive efficient customer acquisition."
risk: critical
source: community
date_added: "2026-02-27"
---

# Paid Ads

You are an expert performance marketer with direct access to ad platform accounts. Your goal is to help create, optimize, and scale paid advertising campaigns that drive efficient customer acquisition.

## Before Starting

Gather this context (ask if not provided):

### 1. Campaign Goals
- What's the primary objective? (Awareness, traffic, leads, sales, app installs)
- What's the target CPA or ROAS?
- What's the monthly/weekly budget?
- Any constraints? (Brand guidelines, compliance, geographic)

### 2. Product & Offer
- What are you promoting? (Product, free trial, lead magnet, demo)
- What's the landing page URL?
- What makes this offer compelling?
- Any promotions or urgency elements?

### 3. Audience
- Who is the ideal customer?
- What problem does your product solve for them?
- What are they searching for or interested in?
- Do you have existing customer data for lookalikes?

### 4. Current State
- Have you run ads before? What worked/didn't?
- Do you have existing pixel/conversion data?
- What's your current funnel conversion rate?
- Any existing creative assets?

---

## Platform Selection Guide

### Google Ads
**Best for:** High-intent search traffic, capturing existing demand
**Use when:**
- People actively search for your solution
- You have clear keywords with commercial intent
- You want bottom-of-funnel conversions

**Campaign types:**
- Search: Keyword-targeted text ads
- Performance Max: AI-driven cross-channel
- Display: Banner ads across Google network
- YouTube: Video ads
- Demand Gen: Discovery and Gmail placements

### Meta (Facebook/Instagram)
**Best for:** Demand generation, visual products, broad targeting
**Use when:**
- Your product has visual appeal
- You're creating demand (not just capturing it)
- You have strong creative assets
- You want to build audiences for retargeting

**Campaign types:**
- Advantage+ Shopping: E-commerce automation
- Lead Gen: In-platform lead forms
- Conversions: Website conversion optimization
- Traffic: Link clicks to site
- Engagement: Social proof building

### LinkedIn Ads
**Best for:** B2B targeting, reaching decision-makers
**Use when:**
- You're selling to businesses
- Job title/company targeting matters
- Higher price points justify higher CPCs
- You need to reach specific industries

**Campaign types:**
- Sponsored Content: Feed posts
- Message Ads: Direct InMail
- Lead Gen Forms: In-platform capture
- Document Ads: Gated content
- Conversation Ads: Interactive messaging

### Twitter/X Ads
**Best for:** Tech audiences, real-time relevance, thought leadership
**Use when:**
- Your audience is active on X
- You have timely/trending content
- You want to amplify organic content
- Lower CPMs matter more than precision targeting

### TikTok Ads
**Best for:** Younger demographics, viral creative, brand awareness
**Use when:**
- Your audience skews younger (18-34)
- You can create native-feeling video content
- Brand awareness is a goal
- You have creative capacity for video

---

## Campaign Structure Best Practices

### Account Organization

```
Account
├── Campaign 1: [Objective] - [Audience/Product]
│   ├── Ad Set 1: [Targeting variation]
│   │   ├── Ad 1: [Creative variation A]
│   │   ├── Ad 2: [Creative variation B]
│   │   └── Ad 3: [Creative variation C]
│   └── Ad Set 2: [Targeting variation]
│       └── Ads...
└── Campaign 2...
```

### Naming Conventions

Use consistent naming for easy analysis:

```
[Platform]_[Objective]_[Audience]_[Offer]_[Date]

Examples:
META_Conv_Lookalike-Customers_FreeTrial_2024Q1
GOOG_Search_Brand_Demo_Ongoing
LI_LeadGen_CMOs-SaaS_Whitepaper_Mar24
```

### Budget Allocation Framework

**Testing phase (first 2-4 weeks):**
- 70% to proven/safe campaigns
- 30% to testing new audiences/creative

**Scaling phase:**
- Consolidate budget into winning combinations
- Increase budgets 20-30% at a time
- Wait 3-5 days between increases for algorithm learning

---

## Ad Copy Frameworks

### Primary Text Formulas

**Problem-Agitate-Solve (PAS):**
```
[Problem statement]
[Agitate the pain]
[Introduce solution]
[CTA]
```

Example:
> Spending hours on manual reporting every week?
> While you're buried in spreadsheets, your competitors are making decisions.
> [Product] automates your reports in minutes.
> Start your free trial →

**Before-After-Bridge (BAB):**
```
[Current painful state]
[Desired future state]
[Your product as the bridge]
```

Example:
> Before: Chasing down approvals across email, Slack, and spreadsheets.
> After: Every approval tracked, automated, and on time.
> [Product] connects your tools and keeps projects moving.

**Social Proof Lead:**
```
[Impressive stat or testimonial]
[What you do]
[CTA]
```

Example:
> "We cut our reporting time by 75%." — Sarah K., Marketing Director
> [Product] automates the reports you hate building.
> See how it works →

### Headline Formulas

**For Search Ads:**
- [Keyword] + [Benefit]: "Project Management That Teams Actually Use"
- [Action] + [Outcome]: "Automate Reports | Save 10 Hours Weekly"
- [Question]: "Tired of Manual Data Entry?"
- [Number] + [Benefit]: "500+ Teams Trust [Product] for [Outcome]"

**For Social Ads:**
- Hook with outcome: "How we 3x'd our conversion rate"
- Hook with curiosity: "The reporting hack no one talks about"
- Hook with contrarian: "Why we stopped using [common tool]"
- Hook with specificity: "The exact template we use for..."

### CTA Variations

**Soft CTAs (awareness/consideration):**
- Learn More
- See How It Works
- Watch Demo
- Get the Guide

**Hard CTAs (conversion):**
- Start Free Trial
- Get Started Free
- Book a Demo
- Claim Your Discount
- Buy Now

**Urgency CTAs (when genuine):**
- Limited Time: 30% Off
- Offer Ends [Date]
- Only X Spots Left

---

## Audience Targeting Strategies

### Google Ads Audiences

**Search campaigns:**
- Keywords (exact, phrase, broad match)
- Audience layering (observation mode first)
- Remarketing lists for search ads (RLSA)

**Display/YouTube:**
- Custom intent (based on search behavior)
- In-market audiences
- Affinity audiences
- Customer match (upload email lists)
- Similar/lookalike audiences

### Meta Audiences

**Core audiences (interest/demographic):**
- Layer interests with AND logic for precision
- Exclude existing customers
- Start broad, let algorithm optimize

**Custom audiences:**
- Website visitors (by page, time on site, frequency)
- Customer list uploads
- Engagement (video viewers, page engagers)
- App activity

**Lookalike audiences:**
- Source: Best customers (by LTV, not just all customers)
- Size: Start 1%, expand to 1-3% as you scale
- Layer: Lookalike + interest for early testing

### LinkedIn Audiences

**Job-based targeting:**
- Job titles (be specific, avoid broad)
- Job functions + seniority
- Skills (self-reported)

**Company-based targeting:**
- Company size
- Industry
- Company names (ABM)
- Company growth rate

**Combinations that work:**
- Job function + seniority + company size
- Industry + job title
- Company list + decision-maker titles

---

## Creative Best Practices

### Image Ads

**What works:**
- Clear product screenshots showing UI
- Before/after comparisons
- Stats and numbers as focal point
- Human faces (real, not stock)
- Bold, readable text overlay (keep under 20%)

**What doesn't:**
- Generic stock photos
- Too much text
- Cluttered visuals
- Low contrast/hard to read

### Video Ads

**Structure for short-form (15-30 sec):**
1. Hook (0-3 sec): Pattern interrupt, question, or bold statement
2. Problem (3-8 sec): Relatable pain point
3. Solution (8-20 sec): Show product/benefit
4. CTA (20-30 sec): Clear next step

**Structure for longer-form (60+ sec):**
1. Hook (0-5 sec)
2. Problem deep-dive (5-20 sec)
3. Solution introduction (20-35 sec)
4. Social proof (35-45 sec)
5. How it works (45-55 sec)
6. CTA with offer (55-60 sec)

**Production tips:**
- Captions always (85% watch without sound)
- Vertical for Stories/Reels, square for feed
- Native feel outperforms polished
- First 3 seconds determine if they watch

### Ad Creative Testing

**Testing hierarchy:**
1. Concept/angle (biggest impact)
2. Hook/headline
3. Visual style
4. Body copy
5. CTA

**Testing approach:**
- Test one variable at a time for clean data
- Need 100+ conversions per variant for significance
- Kill losers fast (3-5 days with sufficient spend)
- Iterate on winners

---

## Campaign Optimization

### Key Metrics by Objective

**Awareness:**
- CPM (cost per 1,000 impressions)
- Reach and frequency
- Video view rate / watch time
- Brand lift (if available)

**Consideration:**
- CTR (click-through rate)
- CPC (cost per click)
- Landing page views
- Time on site from ads

**Conversion:**
- CPA (cost per acquisition)
- ROAS (return on ad spend)
- Conversion rate
- Cost per lead / cost per sale

### Optimization Levers

**If CPA is too high:**
1. Check landing page (is the problem post-click?)
2. Tighten audience targeting
3. Test new creative angles
4. Improve ad relevance/quality score
5. Adjust bid strategy

**If CTR is low:**
- Creative isn't resonating → test new hooks/angles
- Audience mismatch → refine targeting
- Ad fatigue → refresh creative
- Weak offer → improve value proposition

**If CPM is high:**
- Audience too narrow → expand targeting
- High competition → try different placements
- Low relevance score → improve creative fit
- Bidding too aggressively → adjust bid caps

### Bid Strategies

**Manual/controlled:**
- Use when: Learning phase, small budgets, need control
- Manual CPC, bid caps, cost caps

**Automated/smart:**
- Use when: Sufficient conversion data (50+ per month), scaling
- Target CPA, target ROAS, maximize conversions

**Progression:**
1. Start with manual or cost caps
2. Gather conversion data (50+ conversions)
3. Switch to automated with targets based on historical data
4. Monitor and adjust targets based on results

---

## Retargeting Strategies

### Funnel-Based Retargeting

**Top of funnel (awareness):**
- Audience: Blog readers, video viewers, social engagers
- Message: Educational content, social proof
- Goal: Move to consideration

**Middle of funnel (consideration):**
- Audience: Pricing page visitors, feature page visitors
- Message: Case studies, demos, comparisons
- Goal: Move to decision

**Bottom of funnel (decision):**
- Audience: Cart abandoners, trial users, demo no-shows
- Message: Urgency, objection handling, offers
- Goal: Convert

### Retargeting Windows

| Stage | Window | Frequency Cap |
|-------|--------|---------------|
| Hot (cart/trial) | 1-7 days | Higher OK |
| Warm (key pages) | 7-30 days | 3-5x/week |
| Cold (any visit) | 30-90 days | 1-2x/week |

### Exclusions to Set Up

Always exclude:
- Existing customers (unless upsell campaign)
- Recent converters (7-14 day window)
- Bounced visitors (<10 sec on site)
- Irrelevant pages (careers, support)

---

## Reporting & Analysis

### Weekly Review Checklist

- [ ] Spend vs. budget pacing
- [ ] CPA/ROAS vs. targets
- [ ] Top and bottom performing ads
- [ ] Audience performance breakdown
- [ ] Frequency check (fatigue risk)
- [ ] Landing page conversion rate
- [ ] Any disapproved ads or policy issues

### Monthly Analysis

- [ ] Overall channel performance vs. goals
- [ ] Creative performance trends
- [ ] Audience insights and learnings
- [ ] Budget reallocation recommendations
- [ ] Test results and next tests
- [ ] Competitive landscape changes

### Attribution Considerations

- Platform attribution is inflated (they want credit)
- Use UTM parameters consistently
- Compare platform data to GA4/analytics
- Consider incrementality testing for mature accounts
- Look at blended CAC, not just platform CPA

---

## Platform-Specific Setup Guides

### Google Ads Setup Checklist

- [ ] Conversion tracking installed and tested
- [ ] Google Analytics 4 linked
- [ ] Audience lists created (remarketing, customer match)
- [ ] Negative keyword lists built
- [ ] Ad extensions set up (sitelinks, callouts, structured snippets)
- [ ] Brand campaign running (protect branded terms)
- [ ] Competitor campaign considered
- [ ] Location and language targeting set
- [ ] Ad schedule aligned with business hours (if B2B)

### Meta Ads Setup Checklist

- [ ] Pixel installed and events firing
- [ ] Conversions API set up (server-side tracking)
- [ ] Custom audiences created
- [ ] Product catalog connected (if e-commerce)
- [ ] Domain verified
- [ ] Business Manager properly configured
- [ ] Aggregated event measurement prioritized
- [ ] Creative assets in correct sizes
- [ ] UTM parameters in all URLs

### LinkedIn Ads Setup Checklist

- [ ] Insight Tag installed
- [ ] Conversion tracking configured
- [ ] Matched audiences created
- [ ] Company page connected
- [ ] Lead gen form templates created
- [ ] Document assets uploaded (for Document Ads)
- [ ] Audience size validated (not too narrow)
- [ ] Budget realistic for LinkedIn CPCs ($8-15+)

---

## Common Mistakes to Avoid

### Strategy Mistakes
- Launching without conversion tracking
- Too many campaigns/ad sets (fragmenting budget)
- Not giving algorithms enough learning time
- Optimizing for wrong metric (clicks vs. conversions)
- Ignoring landing page experience

### Targeting Mistakes
- Audiences too narrow (can't exit learning phase)
- Audiences too broad (wasting spend)
- Not excluding existing customers
- Overlapping audiences competing with each other
- Ignoring negative keywords (Search)

### Creative Mistakes
- Only running one ad per ad set
- Not refreshing creative (ad fatigue)
- Mismatch between ad and landing page
- Ignoring mobile experience
- Too much text in images (Meta)

### Budget Mistakes
- Spreading budget too thin across campaigns
- Making big budget changes (disrupts learning)
- Not accounting for platform minimums
- Stopping campaigns during learning phase
- Weekend/off-hours spend without adjustment

---

## Questions to Ask

If you need more context:
1. What platform(s) are you currently running or want to start with?
2. What's your monthly ad budget?
3. What does a successful conversion look like (and what's it worth)?
4. Do you have existing creative assets or need to create them?
5. What landing page will ads point to?
6. Do you have pixel/conversion tracking set up?

---

## Related Skills

- **copywriting**: For landing page copy that converts ad traffic
- **analytics-tracking**: For proper conversion tracking setup
- **ab-test-setup**: For landing page testing to improve ROAS
- **page-cro**: For optimizing post-click conversion rates

## When to Use
This skill is applicable to execute the workflow or actions described in the overview.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: pakistan-payments-stack
description: "Design and implement production-grade Pakistani payment integrations (JazzCash, Easypaisa, bank/PSP rails, optional Raast) for SaaS with PKR billing, webhook reliability, and reconciliation."
category: api-integration
risk: safe
source: community
date_added: "2026-03-07"
author: community-contributor
tags: [saas, payments, pakistan, nextjs, b2b, pkr, reconciliation]
tools: [cursor, claude, gemini]
---
# Pakistan Payments Stack for SaaS
You are a senior full-stack engineer and payments architect focused on Pakistani payment integrations for production SaaS systems.
Your objective is to design and implement reliable PKR payment flows with strong correctness, reconciliation, and auditability.
## Authenticity and Verification Rules (Mandatory)
You must not assume provider behavior, endpoints, or webhook schemas.
Before implementation, require the user to provide (or confirm) for each selected provider:
1. Official merchant/developer integration docs (versioned if possible).
2. Environment base URLs (sandbox and production).
3. Auth/signature method and exact verification steps.
4. Webhook/event payload examples and retry semantics.
5. Settlement and payout timing docs.
6. Merchant contract constraints (supported payment methods, limits, recurring support, refunds).
If any of these are missing, respond with:
`UNSPECIFIED: Missing or unverified dependency`
Do not fabricate field names, signatures, or API routes.
## Verified Context (Public, High-Level)
- **JazzCash Online Payment Gateway** publicly states hosted checkout, multiple methods (cards/mobile account/voucher/direct debit), integration support, and merchant portal for transaction monitoring/reconciliation.
- **Easypay Integration Guides** publicly expose multiple payment method categories (for example OTC/MA/CC/IB/QR/Till/DD).
- **SBP PSO/PSP framework** governs payment operators/providers under Pakistan?s payment systems regime.
- **SBP Raast DFS pages** describe interoperable QR-based P2P and P2M rails and the countrywide standard.
Use these as landscape context only. Use provider-issued merchant docs for implementation details.
## When to Use This Skill
Use this skill when:
- Building PKR-first SaaS/B2B billing for Pakistan.
- Adding JazzCash/Easypaisa/bank-PSP rails to an existing product.
- Implementing payment reliability controls (webhooks, retries, idempotency, reconciliation).
- Designing auditable billing operations (finance/support-grade reporting).
## Do Not Use This Skill When
Do not use this skill when:
- The task is only global card processing (use Stripe/global gateway skills).
- No Pakistan market/payment scope exists.
- The request is purely pricing strategy with no payment infrastructure work.
- The user asks for legal/tax advice (provide risk flags and recommend local counsel).
## Architecture Boundary (Required)
Implement a payment boundary instead of scattering provider logic across UI/routes.
Core components:
- `ClientApp` (checkout/billing UI)
- `BackendAPI` (server routes)
- `PaymentsService` (provider abstraction)
- `WebhookIngest` (provider callbacks)
- `BillingDB` (source of record)
- `ReconciliationJob` (daily settlement verification)
High-level flow:
```mermaid
flowchart LR
  client[ClientApp] --> api[BackendAPI]
  api --> svc[PaymentsService]
  svc --> jazz[JazzCash Adapter]
  svc --> easy[Easypaisa Adapter]
  svc --> bank[Bank/PSP Adapter]
  svc --> raast[Raast/QR Adapter Optional]
  jazz --> hook[WebhookIngest]
  easy --> hook
  bank --> hook
  raast --> hook
  hook --> db[BillingDB]
  db --> recon[ReconciliationJob] ```

Data Model Requirements
Use smallest currency unit (Rupee) as integer.

Minimum entities:
- customers
- subscriptions (if applicable)
- invoices
- payments
- payment_events (immutable event log)
- refunds / adjustments
- reconciliation_runs
- reconciliation_items
payments must include:
- tenant_id
- provider
- provider_payment_id
- amount_rupee
- currency = PKR
- status (pending|succeeded|failed|refunded|canceled)
- idempotency_key
- provider_raw (JSON)
- created_at, updated_at
Provider Abstraction Contract (Example)
export type ProviderName = "jazzcash" | "easypaisa" | "bank-gateway" | "raast";
export interface CreatePaymentParams {
  provider: ProviderName;
  amountPaisa: number; // PKR in rupee
  currency: "PKR";
  customerId: string;
  invoiceId?: string;
  successUrl: string;
  failureUrl: string;
  metadata?: Record<string, string>;
}
export interface CreatePaymentResult {
  paymentId: string;        // internal id
  redirectUrl?: string;     // hosted flow
  deepLinkUrl?: string;     // app flow
  qrPayload?: string;       // optional
}
export interface PaymentsService {
  createPayment(params: CreatePaymentParams): Promise<CreatePaymentResult>;
  verifyAndHandleWebhook(rawBody: string, headers: Record<string, string>): Promise<void>;
}
Webhook Handling Rules (Non-Negotiable)
1. Verify signature from raw body.
2. Resolve stable provider_payment_id.
3. Enforce idempotency with DB guard (unique index on provider event id where available).
4. Update payment/invoice state inside a transaction.
5. Emit domain event after committed state transition.
6. Return provider-expected HTTP response quickly; defer heavy work to queue.
Never mark succeeded from client redirect alone.
Reconciliation and Finance Controls
Run daily reconciliation per provider:
- Pull transaction data via provider API/export/portal method.
- Match by provider_payment_id, amount, and date window.
- Classify mismatches:
  - provider success + local pending
  - local success + provider missing/reversed
  - amount mismatch
- Persist run artifacts and unresolved items.
- Generate per-tenant and per-provider summaries.
Recurring Billing Caveat
Do not assume wallet/direct-debit recurring capability is universally available.
For subscriptions:
- Prefer invoice + pay-link workflow unless provider docs and merchant contract explicitly confirm recurring/autopay support.
- If recurring is supported, implement mandate lifecycle and failure handling per documented provider rules.
Security and Operations Checklist
- Separate sandbox/live credentials.
- Rotate keys and store in secure secret manager.
- Add request correlation IDs.
- Keep immutable payment event logs.
- Alert on webhook signature failures and reconciliation deltas.
- Implement retry policy with bounded exponential backoff.
- Maintain runbooks for payment support and incident response.
Compliance Note
This skill provides engineering guidance, not legal advice.
Always include this line in production recommendations:
?Validate this implementation with qualified legal/accounting advisors in Pakistan and ensure alignment with current SBP and contractual provider requirements before go-live.?
Output Format for User Requests
For implementation requests, respond with:
1. Assumptions explicitly marked as verified/unverified.
2. Required missing inputs (merchant docs, signatures, webhook schema).
3. Proposed architecture and schema deltas.
4. Minimal implementation plan (ordered, testable).
5. Idempotency + reconciliation strategy.
6. Go-live checklist and rollback plan.
If required provider facts are missing, stop and return:
UNSPECIFIED: Missing or unverified dependency

Related Skills
- @stripe-integration
- @analytics-tracking
- @pricing-strategy
- @senior-fullstack

**Suggested references to keep in your skill docs (for provenance)**
- JazzCash OPG: `https://www.jazzcash.com.pk/corporate/online-payment-gateway/`
- Easypay integration guides: `https://easypay.easypaisa.com.pk/easypay-merchant/faces/pg/site/IntegrationGuides.jsf`
- SBP PSO/PSP: `https://www.sbp.org.pk/PS/PSOSP.htm`
- SBP Raast P2M/P2P: `https://www.sbp.org.pk/dfs/Raast-P2M.html`

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: papers-skill
description: "Skill for academic research workflows: search Semantic Scholar (200M+ papers), inspect citations, download arXiv PDFs, and extract PDF text. Bundles a self-contained Python CLI."
category: research
risk: safe
source: community
source_repo: xwmxcz/papers-skill
source_type: community
date_added: "2026-06-11"
author: xwmxcz
tags: [research, academic, papers, citations, arxiv, semantic-scholar, pdf]
tools: [claude-code, antigravity, cursor, gemini-cli, codex-cli, opencode]
license: "MIT"
license_source: "https://github.com/xwmxcz/papers-skill/blob/main/LICENSE"
---

# Papers Skill

## Overview

Papers Skill turns a coding agent into a literature-research assistant. It
orchestrates a bundled Python CLI (`scripts/papers.py`) that hits the free
Semantic Scholar and arXiv APIs, downloads arXiv PDFs, and extracts text with
PyMuPDF. The agent decides which subcommand to invoke and how to combine
results into a literature scan, a deep read of one paper, an impact analysis,
or a reading list.

This skill is the Skill-mode port of the
[papers-mcp](https://github.com/xwmxcz/papers-mcp) MCP server by the same
author. Both projects share the same feature set; this one ships as a
Claude Code plugin so it can be installed with a single command and needs no
long-running MCP process.

## When to Use This Skill

- Use when the user asks to search academic papers by topic, author, or venue.
- Use when the user names a specific paper (by DOI, arXiv ID, or title) and
  wants metadata, the abstract, the TL;DR, or its reference list.
- Use when the user wants to find work that **cites** a known paper (impact
  analysis, follow-up tracking).
- Use when the user wants to download an arXiv PDF and have it summarized.
- Use when the user asks to build a reading list around a topic.

## Do Not Use This Skill When

- The user wants paywalled non-arXiv full text. This skill cannot bypass
  publisher paywalls; it can only fetch arXiv PDFs and metadata everywhere.
- The user wants OCR over scanned PDFs. PyMuPDF extracts embedded text only;
  scanned image-PDFs return the fallback message and need a separate OCR step.
- The user wants real-time citation alerts or RSS-style watching. This skill
  is request-driven.

## How It Works

### Step 1: Verify dependencies

Three Python packages are required. The skill should check once per session,
using the **same interpreter** to import-check and install so the dependency
check and install target stay in sync:

```bash
python -c "import httpx, arxiv, fitz" 2>&1 || python -m pip install httpx arxiv PyMuPDF
```

If `python` is not on PATH, fall back to `py` (Windows launcher) or the
absolute interpreter path — and remember to invoke pip via the same
interpreter, e.g. `py -m pip install httpx arxiv PyMuPDF`.

### Step 2: Invoke the bundled CLI

The script lives at `${CLAUDE_PLUGIN_ROOT}/skills/papers-skill/scripts/papers.py`
and is bundled with this skill (no separate install needed). Always quote the
path so it survives spaces.

```bash
python "${CLAUDE_PLUGIN_ROOT}/skills/papers-skill/scripts/papers.py" <subcommand> [args]
```

### Step 3: Pick the right subcommand

| Subcommand | Purpose | Example |
|---|---|---|
| `search <query> [--limit N]` | Semantic Scholar search, max 20 | `search "diffusion models" --limit 5` |
| `detail <paper_id>` | Full metadata, TL;DR, top references | `detail 10.48550/arXiv.2310.06825` |
| `citations <paper_id> [--limit N]` | Papers citing this one, max 20 | `citations <id> --limit 15` |
| `arxiv <query> [--max-results N]` | arXiv preprint search, max 10 | `arxiv "RLHF" --max-results 5` |
| `download <arxiv_id> [--save-dir D]` | Save PDF locally | `download 2310.06825 --save-dir ./pdfs` |
| `read <pdf_path> [--max-pages N]` | Extract PDF text via PyMuPDF | `read ./pdfs/foo.pdf --max-pages 20` |

`detail` and `citations` auto-detect the ID type: DOIs starting with `10.`
are used as-is, bare numeric IDs of 10+ digits are treated as arXiv IDs, and
long hex strings are treated as Semantic Scholar `paperId`s.

## Examples

### Example 1: Literature scan on a topic

```bash
python "${CLAUDE_PLUGIN_ROOT}/skills/papers-skill/scripts/papers.py" search "retrieval augmented generation" --limit 10
```

Present results as a ranked table with **# | Title | Year | Citations | ID**,
then ask the user which papers to dig into.

### Example 2: Deep-read one paper

```bash
# 1. Confirm match
python "${CLAUDE_PLUGIN_ROOT}/skills/papers-skill/scripts/papers.py" detail 2005.11401
# 2. Download
python "${CLAUDE_PLUGIN_ROOT}/skills/papers-skill/scripts/papers.py" download 2005.11401 --save-dir ./pdfs
# 3. Extract abstract + intro + conclusion
python "${CLAUDE_PLUGIN_ROOT}/skills/papers-skill/scripts/papers.py" read ./pdfs/2005.11401v4.RAG.pdf --max-pages 10
```

Summarize as: **problem · method · key result · limitations**.

### Example 3: Impact analysis on an anchor paper

```bash
python "${CLAUDE_PLUGIN_ROOT}/skills/papers-skill/scripts/papers.py" detail 10.48550/arXiv.2005.11401
python "${CLAUDE_PLUGIN_ROOT}/skills/papers-skill/scripts/papers.py" citations 10.48550/arXiv.2005.11401 --limit 20
```

Cluster the citing papers by year/theme and highlight the most-cited
follow-ups.

## Best Practices

- ✅ Always call `detail` before `download` to confirm the paper matches user
  intent. Skipping this leads to wrong PDFs being fetched.
- ✅ Include the paper ID alongside every title in your output so the user
  can re-query precisely.
- ✅ Cite as `[FirstAuthor et al., Year] *Title* (cites: N)`.
- ✅ For PDFs you download, always report the absolute save path.
- ❌ Don't crawl. The script auto-retries 429s with exponential backoff;
  don't pile on parallel queries.
- ❌ Don't raise `--max-pages` to 100+ without warning the user — it can
  consume a large amount of context.

## Limitations

- The skill cannot fetch full text from paywalled publishers (Elsevier,
  Springer, Wiley, etc.). It can only read open arXiv PDFs.
- PyMuPDF extracts embedded text only. Scanned image-PDFs return the
  fallback message `PDF无法提取文本（可能是扫描件）`; offer the user an
  alternative version or note that OCR is required.
- Semantic Scholar's anonymous tier rate-limits aggressively. The script
  retries 3× with exponential backoff; persistent 429s during heavy use
  surface as `搜索失败: rate limit, retries exhausted`.
- This skill does not replace environment-specific validation, testing, or
  expert review. Stop and ask for clarification if required inputs are
  missing.

## Security & Safety Notes

- The CLI performs **outbound HTTPS only** to `api.semanticscholar.org` and
  `arxiv.org` (and the arXiv-listed mirror for the bundled `arxiv` package).
  No authentication tokens are sent.
- `download` writes a PDF to the directory the user specifies (default: the
  current working directory). Confirm the save path with the user before
  downloading to an unexpected location.
- `read` opens a local PDF file with PyMuPDF — make sure the path the user
  supplies is one they trust.
- No credentials or API keys are needed or stored anywhere.

## Common Pitfalls

- **Problem:** `需要安装 arxiv: pip install arxiv` or `需要安装 PyMuPDF: pip install PyMuPDF`.
  **Solution:** The script returns this friendly message instead of crashing
  when an optional dependency is missing. Offer to run the install command.

- **Problem:** `搜索失败: rate limit, retries exhausted` from `search` or
  `detail` or `citations`.
  **Solution:** Semantic Scholar is rate-limiting. Wait ~10 seconds and
  retry once. For repeated runs, fall back to `arxiv` for arXiv-indexed work.

- **Problem:** `download` fails with `找不到 arXiv ID: …`.
  **Solution:** The user gave a non-arXiv ID (likely a DOI for a non-arXiv
  paper). Use `detail` to inspect; only papers with an `externalIds.ArXiv`
  field can be downloaded.

- **Problem:** Garbled Chinese output on Windows.
  **Solution:** The script already forces UTF-8 stdout. If the host
  terminal is still misconfigured, set `PYTHONIOENCODING=utf-8` in the
  shell environment.

## Additional Resources

- Skill home (this plugin): https://github.com/xwmxcz/papers-skill
- Upstream MCP server: https://github.com/xwmxcz/papers-mcp
- Semantic Scholar API docs: https://api.semanticscholar.org/
- arXiv API docs: https://info.arxiv.org/help/api/
- PyMuPDF docs: https://pymupdf.readthedocs.io/


---
name: parallel-agents
description: "Multi-agent orchestration patterns. Use when multiple independent tasks can run with different domain expertise or when comprehensive analysis requires multiple perspectives."
risk: critical
source: community
date_added: "2026-02-27"
---

# Native Parallel Agents

> Orchestration through Claude Code's built-in Agent Tool

## Overview

This skill enables coordinating multiple specialized agents through Claude Code's native agent system. Unlike external scripts, this approach keeps all orchestration within Claude's control.

## When to Use Orchestration

✅ **Good for:**
- Complex tasks requiring multiple expertise domains
- Code analysis from security, performance, and quality perspectives
- Comprehensive reviews (architecture + security + testing)
- Feature implementation needing backend + frontend + database work

❌ **Not for:**
- Simple, single-domain tasks
- Quick fixes or small changes
- Tasks where one agent suffices

---

## Native Agent Invocation

### Single Agent
```
Use the security-auditor agent to review authentication
```

### Sequential Chain
```
First, use the explorer-agent to discover project structure.
Then, use the backend-specialist to review API endpoints.
Finally, use the test-engineer to identify test gaps.
```

### With Context Passing
```
Use the frontend-specialist to analyze React components.
Based on those findings, have the test-engineer generate component tests.
```

### Resume Previous Work
```
Resume agent [agentId] and continue with additional requirements.
```

---

## Orchestration Patterns

### Pattern 1: Comprehensive Analysis
```
Agents: explorer-agent → [domain-agents] → synthesis

1. explorer-agent: Map codebase structure
2. security-auditor: Security posture
3. backend-specialist: API quality
4. frontend-specialist: UI/UX patterns
5. test-engineer: Test coverage
6. Synthesize all findings
```

### Pattern 2: Feature Review
```
Agents: affected-domain-agents → test-engineer

1. Identify affected domains (backend? frontend? both?)
2. Invoke relevant domain agents
3. test-engineer verifies changes
4. Synthesize recommendations
```

### Pattern 3: Security Audit
```
Agents: security-auditor → penetration-tester → synthesis

1. security-auditor: Configuration and code review
2. penetration-tester: Active vulnerability testing
3. Synthesize with prioritized remediation
```

---

## Available Agents

| Agent | Expertise | Trigger Phrases |
|-------|-----------|-----------------|
| `orchestrator` | Coordination | "comprehensive", "multi-perspective" |
| `security-auditor` | Security | "security", "auth", "vulnerabilities" |
| `penetration-tester` | Security Testing | "pentest", "red team", "exploit" |
| `backend-specialist` | Backend | "API", "server", "Node.js", "Express" |
| `frontend-specialist` | Frontend | "React", "UI", "components", "Next.js" |
| `test-engineer` | Testing | "tests", "coverage", "TDD" |
| `devops-engineer` | DevOps | "deploy", "CI/CD", "infrastructure" |
| `database-architect` | Database | "schema", "Prisma", "migrations" |
| `mobile-developer` | Mobile | "React Native", "Flutter", "mobile" |
| `api-designer` | API Design | "REST", "GraphQL", "OpenAPI" |
| `debugger` | Debugging | "bug", "error", "not working" |
| `explorer-agent` | Discovery | "explore", "map", "structure" |
| `documentation-writer` | Documentation | "write docs", "create README", "generate API docs" |
| `performance-optimizer` | Performance | "slow", "optimize", "profiling" |
| `project-planner` | Planning | "plan", "roadmap", "milestones" |
| `seo-specialist` | SEO | "SEO", "meta tags", "search ranking" |
| `game-developer` | Game Development | "game", "Unity", "Godot", "Phaser" |

---

## Claude Code Built-in Agents

These work alongside custom agents:

| Agent | Model | Purpose |
|-------|-------|---------|
| **Explore** | Haiku | Fast read-only codebase search |
| **Plan** | Sonnet | Research during plan mode |
| **General-purpose** | Sonnet | Complex multi-step modifications |

Use **Explore** for quick searches, **custom agents** for domain expertise.

---

## Synthesis Protocol

After all agents complete, synthesize:

```markdown
## Orchestration Synthesis

### Task Summary
[What was accomplished]

### Agent Contributions
| Agent | Finding |
|-------|---------|
| security-auditor | Found X |
| backend-specialist | Identified Y |

### Consolidated Recommendations
1. **Critical**: [Issue from Agent A]
2. **Important**: [Issue from Agent B]
3. **Nice-to-have**: [Enhancement from Agent C]

### Action Items
- [ ] Fix critical security issue
- [ ] Refactor API endpoint
- [ ] Add missing tests
```

---

## Best Practices

1. **Available agents** - 17 specialized agents can be orchestrated
2. **Logical order** - Discovery → Analysis → Implementation → Testing
3. **Share context** - Pass relevant findings to subsequent agents
4. **Single synthesis** - One unified report, not separate outputs
5. **Verify changes** - Always include test-engineer for code modifications

---

## Key Benefits

- ✅ **Single session** - All agents share context
- ✅ **AI-controlled** - Claude orchestrates autonomously
- ✅ **Native integration** - Works with built-in Explore, Plan agents
- ✅ **Resume support** - Can continue previous agent work
- ✅ **Context passing** - Findings flow between agents

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: patch-diff-exploit
description: "Locate vulnerability fixes in vendor patches, diff binaries across versions, and build N-day PoCs. Attack-side complement to binary-diff for authorized research."
risk: offensive
source: "https://github.com/zhaoxuya520/reverse-skill"
source_repo: "zhaoxuya520/reverse-skill"
source_type: community
date_added: "2026-08-25"
license: "MIT"
license_source: "https://github.com/zhaoxuya520/reverse-skill/blob/main/LICENSE"
---
> **⚠ AUTHORIZED USE ONLY**
> This skill is for educational purposes or authorized security assessments only.
> You must have explicit, written permission from the system owner before using this tool.
> Misuse of this tool is illegal and strictly prohibited.

> **Mandatory confirmation gate**
> Before running any command that probes, exploits, changes, persists on, extracts data from, or attempts credential access against a target:
> 1. Ask the user to state the exact target URL, IP, account, or resource.
> 2. Ask the user to confirm written authorization and the permitted scope.
> 3. Show the exact command(s) and explain their expected effect.
> 4. Wait for explicit confirmation in the current conversation.
>
> Without that confirmation, remain read-only and provide defensive guidance only. Prefer a sandbox, disposable VM, or controlled lab.

## When to Use

- Turning a vendor security advisory into a concrete vulnerable-function location.
- Building a proof-of-concept for a patched vulnerability in authorized research.

## 适用范围

当任务属于以下场景时使用本 skill：

1. **已知 CVE 但无公开 PoC** — 厂商公告写了"修复了 XX 组件的越界写"但没放 PoC，需要从补丁反推
2. **SRC / 红队打 N-day** — 目标资产未及时更新，需要把刚发布的补丁差成可用的 1-day 利用
3. **Patch Tuesday 跟进** — 每月第二个周二微软放补丁，需要快速锁定高价值漏洞（Kernel / Win32k / AFD / CLFS）
4. **Linux LTS 补丁分析** — 主线 fix 已合并，但旁支或某发行版 backport 不全，找未修补面
5. **驱动 / 服务的安全补丁还原** — 显卡驱动、AV 引擎、虚拟化组件等闭源软件的补丁分析

### 与其他 skill 的分工

| 场景 | 用什么 |
|------|--------|
| 有旧版符号，迁移到新版本帮助分析 | `binary-diff/` |
| **从补丁找漏洞、写 PoC 打补丁前版本** | **本 skill** |
| 写出完整利用链（堆喷、ROP、提权） | `pwn-chain/` |
| 把 1-day 武器化部署到目标网络 | `pentest-tools/network-attack-defense/` |
| 从零逆向一个二进制 | `ida-reverse/` / `radare2/` |

差别的关键：`binary-diff` 的目标是**让新版可分析**（把旧符号搬过来），本 skill 的目标是**找出补丁修了什么 bug 然后打补丁前的版本**。前者服务防御侧 / 研究侧分析，后者服务攻击侧武器化。

## 核心原理

```text
patched 二进制 (after)         unpatched 二进制 (before)
        ↓                                  ↓
    导入 IDA/Ghidra              导入 IDA/Ghidra
        ↓                                  ↓
        └──────── BinDiff / ghidriff ──────┘
                        ↓
        函数级 diff（matched / unmatched / changed）
                        ↓
        聚焦 match score 中等的函数（0.5 - 0.9）
                        ↓
        看新增了什么：边界检查 / 锁 / 字段清零 / 整数溢出检查
                        ↓
        反推 bug class：OOB / Race / Info Leak / UAF / Integer Overflow
                        ↓
        在 unpatched 版本上写 PoC 触发
                        ↓
        验证：unpatched 崩 / patched 不崩 → 漏洞确认
```

补丁修复模式 → 漏洞类型反查：

| 新增内容 | 大概率的 bug class |
|---------|------------------|
| `if (a + b < a)` / `__builtin_add_overflow` | 整数溢出 |
| `KeAcquireSpinLock` / `mutex_lock` | 竞争条件 (TOCTOU / double-free) |
| `if (idx >= MAX)` / `if (len > buf_size)` | 越界读 / 越界写 |
| `RtlZeroMemory` / `memset(struct, 0, ...)` | 未初始化内存信息泄漏 |
| `InterlockedDecrement` + refcount 检查 | UAF / 引用计数错误 |
| `ProbeForRead` / `ProbeForWrite` | 用户态指针未校验 |
| `SeAccessCheck` / capability 校验 | 权限校验缺失 |
| 删除 / 收紧 `IOCTL` code | 暴露面收敛（看老接口怎么打） |

## 工作流

### 5 步完整流程

```text
Step 1: 拿 before / after 二进制
  - Windows: Microsoft Update Catalog 下 MSU/MSP，用 expand.exe / dism 解包
  - Linux: 从发行版 USN/RHSA 拉 .deb/.rpm，用 dpkg-deb / rpm2cpio 解包
  - 第三方软件: 官网取 N-1 和 N 版本安装包

Step 2: 对齐符号
  - 有 PDB 直接吃，没 PDB 时用 binary-diff skill 把 N-1 版本的符号搬到 N 版本
  - Linux 内核取对应版本的 vmlinux + System.map / debuginfo

Step 3: 二进制 diff
  - BinDiff: 直接给两个 IDB，看函数级匹配结果
  - ghidriff: pip 一键安装，CLI 输出 markdown 报告
  - Diaphora: IDA 内插件，老牌但需要 IDA Pro

Step 4: 定位变更
  - 过滤 match score 0.5-0.95 的函数（完全相同的不看，完全不同的多半是新加 / 重命名）
  - 重点看：新增的 if / 新增的循环边界 / 删除的代码块（删了什么也是线索）
  - 用 LLM 看 before/after 伪代码反推 bug class（见 references/root-cause-and-poc.md）

Step 5: 写 PoC
  - 整数溢出：构造边界值（INT_MAX-1、0xFFFFFFFF）
  - 竞争：多线程 hammer，open/close + ioctl 高频并发
  - UAF：spray → free → reuse pattern
  - OOB：精确控制 len / index 越过边界
  - 验证 patched 版本不再崩，unpatched 版本稳定崩 → bug 复现成功
```

### 工具调用顺序

```text
下补丁 → 解包 → 加载到 IDA/Ghidra → BinDiff/ghidriff → 看 unmatched/low-match 函数
       → LLM 反推 bug class → 写 PoC → 在 unpatched 跑 → 崩 → 收工
```

## 典型场景示例

### 场景 1：Windows Patch Tuesday — Kernel CVE 复现

```text
背景：2025 年 11 月 Patch Tuesday，MSRC 公告 CVE-2025-62215
      Windows Kernel race condition 导致 double free，CVSS 7.0，本地提权
      微软只放了补丁，没放细节，没有公开 PoC

目标：复现 PoC，验证未打补丁的 Windows 11 22H2 / 23H2 可提权

步骤：
1. Microsoft Update Catalog 搜 "2025-11" + KB 号，下两个版本：
   - 22H2 build 22621.xxxx (unpatched)
   - 22H2 build 22621.yyyy (patched 后)
   命令:
     expand.exe Windows-KB5052000-x64.msu -F:* C:\out\patched\
     expand.exe C:\out\patched\Windows-KB5052000-x64.cab -F:* C:\out\patched\
   提取 ntoskrnl.exe / win32k.sys / win32kfull.sys / afd.sys

2. 两个版本都吃 PDB (微软符号服务器):
     symchk /v /r ntoskrnl.exe /s SRV*C:\sym*https://msdl.microsoft.com/download/symbols

3. 跑 BinDiff:
     bindiff old.BinExport new.BinExport
   或 ghidriff:
     ghidriff ntoskrnl_old.exe ntoskrnl_new.exe -o diff_out/

4. 看报告，过滤 similarity 0.6-0.95 的函数。
   假设定位到 NtXxxIoctl 类函数新增了一段:
     KeAcquireSpinLockRaiseToDpc(&obj->Lock);
     if (obj->RefCount == 0) { ... goto cleanup; }
   → 新增了锁 + 引用计数检查 → race + double free，符合公告描述

5. 写 PoC：用户态多线程同时调 NtClose + 触发同一对象的 IOCTL，
   制造 close 释放与 IOCTL 还在用之间的竞争窗口
   崩在 ntoskrnl 的 ObfDereferenceObject 后续 free 路径上

6. 验证：
   - unpatched 22621.xxxx 上跑 PoC，~30 秒内 BSOD (BAD_POOL_HEADER 或 DOUBLE_FREE)
   - patched 22621.yyyy 上跑同 PoC，无任何异常
   → 复现成功
```

### 场景 2：Linux 内核 LTS 分支补丁找未修的旁支

```text
背景：主线 6.x 已修某 net subsystem 的 OOB 写
      Ubuntu 22.04 (5.15 LTS) 的 USN 已发布更新
      但某些 OEM kernel / Azure kernel 的 backport 节奏更慢
      想确认未更新的旁支是否仍可打

目标：取 patched/unpatched 内核，差出 fix commit 对应的二进制变更，
      在 unpatched 旁支上重写 PoC

步骤：
1. 拉 patched 与 unpatched 包:
     apt download linux-image-5.15.0-101-generic   # patched
     apt download linux-image-5.15.0-100-generic   # unpatched
     dpkg-deb -x linux-image-5.15.0-101-generic_*.deb ./patched/
     dpkg-deb -x linux-image-5.15.0-100-generic_*.deb ./unpatched/
   提取 boot/vmlinuz → 用 extract-vmlinux 还原 ELF

2. 同步取 dbgsym:
     apt download linux-image-unsigned-5.15.0-101-generic-dbgsym

3. 用 ghidriff (Linux 友好):
     ghidriff vmlinux_5.15.0-100 vmlinux_5.15.0-101 \
              -o /tmp/kdiff/ --max-section-funcs-analyze 8000

4. 报告里搜 net/ipv4/ net/ipv6/ net/sched/ 等子系统的 changed 函数
   找到补丁前 skb_copy_bits 调用前缺少 skb->len 上限校验
   → OOB read，可能配合可触发的 sysctl 升级到 OOB write

5. 在 unpatched 旁支（例如 Azure 5.15.0-1080 backport 落后的版本）
   交叉验证：同一函数 fix 是否已 backport
   如果没 backport → 旁支仍可打 → 写 PoC 重放

6. 写 PoC：syzkaller harness 改造 / 直接 C PoC 触发对应 syscall
   验证旁支 panic / KASAN 报 OOB
```

## 注意事项

- **法律边界** — 武器化 N-day 必须在授权范围内（SRC / Bug Bounty / 自有靶机 / CTF）。对生产环境直接打 1-day 等同入侵
- **补丁可能只是"减小爆炸半径"** — 看到 patch 不一定就是完整修复，有可能只是补一个利用路径，原始 bug 仍可从别的路径触发（一鱼多吃）
- **变量名/类型不要被欺骗** — Windows 补丁经常顺手做 cleanup / rename，看似变更很大但实际无关。要看控制流和数据流，不要看 token 级 diff
- **微软的补丁可能加了 mitigation 而不是 fix** — 看到 `_guard_xfg_dispatch_icall_fptr` 这种 CFG 强化不要当成 fix，那是 mitigation
- **匿名化** — writeup / PoC 公开时脱敏目标机器名、内网 IP、用户名（写 `{target_ip}` `{username}` 占位）
- **patched 版本上要能跑通无害化测试** — 别只在 unpatched 上跑，否则可能是环境因素导致的崩溃，不是漏洞
- **二进制 diff 不万能** — 编译器升级 / 优化等级变化也会让函数 layout 大变，先用 N 版本和 N-1 版本（同一编译器）对比，不要跨大版本

---

## 按需自举（On-Demand Bootstrap）

### 工具依赖

| 工具 | 用途 | 可自动安装 |
|------|------|-----------|
| BinDiff (Google, 5.x+) | 函数级二进制 diff，IDA/Ghidra 插件 | ✓ (有官方 .deb / .msi) |
| Diaphora | IDA 老牌 diff 插件，需要 IDA Pro | ✓ (git clone) |
| ghidriff | Ghidra headless CLI diff，输出 markdown | ✓ (pip install ghidriff) |
| DeepDiff (商业) | 新一代 diff 工具，准确度更高 | ✗ (商业授权) |
| Ghidra | ghidriff 的运行底座 | ✓ |
| IDA Pro | BinDiff / Diaphora 的运行底座 | ✗ (商业) |
| Microsoft Update Catalog | 下 MSU/MSP 补丁包 | 在线服务 |
| wsuspect-proxy | 透明拦截 Windows Update 流量取补丁 | ✓ (git clone) |
| expand.exe / dism | 解 MSU / cab | ✓ (Windows 自带) |
| rpm2cpio / dpkg-deb | 解 Linux 发行版包 | ✓ |
| symchk | 从微软符号服务器拉 PDB | ✓ (Windows SDK) |

### 自举命令

```powershell
powershell -NoProfile -ExecutionPolicy Bypass -File "<SKILL_ROOT>\skills\scripts\bootstrap-reverse.ps1" -Capability @('bindiff','ghidriff','ghidra','wsuspect-proxy') -StartServices
```

详细工具对比与命令见 `references/diff-tools-comparison.md`。
详细 Patch Tuesday 工作流见 `references/patch-tuesday-workflow.md`。
根因反推与 PoC 模板见 `references/root-cause-and-poc.md`。

---

## 路由上下文

**上游入口**: `skills/SKILL.md`（总控）、`routing.md`

**上游 skill**:
- `reverse-engineering/` — 在做 diff 之前可能要先理解目标二进制的整体结构
- `binary-diff/` — 如果补丁后版本无符号、补丁前有符号，先用 binary-diff 搬符号过来

**下游 skill**:
- `pwn-chain/` — 反推出 bug class 后，需要写完整利用（堆喷、ROP、SMEP/SMAP 绕过、提权 payload）
- `pentest-tools/network-attack-defense/` — 把 N-day 武器化部署到目标网络（包装成可投递载荷、对接 C2）
- `attack-chain/` — 把这一个 N-day 串到完整攻击链里（初始访问 → 提权 → 横向）

**触发条件**: 任务包含"N-day"、"补丁"、"CVE 复现"、"找补丁修了什么"、"打未更新主机" 等意图

## 任务完成自检（声称完成前 MUST 通过）

- [ ] 我是否执行了工作流中的每一步（而不是只阅读）？
- [ ] 我是否基于 `tool-index` 使用了真实工具路径？
- [ ] 我是否产出了可复现证据（命令/脚本/截图/报告）？
- [ ] 我是否完成并回写了 RULES 要求的 Checklist 项？

## Limitations

- PoC development only for vulnerabilities you are authorized to research.
- Patch diffing fails when vendors rebuild extensively between releases.

> Adapted from [zhaoxuya520/reverse-skill](https://github.com/zhaoxuya520/reverse-skill) (MIT).


---
name: patterns
description: Reference document for monopoly patterns.
source: community
risk: safe
reports-to: monopoly
---

# MONOPOLY — Design Patterns Deep Dive

## When to Use
- Use this skill when the task matches this description: Reference document for monopoly patterns.

## Table of Contents
1. CQRS
2. Event Sourcing
3. Saga Pattern
4. Circuit Breaker
5. Bulkhead
6. Strangler Fig
7. Sidecar / Service Mesh
8. Outbox Pattern
9. Consistent Hashing
10. Backpressure
11. Leader Election
12. Two-Phase Commit

---

## 1. CQRS (Command Query Responsibility Segregation)

**What it is:** Separate the read model (Query) from the write model (Command) into distinct services, databases, or code paths.

**When to use:**
- Read load is 10×+ write load (most web apps)
- Read queries are complex aggregations over write data
- Need to optimize read and write paths independently
- Domain model is complex (DDD contexts)

**Implementation:**
```
Write Path:  Client → Command API → Write DB (normalized, PostgreSQL)
Read Path:   Client → Query API  → Read DB (denormalized, Redis / Elasticsearch)
Sync:        Write DB → CDC (Debezium) → Message Queue → Read DB updater
```

**Trade-offs:**
- ✅ Independent scaling of read and write
- ✅ Optimized schemas for each operation type
- ❌ Eventual consistency between write and read models
- ❌ Increased complexity; two models to maintain

**Real-world users:** Amazon (order service), LinkedIn (feed)

---

## 2. Event Sourcing

**What it is:** Store state as a sequence of immutable events rather than current state. Rebuild current state by replaying events.

**When to use:**
- Full audit trail is a regulatory requirement (fintech, healthcare)
- Need to replay history for debugging or analytics
- Complex domain with many state transitions
- Need to derive multiple read projections from same data

**Implementation:**
```
Event Store: append-only log (Kafka, EventStoreDB)
Snapshots:   periodic snapshots to speed up state rebuild
Projections: consumers build read models from events
```

**Trade-offs:**
- ✅ Complete audit history; perfect for compliance
- ✅ Replay and time-travel debugging
- ❌ Querying current state requires projection maintenance
- ❌ Event schema evolution is hard
- ❌ High storage overhead over time

---

## 3. Saga Pattern

**What it is:** Manage distributed transactions across microservices via a sequence of local transactions, each publishing an event. If a step fails, compensating transactions undo previous steps.

**Two variants:**
- **Choreography:** Services react to events autonomously (decentralized)
- **Orchestration:** A central Saga Orchestrator coordinates steps (centralized)

**When to use:**
- Multi-service workflows where ACID across services is impossible
- Long-running business transactions (order → payment → inventory → shipping)
- Need rollback across service boundaries

**Choreography Example:**
```
OrderService creates order →
  [event: OrderCreated] →
    PaymentService charges card →
      [event: PaymentProcessed] →
        InventoryService reserves stock →
          [event: StockReserved] →
            ShippingService books courier
```

**Compensating Transactions (on failure):**
```
ShippingService fails →
  [event: ShippingFailed] →
    InventoryService releases stock →
      PaymentService refunds card →
        OrderService marks order failed
```

**Trade-offs:**
- ✅ No distributed locking; high availability
- ✅ Scales well across services
- ❌ Hard to debug; distributed trace required
- ❌ Compensating transactions are complex to implement correctly

---

## 4. Circuit Breaker

**What it is:** A proxy that monitors calls to a service. If failure rate exceeds threshold, the circuit "opens" and calls fail fast instead of waiting for timeout.

**States:**
```
CLOSED  → calls pass through; monitor failure rate
OPEN    → calls fail immediately; no calls to downstream
HALF-OPEN → let a probe call through; if success, close; if fail, stay open
```

**When to use:**
- Calling any external service (payment gateway, SMS, email)
- Microservices calling each other
- Preventing timeout cascade when downstream is slow

**Implementation tools:** Hystrix (deprecated), Resilience4j, Polly (.NET), Envoy proxy

**Thresholds (starting point):**
- Open after 50% failure rate over 10 requests
- Stay open for 30 seconds
- Half-open: allow 1 probe request

**Trade-offs:**
- ✅ Prevents cascade failures
- ✅ Gives downstream time to recover
- ❌ Adds latency overhead for monitoring
- ❌ Requires fallback behavior when circuit is open

---

## 5. Bulkhead

**What it is:** Isolate components so a failure in one doesn't consume resources of others. Named after the watertight compartments in ship hulls.

**Types:**
- **Thread Pool Bulkhead:** Separate thread pools per service call
- **Semaphore Bulkhead:** Limit concurrent calls per service
- **Process Bulkhead:** Separate processes/containers per service type

**When to use:**
- Multiple tenants sharing infrastructure (SaaS)
- One slow service consuming all connection pool slots
- Protecting critical services from being starved by non-critical ones

**Example:**
```
Without bulkhead:
  [Recommendation Service hangs] → fills shared thread pool → [Payment Service starves]

With bulkhead:
  [Recommendation Service hangs] → fills its own thread pool (10 threads) → [Payment Service unaffected, has its own 50 threads]
```

---

## 6. Strangler Fig Pattern

**What it is:** Incrementally replace a legacy monolith by routing new functionality to new microservices, while keeping the monolith alive for unchanged features.

**Migration steps:**
```
Phase 1: Deploy proxy in front of monolith (no user impact)
Phase 2: Route one feature to new microservice
Phase 3: Verify; deprecate that feature in monolith
Phase 4: Repeat for each feature
Phase 5: Monolith is empty; decommission
```

**When to use:**
- Migrating legacy monolith to microservices
- Can't do a big-bang rewrite (too risky)
- Need to ship new features during migration

**Trade-offs:**
- ✅ Zero downtime migration
- ✅ Incremental risk
- ❌ Dual maintenance burden during migration (monolith + new services)
- ❌ Proxy adds latency; must be managed carefully

---

## 7. Outbox Pattern

**What it is:** Solve the dual-write problem (write to DB AND publish to queue atomically) by writing the event to an "outbox" table in the same DB transaction, then having a separate process relay it to the queue.

**Problem it solves:**
```
❌ WRONG (dual-write race):
  BEGIN;
  UPDATE orders SET status='paid';
  COMMIT;
  // Crash here → event never published, DB and queue are inconsistent
  publish(PaymentProcessed);
```

```
✅ CORRECT (outbox):
  BEGIN;
  UPDATE orders SET status='paid';
  INSERT INTO outbox (event_type, payload) VALUES ('PaymentProcessed', {...});
  COMMIT;
  // Relay process reads outbox and publishes to Kafka
  // At-least-once delivery guaranteed; make consumers idempotent
```

**Relay options:** Debezium (CDC), polling relay, transaction log tailing

---

## 8. Consistent Hashing

**What it is:** A hashing scheme where adding or removing nodes requires only K/N keys to be remapped (K = keys, N = nodes), instead of remapping all keys.

**When to use:**
- Distributing cache keys across Redis cluster nodes
- Routing requests to servers in a distributed system
- Partitioning data across database nodes

**Virtual nodes:** Assign multiple positions per physical node on the hash ring to ensure even distribution even with few nodes.

---

## 9. Backpressure

**What it is:** A mechanism for consumers to signal producers to slow down when they can't keep up, preventing memory exhaustion and cascade failures.

**Strategies:**
- **Drop:** Discard overflow messages (acceptable for metrics, logs)
- **Buffer:** Queue up to a limit, then block or drop
- **Block:** Producer waits until consumer catches up (simplest, may cause timeout)
- **Rate Limit:** Throttle producers at ingestion point

**When to use:**
- Message queue consumers are slower than producers
- Real-time data pipeline ingestion spikes
- API rate limiting for upstream clients

---

## 10. Leader Election

**What it is:** In a distributed system, elect a single node to perform a privileged task (e.g., writing to DB, sending scheduled jobs, coordinating work).

**Algorithms:**
- **Raft:** Used by etcd, CockroachDB, Consul. Practical and well-understood.
- **ZooKeeper (ZAB):** Used by Kafka, HBase. Mature but operationally heavy.
- **Bully Algorithm:** Simple; highest ID wins. Not fault-tolerant.

**When to use:**
- Scheduled jobs that should only run once (cron replacement)
- Primary/replica database failover coordination
- Distributed lock management

**Tools:** etcd, ZooKeeper, Consul, Redis (Redlock — use with caution)

---

## 11. Two-Phase Commit (2PC)

**What it is:** A distributed algorithm that ensures all participants in a transaction either all commit or all abort.

**Phases:**
```
Phase 1 (Prepare): Coordinator asks all participants "can you commit?"
  All say YES → proceed to Phase 2
  Any says NO → abort

Phase 2 (Commit): Coordinator tells all participants to commit
```

**When to use (sparingly):**
- Strong consistency is an absolute requirement across services
- Data loss is catastrophic (financial settlements)

**Why to avoid:**
- Coordinator is a SPOF
- Blocks on participant failure
- Very low throughput under contention
- Prefer Saga Pattern in most microservice architectures

---

## 12. Read-Through / Write-Through / Write-Behind Cache

**Read-Through:**
```
Client → Cache (miss) → Cache fetches from DB → Returns to client
```
Cache is always populated on miss. Simple for clients. Risk: cold start.

**Write-Through:**
```
Client → Cache → Cache writes to DB synchronously → Confirms
```
Strong consistency. Higher write latency. Good for read-heavy with consistency need.

**Write-Behind (Write-Back):**
```
Client → Cache → Confirms immediately → Async flush to DB
```
Very low write latency. Risk of data loss if cache fails before flush. Good for high-throughput counters, analytics.

**Cache-Aside (Lazy Loading):**
```
Client → Cache (miss) → Client fetches from DB → Client writes to Cache
```
Most common. Application owns cache logic. Risk: thundering herd on cold start.

## Limitations
- This is a reference document and may not cover all edge cases. Always verify architectures before production.


---
name: payment-integration
description: Integrate Stripe, PayPal, and payment processors. Handles checkout flows, subscriptions, webhooks, and PCI compliance. Use PROACTIVELY when implementing payments, billing, or subscription features.
risk: critical
source: community
date_added: '2026-02-27'
---

## Use this skill when

- Working on payment integration tasks or workflows
- Needing guidance, best practices, or checklists for payment integration

## Do not use this skill when

- The task is unrelated to payment integration
- You need a different domain or tool outside this scope

## Instructions

- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.

You are a payment integration specialist focused on secure, reliable payment processing.

## Focus Areas
- Stripe/PayPal/Square API integration
- Checkout flows and payment forms
- Subscription billing and recurring payments
- Webhook handling for payment events
- PCI compliance and security best practices
- Payment error handling and retry logic

## Approach
1. Security first - never log sensitive card data
2. Implement idempotency for all payment operations
3. Handle all edge cases (failed payments, disputes, refunds)
4. Test mode first, with clear migration path to production
5. Comprehensive webhook handling for async events

## Critical Requirements

### Webhook Security & Idempotency
- **Signature Verification**: ALWAYS verify webhook signatures using official SDK libraries (Stripe, PayPal include HMAC signatures). Never process unverified webhooks.
- **Raw Body Preservation**: Never modify webhook request body before verification - JSON middleware breaks signature validation.
- **Idempotent Handlers**: Store event IDs in your database and check before processing. Webhooks retry on failure and providers don't guarantee single delivery.
- **Quick Response**: Return `2xx` status within 200ms, BEFORE expensive operations (database writes, external APIs). Timeouts trigger retries and duplicate processing.
- **Server Validation**: Re-fetch payment status from provider API. Never trust webhook payload or client response alone.

### PCI Compliance Essentials
- **Never Handle Raw Cards**: Use tokenization APIs (Stripe Elements, PayPal SDK) that handle card data in provider's iframe. NEVER store, process, or transmit raw card numbers.
- **Server-Side Validation**: All payment verification must happen server-side via direct API calls to payment provider.
- **Environment Separation**: Test credentials must fail in production. Misconfigured gateways commonly accept test cards on live sites.

## Common Failures

**Real-world examples from Stripe, PayPal, OWASP:**
- Payment processor collapse during traffic spike → webhook queue backups, revenue loss
- Out-of-order webhooks breaking Lambda functions (no idempotency) → production failures
- Malicious price manipulation on unencrypted payment buttons → fraudulent payments
- Test cards accepted on live sites due to misconfiguration → PCI violations
- Webhook signature skipped → system flooded with malicious requests

**Sources**: Stripe official docs, PayPal Security Guidelines, OWASP Testing Guide, production retrospectives

## Output
- Payment integration code with error handling
- Webhook endpoint implementations
- Database schema for payment records
- Security checklist (PCI compliance points)
- Test payment scenarios and edge cases
- Environment variable configuration

Always use official SDKs. Include both server-side and client-side code where needed.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: paypal-integration
description: "Master PayPal payment integration including Express Checkout, IPN handling, recurring billing, and refund workflows."
risk: critical
source: community
date_added: "2026-02-27"
---

# PayPal Integration

Master PayPal payment integration including Express Checkout, IPN handling, recurring billing, and refund workflows.

## Do not use this skill when

- The task is unrelated to paypal integration
- You need a different domain or tool outside this scope

## Instructions

- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.

## Use this skill when

- Integrating PayPal as a payment option
- Implementing express checkout flows
- Setting up recurring billing with PayPal
- Processing refunds and payment disputes
- Handling PayPal webhooks (IPN)
- Supporting international payments
- Implementing PayPal subscriptions

## Core Concepts

### 1. Payment Products
**PayPal Checkout**
- One-time payments
- Express checkout experience
- Guest and PayPal account payments

**PayPal Subscriptions**
- Recurring billing
- Subscription plans
- Automatic renewals

**PayPal Payouts**
- Send money to multiple recipients
- Marketplace and platform payments

### 2. Integration Methods
**Client-Side (JavaScript SDK)**
- Smart Payment Buttons
- Hosted payment flow
- Minimal backend code

**Server-Side (REST API)**
- Full control over payment flow
- Custom checkout UI
- Advanced features

### 3. IPN (Instant Payment Notification)
- Webhook-like payment notifications
- Asynchronous payment updates
- Verification required

## Quick Start

```javascript
// Frontend - PayPal Smart Buttons
<div id="paypal-button-container"></div>

<script src="https://www.paypal.com/sdk/js?client-id=YOUR_CLIENT_ID&currency=USD"></script>
<script>
  paypal.Buttons({
    createOrder: function(data, actions) {
      return actions.order.create({
        purchase_units: [{
          amount: {
            value: '25.00'
          }
        }]
      });
    },
    onApprove: function(data, actions) {
      return actions.order.capture().then(function(details) {
        // Payment successful
        console.log('Transaction completed by ' + details.payer.name.given_name);

        // Send to backend for verification
        fetch('/api/paypal/capture', {
          method: 'POST',
          headers: {'Content-Type': 'application/json'},
          body: JSON.stringify({orderID: data.orderID})
        });
      });
    }
  }).render('#paypal-button-container');
</script>
```

```python
# Backend - Verify and capture order
from paypalrestsdk import Payment
import paypalrestsdk

paypalrestsdk.configure({
    "mode": "sandbox",  # or "live"
    "client_id": "YOUR_CLIENT_ID",
    "client_secret": "YOUR_CLIENT_SECRET"
})

def capture_paypal_order(order_id):
    """Capture a PayPal order."""
    payment = Payment.find(order_id)

    if payment.execute({"payer_id": payment.payer.payer_info.payer_id}):
        # Payment successful
        return {
            'status': 'success',
            'transaction_id': payment.id,
            'amount': payment.transactions[0].amount.total
        }
    else:
        # Payment failed
        return {
            'status': 'failed',
            'error': payment.error
        }
```

## Express Checkout Implementation

### Server-Side Order Creation
```python
import requests
import json

class PayPalClient:
    def __init__(self, client_id, client_secret, mode='sandbox'):
        self.client_id = client_id
        self.client_secret = client_secret
        self.base_url = 'https://api-m.sandbox.paypal.com' if mode == 'sandbox' else 'https://api-m.paypal.com'
        self.access_token = self.get_access_token()

    def get_access_token(self):
        """Get OAuth access token."""
        url = f"{self.base_url}/v1/oauth2/token"
        headers = {"Accept": "application/json", "Accept-Language": "en_US"}

        response = requests.post(
            url,
            headers=headers,
            data={"grant_type": "client_credentials"},
            auth=(self.client_id, self.client_secret)
        )

        return response.json()['access_token']

    def create_order(self, amount, currency='USD'):
        """Create a PayPal order."""
        url = f"{self.base_url}/v2/checkout/orders"
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.access_token}"
        }

        payload = {
            "intent": "CAPTURE",
            "purchase_units": [{
                "amount": {
                    "currency_code": currency,
                    "value": str(amount)
                }
            }]
        }

        response = requests.post(url, headers=headers, json=payload)
        return response.json()

    def capture_order(self, order_id):
        """Capture payment for an order."""
        url = f"{self.base_url}/v2/checkout/orders/{order_id}/capture"
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.access_token}"
        }

        response = requests.post(url, headers=headers)
        return response.json()

    def get_order_details(self, order_id):
        """Get order details."""
        url = f"{self.base_url}/v2/checkout/orders/{order_id}"
        headers = {
            "Authorization": f"Bearer {self.access_token}"
        }

        response = requests.get(url, headers=headers)
        return response.json()
```

## IPN (Instant Payment Notification) Handling

### IPN Verification and Processing
```python
from flask import Flask, request
import requests
from urllib.parse import parse_qs

app = Flask(__name__)

@app.route('/ipn', methods=['POST'])
def handle_ipn():
    """Handle PayPal IPN notifications."""
    # Get IPN message
    ipn_data = request.form.to_dict()

    # Verify IPN with PayPal
    if not verify_ipn(ipn_data):
        return 'IPN verification failed', 400

    # Process IPN based on transaction type
    payment_status = ipn_data.get('payment_status')
    txn_type = ipn_data.get('txn_type')

    if payment_status == 'Completed':
        handle_payment_completed(ipn_data)
    elif payment_status == 'Refunded':
        handle_refund(ipn_data)
    elif payment_status == 'Reversed':
        handle_chargeback(ipn_data)

    return 'IPN processed', 200

def verify_ipn(ipn_data):
    """Verify IPN message authenticity."""
    # Add 'cmd' parameter
    verify_data = ipn_data.copy()
    verify_data['cmd'] = '_notify-validate'

    # Send back to PayPal for verification
    paypal_url = 'https://ipnpb.sandbox.paypal.com/cgi-bin/webscr'  # or production URL

    response = requests.post(paypal_url, data=verify_data)

    return response.text == 'VERIFIED'

def handle_payment_completed(ipn_data):
    """Process completed payment."""
    txn_id = ipn_data.get('txn_id')
    payer_email = ipn_data.get('payer_email')
    mc_gross = ipn_data.get('mc_gross')
    item_name = ipn_data.get('item_name')

    # Check if already processed (prevent duplicates)
    if is_transaction_processed(txn_id):
        return

    # Update database
    # Send confirmation email
    # Fulfill order
    print(f"Payment completed: {txn_id}, Amount: ${mc_gross}")

def handle_refund(ipn_data):
    """Handle refund."""
    parent_txn_id = ipn_data.get('parent_txn_id')
    mc_gross = ipn_data.get('mc_gross')

    # Process refund in your system
    print(f"Refund processed: {parent_txn_id}, Amount: ${mc_gross}")

def handle_chargeback(ipn_data):
    """Handle payment reversal/chargeback."""
    txn_id = ipn_data.get('txn_id')
    reason_code = ipn_data.get('reason_code')

    # Handle chargeback
    print(f"Chargeback: {txn_id}, Reason: {reason_code}")
```

## Subscription/Recurring Billing

### Create Subscription Plan
```python
def create_subscription_plan(name, amount, interval='MONTH'):
    """Create a subscription plan."""
    client = PayPalClient(CLIENT_ID, CLIENT_SECRET)

    url = f"{client.base_url}/v1/billing/plans"
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {client.access_token}"
    }

    payload = {
        "product_id": "PRODUCT_ID",  # Create product first
        "name": name,
        "billing_cycles": [{
            "frequency": {
                "interval_unit": interval,
                "interval_count": 1
            },
            "tenure_type": "REGULAR",
            "sequence": 1,
            "total_cycles": 0,  # Infinite
            "pricing_scheme": {
                "fixed_price": {
                    "value": str(amount),
                    "currency_code": "USD"
                }
            }
        }],
        "payment_preferences": {
            "auto_bill_outstanding": True,
            "setup_fee": {
                "value": "0",
                "currency_code": "USD"
            },
            "setup_fee_failure_action": "CONTINUE",
            "payment_failure_threshold": 3
        }
    }

    response = requests.post(url, headers=headers, json=payload)
    return response.json()

def create_subscription(plan_id, subscriber_email):
    """Create a subscription for a customer."""
    client = PayPalClient(CLIENT_ID, CLIENT_SECRET)

    url = f"{client.base_url}/v1/billing/subscriptions"
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {client.access_token}"
    }

    payload = {
        "plan_id": plan_id,
        "subscriber": {
            "email_address": subscriber_email
        },
        "application_context": {
            "return_url": "https://yourdomain.com/subscription/success",
            "cancel_url": "https://yourdomain.com/subscription/cancel"
        }
    }

    response = requests.post(url, headers=headers, json=payload)
    subscription = response.json()

    # Get approval URL
    for link in subscription.get('links', []):
        if link['rel'] == 'approve':
            return {
                'subscription_id': subscription['id'],
                'approval_url': link['href']
            }
```

## Refund Workflows

```python
def create_refund(capture_id, amount=None, note=None):
    """Create a refund for a captured payment."""
    client = PayPalClient(CLIENT_ID, CLIENT_SECRET)

    url = f"{client.base_url}/v2/payments/captures/{capture_id}/refund"
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {client.access_token}"
    }

    payload = {}
    if amount:
        payload["amount"] = {
            "value": str(amount),
            "currency_code": "USD"
        }

    if note:
        payload["note_to_payer"] = note

    response = requests.post(url, headers=headers, json=payload)
    return response.json()

def get_refund_details(refund_id):
    """Get refund details."""
    client = PayPalClient(CLIENT_ID, CLIENT_SECRET)

    url = f"{client.base_url}/v2/payments/refunds/{refund_id}"
    headers = {
        "Authorization": f"Bearer {client.access_token}"
    }

    response = requests.get(url, headers=headers)
    return response.json()
```

## Error Handling

```python
class PayPalError(Exception):
    """Custom PayPal error."""
    pass

def handle_paypal_api_call(api_function):
    """Wrapper for PayPal API calls with error handling."""
    try:
        result = api_function()
        return result
    except requests.exceptions.RequestException as e:
        # Network error
        raise PayPalError(f"Network error: {str(e)}")
    except Exception as e:
        # Other errors
        raise PayPalError(f"PayPal API error: {str(e)}")

# Usage
try:
    order = handle_paypal_api_call(lambda: client.create_order(25.00))
except PayPalError as e:
    # Handle error appropriately
    log_error(e)
```

## Testing

```python
# Use sandbox credentials
SANDBOX_CLIENT_ID = "..."
SANDBOX_SECRET = "..."

# Test accounts
# Create test buyer and seller accounts at developer.paypal.com

def test_payment_flow():
    """Test complete payment flow."""
    client = PayPalClient(SANDBOX_CLIENT_ID, SANDBOX_SECRET, mode='sandbox')

    # Create order
    order = client.create_order(10.00)
    assert 'id' in order

    # Get approval URL
    approval_url = next((link['href'] for link in order['links'] if link['rel'] == 'approve'), None)
    assert approval_url is not None

    # After approval (manual step with test account)
    # Capture order
    # captured = client.capture_order(order['id'])
    # assert captured['status'] == 'COMPLETED'
```

## Resources

- **references/express-checkout.md**: Express Checkout implementation guide
- **references/ipn-handling.md**: IPN verification and processing
- **references/refund-workflows.md**: Refund handling patterns
- **references/billing-agreements.md**: Recurring billing setup
- **assets/paypal-client.py**: Production PayPal client
- **assets/ipn-processor.py**: IPN webhook processor
- **assets/recurring-billing.py**: Subscription management

## Best Practices

1. **Always Verify IPN**: Never trust IPN without verification
2. **Idempotent Processing**: Handle duplicate IPN notifications
3. **Error Handling**: Implement robust error handling
4. **Logging**: Log all transactions and errors
5. **Test Thoroughly**: Use sandbox extensively
6. **Webhook Backup**: Don't rely solely on client-side callbacks
7. **Currency Handling**: Always specify currency explicitly

## Common Pitfalls

- **Not Verifying IPN**: Accepting IPN without verification
- **Duplicate Processing**: Not checking for duplicate transactions
- **Wrong Environment**: Mixing sandbox and production URLs/credentials
- **Missing Webhooks**: Not handling all payment states
- **Hardcoded Values**: Not making configurable for different environments

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: paywall-upgrade-cro
description: "You are an expert in in-app paywalls and upgrade flows. Your goal is to convert free users to paid, or upgrade users to higher tiers, at moments when they've experienced enough value to justify the commitment."
risk: critical
source: community
date_added: "2026-02-27"
---

# Paywall and Upgrade Screen CRO

You are an expert in in-app paywalls and upgrade flows. Your goal is to convert free users to paid, or upgrade users to higher tiers, at moments when they've experienced enough value to justify the commitment.

## Initial Assessment

Before providing recommendations, understand:

1. **Upgrade Context**
   - Freemium → Paid conversion
   - Trial → Paid conversion
   - Tier upgrade (Basic → Pro)
   - Feature-specific upsell
   - Usage limit upsell

2. **Product Model**
   - What's free forever?
   - What's behind the paywall?
   - What triggers upgrade prompts?
   - What's the current conversion rate?

3. **User Journey**
   - At what point does this appear?
   - What have they experienced already?
   - What are they trying to do when blocked?

---

## Core Principles

### 1. Value Before Ask
- User should have experienced real value first
- The upgrade should feel like a natural next step
- Timing: After "aha moment," not before

### 2. Show, Don't Just Tell
- Demonstrate the value of paid features
- Preview what they're missing
- Make the upgrade feel tangible

### 3. Friction-Free Path
- Easy to upgrade when ready
- Don't make them hunt for pricing
- Remove barriers to conversion

### 4. Respect the No
- Don't trap or pressure
- Make it easy to continue free
- Maintain trust for future conversion

---

## Paywall Trigger Points

### Feature Gates
When user clicks a paid-only feature:
- Clear explanation of why it's paid
- Show what the feature does
- Quick path to unlock
- Option to continue without

### Usage Limits
When user hits a limit:
- Clear indication of what limit was reached
- Show what upgrading provides
- Option to buy more without full upgrade
- Don't block abruptly

### Trial Expiration
When trial is ending:
- Early warnings (7 days, 3 days, 1 day)
- Clear "what happens" on expiration
- Easy re-activation if expired
- Summarize value received

### Time-Based Prompts
After X days/sessions of free use:
- Gentle upgrade reminder
- Highlight unused paid features
- Not intrusive—banner or subtle modal
- Easy to dismiss

### Context-Triggered
When behavior indicates upgrade fit:
- Power users who'd benefit
- Teams using solo features
- Heavy usage approaching limits
- Inviting teammates

---

## Paywall Screen Components

### 1. Headline
Focus on what they get, not what they pay:
- "Unlock [Feature] to [Benefit]"
- "Get more [value] with [Plan]"
- Not: "Upgrade to Pro for $X/month"

### 2. Value Demonstration
Show what they're missing:
- Preview of the feature in action
- Before/after comparison
- "With Pro, you could..." examples
- Specific to their use case if possible

### 3. Feature Comparison
If showing tiers:
- Highlight key differences
- Current plan clearly marked
- Recommended plan emphasized
- Focus on outcomes, not feature lists

### 4. Pricing
- Clear, simple pricing
- Annual vs. monthly options
- Per-seat clarity if applicable
- Any trials or guarantees

### 5. Social Proof (Optional)
- Customer quotes about the upgrade
- "X teams use this feature"
- Success metrics from upgraded users

### 6. CTA
- Specific: "Upgrade to Pro" not "Upgrade"
- Value-oriented: "Start Getting [Benefit]"
- If trial: "Start Free Trial"

### 7. Escape Hatch
- Clear "Not now" or "Continue with Free"
- Don't make them feel bad
- "Maybe later" vs. "No, I'll stay limited"

---

## Specific Paywall Types

### Feature Lock Paywall
When clicking a paid feature:

```
[Lock Icon]
This feature is available on Pro

[Feature preview/screenshot]

[Feature name] helps you [benefit]:
• [Specific capability]
• [Specific capability]
• [Specific capability]

[Upgrade to Pro - $X/mo]
[Maybe Later]
```

### Usage Limit Paywall
When hitting a limit:

```
You've reached your free limit

[Visual: Progress bar at 100%]

Free plan: 3 projects
Pro plan: Unlimited projects

You're active! Upgrade to keep building.

[Upgrade to Pro]    [Delete a project]
```

### Trial Expiration Paywall
When trial is ending:

```
Your trial ends in 3 days

What you'll lose:
• [Feature they've used]
• [Feature they've used]
• [Data/work they've created]

What you've accomplished:
• Created X projects
• [Specific value metric]

[Continue with Pro - $X/mo]
[Remind me later]    [Downgrade to Free]
```

### Soft Upgrade Prompt
Non-blocking suggestion:

```
[Banner or subtle modal]

You've been using [Product] for 2 weeks!
Teams like yours get X% more [value] with Pro.

[See Pro Features]    [Dismiss]
```

### Team/Seat Upgrade
When adding users:

```
Invite your team

Your plan: Solo (1 user)
Team plans start at $X/user

• Shared projects
• Collaboration features
• Admin controls

[Upgrade to Team]    [Continue Solo]
```

---

## Mobile Paywall Patterns

### iOS/Android Conventions
- System-like styling builds trust
- Standard paywall patterns users recognize
- Free trial emphasis common
- Subscription terminology they expect

### Mobile-Specific UX
- Full-screen often acceptable
- Swipe to dismiss
- Large tap targets
- Plan selection with clear visual state

### App Store Considerations
- Clear pricing display
- Subscription terms visible
- Restore purchases option
- Meet review guidelines

---

## Timing and Frequency

### When to Show
- **Best**: After value moment, before frustration
- After activation/aha moment
- When hitting genuine limits
- When using adjacent-to-paid features

### When NOT to Show
- During onboarding (too early)
- When they're in a flow
- Repeatedly after dismissal
- Before they understand the product

### Frequency Rules
- Limit to X per session
- Cool-down after dismiss (days, not hours)
- Escalate urgency appropriately (trial end)
- Track annoyance signals (rage clicks, churn)

---

## Upgrade Flow Optimization

### From Paywall to Payment
- Minimize steps
- Keep them in-context if possible
- Pre-fill known information
- Show security signals

### Plan Selection
- Default to recommended plan
- Annual vs. monthly clear trade-off
- Feature comparison if helpful
- FAQ or objection handling nearby

### Checkout
- Minimal fields
- Multiple payment methods
- Trial terms clear
- Easy cancellation visible (builds trust)

### Post-Upgrade
- Immediate access to features
- Confirmation and receipt
- Guide to new features
- Celebrate the upgrade

---

## A/B Testing Paywalls

### What to Test
- Trigger timing (earlier vs. later)
- Trigger type (feature gate vs. soft prompt)
- Headline/copy variations
- Price presentation
- Trial length
- Feature emphasis
- Social proof presence
- Design/layout

### Metrics to Track
- Paywall impression rate
- Click-through to upgrade
- Upgrade completion rate
- Revenue per user
- Churn rate post-upgrade
- Time to upgrade

---

## Output Format

### Paywall Design
For each paywall:
- **Trigger**: When it appears
- **Context**: What user was doing
- **Type**: Feature gate, limit, trial, etc.
- **Copy**: Full copy with headline, body, CTA
- **Design notes**: Layout, visual elements
- **Mobile**: Mobile-specific considerations
- **Frequency**: How often shown
- **Exit path**: How to dismiss

### Upgrade Flow
- Step-by-step screens
- Copy for each step
- Decision points
- Success state

### Metrics Plan
What to measure and expected benchmarks

---

## Common Patterns by Business Model

### Freemium SaaS
- Generous free tier to build habit
- Feature gates for power features
- Usage limits for volume
- Soft prompts for heavy free users

### Free Trial
- Trial countdown prominent
- Value summary at expiration
- Grace period or easy restart
- Win-back for expired trials

### Usage-Based
- Clear usage tracking
- Alerts at thresholds (75%, 100%)
- Easy to add more without plan change
- Volume discounts visible

### Per-Seat
- Friction at invitation
- Team feature highlights
- Volume pricing clear
- Admin value proposition

---

## Anti-Patterns to Avoid

### Dark Patterns
- Hiding the close button
- Confusing plan selection
- Buried downgrade option
- Misleading urgency
- Guilt-trip copy

### Conversion Killers
- Asking before value delivered
- Too frequent prompts
- Blocking critical flows
- Unclear pricing
- Complicated upgrade process

### Trust Destroyers
- Surprise charges
- Hard-to-cancel subscriptions
- Bait and switch
- Data hostage tactics

---

## Experiment Ideas

### Trigger & Timing Experiments

**When to Show**
- Test trigger timing: after aha moment vs. at feature attempt
- Early trial reminder (7 days) vs. late reminder (1 day before)
- Show after X actions completed vs. after X days
- Test soft prompts at different engagement thresholds
- Trigger based on usage patterns vs. time-based only

**Trigger Type**
- Hard gate (can't proceed) vs. soft gate (preview + prompt)
- Feature lock vs. usage limit as primary trigger
- In-context modal vs. dedicated upgrade page
- Banner reminder vs. modal prompt
- Exit-intent on free plan pages

---

### Paywall Design Experiments

**Layout & Format**
- Full-screen paywall vs. modal overlay
- Minimal paywall (CTA-focused) vs. feature-rich paywall
- Single plan display vs. plan comparison
- Image/preview included vs. text-only
- Vertical layout vs. horizontal layout on desktop

**Value Presentation**
- Feature list vs. benefit statements
- Show what they'll lose (loss aversion) vs. what they'll gain
- Personalized value summary based on usage
- Before/after demonstration
- ROI calculator or value quantification

**Visual Elements**
- Add product screenshots or previews
- Include short demo video or GIF
- Test illustration vs. product imagery
- Animated vs. static paywall
- Progress visualization (what they've accomplished)

---

### Pricing Presentation Experiments

**Price Display**
- Show monthly vs. annual vs. both with toggle
- Highlight savings for annual ($ amount vs. % off)
- Price per day framing ("Less than a coffee")
- Show price after trial vs. emphasize "Start Free"
- Display price prominently vs. de-emphasize until click

**Plan Options**
- Single recommended plan vs. multiple tiers
- Add "Most Popular" badge to target plan
- Test number of visible plans (2 vs. 3)
- Show enterprise/custom tier vs. hide it
- Include one-time purchase option alongside subscription

**Discounts & Offers**
- First month/year discount for conversion
- Limited-time upgrade offer with countdown
- Loyalty discount based on free usage duration
- Bundle discount for annual commitment
- Referral discount for social proof

---

### Copy & Messaging Experiments

**Headlines**
- Benefit-focused ("Unlock unlimited projects") vs. feature-focused ("Get Pro features")
- Question format ("Ready to do more?") vs. statement format
- Urgency-based ("Don't lose your work") vs. value-based
- Personalized headline with user's name or usage data
- Social proof headline ("Join 10,000+ Pro users")

**CTAs**
- "Start Free Trial" vs. "Upgrade Now" vs. "Continue with Pro"
- First person ("Start My Trial") vs. second person ("Start Your Trial")
- Value-specific ("Unlock Unlimited") vs. generic ("Upgrade")
- Add urgency ("Upgrade Today") vs. no pressure
- Include price in CTA vs. separate price display

**Objection Handling**
- Add money-back guarantee messaging
- Show "Cancel anytime" prominently
- Include FAQ on paywall
- Address specific objections based on feature gated
- Add chat/support option on paywall

---

### Trial & Conversion Experiments

**Trial Structure**
- 7-day vs. 14-day vs. 30-day trial length
- Credit card required vs. not required for trial
- Full-access trial vs. limited feature trial
- Trial extension offer for engaged users
- Second trial offer for expired/churned users

**Trial Expiration**
- Countdown timer visibility (always vs. near end)
- Email reminders: frequency and timing
- Grace period after expiration vs. immediate downgrade
- "Last chance" offer with discount
- Pause option vs. immediate cancellation

**Upgrade Path**
- One-click upgrade from paywall vs. separate checkout
- Pre-filled payment info for returning users
- Multiple payment methods offered
- Quarterly plan option alongside monthly/annual
- Team invite flow for solo-to-team conversion

---

### Personalization Experiments

**Usage-Based**
- Personalize paywall copy based on features used
- Highlight most-used premium features
- Show usage stats ("You've created 50 projects")
- Recommend plan based on behavior patterns
- Dynamic feature emphasis based on user segment

**Segment-Specific**
- Different paywall for power users vs. casual users
- B2B vs. B2C messaging variations
- Industry-specific value propositions
- Role-based feature highlighting
- Traffic source-based messaging

---

### Frequency & UX Experiments

**Frequency Capping**
- Test number of prompts per session
- Cool-down period after dismiss (hours vs. days)
- Escalating urgency over time vs. consistent messaging
- Once per feature vs. consolidated prompts
- Re-show rules after major engagement

**Dismiss Behavior**
- "Maybe later" vs. "No thanks" vs. "Remind me tomorrow"
- Ask reason for declining
- Offer alternative (lower tier, annual discount)
- Exit survey on dismiss
- Friendly vs. neutral decline copy

---

## Questions to Ask

If you need more context:
1. What's your current free → paid conversion rate?
2. What triggers upgrade prompts today?
3. What features are behind the paywall?
4. What's your "aha moment" for users?
5. What pricing model? (per seat, usage, flat)
6. Mobile app, web app, or both?

---

## Related Skills

- **page-cro**: For public pricing page optimization
- **onboarding-cro**: For driving to aha moment before upgrade
- **ab-test-setup**: For testing paywall variations
- **analytics-tracking**: For measuring upgrade funnel

## When to Use
This skill is applicable to execute the workflow or actions described in the overview.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: pc-games
description: "PC and console game development principles. Engine selection, platform features, optimization strategies."
risk: safe
source: community
date_added: "2026-02-27"
---

# PC/Console Game Development

> Engine selection and platform-specific principles.

---

## 1. Engine Selection

### Decision Tree

```
What are you building?
│
├── 2D Game
│   ├── Open source important? → Godot
│   └── Large team/assets? → Unity
│
├── 3D Game
│   ├── AAA visual quality? → Unreal
│   ├── Cross-platform priority? → Unity
│   └── Indie/open source? → Godot 4
│
└── Specific Needs
    ├── DOTS performance? → Unity
    ├── Nanite/Lumen? → Unreal
    └── Lightweight? → Godot
```

### Comparison

| Factor | Unity 6 | Godot 4 | Unreal 5 |
|--------|---------|---------|----------|
| 2D | Good | Excellent | Limited |
| 3D | Good | Good | Excellent |
| Learning | Medium | Easy | Hard |
| Cost | Revenue share | Free | 5% after $1M |
| Team | Any | Solo-Medium | Medium-Large |

---

## 2. Platform Features

### Steam Integration

| Feature | Purpose |
|---------|---------|
| Achievements | Player goals |
| Cloud Saves | Cross-device progress |
| Leaderboards | Competition |
| Workshop | User mods |
| Rich Presence | Show in-game status |

### Console Requirements

| Platform | Certification |
|----------|--------------|
| PlayStation | TRC compliance |
| Xbox | XR compliance |
| Nintendo | Lotcheck |

---

## 3. Controller Support

### Input Abstraction

```
Map ACTIONS, not buttons:
- "confirm" → A (Xbox), Cross (PS), B (Nintendo)
- "cancel" → B (Xbox), Circle (PS), A (Nintendo)
```

### Haptic Feedback

| Intensity | Use |
|-----------|-----|
| Light | UI feedback |
| Medium | Impacts |
| Heavy | Major events |

---

## 4. Performance Optimization

### Profiling First

| Engine | Tool |
|--------|------|
| Unity | Profiler Window |
| Godot | Debugger → Profiler |
| Unreal | Unreal Insights |

### Common Bottlenecks

| Bottleneck | Solution |
|------------|----------|
| Draw calls | Batching, atlases |
| GC spikes | Object pooling |
| Physics | Simpler colliders |
| Shaders | LOD shaders |

---

## 5. Engine-Specific Principles

### Unity 6

- DOTS for performance-critical systems
- Burst compiler for hot paths
- Addressables for asset streaming

### Godot 4

- GDScript for rapid iteration
- C# for complex logic
- Signals for decoupling

### Unreal 5

- Blueprint for designers
- C++ for performance
- Nanite for high-poly environments
- Lumen for dynamic lighting

---

## 6. Anti-Patterns

| ❌ Don't | ✅ Do |
|----------|-------|
| Choose engine by hype | Choose by project needs |
| Ignore platform guidelines | Study certification requirements |
| Hardcode input buttons | Abstract to actions |
| Skip profiling | Profile early and often |

---

> **Remember:** Engine is a tool. Master the principles, then adapt to any engine.

## When to Use
This skill is applicable to execute the workflow or actions described in the overview.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.