Trading strategy lifecycle skills with postmortem compliance (plan, develop, review, optimize)

version
1.0.4

Install

/plugin install blueprint-skills@morris-marketplace

Run it inside Claude Code after adding the marketplace with /plugin marketplace add morris-y/claude-marketplace.

Contents

Discovered from source

Skills 4

Blueprint Develop - Test-Driven Strategy Implementation

Overview

Execute strategy implementation with TDD discipline and Postmortem regression prevention. Every code change must align with backtest interfaces, pass PM compliance checks, and have synchronized test coverage.

Core Principle

./postmortem/ = 深度病历库 (Deep Case History)
./CLAUDE.md   = 高频手术准则 (High-Frequency Operating Rules)

Rule: 每写一行代码前,先查 CLAUDE.md;每改一个模块前,先查相关 postmortem

When to Use

  • Implementing new trading strategy logic from Linear tickets
  • Modifying existing strategy code in strategies/
  • User mentions "开发", "implement", or "code the strategy"
  • Any code change that affects trading logic

Do NOT use when:

  • Planning strategy (use blueprint-plan instead)
  • Pure backtest runs without code changes
  • Documentation or config changes only

Prerequisites

Before invoking this skill, verify:

  • Linear ticket exists for the work (from blueprint-plan)
  • Backtest framework is in place (backtest/ directory)
  • Test file location confirmed (tests/backtest_unit.py)
  • PM mitigations from ticket identified (from blueprint-plan Phase 0)

Workflow

digraph blueprint_develop {
    rankdir=TB;
    node [shape=box];

    start [label="Start: Linear Ticket Ready" shape=ellipse];
    pm_load [label="0. Load PM Context\n(CLAUDE.md + postmortem/)" style=filled fillcolor=lightyellow];
    env [label="1. Environment Alignment\n(GitHub MCP)"];
    pm_test [label="2. PM Regression Tests First\n(TDD Red Phase)" style=filled fillcolor=lightyellow];
    test_first [label="3. Feature Tests\n(TDD Red Phase)"];
    impl [label="4. Atomic Implementation\n(code-simplifier)"];
    sync [label="5. Sync Test Update\n(TDD Green Phase)"];
    impact [label="6. Impact + PM Compliance\n(context7)"];
    done [label="Code Ready for Review" shape=ellipse];

    start -> pm_load;
    pm_load -> env;
    env -> pm_test;
    pm_test -> test_first;
    test_first -> impl;
    impl -> sync;
    sync -> impact;
    impact -> done;
}

🔄 Ralph Loop Integration (Optional Iterative Mode)

When to Activate: Complex implementations requiring multiple test-fix cycles.

Ralph Loop enables iterative self-correction: Claude repeatedly sees its own work and improves until all tests pass.

Triggering Ralph Loop

Invoke when:

  • Multiple test failures expected during implementation
  • Complex logic requiring iterative refinement
  • User requests "迭代开发" or "ralph mode"
Skill: ralph-loop:ralph-loop

Prompt Template:
"Implement [strategy component] following TDD.
PM Compliance Checklist: [from Phase 0]
Current test failures: [list from pytest]
Target: ALL tests in tests/backtest_unit.py and tests/pm_regression/ passing.
Output <promise>ALL TESTS PASSING</promise> when complete."

Options:
--max-iterations 15
--completion-promise "ALL TESTS PASSING"

Ralph Loop Development Cycle

digraph ralph_develop {
    rankdir=LR;
    node [shape=box];

    start [label="Ralph Start" shape=ellipse];
    pytest [label="Run pytest"];
    fail [label="Tests Fail?" shape=diamond];
    fix [label="Fix Code\n(PM Compliant)"];
    pass [label="<promise>\nALL TESTS PASSING" shape=ellipse style=filled fillcolor=lightgreen];

    start -> pytest;
    pytest -> fail;
    fail -> fix [label="Yes"];
    fix -> pytest;
    fail -> pass [label="No"];
}

Ralph Loop Exit Conditions

ConditionAction
All tests passOutput <promise>ALL TESTS PASSING</promise>, exit loop
Max iterations reachedExit with summary, human decision needed
PM violation detectedSTOP LOOP, fix compliance first
Blocked by external issueExit with <promise>BLOCKED: [reason]</promise>

PM Compliance During Ralph Loop

CRITICAL: Each iteration must maintain PM compliance:

# Ralph Loop PM Check (every iteration)
1. Before each code change:
   - Reference PM Compliance Checklist
   - Check CLAUDE.md directives

2. After each test run:
   - Verify no PM regression test failures
   - If PM test fails: PRIORITY FIX before feature tests

When NOT to Use Ralph Loop

  • Simple single-function implementations
  • Clear, non-iterative changes
  • When human guidance needed mid-implementation

Phase 0: Load PM Context (MANDATORY)

Goal: Internalize all relevant warnings before writing any code.

Step 0.1: Read CLAUDE.md

# ALWAYS read first
cat ./CLAUDE.md

Extract all directives and warnings relevant to the current task.

Step 0.2: Read Relevant Postmortems

From the Linear ticket's PM Immune Screening section, identify related PMs:

# Read each PM mentioned in ticket
cat ./postmortem/PM-XXX-*.md

Step 0.3: Create PM Compliance Checklist

Generate a checklist to verify during implementation:

## 📋 PM Compliance Checklist for This Implementation

### From CLAUDE.md (High-Frequency Rules)
- [ ] [Directive 1]
- [ ] [Directive 2]
- [ ] [Warning to avoid]

### From Postmortems (Specific to Ticket)
- [ ] PM-001: [Specific mitigation]
- [ ] PM-003: [Specific mitigation]

### Code Patterns to AVOID (from PMs)
```python
# DON'T: [anti-pattern from PM]
# DO: [correct pattern]

**Output:** PM Compliance Checklist visible throughout implementation.

## Phase 1: Environment Alignment

**Goal:** Ensure new strategy aligns with existing backtest interfaces.

### Step 1.1: Execute Implementation Plan

Use Skill tool: superpowers:executing-plans Purpose: Execute the implementation plan from Linear ticket Context: Strategy requirements, PM mitigations, test requirements


### Checklist

Use GitHub MCP to inspect:

  1. mcp__github__get_file_contents: backtest/ directory structure
  2. Identify interface contracts:
    • Data input format (OHLCV? Tick? Custom?)
    • Required method signatures (run(), evaluate(), etc.)
    • Output format (trades[], metrics{})

### Interface Alignment Matrix

| Interface | Check | Action if Mismatch |
|-----------|-------|-------------------|
| **Data Format** | Input schema matches historical data | Adapt strategy to use existing format |
| **Method Signature** | Strategy implements required methods | Add missing methods |
| **Output Format** | Results compatible with metrics pipeline | Convert output format |
| **Dependencies** | No version conflicts | Pin versions in requirements |

**Output:** Interface alignment report or list of adaptations needed.

## Phase 2: PM Regression Tests First (CRITICAL)

**Goal:** Write tests that specifically prevent PM-documented failures from recurring.

### PM Regression Test Template

```python
# tests/pm_regression/test_pm_XXX.py

class TestPM001Regression:
    """Regression tests for PM-001: Order Duplication

    Root Cause: Missing idempotency key
    Mitigation: All orders must include client_order_id
    """

    def test_order_has_idempotency_key(self):
        """Every order placement must include client_order_id"""
        order = strategy.create_order(...)
        assert order.client_order_id is not None
        assert len(order.client_order_id) >= 16

    def test_duplicate_order_rejected(self):
        """Attempting duplicate order raises DuplicateOrderError"""
        order_id = "test-order-123"
        strategy.place_order(client_order_id=order_id)
        with pytest.raises(DuplicateOrderError):
            strategy.place_order(client_order_id=order_id)


class TestPM003Regression:
    """Regression tests for PM-003: Liquidity Trap

    Root Cause: No exit strategy for illiquid markets
    Mitigation: Check liquidity before entry, implement timeout exit
    """

    def test_liquidity_check_before_entry(self):
        """Strategy refuses entry when liquidity below threshold"""
        illiquid_market = MockMarket(depth=100)  # Below threshold
        signal = strategy.evaluate(illiquid_market)
        assert signal.action == "NO_ENTRY"
        assert "insufficient_liquidity" in signal.reason

    def test_timeout_exit_triggered(self):
        """Position exits after max_hold_time if no liquidity"""
        # ... test implementation

Required PM Test Categories

PM CategoryTest Coverage
API IssuesRate limit handling, timeout recovery, retry logic
Order IssuesIdempotency, duplication, rejection handling
Market IssuesLiquidity checks, spread validation, halt detection
Data IssuesMissing data handling, stale data detection

BLOCKING: All PM regression tests must PASS before proceeding to feature tests.

Phase 3: Feature Tests (TDD Red Phase)

Goal: Define expected feature behavior before implementation.

Test File Location

tests/backtest_unit.py  # Primary location
tests/strategies/       # Strategy-specific tests (if exists)
tests/pm_regression/    # PM regression tests (NEW)

Test Template

# tests/backtest_unit.py

class Test[StrategyName]:
    """Tests for [Strategy Name] - Ticket: [LINEAR-XXX]"""

    def test_entry_signal(self):
        """Strategy generates entry signal under expected conditions"""
        # Arrange: Set up market state
        # Act: Call strategy logic
        # Assert: Verify signal generated
        pass

    def test_exit_signal(self):
        """Strategy generates exit signal for position management"""
        pass

    def test_position_limits(self):
        """Strategy respects position limits from risk parameters"""
        pass

    def test_edge_case_no_data(self):
        """Strategy handles missing data gracefully"""
        pass

Test Categories Required

CategoryCoveragePriority
PM RegressionAll PM mitigations from ticketP0 (BLOCKING)
Entry LogicSignal generation, threshold triggersP0
Exit LogicStop loss, take profit, time-basedP0
Risk LimitsPosition caps, exposure limitsP0
Edge CasesMissing data, API errors, market haltsP1
PerformanceExecution time, memory usageP2

Action: Write failing tests BEFORE any implementation code.

Phase 4: Atomic Implementation

Goal: Keep strategy logic minimal, PM-compliant, and focused.

Pre-Implementation PM Check

Before writing ANY code, verify against PM Compliance Checklist:

For each function/method:
1. Does this touch any PM-flagged area?
   - If YES: Reference the PM mitigation pattern
   - If NO: Proceed with standard implementation
2. Am I violating any CLAUDE.md directive?
3. Am I introducing a pattern documented as "DON'T" in a PM?

Step 4.1: Frontend Design (if frontend-related)

If the implementation involves frontend components, UI, or web interfaces:

Use Skill tool: frontend-design:frontend-design
Purpose: Create high-quality frontend interfaces
Focus: Modern UI/UX, component design, user experience

Step 4.2: Invoke code-simplifier Skill

Use Skill tool: code-simplifier:code-simplifier
Purpose: Review implementation for simplicity before commit

Atomic Implementation Rules

RuleGuidelineAnti-pattern
Single File < 200 LOCSplit into modules if exceeding500+ line strategy file
One ResponsibilityEach function does one thingcalculate_and_place_and_log()
No Premature OptimizationSimple first, optimize with profilerCustom data structures without need
Explicit DependenciesImport at top, no dynamic imports__import__() or lazy loading
PM Pattern ComplianceUse patterns from PMs, not anti-patternsRepeating documented mistakes

File Structure

strategies/
├── base.py           # Abstract base class
├── [strategy_name]/
│   ├── __init__.py
│   ├── signals.py    # Signal generation (< 100 LOC)
│   ├── execution.py  # Order management (< 100 LOC)
│   └── risk.py       # Risk checks (< 50 LOC)

Output: Implementation that passes tests from Phase 2 AND Phase 3.

Phase 5: Synchronized Test Update

Goal: Maintain 1:1 correspondence between code and tests.

Sync Protocol

For EVERY code change:

Code Change                    → Required Test Update
─────────────────────────────────────────────────────
New function added             → New test case added
Function signature changed     → Update test calls
Threshold/parameter changed    → Update test assertions
Logic branch added             → Add test for branch
PM mitigation added            → Add PM regression test

Verification Command

# Run ALL tests including PM regression
pytest tests/ -v --tb=short

# PM regression tests specifically (must all pass)
pytest tests/pm_regression/ -v

# Coverage check (should increase or stay same, never decrease)
pytest --cov=strategies --cov-report=term-missing

Step 5.2: Systematic Debugging (if tests fail)

If any tests fail:

Use Skill tool: superpowers:systematic-debugging
Purpose: Systematic approach to debugging test failures
Focus: Identify root cause, fix while maintaining PM compliance

Output: All tests passing, coverage maintained.

Phase 6: Impact + PM Compliance Analysis

Goal: Verify changes don't break existing strategies AND don't violate PM mitigations.

Step 6.1: Gather Context for Impact Analysis

Use Skill tool: context7:context7
Purpose: Gather comprehensive context about code changes and their impact
Focus: Related code patterns, dependencies, existing strategies, PM mitigations

Step 6.2: PM Compliance Final Check

## PM Compliance Verification

### CLAUDE.md Directives
| Directive | Compliant? | Evidence |
|-----------|------------|----------|
| [Directive 1] | ✅ | Line XX in file.py |
| [Directive 2] | ✅ | Test case test_xxx |

### Postmortem Mitigations
| PM | Mitigation | Implemented? | Test Coverage |
|----|------------|--------------|---------------|
| PM-001 | Idempotency key | ✅ | test_pm_001.py |
| PM-003 | Liquidity check | ✅ | test_pm_003.py |

### Anti-Patterns Avoided
- [x] No hardcoded API keys (PM-002)
- [x] No unbounded retries (PM-004)

Cross-Strategy Impact Matrix

Use Grep to search for:
1. Shared base class usage
2. Common utility function calls
3. Config key references
4. Event/signal handlers

Output: Impact report + PM Compliance Verification.

Phase 7: Finalize Development Branch

Goal: Commit changes and prepare branch for review.

Step 7.1: Commit Changes

Use Skill tool: commit-commands:commit
Purpose: Create standardized commit message for strategy implementation
Message should reference: Linear ticket, PM mitigations implemented

Step 7.2: Finish Development Branch

Use Skill tool: superpowers:finishing-a-development-branch
Purpose: Integrate work, ensure branch is ready for review
Verify:
- All tests passing
- PM compliance verified
- Code follows conventions
- Ready for blueprint-review

Output: Branch committed and ready for review.

Quick Reference

PhaseTool/SkillKey Action
0. PM LoadReadLoad CLAUDE.md + relevant postmortems
1. Executesuperpowers:executing-plansExecute implementation plan
1. Alignmcp__github__get_file_contentsCheck backtest/ interfaces
2. PM TestManualWrite PM regression tests FIRST
3. Testsuperpowers:test-driven-developmentWrite feature tests
4. Frontendfrontend-design:frontend-designIf frontend-related (optional)
4. Implementcode-simplifier:code-simplifierPM-compliant, atomic, < 200 LOC
5. Syncpytest via BashRun ALL tests after each change
5b. Debugsuperpowers:systematic-debuggingIf tests fail
6. Impactcontext7:context7 + GrepGather context + Impact + PM compliance check
7. Finishcommit-commands:commit + superpowers:finishing-a-development-branchCommit and prepare for review
🔄 Ralphralph-loop:ralph-loopIterative test-fix cycle (optional)

Common Mistakes

MistakePrevention
Skipping PM context loadPhase 0 is MANDATORY before any code
No PM regression testsWrite PM tests before feature tests
Implementing before testsAlways write test first, run to see it fail
Large monolithic filesSplit at 200 LOC, use module structure
Changing shared code without impact checkRun Phase 6 before any shared code change
Repeating PM anti-patternsReference PM "DON'T" patterns before coding
Test-code desyncUse checklist: code change → test change

Exit Criteria

Before marking Linear ticket as "Done":

  • PM Compliance Checklist: All items verified
  • PM regression tests: All passing
  • All feature tests in tests/backtest_unit.py pass
  • Test coverage ≥ 80% for new code
  • No files exceed 200 LOC
  • Impact analysis completed
  • No regression in existing strategy tests

Example Invocation

Standard Mode

User: "Implement the mean-reversion strategy from ticket LIN-123"

Claude:
0. [PM Load] Reading CLAUDE.md... 5 relevant directives found
   Reading PM-003 (liquidity trap)... Mitigation: exit_timeout required
   PM Compliance Checklist created with 7 items

1. [Align] Checking backtest/ interfaces... Data format: OHLCV, 1-min candles

2. [PM Test] Writing PM regression tests...
   - test_liquidity_check_before_entry ❌ (not implemented yet)
   - test_exit_timeout_triggers ❌ (not implemented yet)

3. [Test] Writing feature tests...
   - test_entry_signal ❌
   - test_exit_signal ❌

4. [Implement] Creating strategies/mean_reversion/...
   - PM-compliant: liquidity check added to signals.py:45
   - PM-compliant: exit_timeout in execution.py:78

5. [Sync] All tests passing:
   - PM regression: 4/4 ✅
   - Feature tests: 12/12 ✅
   - Coverage: 87%

6. [Impact] No impact on existing strategies
   PM Compliance: All 7 checklist items verified ✅

Output: PR ready for review, PM compliant

🔄 Ralph Loop Mode (Iterative)

User: "迭代开发 order execution module,用 ralph loop"

Claude:
0-3. [Standard Phases Complete]
   PM Compliance Checklist: 5 items
   Tests written: 8 failing

🔄 [Ralph Loop Activated]
   Invoking: /ralph-loop "Implement order execution for mean-reversion.
   PM Checklist: [5 items]
   Failing tests: 8
   Output <promise>ALL TESTS PASSING</promise> when done."
   --max-iterations 10
   --completion-promise "ALL TESTS PASSING"

   Iteration 1: 8/8 tests failing → Fixed signal generation
   Iteration 2: 5/8 tests failing → Fixed order placement
   Iteration 3: 3/8 tests failing → Fixed PM-001 idempotency
   Iteration 4: 1/8 tests failing → Fixed edge case
   Iteration 5: 0/8 tests failing

   <promise>ALL TESTS PASSING</promise>

🔄 [Ralph Loop Complete]
   Iterations: 5/10
   Tests: 8/8 ✅
   PM Compliance: Maintained throughout ✅

6. [Impact] Proceeding with impact analysis...

Output: Complex implementation completed via iterative refinement

Blueprint Optimize - Dual-Layer Memory Crystallization

Overview

Complete the iteration cycle by syncing status, committing properly, and permanently capturing hard-won lessons in the dual-layer memory system:

  • ./postmortem/ = Deep case history (detailed analysis)
  • ./CLAUDE.md = High-frequency operating rules (concise directives)

Core Principle

./postmortem/ = 深度病历库 (Deep Case History)
                → 完整的事故分析、root cause、时间线、详细修复
                → 无行数限制,越详细越好

./CLAUDE.md   = 高频手术准则 (High-Frequency Operating Rules)
                → 只有指令和警告,无解释
                → 严格 ≤ 100 行

Rule: 先写病历 (postmortem),再提炼准则 (CLAUDE.md)

When to Use

  • PR has been merged (after blueprint-review)
  • Ready to close out the iteration
  • User mentions "上线", "merge complete", "close ticket", or "记录经验"
  • After any incident, bug, or significant learning

Do NOT use when:

  • PR still under review (use blueprint-review)
  • Still implementing (use blueprint-develop)

Prerequisites

Before invoking this skill, verify:

  • PR merged to main branch
  • All tests passing on main
  • Linear ticket exists and is linked to PR

Workflow

digraph blueprint_optimize {
    rankdir=TB;
    node [shape=box];

    start [label="Start: PR Merged" shape=ellipse];
    sync [label="1. Status Sync\n(Linear MCP)"];
    commit [label="2. Final Commit\n(commit-commands)"];
    pm_decision [label="3. PM Decision\n(Need New Postmortem?)" shape=diamond style=filled fillcolor=lightyellow];
    pm_write [label="3a. Write Postmortem\n(./postmortem/)" style=filled fillcolor=lightyellow];
    claude_preview [label="4. CLAUDE.md Preview\n(Extract from PM)" style=filled fillcolor=lightyellow];
    confirm [label="5. Human Confirms" shape=diamond];
    claude_write [label="6. Write to CLAUDE.md"];
    done [label="Iteration Complete" shape=ellipse];

    start -> sync;
    sync -> commit;
    commit -> pm_decision;
    pm_decision -> pm_write [label="Yes: Incident/Bug Found"];
    pm_decision -> claude_preview [label="No: Minor Learnings Only"];
    pm_write -> claude_preview;
    claude_preview -> confirm;
    confirm -> claude_write [label="Approved"];
    confirm -> claude_preview [label="Revise"];
    claude_write -> done;
}

Phase 1: Status Sync

Goal: Mark Linear ticket as Done and ensure all links are in place.

Step 1.0: Gather Context (if needed)

When syncing status or analyzing merged changes:

Use Skill tool: context7:context7
Purpose: Gather context about merged PR, related tickets, and impact
Focus: PR changes, related code, dependencies, PM context

Update Linear Ticket

Tool: mcp__plugin_linear_linear__update_issue

Parameters:
- id: [ticket_id]
- state: "Done"

Verification Checklist

ItemAction
Ticket state → Doneupdate_issue with state
PR link attachedVerify via get_issue
Sub-tickets closedUpdate each child ticket
Labels updatedAdd "shipped" or equivalent

Comment Summary

Add closing comment to ticket:

Tool: mcp__plugin_linear_linear__create_comment

Body:
✅ Strategy shipped to main
- PR: [PR link]
- Backtest Sharpe: X.XX
- PM: [PM-XXX if created, or "None"]
- CLAUDE.md: [Updated/No change]

Output: Linear ticket marked Done with closing comment.

Phase 2: Final Commit (if needed)

Goal: Ensure any final changes follow commit conventions.

Invoke commit-commands Skill

Use Skill tool: commit-commands:commit
Purpose: Generate standardized commit message

Commit Message Format

<type>(<scope>): <subject>

<body>

<footer>

Co-Authored-By: Claude Code <noreply@anthropic.com>

Output: Clean commit following project conventions.

Phase 3: Postmortem Decision & Creation

Goal: Determine if a new postmortem is needed, and create if yes.

Decision Matrix

ConditionCreate PM?PM Severity
Bug caused incorrect tradesYESCRITICAL
API issue discoveredYESHIGH
Performance degradation foundYESMEDIUM
Edge case hit in backtestYESMEDIUM
Code worked but pattern was suboptimalNO-
Simple refactor, no issuesNO-

Postmortem Template

Create file: ./postmortem/PM-[NNN]-[brief-description].md

# PM-[NNN]: [Incident Title]

## Metadata
- **Date:** [YYYY-MM-DD]
- **Severity:** CRITICAL | HIGH | MEDIUM | LOW
- **Strategy:** [Strategy Name]
- **Linear Ticket:** [LIN-XXX]
- **Author:** [Name/Claude Code]

## Summary
[One paragraph describing what happened]

## Timeline
- [HH:MM] [Event 1]
- [HH:MM] [Event 2]
- [HH:MM] [Detection/Discovery]
- [HH:MM] [Resolution]

## Root Cause Analysis

### What Happened
[Detailed technical explanation]

### Why It Happened
[5 Whys analysis or similar]

### Contributing Factors
- [Factor 1]
- [Factor 2]

## Impact
- **Financial:** [Estimated loss/gain, if any]
- **Operational:** [Service disruption, if any]
- **Data:** [Data corruption/loss, if any]

## Resolution
[What was done to fix the immediate issue]

## Mitigations Implemented

### Code Changes
```python
# BEFORE (anti-pattern)
[code snippet]

# AFTER (correct pattern)
[code snippet]

Tests Added

  • tests/pm_regression/test_pm_[NNN].py

Configuration Changes

  • [Config change 1]

Lessons Learned

What Went Well

  • [Item 1]

What Went Wrong

  • [Item 1]

Action Items

  • [Action 1] - Owner: [Name]
  • [Action 2] - Owner: [Name]

Keywords

[keyword1] [keyword2] [keyword3]

Related

  • Previous: PM-[XXX] (if related)
  • See also: [Link to docs/code]

### PM Naming Convention

PM-001-order-duplication.md PM-002-api-timeout-cascade.md PM-003-liquidity-trap-election.md


**Output:** Postmortem file created (or decision to skip documented).

### 🔄 Ralph Loop: Iterative PM Refinement (Optional)

**When to Activate:** Complex incidents requiring thorough root cause analysis.

For significant incidents, use Ralph Loop to iteratively refine the postmortem quality:

Skill: ralph-loop:ralph-loop

Prompt Template: "Refine Postmortem PM-[NNN] for quality. Incident: [brief description]

Quality Checklist:

  • Root cause identified (not just symptoms)
  • 5 Whys analysis complete
  • Code snippets include before/after
  • Action items are specific and assigned
  • Keywords comprehensive for future search

Current gaps: [list] Output PM REFINED when all checklist items complete."

Options: --max-iterations 5 --completion-promise "PM REFINED"


### Ralph Loop PM Refinement Cycle

```dot
digraph ralph_pm {
    rankdir=LR;
    node [shape=box];

    start [label="Draft PM\nCreated" shape=ellipse];
    check [label="Quality Check"];
    gaps [label="Gaps Found?" shape=diamond];
    refine [label="Refine Section"];
    done [label="<promise>\nPM REFINED" shape=ellipse style=filled fillcolor=lightgreen];

    start -> check;
    check -> gaps;
    gaps -> refine [label="Yes"];
    refine -> check;
    gaps -> done [label="No"];
}

PM Quality Checklist for Ralph Loop

SectionQuality Criteria
Root CauseSpecific, technical, not "human error"
5 WhysChain leads to systemic fix, not blame
Code SnippetsActual code, not pseudocode
TimelineTimestamped, includes detection method
Action ItemsSMART: Specific, Measurable, Assigned
Keywords≥5 relevant search terms

When to Use Ralph Loop for PM

SituationUse Ralph Loop?
CRITICAL severity incident✅ Yes - thorough analysis needed
First incident of its type✅ Yes - establish good template
Similar to existing PM❌ No - reference existing, add delta
Simple config error❌ No - straightforward PM sufficient

Phase 4: CLAUDE.md Preview Generation

Goal: Extract high-frequency rules from postmortem (or learnings) for CLAUDE.md.

Extraction Rules

From PostmortemTo CLAUDE.md
Root Cause⚠️ WARNING (one line)
Code Fix Pattern📋 DIRECTIVE (one line)
Parameter Value🔢 PARAMETER (one line)
Timeline Detail❌ OMIT
5 Whys Analysis❌ OMIT
Impact Assessment❌ OMIT

CRITICAL: Human Review Required

DO NOT write directly to CLAUDE.md. Generate preview first.

Preview Template

---
## 📝 Proposed Addition to CLAUDE.md

### Source: PM-[NNN] - [Title] ([Date])

#### ⚠️ WARNINGS
- [Extracted from Root Cause - ONE LINE, specific values]

#### 📋 DIRECTIVES
- [Extracted from Resolution - ONE LINE, actionable]

#### 🔢 PARAMETERS
- [Parameter]: [Value] ([brief reason])

---

**Estimated CLAUDE.md impact:** +X lines (current: Y, after: Z)
**Total after update:** Z/100 lines

⚡ Please review the above. Reply "确认" to write, or provide edits.

Quality Checklist for Preview

CheckExample PassExample Fail
Specific values"429 after 50 req/min""API has rate limits"
Actionable"Use decimal.Decimal""Be careful with floats"
One line max"Check market.active before orders"[Multi-line explanation]
No proseJust the rule"Because we found that..."

Output: Markdown preview displayed to user, awaiting confirmation.

Phase 5: Human Confirmation

Goal: Ensure human approves before modifying project memory.

Wait for User Response

ResponseAction
"确认" / "confirm" / "yes"Proceed to Phase 6
Edits providedRegenerate preview with changes
"取消" / "cancel"Skip CLAUDE.md update

Revision Handling

If user provides edits:

  1. Incorporate feedback
  2. Regenerate preview
  3. Show updated preview
  4. Wait for confirmation again

Output: User confirmation received.

Phase 6: Write to CLAUDE.md

Goal: Append high-frequency rules to project memory file.

Pre-Write Line Count Check

wc -l CLAUDE.md
# MUST check before writing

100 Line Limit Enforcement

If exceeding 100 lines after addition:

⚠️ CLAUDE.md will exceed 100 lines after this addition.

Current: 92 lines
Adding: 15 lines
Total: 107 lines (7 over limit)

### Pruning Candidates (Oldest First)

1. **Lines 5-12:** Mean-Reversion v1 (2023-06-01) - 8 lines
   - Superseded by PM-015? [Y/N]

2. **Lines 13-20:** Early API Learnings (2023-07-15) - 8 lines
   - Still relevant? [Y/N]

### Options:
1. Prune selected entries
2. Condense new content further
3. Move old entries to postmortem archive
4. Proceed anyway (NOT RECOMMENDED)

Which entries should be pruned?

Write Rules

RuleImplementation
Append onlyAdd at end, never delete without approval
100 line HARD limitMust prune if exceeding
Preserve structureMatch existing formatting
Date stampAlways include date for each entry
PM ReferenceAlways link to source postmortem

Write Action

Tool: Edit or Write (append mode)
File: CLAUDE.md
Content: [Approved preview content]

Post-Write Verification

# Verify line count
wc -l CLAUDE.md
# MUST be ≤ 100

Output: CLAUDE.md updated, line count confirmed.

Quick Reference

PhaseTool/SkillKey Action
1. Contextcontext7:context7 (if needed)Gather context about merged PR
1. Syncmcp__plugin_linear_linear__update_issueMark ticket Done
2. Commitcommit-commands:commitStandardized commit
3. PMWrite to ./postmortem/Create if incident found
3b. 🔄 Ralphralph-loop:ralph-loopIterative PM refinement (optional)
4. PreviewManual generationExtract rules from PM
5. ConfirmAskUserQuestion or waitHuman approval required
6. WriteEdit to CLAUDE.mdAppend, enforce 100 line limit

Dual-Layer Memory Architecture

┌─────────────────────────────────────────────────────────────┐
│                    INCIDENT OCCURS                           │
└─────────────────────────────────────────────────────────────┘
                            │
                            ▼
┌─────────────────────────────────────────────────────────────┐
│  ./postmortem/PM-XXX.md (深度病历库)                          │
│  ─────────────────────────────────────────────────────────  │
│  • Full timeline                                            │
│  • Root cause analysis (5 Whys)                             │
│  • Code snippets (before/after)                             │
│  • Impact assessment                                        │
│  • Action items                                             │
│  • NO LINE LIMIT - be thorough                              │
└─────────────────────────────────────────────────────────────┘
                            │
                            │ EXTRACT
                            ▼
┌─────────────────────────────────────────────────────────────┐
│  ./CLAUDE.md (高频手术准则)                                   │
│  ─────────────────────────────────────────────────────────  │
│  • ⚠️ WARNING: [one line]                                   │
│  • 📋 DIRECTIVE: [one line]                                 │
│  • 🔢 PARAMETER: [value]                                    │
│  • STRICT 100 LINE LIMIT                                    │
│  • Reference: PM-XXX                                        │
└─────────────────────────────────────────────────────────────┘

Common Mistakes

MistakePrevention
Skipping postmortem for incidentsIf there was a bug/issue, PM is MANDATORY
Verbose CLAUDE.md entriesExtract only: warning, directive, parameter
Exceeding 100 linesPrune old entries, ask user to choose
No PM reference in CLAUDE.mdAlways link source: "See: PM-XXX"
Writing CLAUDE.md without previewALWAYS generate preview, wait for "确认"
Missing specifics"API is slow" ❌ → "API 429s after 50 req/min" ✅
Forgetting Linear syncFirst action is always status update

Exit Criteria

Before marking iteration complete:

  • Linear ticket state = Done
  • Closing comment added with summary
  • Final commit follows conventions
  • Postmortem created (if incident occurred)
  • Lesson preview shown to user
  • User explicitly confirmed ("确认")
  • CLAUDE.md updated with PM reference
  • Line count ≤ 100 verified

Example Invocation

Standard Mode

User: "PR merged, close out the mean-reversion iteration. We hit a rate limit bug during testing."

Claude:
1. [Sync] Updating Linear ticket LIN-123 → Done ✅
   Added closing comment

2. [Commit] No pending changes, main branch clean ✅

3. [PM Decision] Rate limit bug found → Creating postmortem

   Creating: ./postmortem/PM-007-rate-limit-429.md
   - Severity: HIGH
   - Root Cause: No delay between API calls
   - Resolution: Added 1.2s minimum delay
   - Tests Added: tests/pm_regression/test_pm_007.py ✅

4. [Preview] Extracting rules from PM-007...

---
## 📝 Proposed Addition to CLAUDE.md

### Source: PM-007 - Rate Limit 429 (2024-01-15)

#### ⚠️ WARNINGS
- Polymarket API returns 429 after 50 req/min without warning header

#### 📋 DIRECTIVES
- Implement minimum 1.2s delay between all API calls
- Parse X-RateLimit-Remaining header when available

#### 🔢 PARAMETERS
- API_MIN_DELAY: 1.2s (discovered empirically, see PM-007)

---

**Estimated CLAUDE.md impact:** +8 lines (current: 52, after: 60)
**Total after update:** 60/100 lines ✅

⚡ Please review the above. Reply "确认" to write, or provide edits.

User: "确认"

Claude:
5. [Write] Appending to CLAUDE.md... ✅
   Line count verified: 60/100 ✅

Iteration complete:
- Linear: LIN-123 Done
- Postmortem: PM-007-rate-limit-429.md created
- CLAUDE.md: +8 lines (total: 60/100)
- Ready for next strategy

🔄 Ralph Loop Mode (PM Refinement)

User: "PR merged. 有个严重的 order cascade 事故需要详细分析"

Claude:
1-2. [Standard Phases Complete] ✅

3. [PM Decision] CRITICAL severity → Creating postmortem
   Creating: ./postmortem/PM-008-order-cascade-failure.md

   Initial draft quality check:
   - Root cause: ❌ Too vague ("system overload")
   - 5 Whys: ❌ Incomplete (only 2 levels)
   - Code snippets: ⚠️ Missing before/after
   - Action items: ❌ Not specific

   CRITICAL incident → Activating Ralph Loop for thorough analysis

🔄 [Ralph Loop: PM Refinement]
   Invoking: /ralph-loop "Refine PM-008 for quality.
   Incident: Order cascade causing $X loss
   Gaps: root cause vague, 5 whys incomplete, no code snippets
   Output <promise>PM REFINED</promise> when all sections complete."
   --max-iterations 5
   --completion-promise "PM REFINED"

   Iteration 1: Root cause refined → "Unbounded retry loop in error handler"
   Iteration 2: 5 Whys complete → leads to "missing circuit breaker"
   Iteration 3: Code snippets added with before/after
   Iteration 4: Action items made SMART, owners assigned

   <promise>PM REFINED</promise>

🔄 [Ralph Loop Complete]
   PM Quality: All checklist items ✅
   - Root cause: Specific technical issue identified
   - 5 Whys: Complete chain to systemic fix
   - Code: Actual snippets with fix
   - Actions: 4 SMART items with owners

4-6. [Continuing to CLAUDE.md preview and write...]

Output: High-quality PM-008 created via iterative refinement

Blueprint Plan - Strategy Architecture & Task Decomposition

Overview

Transform vague strategy ideas into executable Linear Tickets with proper risk assessment, backtest specifications, and Postmortem immune screening to prevent regression.

Core Principle

./postmortem/ = 深度病历库 (Deep Case History)
./CLAUDE.md   = 高频手术准则 (High-Frequency Operating Rules)

Rule: 新策略必须通过历史病历的"免疫筛查"

When to Use

  • User wants to plan a new trading strategy for Polymarket
  • User mentions "策略规划", "strategy planning", or "feature decomposition"
  • Before any implementation of market-making or trading logic

Do NOT use when:

  • Debugging existing strategy code
  • Running backtests (use execution skills instead)
  • Simple code changes unrelated to strategy

Workflow

digraph blueprint_plan {
    rankdir=TB;
    node [shape=box];

    start [label="User: New Strategy Idea" shape=ellipse];
    pm_scan [label="0. Postmortem Immune Scan\n(MANDATORY FIRST)" style=filled fillcolor=lightyellow];
    context [label="1. Context Retrieval\n(GitHub MCP)"];
    review [label="2. Strategy Risk Review\n(Superpowers Analysis)"];
    linear [label="3. Linear Ticket Creation\n(Linear MCP)"];
    done [label="Tickets Ready" shape=ellipse];

    start -> pm_scan;
    pm_scan -> context;
    context -> review;
    review -> linear;
    linear -> done;
}

Phase 0: Postmortem Immune Scan (MANDATORY)

Goal: Screen new strategy against historical failures to prevent regression.

Step 0.1: Scan Postmortem Directory

# List all postmortem files
ls -la ./postmortem/

# Read each relevant postmortem
cat ./postmortem/*.md

Step 0.2: Keyword Matching

Search postmortems for terms related to the new strategy:

Strategy TypeKeywords to Scan
Market Makingspread, inventory, quote, bid, ask, fill
Mean Reversionrevert, mean, deviation, zscore, band
Momentumtrend, breakout, signal, momentum
Arbitragearb, spread, cross-market, latency
Any StrategyAPI, rate limit, timeout, websocket, order
Tool: Grep
Pattern: [relevant keywords]
Path: ./postmortem/

Step 0.3: Immune Report Generation

For each relevant postmortem found, extract:

## 🛡️ Immune Screening Report

### Relevant Historical Incidents

| PM File | Incident | Root Cause | Relevance to New Strategy |
|---------|----------|------------|---------------------------|
| PM-001.md | Order duplication | Missing idempotency | HIGH - uses same order API |
| PM-003.md | Liquidity trap | No exit strategy | MEDIUM - similar market type |

### Mandatory Mitigations (from Postmortems)

- [ ] [Mitigation 1 from PM-001]
- [ ] [Mitigation 2 from PM-003]

### Cleared (No Relevant History)

- [List of scanned categories with no matches]

BLOCKING: If HIGH relevance incidents found, mitigations MUST be included in ticket acceptance criteria.

Output: Immune Screening Report appended to ticket.

🔄 Ralph Loop: Thorough Context Gathering (Optional)

When to Activate: Complex strategies requiring deep codebase understanding.

For strategies touching multiple existing systems, use Ralph Loop to iteratively build comprehensive context:

Skill: ralph-loop:ralph-loop

Prompt Template:
"Gather comprehensive context for [strategy_name].

Target areas:
- Existing strategies in strategies/
- Backtest framework in backtest/
- API integrations in api/
- PM files in postmortem/

Build context map:
- [ ] All relevant files identified
- [ ] Interface contracts documented
- [ ] PM risks catalogued
- [ ] Dependencies mapped

Output <promise>CONTEXT COMPLETE</promise> when context map is comprehensive."

Options:
--max-iterations 8
--completion-promise "CONTEXT COMPLETE"

Ralph Loop Context Gathering Cycle

digraph ralph_context {
    rankdir=LR;
    node [shape=box];

    start [label="Strategy Idea" shape=ellipse];
    explore [label="Explore Codebase"];
    gap [label="Gaps Found?" shape=diamond];
    deepen [label="Deepen Search"];
    done [label="<promise>\nCONTEXT COMPLETE" shape=ellipse style=filled fillcolor=lightgreen];

    start -> explore;
    explore -> gap;
    gap -> deepen [label="Yes"];
    deepen -> explore;
    gap -> done [label="No"];
}

Context Completeness Checklist

AreaQuestions to Answer
StrategiesWhat patterns exist? What interfaces are required?
BacktestWhat data format? What metrics calculated?
APIWhat rate limits? What auth method?
PostmortemsWhat risks relate to this strategy type?
DependenciesWhat versions? What conflicts possible?

When to Use Ralph Loop for Planning

SituationUse Ralph Loop?
New strategy type (no similar exists)✅ Yes - need thorough exploration
Many existing strategies to learn from✅ Yes - comprehensive pattern mining
Simple variant of existing strategy❌ No - direct PM scan sufficient
User provided detailed specs❌ No - context already clear

Phase 1: Context Retrieval

Required: Confirm project structure before proceeding.

Step 1.1: Write Implementation Plan

Use Skill tool: superpowers:writing-plans
Purpose: Create structured implementation plan for the strategy
Input: Strategy idea, PM mitigations from Phase 0, risk assessment
Output: Detailed plan with phases, acceptance criteria, dependencies

Step 1.2: Gather Comprehensive Context

Use Skill tool: context7:context7
Purpose: Gather comprehensive context about existing codebase
Focus: Backtest framework, existing strategies, patterns, dependencies

Step 1.3: Retrieve Codebase Context

Use GitHub MCP to inspect:

  • backtest/ directory: Existing backtest framework, data sources, metrics
  • strategies/ directory: Current strategy implementations, common patterns
Action: Use mcp__github__get_file_contents to list directories
If directories don't exist: Note this as "greenfield implementation"

Output: Implementation plan + comprehensive context + summary of existing codebase or "greenfield" status.

Phase 2: Strategy Risk Review

Analyze the proposed strategy for Polymarket-specific risks.

Step 2.1: Invoke Code Review for Risk Analysis

If strategy design document or pseudo-code exists, use superpowers to analyze risks:

Use Skill tool: superpowers:requesting-code-review
Focus areas:
- Risk patterns in strategy logic
- Error handling assumptions
- Edge case coverage
- PM anti-pattern detection in design

Step 2.2: Manual Risk Matrix Analysis

Analyze the proposed strategy for Polymarket-specific risks:

Risk CategoryCheck Items
Inventory RiskPosition limits, hedging approach, exposure caps
SlippageOrder book depth, spread compensation, market impact
LiquidityMarket depth assumptions, exit strategy
Model RiskProbability estimation method, edge decay
PM-Flagged RisksAll HIGH/MEDIUM items from Phase 0

Output: Risk assessment summary with mitigation recommendations (combining superpowers analysis + manual review).

Phase 3: Linear Ticket Creation

Main Ticket Structure

Create a Feature/Strategy ticket with:

## Strategy: [Strategy Name]

### Description
[Brief strategy overview]

### 🛡️ Postmortem Immune Screening
[Summary from Phase 0 - REQUIRED SECTION]

**Relevant Incidents:** [count]
**Mandatory Mitigations:** [list]

### Risk Assessment
[Summary from Phase 2]

### Backtest Baseline Metrics
| Metric | Target | Minimum Acceptable |
|--------|--------|-------------------|
| Sharpe Ratio | ≥ 2.0 | ≥ 1.5 |
| Max Drawdown (MDD) | ≤ 10% | ≤ 15% |
| APR | ≥ 30% | ≥ 20% |

### Acceptance Criteria
- [ ] Strategy passes backtest with baseline metrics
- [ ] Risk limits implemented
- [ ] Paper trading validation complete
- [ ] **PM mitigations verified:** [list each]

Required Sub-tickets

Auto-create two child tickets:

  1. 策略实现 (Strategy Implementation)

    • Core trading logic
    • Order placement/cancellation
    • Position management
    • PM mitigation implementations
  2. 回测用例编写 (Backtest Case Development)

    • Historical data integration
    • Performance metrics calculation
    • Edge case scenarios
    • PM regression test cases

Use mcp__plugin_linear_linear__create_issue with parentId for sub-tickets.

Quick Reference

PhaseToolKey Action
0. PM ScanGrep + ReadScan postmortem/ for relevant incidents
0b. 🔄 Ralphralph-loop:ralph-loopThorough context gathering (optional)
1. Plansuperpowers:writing-plansCreate structured implementation plan
1. Contextcontext7:context7Gather comprehensive codebase context
1. Contextmcp__github__get_file_contentsList backtest/, strategies/
2. Reviewsuperpowers:requesting-code-reviewRisk analysis + code review (if design doc exists)
3. Linearmcp__plugin_linear_linear__create_issueCreate tickets with PM section

Common Mistakes

MistakeFix
Skipping PM scanPhase 0 is MANDATORY, not optional
Ignoring HIGH relevance incidentsMUST include mitigations in acceptance criteria
Skipping context checkAlways verify codebase structure first
Missing metrics baselineInclude Sharpe, MDD, APR targets in every ticket
No sub-ticket linkingUse parentId to properly link sub-tasks
Vague risk assessmentBe specific: "10% position cap" not "manage inventory"

Postmortem File Format Reference

Expected structure in ./postmortem/:

postmortem/
├── PM-001-order-duplication.md
├── PM-002-api-timeout-cascade.md
├── PM-003-liquidity-trap.md
└── TEMPLATE.md

Each PM file should contain:

  • Incident Date
  • Root Cause
  • Impact
  • Mitigations Implemented
  • Keywords (for searchability)

Example Invocation

Standard Mode

User: "Plan a mean-reversion strategy for Polymarket presidential election markets"

Claude:
0. [PM Scan] Scanning postmortem/ for: revert, mean, election, spread...
   Found: PM-003 (liquidity trap in election markets) - HIGH relevance
   Mitigation required: Exit strategy for illiquid periods

1. [Context] Checking backtest/ and strategies/ via GitHub...
   Found existing mean-reversion base class

2. [Review] Risk assessment for mean-reversion in binary markets...
   Added PM-003 mitigation to risk matrix

3. [Linear] Creating main ticket + 2 sub-tickets...
   - Main ticket includes PM Immune Screening section
   - Acceptance criteria includes PM-003 mitigation verification

Output: Links to created Linear tickets with PM screening embedded

🔄 Ralph Loop Mode (Deep Context Gathering)

User: "Plan a cross-market arbitrage strategy,这是我们第一次做套利"

Claude:
0. [PM Scan] Scanning postmortem/ for: arb, spread, cross-market, latency...
   Found: Multiple potential risks
   First arbitrage strategy → Need thorough context

🔄 [Ralph Loop: Context Gathering]
   Invoking: /ralph-loop "Gather comprehensive context for cross-market arbitrage.
   Areas: strategies/, backtest/, api/, postmortem/
   First arb strategy - need complete understanding.
   Output <promise>CONTEXT COMPLETE</promise> when map is comprehensive."
   --max-iterations 8
   --completion-promise "CONTEXT COMPLETE"

   Iteration 1: Explored strategies/ → Found market-making base, no arb
   Iteration 2: Explored backtest/ → Multi-market data format identified
   Iteration 3: Explored api/ → Rate limits per exchange documented
   Iteration 4: Deep PM scan → 3 latency-related incidents found
   Iteration 5: Dependencies → Websocket libraries identified

   <promise>CONTEXT COMPLETE</promise>

🔄 [Ralph Loop Complete]
   Context Map Built:
   - Existing patterns: Market-making (adaptable)
   - Backtest: Supports multi-market (need sync logic)
   - API: 3 exchange connectors, different rate limits
   - PM Risks: Latency (PM-004), Data sync (PM-006), Order timing (PM-009)
   - Dependencies: asyncio, websockets (no conflicts)

1-3. [Proceeding with Context, Review, Linear...]
   Tickets created with comprehensive PM risks from deep scan

Output: Well-informed tickets based on thorough codebase exploration

Blueprint Review - Security, Quality & PM Compliance Assessment

Overview

Multi-dimensional code review ensuring Postmortem compliance, security compliance, error handling robustness, and validated backtest results before PR creation.

Core Principle

./postmortem/ = 深度病历库 (Deep Case History)
./CLAUDE.md   = 高频手术准则 (High-Frequency Operating Rules)

Rule: PR 不能引入任何已记录在案的反模式,必须通过"病历复查"

When to Use

  • Strategy implementation is complete (after blueprint-develop)
  • Ready to create PR for merge
  • User mentions "review", "审核", "PR ready", or "quality check"
  • Before any strategy code goes to production

Do NOT use when:

  • Still implementing features (use blueprint-develop)
  • Planning phase (use blueprint-plan)
  • Backtest-only runs without code review intent

Prerequisites

Before invoking this skill, verify:

  • All tests passing (from blueprint-develop Phase 5)
  • PM regression tests passing (from blueprint-develop Phase 2)
  • Code committed to feature branch
  • Linear ticket linked to the work

Workflow

digraph blueprint_review {
    rankdir=TB;
    node [shape=box];

    start [label="Start: Code Ready for Review" shape=ellipse];
    pm_audit [label="0. PM Compliance Audit\n(MANDATORY FIRST)" style=filled fillcolor=lightyellow];
    security [label="1. Security Audit\n(security-guidance)"];
    code_review [label="2. Code Quality Review\n(code-review)"];
    backtest [label="3. Backtest Validation\n(Execute & Capture)"];
    pm_final [label="4. PM Final Check\n(Anti-Pattern Scan)" style=filled fillcolor=lightyellow];
    pr [label="5. Create PR\n(GitHub MCP)"];
    done [label="PR Ready for Human Review" shape=ellipse];

    start -> pm_audit;
    pm_audit -> security;
    security -> code_review;
    code_review -> backtest;
    backtest -> pm_final;
    pm_final -> pr;
    pr -> done;
}

Phase 0: PM Compliance Audit (MANDATORY)

Goal: Verify implementation doesn't repeat any documented failures.

Step 0.0: Gather Context (if needed)

When analyzing complex PM compliance issues:

Use Skill tool: context7:context7
Purpose: Gather comprehensive context about PM mitigations and related code
Focus: PM-related code patterns, historical fixes, compliance requirements

Step 0.1: Run PM Regression Tests

# MUST pass before proceeding
pytest tests/pm_regression/ -v --tb=short

# If any fail, STOP and return to blueprint-develop

Step 0.2: Cross-Reference PM Mitigations

From the Linear ticket, verify each PM mitigation is implemented:

## PM Compliance Verification

| PM | Required Mitigation | Implemented? | Evidence |
|----|---------------------|--------------|----------|
| PM-001 | Idempotency key on orders | ✅ | execution.py:45 |
| PM-003 | Liquidity check before entry | ✅ | signals.py:23 |
| PM-003 | Exit timeout mechanism | ✅ | execution.py:89 |

Step 0.3: CLAUDE.md Directive Check

# Read current directives
cat ./CLAUDE.md

Verify code adheres to ALL directives:

## CLAUDE.md Compliance

| Directive | Compliant? | Evidence |
|-----------|------------|----------|
| Use decimal.Decimal for prices | ✅ | grep -r "Decimal" strategies/ |
| Rate limit: 1.2s min delay | ✅ | api/client.py:34 |
| Log order IDs immediately | ✅ | execution.py:47 |

BLOCKING: If ANY PM mitigation is missing or CLAUDE.md directive violated, STOP and return to blueprint-develop.

Output: PM Compliance Report.

Phase 1: Security Audit

Goal: Ensure no security vulnerabilities in trading bot code.

Step 1.1: Invoke Security Guidance

Use Skill tool: security-guidance:security-guidance
Purpose: Get security best practices and vulnerability guidance
Focus: Trading bot security, API key handling, credential management

Step 1.2: Security Checklist

CategoryCheck ItemsSeverity
Private Key HandlingNo hardcoded keys, env vars only, no logging of secretsCRITICAL
API CredentialsSecure storage, rotation support, no plaintextCRITICAL
Rate LimitingBackoff logic, rate limit headers respectedHIGH
Input ValidationAll external data sanitizedHIGH
Error MessagesNo sensitive data in logs/errorsMEDIUM

Security Scan Actions

1. Grep for security anti-patterns:
   - "private_key\s*=" (hardcoded keys)
   - "api_key\s*=" (hardcoded credentials)
   - "password\s*=" (plaintext passwords)
   - "print.*key|secret|password" (secret logging)

2. Verify secure patterns:
   - os.environ.get() or dotenv usage
   - try/except around API calls with rate limit handling
   - No credentials in git history

PM-Informed Security Patterns

Check for security issues documented in postmortems:

# Search postmortems for security-related incidents
grep -l "security\|credential\|key\|leak" ./postmortem/*.md

Output: Security audit report with PASS/FAIL per category.

Phase 2: Code Quality Review

Goal: Ensure robust error handling for market-making bot reliability.

Step 2.1: Invoke Superpowers Code Review

Use Skill tool: superpowers:requesting-code-review
Focus areas:
- Exception handling completeness
- Network resilience
- State recovery after failures
- PM anti-pattern avoidance

Step 2.2: Invoke Code Review Skill (Complementary)

Use Skill tool: code-review:code-review
Purpose: Additional code review perspective, especially for PR-specific concerns
Focus: PR readiness, merge conflicts, branch hygiene

Step 2.3: Code Simplification

Before creating PR, simplify and refactor code if needed:

Use Skill tool: code-simplifier:code-simplifier
Purpose: Simplify code before PR creation
Focus: Reduce complexity, improve maintainability, remove redundancy

Critical Error Handling Patterns

ScenarioRequired HandlingAnti-pattern
Network TimeoutRetry with exponential backoffSingle try, crash on fail
API Error 5xxLog, wait, retry (max 3)Immediate retry flood
WebSocket DisconnectAuto-reconnect with state syncManual restart required
Order RejectionLog reason, adjust, retrySilent failure
Data Feed GapDetect, flag, use stale indicatorTrade on stale data

PM-Specific Anti-Pattern Scan

# For each PM, grep for the documented anti-pattern
# Example from PM-002:
grep -rn "time.sleep(0)" strategies/  # Should find nothing

# Example from PM-004:
grep -rn "while True:" strategies/  # Check for unbounded loops

Bot Resilience Checklist

  • All API calls wrapped in try/except
  • Retry logic with backoff for transient errors
  • WebSocket auto-reconnect implemented
  • Graceful shutdown on SIGTERM/SIGINT
  • State persistence for recovery after restart
  • Health check endpoint or heartbeat logging

Output: Code review report with findings and required fixes.

Phase 3: Backtest Validation

Goal: Execute backtest and capture results for PR documentation.

CRITICAL: Claude Code MUST Execute Backtest

Do not skip this phase. Run the actual backtest script.

# Standard backtest execution
python -m backtest.run --strategy [strategy_name] --output results/

# Or project-specific command (check backtest/README.md)

Capture Required Outputs

Output TypeLocationPR Inclusion
Performance MetricsTerminal stdoutCopy to PR body
Equity Curve Chartresults/*.pngReference path in PR
Trade Logresults/trades.csvSummarize stats
Risk MetricsTerminal or JSONInclude in table

Metrics Summary Template

## Backtest Results

**Period:** [start_date] to [end_date]
**Markets:** [list of markets tested]

### Performance Metrics
| Metric | Value | Target | Status |
|--------|-------|--------|--------|
| Sharpe Ratio | X.XX | ≥ 2.0 | ✅/❌ |
| Max Drawdown | X.X% | ≤ 10% | ✅/❌ |
| APR | XX.X% | ≥ 30% | ✅/❌ |
| Win Rate | XX.X% | ≥ 55% | ✅/❌ |
| Total Trades | XXX | - | - |

### Charts
- Equity Curve: `results/equity_curve.png`
- Drawdown Chart: `results/drawdown.png`

### Notes
[Any observations, edge cases, or caveats]

Backtest Failure Handling

If backtest fails or metrics below threshold:

  1. DO NOT proceed to PR creation
  2. Document failure reason
  3. Check if failure relates to a PM (potential new PM candidate)
  4. Return to blueprint-develop for fixes
  5. Re-run this skill after fixes

Output: Backtest results summary formatted for PR.

🔄 Ralph Loop: Iterative Backtest Optimization (Optional)

When to Activate: Backtest metrics close to threshold but not passing.

Instead of returning to blueprint-develop, use Ralph Loop for iterative parameter tuning:

Skill: ralph-loop:ralph-loop

Prompt Template:
"Optimize [strategy_name] backtest parameters.
Current metrics:
- Sharpe: X.XX (target: ≥ 2.0)
- MDD: X.X% (target: ≤ 10%)
- APR: XX% (target: ≥ 30%)

Constraints:
- PM compliance must be maintained
- Only tune: [allowed_parameters]
- DO NOT modify core logic

Output <promise>BACKTEST PASSED</promise> when ALL metrics meet targets."

Options:
--max-iterations 10
--completion-promise "BACKTEST PASSED"

Ralph Loop Backtest Cycle

digraph ralph_backtest {
    rankdir=LR;
    node [shape=box];

    start [label="Backtest\nBelow Threshold" shape=ellipse];
    tune [label="Tune Parameters"];
    run [label="Run Backtest"];
    check [label="Metrics OK?" shape=diamond];
    pass [label="<promise>\nBACKTEST PASSED" shape=ellipse style=filled fillcolor=lightgreen];

    start -> tune;
    tune -> run;
    run -> check;
    check -> tune [label="No"];
    check -> pass [label="Yes"];
}

Ralph Loop Constraints for Backtest

AllowedNOT Allowed
Risk parameters (stop loss %, position size)Core signal logic
Entry/exit thresholdsPM mitigation removal
Spread compensation factorsTest modifications
Timing parametersChanging target metrics

When to Use Ralph Loop vs Return to Develop

SituationAction
Sharpe 1.8, need 2.0🔄 Ralph Loop - tune params
Sharpe 0.5, need 2.0❌ Return to develop - fundamental issue
MDD 12%, need 10%🔄 Ralph Loop - adjust risk params
Tests failing❌ Return to develop - not a tuning issue
PM compliance issue❌ Return to develop - NEVER tune away compliance

Phase 4: PM Final Check (Anti-Pattern Scan)

Goal: Final sweep for any PM-documented anti-patterns that may have slipped through.

Comprehensive Anti-Pattern Grep

# Load all anti-patterns from postmortems
for pm in ./postmortem/PM-*.md; do
    echo "=== Checking patterns from $pm ==="
    # Extract "DON'T" patterns and grep for them
done

Anti-Pattern Checklist from All PMs

Generate a comprehensive checklist:

## Final Anti-Pattern Sweep

### From PM Files
| PM | Anti-Pattern | Found? | Action |
|----|--------------|--------|--------|
| PM-001 | Missing client_order_id | ❌ None | OK |
| PM-002 | Hardcoded API delay | ❌ None | OK |
| PM-003 | No liquidity check | ❌ None | OK |
| PM-004 | Unbounded retry loop | ❌ None | OK |

### From CLAUDE.md
| Directive Violation | Found? | Action |
|--------------------|--------|--------|
| Float for price calc | ❌ None | OK |
| Missing order log | ❌ None | OK |

BLOCKING: If ANY anti-pattern found, STOP and fix before PR.

Output: Clean anti-pattern scan report.

Phase 5: PR Creation

Goal: Create PR with comprehensive PM compliance documentation.

Step 5.1: Final Verification Before PR

Use Skill tool: superpowers:verification-before-completion
Purpose: Final check that all review phases completed successfully
Verify:
- PM compliance audit passed
- Security audit passed
- Code review passed
- Backtest metrics meet baseline
- Anti-pattern scan clean

Step 5.2: Commit and Push (if needed)

If there are uncommitted changes:

Use Skill tool: commit-commands:commit
Purpose: Create standardized commit before PR

Step 5.3: Create PR

Option A: Use commit-push-pr (Recommended if uncommitted changes)

Use Skill tool: commit-commands:commit-push-pr
Purpose: Commit, push, and create PR in one step

Option B: Use GitHub MCP (if already committed)

Tool: mcp__github__create_pull_request

Parameters:
- owner: [repo owner]
- repo: [repo name]
- title: "[Strategy] [Brief Description] - LIN-XXX"
- head: [feature-branch]
- base: main
- body: [Formatted PR body below]

PR Body Template (PM-Enhanced)

## Summary
[1-2 sentence description of the strategy/change]

**Linear Ticket:** [LIN-XXX](link)

## 🛡️ PM Compliance Report

### Postmortem Mitigations Verified
| PM | Mitigation | Status | Test |
|----|------------|--------|------|
| PM-001 | Idempotency key | ✅ | test_pm_001.py |
| PM-003 | Liquidity check | ✅ | test_pm_003.py |
| PM-003 | Exit timeout | ✅ | test_pm_003.py |

### CLAUDE.md Directives
| Directive | Status |
|-----------|--------|
| Decimal for prices | ✅ |
| Rate limit 1.2s | ✅ |
| Log order IDs | ✅ |

### Anti-Pattern Scan
- [x] No PM-documented anti-patterns found
- [x] All regression tests passing

## Security Review
| Check | Status |
|-------|--------|
| Private Key Handling | ✅ Passed |
| API Credentials | ✅ Passed |
| Rate Limiting | ✅ Passed |
| Input Validation | ✅ Passed |

## Code Quality Review
| Check | Status |
|-------|--------|
| Exception Handling | ✅ Passed |
| Network Resilience | ✅ Passed |
| State Recovery | ✅ Passed |

## Backtest Results

**Period:** [dates]

| Metric | Value | Target | Status |
|--------|-------|--------|--------|
| Sharpe Ratio | X.XX | ≥ 2.0 | ✅ |
| Max Drawdown | X.X% | ≤ 10% | ✅ |
| APR | XX.X% | ≥ 30% | ✅ |

<details>
<summary>Full Backtest Output</summary>

[Paste terminal output here]


</details>

## Test Coverage
- Unit Tests: XX passing
- **PM Regression Tests: XX passing**
- Coverage: XX%

## Checklist
- [ ] **PM compliance audit passed**
- [ ] Security audit passed
- [ ] Code review passed
- [ ] Backtest meets baseline metrics
- [ ] **Anti-pattern scan clean**
- [ ] Tests passing
- [ ] Ready for human review

---
🤖 Generated with Claude Code | PM Compliant ✅

Post-PR Actions

After PR creation:

  1. Add reviewers if known
  2. Link PR to Linear ticket using mcp__plugin_linear_linear__update_issue
  3. Add PR link as attachment to Linear ticket

Output: PR URL and confirmation of Linear ticket update.

Quick Reference

PhaseTool/SkillKey Action
0. PM Auditcontext7:context7 (if needed) + pytest tests/pm_regression/Gather context + Verify PM mitigations
1. Securitysecurity-guidance:security-guidance + Grep + security patternsSecurity guidance + Scan for secrets
2. Qualitysuperpowers:requesting-code-review + code-review:code-reviewException handling + PR review
2b. Simplifycode-simplifier:code-simplifierSimplify code before PR
3. BacktestBash (execute script)Run backtest
3b. 🔄 Ralphralph-loop:ralph-loopIterative param tuning (optional)
4. PM Finalcontext7:context7 (if needed) + Grep + PM anti-patternsGather context + Final sweep
5. Verifysuperpowers:verification-before-completionFinal check before PR
5. PRcommit-commands:commit-push-pr or mcp__github__create_pull_requestCreate with PM report

Common Mistakes

MistakePrevention
Skipping PM auditPhase 0 is MANDATORY, blocking gate
No PM section in PRAlways include PM Compliance Report
Skipping backtest executionMUST run actual script
Generic security scanUse trading-bot-specific patterns
PR without metricsAlways include Sharpe, MDD, APR
Missing Linear linkUpdate ticket with PR reference
Ignoring anti-pattern scanPhase 4 must pass before PR

Exit Criteria

Before marking review complete:

  • PM Compliance Audit: All mitigations verified
  • PM Regression Tests: All passing
  • Anti-Pattern Scan: Clean
  • Security audit: All categories PASSED
  • Code review: No blocking issues
  • Backtest: All metrics meet or exceed baseline
  • PR created with PM Compliance Report
  • Linear ticket updated with PR link

Example Invocation

Standard Mode

User: "Review the mean-reversion strategy and create PR"

Claude:
0. [PM Audit] Running PM regression tests...
   pytest tests/pm_regression/ → 6/6 passed ✅
   PM-001 mitigation: verified in execution.py:45 ✅
   PM-003 mitigations: verified in signals.py:23, execution.py:89 ✅
   CLAUDE.md directives: 5/5 compliant ✅

1. [Security] Scanning for secrets... No hardcoded keys found ✅
   Rate limit handling verified in api/client.py ✅

2. [Quality] Running code-review skill...
   Exception handling: 12/12 API calls wrapped ✅
   Network resilience: Auto-reconnect implemented ✅

3. [Backtest] Executing: python -m backtest.run --strategy mean_reversion
   Sharpe: 2.3 ✅ | MDD: 8.2% ✅ | APR: 34% ✅

4. [PM Final] Anti-pattern scan...
   Scanned for 12 anti-patterns from 4 PMs → None found ✅

5. [PR] Created: https://github.com/org/repo/pull/42
   Includes PM Compliance Report ✅
   Linear ticket LIN-123 updated with PR link

Output: PR #42 ready for human review (PM Compliant)

🔄 Ralph Loop Mode (Backtest Optimization)

User: "Review strategy, backtest 还差一点点达标"

Claude:
0-2. [Standard Phases Complete] ✅

3. [Backtest] First run results:
   Sharpe: 1.85 ❌ (target: ≥ 2.0)
   MDD: 9.5% ✅
   APR: 28% ❌ (target: ≥ 30%)

   Metrics close to threshold → Activating Ralph Loop

🔄 [Ralph Loop: Backtest Optimization]
   Invoking: /ralph-loop "Optimize mean-reversion parameters.
   Current: Sharpe 1.85, APR 28%
   Target: Sharpe ≥ 2.0, APR ≥ 30%
   Allowed params: spread_threshold, position_size_pct, exit_timeout_hours
   PM compliance must be maintained.
   Output <promise>BACKTEST PASSED</promise> when targets met."
   --max-iterations 8
   --completion-promise "BACKTEST PASSED"

   Iteration 1: Sharpe 1.85 → 1.92 (adjusted spread_threshold)
   Iteration 2: Sharpe 1.92 → 1.98 (tuned position_size_pct)
   Iteration 3: Sharpe 1.98 → 2.05, APR 31% ✅

   <promise>BACKTEST PASSED</promise>

🔄 [Ralph Loop Complete]
   Final metrics: Sharpe 2.05 ✅ | MDD 9.8% ✅ | APR 31% ✅
   PM Compliance: Maintained ✅

4-5. [Continuing to PM Final Check and PR...]

Output: PR created with optimized parameters via Ralph Loop

Commands 4

Blueprint Develop Command

Use the blueprint-develop skill for test-driven development of trading strategies.

You should use the Skill tool to invoke blueprint-skills:blueprint-develop and follow its instructions.

Blueprint Optimize Command

Use the blueprint-optimize skill to complete iteration cycle after PR merge.

You should use the Skill tool to invoke blueprint-skills:blueprint-optimize and follow its instructions.

Blueprint Plan Command

Use the blueprint-plan skill to transform a new trading strategy idea into actionable Linear tickets.

You should use the Skill tool to invoke blueprint-skills:blueprint-plan and follow its instructions.

Blueprint Review Command

Use the blueprint-review skill for pre-merge security and quality review.

You should use the Skill tool to invoke blueprint-skills:blueprint-review and follow its instructions.

Sponsors

Details

Marketplace
morris-y/claude-marketplace
Source
morris-y/blueprint-skills
Author
morris-y
Category
Community