{
  "schemaVersion": "1.0",
  "item": {
    "slug": "afrexai-claude-code-production",
    "name": "Claude Code Production Engineering",
    "source": "tencent",
    "type": "skill",
    "category": "开发工具",
    "sourceUrl": "https://clawhub.ai/1kalin/afrexai-claude-code-production",
    "canonicalUrl": "https://clawhub.ai/1kalin/afrexai-claude-code-production",
    "targetPlatform": "OpenClaw"
  },
  "install": {
    "downloadMode": "redirect",
    "downloadUrl": "/downloads/afrexai-claude-code-production",
    "sourceDownloadUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=afrexai-claude-code-production",
    "sourcePlatform": "tencent",
    "targetPlatform": "OpenClaw",
    "installMethod": "Manual import",
    "extraction": "Extract archive",
    "prerequisites": [
      "OpenClaw"
    ],
    "packageFormat": "ZIP package",
    "includedAssets": [
      "README.md",
      "SKILL.md"
    ],
    "primaryDoc": "SKILL.md",
    "quickSetup": [
      "Download the package from Yavira.",
      "Extract the archive and review SKILL.md first.",
      "Import or place the package into your OpenClaw setup."
    ],
    "agentAssist": {
      "summary": "Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.",
      "steps": [
        "Download the package from Yavira.",
        "Extract it into a folder your agent can access.",
        "Paste one of the prompts below and point your agent at the extracted folder."
      ],
      "prompts": [
        {
          "label": "New install",
          "body": "I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Then review README.md for any prerequisites, environment setup, or post-install checks. Tell me what you changed and call out any manual steps you could not complete."
        },
        {
          "label": "Upgrade existing",
          "body": "I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Then review README.md for any prerequisites, environment setup, or post-install checks. Summarize what changed and any follow-up checks I should run."
        }
      ]
    },
    "sourceHealth": {
      "source": "tencent",
      "status": "healthy",
      "reason": "direct_download_ok",
      "recommendedAction": "download",
      "checkedAt": "2026-04-30T16:55:25.780Z",
      "expiresAt": "2026-05-07T16:55:25.780Z",
      "httpStatus": 200,
      "finalUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=network",
      "contentType": "application/zip",
      "probeMethod": "head",
      "details": {
        "probeUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=network",
        "contentDisposition": "attachment; filename=\"network-1.0.0.zip\"",
        "redirectLocation": null,
        "bodySnippet": null
      },
      "scope": "source",
      "summary": "Source download looks usable.",
      "detail": "Yavira can redirect you to the upstream package for this source.",
      "primaryActionLabel": "Download for OpenClaw",
      "primaryActionHref": "/downloads/afrexai-claude-code-production"
    },
    "validation": {
      "installChecklist": [
        "Use the Yavira download entry.",
        "Review SKILL.md after the package is downloaded.",
        "Confirm the extracted package contains the expected setup assets."
      ],
      "postInstallChecks": [
        "Confirm the extracted package includes the expected docs or setup files.",
        "Validate the skill or prompts are available in your target agent workspace.",
        "Capture any manual follow-up steps the agent could not complete."
      ]
    },
    "downloadPageUrl": "https://openagent3.xyz/downloads/afrexai-claude-code-production",
    "agentPageUrl": "https://openagent3.xyz/skills/afrexai-claude-code-production/agent",
    "manifestUrl": "https://openagent3.xyz/skills/afrexai-claude-code-production/agent.json",
    "briefUrl": "https://openagent3.xyz/skills/afrexai-claude-code-production/agent.md"
  },
  "agentAssist": {
    "summary": "Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.",
    "steps": [
      "Download the package from Yavira.",
      "Extract it into a folder your agent can access.",
      "Paste one of the prompts below and point your agent at the extracted folder."
    ],
    "prompts": [
      {
        "label": "New install",
        "body": "I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Then review README.md for any prerequisites, environment setup, or post-install checks. Tell me what you changed and call out any manual steps you could not complete."
      },
      {
        "label": "Upgrade existing",
        "body": "I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Then review README.md for any prerequisites, environment setup, or post-install checks. Summarize what changed and any follow-up checks I should run."
      }
    ]
  },
  "documentation": {
    "source": "clawhub",
    "primaryDoc": "SKILL.md",
    "sections": [
      {
        "title": "Claude Code Production Engineering",
        "body": "The complete methodology for shipping production code with Claude Code at 10X speed. Not installation scripts — actual patterns, workflows, and techniques that compound your output."
      },
      {
        "title": "Quick Health Check (run mentally before every session)",
        "body": "SignalHealthyFixCLAUDE.md exists at project root✅Create one (see §1).claueignore configured✅Add noise directoriesSession context under 60%✅/compact or start freshClear task scope before prompting✅Write task brief firstTests exist for target code✅Write tests first (§7)Git clean before big changes✅Commit or stashSub-agents for parallel work✅Use /new or Task toolVerifying output, not trusting blindly✅Always review diffs\n\nScore: /8. Below 6 = slow, buggy sessions. Fix before coding."
      },
      {
        "title": "1. Project Setup — CLAUDE.md Architecture",
        "body": "CLAUDE.md is your project's brain. Claude reads it at session start. A good one saves thousands of tokens per session."
      },
      {
        "title": "Template",
        "body": "# Project: [name]\n\n## Tech Stack\n- Language: TypeScript (strict mode)\n- Framework: Next.js 15 App Router\n- Database: PostgreSQL via Drizzle ORM\n- Testing: Vitest + Playwright\n- Styling: Tailwind CSS v4\n\n## Architecture Rules\n- Max 50 lines per function, 300 lines per file\n- One responsibility per file\n- All exports typed — no `any`\n- Errors as values (Result type), not thrown exceptions\n- Database: migrations via `drizzle-kit generate` then `drizzle-kit push`\n\n## File Structure\nsrc/\n  app/         → Next.js routes (thin — call services)\n  lib/         → Business logic (pure functions)\n  db/          → Schema, migrations, queries\n  components/  → UI (server components default, 'use client' only when needed)\n  types/       → Shared type definitions\n\n## Commands\n- `pnpm dev` — start dev server\n- `pnpm test` — run vitest\n- `pnpm test:e2e` — run playwright\n- `pnpm lint` — eslint + tsc --noEmit\n- `pnpm db:generate` — generate migration\n- `pnpm db:push` — apply migration\n\n## Conventions\n- Imports: absolute from `@/` (mapped to `src/`)\n- Naming: camelCase functions, PascalCase components/types, SCREAMING_SNAKE constants\n- Commits: conventional commits (feat:, fix:, refactor:, test:, docs:)\n- PRs: always create branch, never commit to main directly"
      },
      {
        "title": "CLAUDE.md Rules",
        "body": "Be specific — \"TypeScript strict\" not \"use types.\" Stack versions, not just names.\nInclude commands — Claude needs to know how to run things. Exact commands, not descriptions.\nArchitecture decisions — document WHY, not just what. \"Errors as values because we use Result type\" tells Claude the pattern.\nKeep it under 200 lines — CLAUDE.md is read every session. Bloat wastes tokens.\nUpdate when patterns change — stale CLAUDE.md causes Claude to fight your codebase.\nNested CLAUDE.md — subdirectories can have their own. Claude merges them. Use for monorepo packages."
      },
      {
        "title": ".claueignore",
        "body": "node_modules/\n.next/\ndist/\ncoverage/\n*.lock\n.git/\n*.min.js\n*.map\npublic/assets/\n\nRule: if Claude doesn't need to read it, ignore it. Large lock files and build artifacts waste context."
      },
      {
        "title": "Pattern 1: Task Brief (use for any non-trivial work)",
        "body": "Task: Add user authentication with magic links\nContext: Using Resend for email, no password system exists yet\nConstraints:\n- Server actions only (no API routes)\n- Session via httpOnly cookies\n- Token expires in 15 minutes\nAcceptance: User enters email → receives link → clicks → logged in → cookie set\nStart with: the database schema for sessions and tokens\n\nWhy it works: scope + constraints + acceptance criteria + starting point. Claude doesn't wander."
      },
      {
        "title": "Pattern 2: Show, Don't Tell",
        "body": "Bad: \"Make the API more robust\"\nGood: \"Add input validation to POST /api/users — validate email format, name 1-100 chars, reject extra fields. Return 422 with field-level errors matching this shape: { errors: { field: string, message: string }[] }\"\n\nRule: if you can't describe the exact output shape, you don't know what you want yet. Think first."
      },
      {
        "title": "Pattern 3: Incremental Refinement",
        "body": "Step 1: \"Create the database schema for a todo app with projects and tasks\"\n[review output]\nStep 2: \"Now add the CRUD service layer for tasks — pure functions, no framework imports\"\n[review output]\nStep 3: \"Now the API routes that call those services — input validation with zod\"\n\nWhy: Claude produces better code in focused steps than in one massive prompt. Each step builds verified context."
      },
      {
        "title": "Pattern 4: Fix With Evidence",
        "body": "Bad: \"It's broken\"\nGood: \"Running pnpm test gives this error:\n\nTypeError: Cannot read properties of undefined (reading 'id')\n  at getUserById (src/lib/users.ts:23:15)\n\nThe function expects a User object but receives undefined when the database query returns no rows. Add a null check and return a Result type.\"\n\nRule: paste the actual error. Claude is excellent at fixing bugs when it can see the stack trace."
      },
      {
        "title": "Pattern 5: Architecture Discussion",
        "body": "I'm deciding between these approaches for real-time updates:\nA) Server-Sent Events from Next.js API routes\nB) WebSocket via separate service\nC) Polling every 5 seconds\n\nContext: 500 concurrent users, updates every 30 seconds on average, deployed on Vercel.\n\nWhat are the tradeoffs? Recommend one with reasoning.\n\nUse this for decisions, not implementation. Get the answer, THEN switch to Task Brief for building."
      },
      {
        "title": "Context Is Milk — It Spoils",
        "body": "Context %Action0-30%Fresh. Do complex work here.30-60%Good. Continue current task.60-80%Getting stale. Finish current unit, then compact.80%+Dangerous. /compact immediately or start new session."
      },
      {
        "title": "When to Start Fresh (/new)",
        "body": "Switching to unrelated task\nContext above 70%\nClaude starts repeating itself or making mistakes it didn't make earlier\nAfter shipping a feature (clean slate for next one)"
      },
      {
        "title": "When to Compact (/compact)",
        "body": "Mid-task but context bloating from exploration\nAfter a debugging session (lots of error output consumed context)\nBefore a complex implementation step"
      },
      {
        "title": "Context-Efficient Habits",
        "body": "Don't paste entire files — reference by path. Claude can read them.\nDon't re-explain — if it's in CLAUDE.md, don't repeat it in prompts.\nUse specific file paths — \"Look at src/lib/auth.ts line 45\" not \"look at the auth code.\"\nClose tangents — if Claude goes down a rabbit hole, redirect immediately. Don't let bad output consume context.\nOne concern per message — \"Fix the auth bug AND refactor the database layer AND add tests\" = context explosion. Sequential > parallel in a single session."
      },
      {
        "title": "When to Use Sub-Agents",
        "body": "ScenarioPatternIndependent featuresSpawn sub-agent per featureTests + implementationOne agent writes tests, main writes codeResearch + buildSub-agent researches API docs, main buildsRefactor + maintainSub-agent refactors module A, main works on BCode reviewSub-agent reviews your PR with fresh eyes"
      },
      {
        "title": "Task Tool Pattern (Claude Code native)",
        "body": "Use the Task tool to:\n1. Research the Stripe API for subscription billing\n2. Return: webhook event types we need, API calls for create/update/cancel, error codes to handle\n\nTask tool spawns a sub-agent with its own context. Results come back summarized. Perfect for research that would bloat your main context."
      },
      {
        "title": "Handoff Documents",
        "body": "When a sub-agent finishes complex work, have it write a HANDOFF.md:\n\n## What Was Done\n- Implemented Stripe webhook handler at src/app/api/webhooks/stripe/route.ts\n- Added 4 event handlers: checkout.session.completed, invoice.paid, invoice.payment_failed, customer.subscription.deleted\n\n## Key Decisions\n- Used Stripe SDK v14 (not raw HTTP) for type safety\n- Webhook signature verification via stripe.webhooks.constructEvent()\n- Idempotency: check processed_events table before handling\n\n## What's Next\n- Wire up subscription status updates to user table\n- Add retry logic for failed database writes\n- E2E test with Stripe CLI: `stripe trigger checkout.session.completed`\n\n## Gotchas\n- Must use raw body (not parsed JSON) for signature verification\n- Next.js App Router: export const runtime = 'nodejs' (not edge)"
      },
      {
        "title": "The DEBUG Protocol",
        "body": "Describe the symptom (what you see vs. what you expect)\nError output (paste full stack trace, not summary)\nBisect (when did it last work? what changed?)\nUnit isolate (can you reproduce in a test?)\nGenerate hypothesis (ask Claude for 3 possible causes, ranked)"
      },
      {
        "title": "Effective Bug Prompts",
        "body": "Bug: Users see stale data after updating their profile.\n\nExpected: After PUT /api/profile, the profile page shows updated data.\nActual: Old data persists until hard refresh (Cmd+Shift+R).\n\nStack:\n- Next.js 15 App Router\n- Server component fetches user data\n- Client component with form calls server action\n- Server action calls db.update()\n\nHypothesis: Next.js is caching the server component fetch. Need to revalidate.\n\nCan you confirm and show me the fix?"
      },
      {
        "title": "When Claude Gets Stuck",
        "body": "Add constraints — \"The fix must not change the API contract\" narrows the search space.\nShare what you've tried — \"I already tried revalidatePath('/profile') and it didn't work because...\"\nAsk for alternatives — \"Give me 3 different approaches to solve this, with tradeoffs.\"\nFresh session — sometimes the context is poisoned. Start clean with just the bug description."
      },
      {
        "title": "The Refactoring Safety Net",
        "body": "Before any refactoring session:\n\nBefore we start refactoring:\n1. Run the test suite and confirm it passes: `pnpm test`\n2. Commit current state: `git add -A && git commit -m \"chore: pre-refactor checkpoint\"`\n3. Create a branch: `git checkout -b refactor/[description]`"
      },
      {
        "title": "Safe Refactoring Prompts",
        "body": "Extract function:\n\nExtract the email validation logic from src/lib/users.ts (lines 34-67) into a separate\nfunction `validateEmail` in src/lib/validation.ts. Update all imports. Run tests after.\n\nRename across codebase:\n\nRename the `getUserData` function to `fetchUserProfile` across the entire codebase.\nThis includes: function definition, all call sites, all imports, all test references.\nRun `pnpm test` and `pnpm lint` after to verify nothing broke.\n\nSplit large file:\n\nsrc/lib/api.ts is 800 lines. Split it into:\n- src/lib/api/users.ts (user-related functions)\n- src/lib/api/projects.ts (project-related functions)\n- src/lib/api/shared.ts (shared types and helpers)\n- src/lib/api/index.ts (re-exports for backward compatibility)\n\nPreserve all existing exports from the index file so no external imports break.\nRun tests after each file move."
      },
      {
        "title": "Multi-File Refactoring Rules",
        "body": "One type of change at a time — don't rename AND restructure AND optimize simultaneously.\nRun tests after each step — catch breaks early, not after 20 files changed.\nPreserve exports — use index.ts re-exports so consumers don't break.\nCommit incrementally — one commit per logical change, not one giant commit."
      },
      {
        "title": "The TDD Loop",
        "body": "Step 1: \"Write a failing test for: creating a user with valid email stores them in the database\"\nStep 2: [verify test fails for the right reason]\nStep 3: \"Now write the minimum code to make this test pass\"\nStep 4: [verify test passes]\nStep 5: \"Refactor the implementation — the test must still pass\""
      },
      {
        "title": "Why TDD Works Especially Well With Claude",
        "body": "Tests are acceptance criteria — Claude knows exactly what \"done\" means.\nImmediate verification — no ambiguity about whether the code works.\nPrevents gold-plating — \"minimum code to pass\" stops Claude from over-engineering.\nRegression safety — future changes can't silently break working features."
      },
      {
        "title": "Test-First Prompts",
        "body": "Write tests for a `calculateShipping` function that:\n- Free shipping for orders over $100\n- $5.99 flat rate for orders $50-$100\n- $9.99 flat rate for orders under $50\n- International orders: add $15 surcharge\n- Express: 2x the base rate\n- Edge cases: $0 order, negative amount (throw), exactly $50, exactly $100\n\nUse vitest. Don't implement the function yet — just the tests.\n\nThen: \"Now implement calculateShipping to pass all tests.\""
      },
      {
        "title": "Pre-Work Checklist",
        "body": "git status          # Clean working tree?\ngit pull            # Up to date?\ngit checkout -b feat/[description]   # New branch"
      },
      {
        "title": "Commit Strategy",
        "body": "ScopeCommit PatternSingle function addedfeat: add calculateShipping functionBug fixedfix: handle null user in profile fetchTests addedtest: add shipping calculation edge casesRefactor (no behavior change)refactor: extract validation into shared moduleMultiple related changesCommit each logical unit separatelyLarge featureMultiple commits on feature branch, squash on merge"
      },
      {
        "title": "Claude Code Git Prompts",
        "body": "# After completing work:\n\"Commit the changes with an appropriate conventional commit message. \nGroup related files into logical commits if there are multiple concerns.\"\n\n# For PR creation:\n\"Create a PR description for these changes. Include:\n- What changed and why\n- How to test it\n- Any migration steps needed\n- Screenshots if UI changed\""
      },
      {
        "title": "Review Prompt Template",
        "body": "Review this code for:\n1. Correctness — does it do what it claims?\n2. Security — any injection, auth bypass, data leak risks?\n3. Performance — N+1 queries, unnecessary re-renders, missing indexes?\n4. Maintainability — clear naming, reasonable complexity, documented edge cases?\n5. Testing — are the tests sufficient? Any missing cases?\n\nBe specific. For each issue, cite the file:line and suggest a fix.\nSkip style nits unless they affect readability."
      },
      {
        "title": "Self-Review Before PR",
        "body": "I'm about to open a PR. Review all changed files (`git diff main`) for:\n- Any hardcoded secrets or credentials\n- TODO/FIXME/HACK comments that should be resolved\n- Console.logs that should be removed\n- Missing error handling\n- Type assertions (as any) that should be proper types\n- Missing tests for new public functions"
      },
      {
        "title": "10. Production Shipping Checklist",
        "body": "Before deploying any Claude-generated code:"
      },
      {
        "title": "P0 — Must Do",
        "body": "All tests pass (pnpm test && pnpm test:e2e)\n Linting clean (pnpm lint)\n Type checking clean (tsc --noEmit)\n No hardcoded secrets in code (grep for API keys, tokens, passwords)\n Error handling exists for all external calls (DB, API, file I/O)\n Input validation on all user-facing endpoints\n Database migrations reviewed (no data loss, backward compatible)"
      },
      {
        "title": "P1 — Should Do",
        "body": "Performance: no N+1 queries, no unbounded lists, pagination exists\n Logging: structured logs at appropriate levels (not console.log)\n Auth: all new endpoints have proper authorization checks\n Rate limiting on public endpoints\n Rollback plan documented (how to revert if broken)"
      },
      {
        "title": "P2 — Nice to Have",
        "body": "Load test with expected traffic\n Monitoring alerts for new endpoints\n Documentation updated (API docs, README, CHANGELOG)\n Accessibility checked (if UI changes)"
      },
      {
        "title": "11. Anti-Patterns — What Kills Productivity",
        "body": "Anti-PatternWhy It's BadFix\"Build me a full app\" in one promptContext explosion, mediocre everythingBreak into 5-10 focused tasksAccepting code without reading itBugs compound, technical debt growsReview every diff. Question anything unclear.Re-prompting the same thing hoping for different resultsWastes tokens and contextChange your prompt. Add constraints. Try a different approach.Ignoring test failures\"It mostly works\" → production incidentsFix tests immediately. Green before moving on.Never using /compactContext degrades, Claude gets confusedCompact every 30-45 minutes of active workPasting entire codebasesContext full of noiseReference files by path. Let Claude read what it needs.Using Claude for tasks you should think throughOutsourcing architecture decisions to AIDiscuss with Claude, but YOU decide.Not committing between tasksCan't revert, can't bisectCommit after every working statePrompting in vague language\"Make it better\" → random changesSpecific inputs, specific outputs, specific constraintsFighting Claude's suggestionsIf Claude keeps suggesting something different, maybe it's rightConsider the suggestion. Explain why your way is better if you disagree."
      },
      {
        "title": "Slash Commands Reference",
        "body": "CommandWhen to Use/newNew task, fresh context/compactContext getting heavy, mid-task/clearNuclear option — wipe everything/costCheck token spend this session/modelSwitch models (Sonnet for speed, Opus for complexity)/vimEnter vim mode for file editing"
      },
      {
        "title": "Model Selection Strategy",
        "body": "Task TypeBest ModelWhySimple bug fixSonnetFast, cheap, sufficientNew feature implementationSonnetGood balance of speed + qualityComplex architectureOpusDeeper reasoning, better tradeoff analysisCode reviewOpusCatches subtle issuesRefactoringSonnetMechanical changes, speed mattersDebugging race conditionsOpusNeeds to reason about state"
      },
      {
        "title": "Keyboard Shortcuts",
        "body": "Esc → interrupt Claude (stop generation if going wrong direction)\nUp arrow → edit last prompt (fix typo without re-typing)\nTab → accept file edit suggestion"
      },
      {
        "title": "Session Stacking",
        "body": "For maximum throughput on a large feature:\n\nTerminal 1: main implementation (Claude Code)\nTerminal 2: tests for what Terminal 1 builds (Claude Code with /new)\nTerminal 3: manual testing / running the app"
      },
      {
        "title": "New Feature Workflow",
        "body": "1. \"Create branch feat/[name]\"\n2. \"Write failing tests for [feature spec]\"\n3. \"Implement minimum code to pass tests\"\n4. \"Refactor — tests must stay green\"\n5. \"Run full test suite + lint + typecheck\"\n6. \"Commit with conventional commit message\"\n7. \"Self-review: check diff for security, performance, missing edge cases\"\n8. \"Create PR with description\""
      },
      {
        "title": "Bug Fix Workflow",
        "body": "1. \"Create branch fix/[description]\"\n2. \"Write a test that reproduces this bug: [paste error]\"\n3. \"Fix the bug — test must pass\"\n4. \"Run full test suite to check for regressions\"\n5. \"Commit: fix: [description of what was wrong]\""
      },
      {
        "title": "Refactoring Workflow",
        "body": "1. \"Create branch refactor/[description]\"\n2. \"Run tests — confirm all green\"\n3. \"Commit pre-refactor state\"\n4. \"[Specific refactoring instruction]\"\n5. \"Run tests — must still be green\"\n6. \"Commit this step\"\n7. [Repeat 4-6 for each refactoring step]"
      },
      {
        "title": "Spike / Research Workflow",
        "body": "1. \"Use Task tool to research [topic]. Return: key findings, API surface, gotchas, recommended approach.\"\n2. [Read Task output]\n3. \"Based on the research, build a minimal proof of concept in /tmp/spike-[name]/\"\n4. [Evaluate POC]\n5. \"Spike looks good. Now implement properly in the main codebase.\""
      },
      {
        "title": "14. Measuring Your Productivity",
        "body": "Track these weekly:\n\nMetricTargetHow to MeasureFeatures shipped3-5/weekGit commits tagged feat:Bugs introduced<1/weekPost-deploy incidentsTest coverage trend↑ or stableCoverage reportsToken cost / featureDecreasing/cost per sessionTime to first working code<30 minStopwatch from task startContext compacts per session1-2Count your /compact usage"
      },
      {
        "title": "Natural Language Commands",
        "body": "Say ThisDoes This\"Set up my project for Claude Code\"Creates CLAUDE.md + .claueignore from your stack\"Review this code\"Runs 5-dimension review on changed files\"Help me debug [error]\"Walks through DEBUG protocol\"Refactor [file/module]\"Safe refactoring with test verification\"Write tests for [function]\"TDD-style test generation\"Ship this feature\"Runs production checklist\"Start a new task\"Clean context + branch setup\"How's my productivity?\"Reviews git log and suggests improvements\"Optimize my CLAUDE.md\"Reviews and improves your project config\"What model should I use for [task]?\"Model selection recommendation\"Help me with my PR\"PR description + self-review\"Estimate this task\"Breaks down into steps with time estimates\n\nBuilt by AfrexAI — AI-native business tools that ship."
      }
    ],
    "body": "Claude Code Production Engineering\n\nThe complete methodology for shipping production code with Claude Code at 10X speed. Not installation scripts — actual patterns, workflows, and techniques that compound your output.\n\nQuick Health Check (run mentally before every session)\nSignal\tHealthy\tFix\nCLAUDE.md exists at project root\t✅\tCreate one (see §1)\n.claueignore configured\t✅\tAdd noise directories\nSession context under 60%\t✅\t/compact or start fresh\nClear task scope before prompting\t✅\tWrite task brief first\nTests exist for target code\t✅\tWrite tests first (§7)\nGit clean before big changes\t✅\tCommit or stash\nSub-agents for parallel work\t✅\tUse /new or Task tool\nVerifying output, not trusting blindly\t✅\tAlways review diffs\n\nScore: /8. Below 6 = slow, buggy sessions. Fix before coding.\n\n1. Project Setup — CLAUDE.md Architecture\n\nCLAUDE.md is your project's brain. Claude reads it at session start. A good one saves thousands of tokens per session.\n\nTemplate\n# Project: [name]\n\n## Tech Stack\n- Language: TypeScript (strict mode)\n- Framework: Next.js 15 App Router\n- Database: PostgreSQL via Drizzle ORM\n- Testing: Vitest + Playwright\n- Styling: Tailwind CSS v4\n\n## Architecture Rules\n- Max 50 lines per function, 300 lines per file\n- One responsibility per file\n- All exports typed — no `any`\n- Errors as values (Result type), not thrown exceptions\n- Database: migrations via `drizzle-kit generate` then `drizzle-kit push`\n\n## File Structure\nsrc/\n  app/         → Next.js routes (thin — call services)\n  lib/         → Business logic (pure functions)\n  db/          → Schema, migrations, queries\n  components/  → UI (server components default, 'use client' only when needed)\n  types/       → Shared type definitions\n\n## Commands\n- `pnpm dev` — start dev server\n- `pnpm test` — run vitest\n- `pnpm test:e2e` — run playwright\n- `pnpm lint` — eslint + tsc --noEmit\n- `pnpm db:generate` — generate migration\n- `pnpm db:push` — apply migration\n\n## Conventions\n- Imports: absolute from `@/` (mapped to `src/`)\n- Naming: camelCase functions, PascalCase components/types, SCREAMING_SNAKE constants\n- Commits: conventional commits (feat:, fix:, refactor:, test:, docs:)\n- PRs: always create branch, never commit to main directly\n\nCLAUDE.md Rules\nBe specific — \"TypeScript strict\" not \"use types.\" Stack versions, not just names.\nInclude commands — Claude needs to know how to run things. Exact commands, not descriptions.\nArchitecture decisions — document WHY, not just what. \"Errors as values because we use Result type\" tells Claude the pattern.\nKeep it under 200 lines — CLAUDE.md is read every session. Bloat wastes tokens.\nUpdate when patterns change — stale CLAUDE.md causes Claude to fight your codebase.\nNested CLAUDE.md — subdirectories can have their own. Claude merges them. Use for monorepo packages.\n.claueignore\nnode_modules/\n.next/\ndist/\ncoverage/\n*.lock\n.git/\n*.min.js\n*.map\npublic/assets/\n\n\nRule: if Claude doesn't need to read it, ignore it. Large lock files and build artifacts waste context.\n\n2. Prompting Patterns — The 5 That Matter\nPattern 1: Task Brief (use for any non-trivial work)\nTask: Add user authentication with magic links\nContext: Using Resend for email, no password system exists yet\nConstraints:\n- Server actions only (no API routes)\n- Session via httpOnly cookies\n- Token expires in 15 minutes\nAcceptance: User enters email → receives link → clicks → logged in → cookie set\nStart with: the database schema for sessions and tokens\n\n\nWhy it works: scope + constraints + acceptance criteria + starting point. Claude doesn't wander.\n\nPattern 2: Show, Don't Tell\n\nBad: \"Make the API more robust\" Good: \"Add input validation to POST /api/users — validate email format, name 1-100 chars, reject extra fields. Return 422 with field-level errors matching this shape: { errors: { field: string, message: string }[] }\"\n\nRule: if you can't describe the exact output shape, you don't know what you want yet. Think first.\n\nPattern 3: Incremental Refinement\nStep 1: \"Create the database schema for a todo app with projects and tasks\"\n[review output]\nStep 2: \"Now add the CRUD service layer for tasks — pure functions, no framework imports\"\n[review output]\nStep 3: \"Now the API routes that call those services — input validation with zod\"\n\n\nWhy: Claude produces better code in focused steps than in one massive prompt. Each step builds verified context.\n\nPattern 4: Fix With Evidence\n\nBad: \"It's broken\" Good: \"Running pnpm test gives this error:\n\nTypeError: Cannot read properties of undefined (reading 'id')\n  at getUserById (src/lib/users.ts:23:15)\n\n\nThe function expects a User object but receives undefined when the database query returns no rows. Add a null check and return a Result type.\"\n\nRule: paste the actual error. Claude is excellent at fixing bugs when it can see the stack trace.\n\nPattern 5: Architecture Discussion\nI'm deciding between these approaches for real-time updates:\nA) Server-Sent Events from Next.js API routes\nB) WebSocket via separate service\nC) Polling every 5 seconds\n\nContext: 500 concurrent users, updates every 30 seconds on average, deployed on Vercel.\n\nWhat are the tradeoffs? Recommend one with reasoning.\n\n\nUse this for decisions, not implementation. Get the answer, THEN switch to Task Brief for building.\n\n3. Context Management — The #1 Productivity Lever\nContext Is Milk — It Spoils\nContext %\tAction\n0-30%\tFresh. Do complex work here.\n30-60%\tGood. Continue current task.\n60-80%\tGetting stale. Finish current unit, then compact.\n80%+\tDangerous. /compact immediately or start new session.\nWhen to Start Fresh (/new)\nSwitching to unrelated task\nContext above 70%\nClaude starts repeating itself or making mistakes it didn't make earlier\nAfter shipping a feature (clean slate for next one)\nWhen to Compact (/compact)\nMid-task but context bloating from exploration\nAfter a debugging session (lots of error output consumed context)\nBefore a complex implementation step\nContext-Efficient Habits\nDon't paste entire files — reference by path. Claude can read them.\nDon't re-explain — if it's in CLAUDE.md, don't repeat it in prompts.\nUse specific file paths — \"Look at src/lib/auth.ts line 45\" not \"look at the auth code.\"\nClose tangents — if Claude goes down a rabbit hole, redirect immediately. Don't let bad output consume context.\nOne concern per message — \"Fix the auth bug AND refactor the database layer AND add tests\" = context explosion. Sequential > parallel in a single session.\n4. Sub-Agent Orchestration — Parallel Productivity\nWhen to Use Sub-Agents\nScenario\tPattern\nIndependent features\tSpawn sub-agent per feature\nTests + implementation\tOne agent writes tests, main writes code\nResearch + build\tSub-agent researches API docs, main builds\nRefactor + maintain\tSub-agent refactors module A, main works on B\nCode review\tSub-agent reviews your PR with fresh eyes\nTask Tool Pattern (Claude Code native)\nUse the Task tool to:\n1. Research the Stripe API for subscription billing\n2. Return: webhook event types we need, API calls for create/update/cancel, error codes to handle\n\n\nTask tool spawns a sub-agent with its own context. Results come back summarized. Perfect for research that would bloat your main context.\n\nHandoff Documents\n\nWhen a sub-agent finishes complex work, have it write a HANDOFF.md:\n\n## What Was Done\n- Implemented Stripe webhook handler at src/app/api/webhooks/stripe/route.ts\n- Added 4 event handlers: checkout.session.completed, invoice.paid, invoice.payment_failed, customer.subscription.deleted\n\n## Key Decisions\n- Used Stripe SDK v14 (not raw HTTP) for type safety\n- Webhook signature verification via stripe.webhooks.constructEvent()\n- Idempotency: check processed_events table before handling\n\n## What's Next\n- Wire up subscription status updates to user table\n- Add retry logic for failed database writes\n- E2E test with Stripe CLI: `stripe trigger checkout.session.completed`\n\n## Gotchas\n- Must use raw body (not parsed JSON) for signature verification\n- Next.js App Router: export const runtime = 'nodejs' (not edge)\n\n5. Debugging Workflow — Systematic, Not Random\nThe DEBUG Protocol\n\nDescribe the symptom (what you see vs. what you expect) Error output (paste full stack trace, not summary) Bisect (when did it last work? what changed?) Unit isolate (can you reproduce in a test?) Generate hypothesis (ask Claude for 3 possible causes, ranked)\n\nEffective Bug Prompts\nBug: Users see stale data after updating their profile.\n\nExpected: After PUT /api/profile, the profile page shows updated data.\nActual: Old data persists until hard refresh (Cmd+Shift+R).\n\nStack:\n- Next.js 15 App Router\n- Server component fetches user data\n- Client component with form calls server action\n- Server action calls db.update()\n\nHypothesis: Next.js is caching the server component fetch. Need to revalidate.\n\nCan you confirm and show me the fix?\n\nWhen Claude Gets Stuck\nAdd constraints — \"The fix must not change the API contract\" narrows the search space.\nShare what you've tried — \"I already tried revalidatePath('/profile') and it didn't work because...\"\nAsk for alternatives — \"Give me 3 different approaches to solve this, with tradeoffs.\"\nFresh session — sometimes the context is poisoned. Start clean with just the bug description.\n6. Refactoring Patterns — Safe Large-Scale Changes\nThe Refactoring Safety Net\n\nBefore any refactoring session:\n\nBefore we start refactoring:\n1. Run the test suite and confirm it passes: `pnpm test`\n2. Commit current state: `git add -A && git commit -m \"chore: pre-refactor checkpoint\"`\n3. Create a branch: `git checkout -b refactor/[description]`\n\nSafe Refactoring Prompts\n\nExtract function:\n\nExtract the email validation logic from src/lib/users.ts (lines 34-67) into a separate\nfunction `validateEmail` in src/lib/validation.ts. Update all imports. Run tests after.\n\n\nRename across codebase:\n\nRename the `getUserData` function to `fetchUserProfile` across the entire codebase.\nThis includes: function definition, all call sites, all imports, all test references.\nRun `pnpm test` and `pnpm lint` after to verify nothing broke.\n\n\nSplit large file:\n\nsrc/lib/api.ts is 800 lines. Split it into:\n- src/lib/api/users.ts (user-related functions)\n- src/lib/api/projects.ts (project-related functions)\n- src/lib/api/shared.ts (shared types and helpers)\n- src/lib/api/index.ts (re-exports for backward compatibility)\n\nPreserve all existing exports from the index file so no external imports break.\nRun tests after each file move.\n\nMulti-File Refactoring Rules\nOne type of change at a time — don't rename AND restructure AND optimize simultaneously.\nRun tests after each step — catch breaks early, not after 20 files changed.\nPreserve exports — use index.ts re-exports so consumers don't break.\nCommit incrementally — one commit per logical change, not one giant commit.\n7. Test-Driven Development With Claude Code\nThe TDD Loop\nStep 1: \"Write a failing test for: creating a user with valid email stores them in the database\"\nStep 2: [verify test fails for the right reason]\nStep 3: \"Now write the minimum code to make this test pass\"\nStep 4: [verify test passes]\nStep 5: \"Refactor the implementation — the test must still pass\"\n\nWhy TDD Works Especially Well With Claude\nTests are acceptance criteria — Claude knows exactly what \"done\" means.\nImmediate verification — no ambiguity about whether the code works.\nPrevents gold-plating — \"minimum code to pass\" stops Claude from over-engineering.\nRegression safety — future changes can't silently break working features.\nTest-First Prompts\nWrite tests for a `calculateShipping` function that:\n- Free shipping for orders over $100\n- $5.99 flat rate for orders $50-$100\n- $9.99 flat rate for orders under $50\n- International orders: add $15 surcharge\n- Express: 2x the base rate\n- Edge cases: $0 order, negative amount (throw), exactly $50, exactly $100\n\nUse vitest. Don't implement the function yet — just the tests.\n\n\nThen: \"Now implement calculateShipping to pass all tests.\"\n\n8. Git Workflow With Claude Code\nPre-Work Checklist\ngit status          # Clean working tree?\ngit pull            # Up to date?\ngit checkout -b feat/[description]   # New branch\n\nCommit Strategy\nScope\tCommit Pattern\nSingle function added\tfeat: add calculateShipping function\nBug fixed\tfix: handle null user in profile fetch\nTests added\ttest: add shipping calculation edge cases\nRefactor (no behavior change)\trefactor: extract validation into shared module\nMultiple related changes\tCommit each logical unit separately\nLarge feature\tMultiple commits on feature branch, squash on merge\nClaude Code Git Prompts\n# After completing work:\n\"Commit the changes with an appropriate conventional commit message. \nGroup related files into logical commits if there are multiple concerns.\"\n\n# For PR creation:\n\"Create a PR description for these changes. Include:\n- What changed and why\n- How to test it\n- Any migration steps needed\n- Screenshots if UI changed\"\n\n9. Code Review Mode — Claude as Reviewer\nReview Prompt Template\nReview this code for:\n1. Correctness — does it do what it claims?\n2. Security — any injection, auth bypass, data leak risks?\n3. Performance — N+1 queries, unnecessary re-renders, missing indexes?\n4. Maintainability — clear naming, reasonable complexity, documented edge cases?\n5. Testing — are the tests sufficient? Any missing cases?\n\nBe specific. For each issue, cite the file:line and suggest a fix.\nSkip style nits unless they affect readability.\n\nSelf-Review Before PR\nI'm about to open a PR. Review all changed files (`git diff main`) for:\n- Any hardcoded secrets or credentials\n- TODO/FIXME/HACK comments that should be resolved\n- Console.logs that should be removed\n- Missing error handling\n- Type assertions (as any) that should be proper types\n- Missing tests for new public functions\n\n10. Production Shipping Checklist\n\nBefore deploying any Claude-generated code:\n\nP0 — Must Do\n All tests pass (pnpm test && pnpm test:e2e)\n Linting clean (pnpm lint)\n Type checking clean (tsc --noEmit)\n No hardcoded secrets in code (grep for API keys, tokens, passwords)\n Error handling exists for all external calls (DB, API, file I/O)\n Input validation on all user-facing endpoints\n Database migrations reviewed (no data loss, backward compatible)\nP1 — Should Do\n Performance: no N+1 queries, no unbounded lists, pagination exists\n Logging: structured logs at appropriate levels (not console.log)\n Auth: all new endpoints have proper authorization checks\n Rate limiting on public endpoints\n Rollback plan documented (how to revert if broken)\nP2 — Nice to Have\n Load test with expected traffic\n Monitoring alerts for new endpoints\n Documentation updated (API docs, README, CHANGELOG)\n Accessibility checked (if UI changes)\n11. Anti-Patterns — What Kills Productivity\nAnti-Pattern\tWhy It's Bad\tFix\n\"Build me a full app\" in one prompt\tContext explosion, mediocre everything\tBreak into 5-10 focused tasks\nAccepting code without reading it\tBugs compound, technical debt grows\tReview every diff. Question anything unclear.\nRe-prompting the same thing hoping for different results\tWastes tokens and context\tChange your prompt. Add constraints. Try a different approach.\nIgnoring test failures\t\"It mostly works\" → production incidents\tFix tests immediately. Green before moving on.\nNever using /compact\tContext degrades, Claude gets confused\tCompact every 30-45 minutes of active work\nPasting entire codebases\tContext full of noise\tReference files by path. Let Claude read what it needs.\nUsing Claude for tasks you should think through\tOutsourcing architecture decisions to AI\tDiscuss with Claude, but YOU decide.\nNot committing between tasks\tCan't revert, can't bisect\tCommit after every working state\nPrompting in vague language\t\"Make it better\" → random changes\tSpecific inputs, specific outputs, specific constraints\nFighting Claude's suggestions\tIf Claude keeps suggesting something different, maybe it's right\tConsider the suggestion. Explain why your way is better if you disagree.\n12. Speed Multipliers — Advanced Techniques\nSlash Commands Reference\nCommand\tWhen to Use\n/new\tNew task, fresh context\n/compact\tContext getting heavy, mid-task\n/clear\tNuclear option — wipe everything\n/cost\tCheck token spend this session\n/model\tSwitch models (Sonnet for speed, Opus for complexity)\n/vim\tEnter vim mode for file editing\nModel Selection Strategy\nTask Type\tBest Model\tWhy\nSimple bug fix\tSonnet\tFast, cheap, sufficient\nNew feature implementation\tSonnet\tGood balance of speed + quality\nComplex architecture\tOpus\tDeeper reasoning, better tradeoff analysis\nCode review\tOpus\tCatches subtle issues\nRefactoring\tSonnet\tMechanical changes, speed matters\nDebugging race conditions\tOpus\tNeeds to reason about state\nKeyboard Shortcuts\nEsc → interrupt Claude (stop generation if going wrong direction)\nUp arrow → edit last prompt (fix typo without re-typing)\nTab → accept file edit suggestion\nSession Stacking\n\nFor maximum throughput on a large feature:\n\nTerminal 1: main implementation (Claude Code)\nTerminal 2: tests for what Terminal 1 builds (Claude Code with /new)\nTerminal 3: manual testing / running the app\n13. Workflow Templates\nNew Feature Workflow\n1. \"Create branch feat/[name]\"\n2. \"Write failing tests for [feature spec]\"\n3. \"Implement minimum code to pass tests\"\n4. \"Refactor — tests must stay green\"\n5. \"Run full test suite + lint + typecheck\"\n6. \"Commit with conventional commit message\"\n7. \"Self-review: check diff for security, performance, missing edge cases\"\n8. \"Create PR with description\"\n\nBug Fix Workflow\n1. \"Create branch fix/[description]\"\n2. \"Write a test that reproduces this bug: [paste error]\"\n3. \"Fix the bug — test must pass\"\n4. \"Run full test suite to check for regressions\"\n5. \"Commit: fix: [description of what was wrong]\"\n\nRefactoring Workflow\n1. \"Create branch refactor/[description]\"\n2. \"Run tests — confirm all green\"\n3. \"Commit pre-refactor state\"\n4. \"[Specific refactoring instruction]\"\n5. \"Run tests — must still be green\"\n6. \"Commit this step\"\n7. [Repeat 4-6 for each refactoring step]\n\nSpike / Research Workflow\n1. \"Use Task tool to research [topic]. Return: key findings, API surface, gotchas, recommended approach.\"\n2. [Read Task output]\n3. \"Based on the research, build a minimal proof of concept in /tmp/spike-[name]/\"\n4. [Evaluate POC]\n5. \"Spike looks good. Now implement properly in the main codebase.\"\n\n14. Measuring Your Productivity\n\nTrack these weekly:\n\nMetric\tTarget\tHow to Measure\nFeatures shipped\t3-5/week\tGit commits tagged feat:\nBugs introduced\t<1/week\tPost-deploy incidents\nTest coverage trend\t↑ or stable\tCoverage reports\nToken cost / feature\tDecreasing\t/cost per session\nTime to first working code\t<30 min\tStopwatch from task start\nContext compacts per session\t1-2\tCount your /compact usage\nNatural Language Commands\nSay This\tDoes This\n\"Set up my project for Claude Code\"\tCreates CLAUDE.md + .claueignore from your stack\n\"Review this code\"\tRuns 5-dimension review on changed files\n\"Help me debug [error]\"\tWalks through DEBUG protocol\n\"Refactor [file/module]\"\tSafe refactoring with test verification\n\"Write tests for [function]\"\tTDD-style test generation\n\"Ship this feature\"\tRuns production checklist\n\"Start a new task\"\tClean context + branch setup\n\"How's my productivity?\"\tReviews git log and suggests improvements\n\"Optimize my CLAUDE.md\"\tReviews and improves your project config\n\"What model should I use for [task]?\"\tModel selection recommendation\n\"Help me with my PR\"\tPR description + self-review\n\"Estimate this task\"\tBreaks down into steps with time estimates\n\nBuilt by AfrexAI — AI-native business tools that ship."
  },
  "trust": {
    "sourceLabel": "tencent",
    "provenanceUrl": "https://clawhub.ai/1kalin/afrexai-claude-code-production",
    "publisherUrl": "https://clawhub.ai/1kalin/afrexai-claude-code-production",
    "owner": "1kalin",
    "version": "1.0.0",
    "license": null,
    "verificationStatus": "Indexed source record"
  },
  "links": {
    "detailUrl": "https://openagent3.xyz/skills/afrexai-claude-code-production",
    "downloadUrl": "https://openagent3.xyz/downloads/afrexai-claude-code-production",
    "agentUrl": "https://openagent3.xyz/skills/afrexai-claude-code-production/agent",
    "manifestUrl": "https://openagent3.xyz/skills/afrexai-claude-code-production/agent.json",
    "briefUrl": "https://openagent3.xyz/skills/afrexai-claude-code-production/agent.md"
  }
}