Claude Code Plugin · v2.0.0

Second Brain

10 production-grade Claude Code skills by Amritpal Singh Boparai. Full-stack multi-tenant SaaS development — from git analysis to architecture, frontend, security, testing, DevOps, and beyond.

10 Skills
12 Knowledge Categories
7 Agent Prompts
6 Runtime Hooks
4 Reference Docs
$ claude /install-plugin boparaiamrit/build-second-brain

// Build Second Brain

Turn your git history into an AI that thinks like you.

// Pipeline

Five phases transform raw git history and project artifacts into a structured second brain with Claude memory injection.

Phase 0
Preflight
Validate repos, resolve absolute paths, detect Python, discover artifacts, confirm brain name and memory scope.
Scans: repos, docs/, .planning/, .claude/, .github/, root .md files
Phase 1 + 1A
Harvest
5 parallel agent teammates analyze every commit via git show. Phase 1A mines non-code artifacts in chronological order.
Output: batch-*.md + artifacts-*.md scratchpad files
Phase 1.5
Index
Python indexer splits all scratchpad findings by category tag using fuzzy matching. Pre-computes statistics.
Output: 12 category-raw.md files + statistics-raw.md
Phase 2
Categorize
12 specialist agents in 2 waves of 6. Each reads pre-indexed content and organizes into patterns, principles, and decisions.
Output: 12 organized category files
Phase 3
Synthesize
Brain Builder creates knowledge base. Profile Generator writes your DNA. Memory Injector persists to Claude memory.
Output: second-brain/ directory + 3 memory files

// 12 Knowledge Categories

Every commit and artifact is tagged with one or more categories. Phase 2 agents specialize in exactly one category each.

Code
architecture
System design, module boundaries, layering decisions, dependency management
Code
tech-stack
Language, framework, and tool choices with rationale
Ops
debugging
Diagnostic approaches, root cause analysis, investigation patterns
Ops
scaling
Performance optimization, growth handling, resource management
Ops
security
Auth patterns, validation, encryption, access control
Code
data-modeling
Schema design, migrations, relationships, query patterns
Quality
code-style
Naming conventions, formatting preferences, structural patterns
Quality
refactoring
Cleanup patterns, tech debt management, incremental improvement
Code
integration
API design, service communication, third-party integrations
Ops
error-handling
Retry logic, fallbacks, circuit breakers, resilience patterns
Thinking
product-thinking
Feature scoping, requirements analysis, trade-off decisions, what gets built vs rejected
Thinking
workflow
Planning patterns, communication style, documentation habits, process decisions

// Knowledge Base Output

The final second-brain/ directory contains organized patterns, playbooks, decisions, and raw data.

second-brain/
  profile/
    engineer-profile.md // Your complete builder DNA
  patterns/
    architecture-patterns.md // System design patterns
    scaling-patterns.md // How you handle growth
    debugging-patterns.md // How you diagnose bugs
    security-patterns.md // Auth & validation approach
    data-modeling-patterns.md // Schema & migration patterns
    integration-patterns.md // API & service connections
    error-handling-patterns.md // Retry & resilience
    refactoring-patterns.md // Cleanup patterns
  philosophy/
    product-thinking.md // Feature scoping & trade-offs
    workflow.md // Planning & process patterns
  decisions/
    tech-decisions.md // Every tech choice with reasoning
  conventions/
    code-style.md // Naming & structure conventions
  evolution/
    architecture-evolution.md // How the system evolved
  playbooks/
    debugging-playbook.md // Step-by-step guide
    scaling-playbook.md // Step-by-step guide
  raw/
    commit-log.md // Annotated commit history
    statistics.md // Numbers breakdown

// Holistic Builder Profile

Not just a developer brain — the combined brain of a product thinker, architect, and engineer. One document that captures your complete DNA.

Core Philosophy
Fundamental beliefs about building products, systems, and code
Tech Stack DNA
Go-to technology choices and why you pick them
Architecture Fingerprint
How you structure systems and make design trade-offs
Debugging Style
Your step-by-step diagnostic process
Decision Patterns
When faced with X, you choose Y because Z
Non-Negotiables
Things you ALWAYS or NEVER do
Product Thinking
How you scope features, analyze trade-offs, say no
Workflow & Process
How you plan, communicate, break down work
Evolution
How your thinking changed over time

// Claude Memory Injection

Three memory files injected into Claude Code so every future session already knows how you think.

User Memory
second-brain-profile.md
Core identity — philosophy, tech stack defaults, architecture fingerprint, debugging style
Feedback Memory
second-brain-patterns.md
Patterns to follow — architecture, product thinking, workflow, scaling, error handling
Feedback Memory
second-brain-decisions.md
Decision rules — tech stack defaults, non-negotiables, when-X-choose-Y rules
Hybrid mode also appends a concise brain summary to ~/.claude/CLAUDE.md — loaded in every Claude session globally.

// 6 Runtime Hooks

Event-driven enforcement that keeps the build honest — validates paths, checks output structure, and prevents premature completion.

PreToolUse · Write|Edit
Path Validator
Ensures files go to correct absolute paths under WORK_DIR or OUTPUT_DIR. Validates batch and artifact filename conventions.
PreToolUse · Bash
Relative Path Warner
Warns if bash commands use relative paths (./.second-brain/) instead of absolute paths from config.md.
PostToolUse · Write
Scratchpad Validator
Verifies scratchpad files contain proper ## Commit: or ## Artifact: headers with category tags.
SubagentStop
Completion Checker
Counts batch files, artifact files, and category files. Reports build progress on every agent completion.
Stop
Stop Guard
Blocks session stop if engineer-profile.md is missing or progress.md has unchecked items.
PreCompact
Compact Reminder
Reminds orchestrator to re-read config.md and progress.md after context compression to restore state.

// Features

Built for production-grade reliability at any repo scale.

Every Commit Analyzed
Zero skipped. Merge commits, empty commits, and binary-only commits are logged appropriately.
Multi-Repo Support
Analyze multiple repos together. Cross-repo pattern detection with per-repo attribution.
Artifact Mining
Harvests design specs, planning docs, CLAUDE.md, ADRs, PR templates. Chronological order reveals thinking hierarchy.
Maximum Parallelism
5 teammate agents for harvest + 12 parallel category agents in 2 waves of 6.
Crash-Proof
Scratchpad persistence on disk. Resume from where you left off after any interruption.
Large Diff Handling
Commits with 500+ line diffs fall back to git show --stat with selective inspection. Binary files skipped.
Hybrid Memory
Global identity in ~/.claude/CLAUDE.md + local detailed files in project memory directory.
Data Isolation
All agent prompts treat commit content as untrusted data. Prevents prompt injection via malicious commits.
Python Fallback
Detects python3 or python with bash fallback indexer if Python is unavailable.
Post-Run Verification
verify.py runs 12+ automated checks on the final output — config, coverage, structure, profile quality.
Configurable Batch Size
20 commits per batch (default). Auto-suggests 50 for repos with 5000+ commits.
Progress Monitoring
Cron-based real-time progress tracking. Checkboxes for every item in every phase.

// Token Estimates

Approximate token usage by repo size and phase.

Repo Size Harvest Categorize Synthesize Total
100 commits 200K-500K ~50K ~50K ~300K-600K
500 commits 1M-2.5M ~250K ~100K ~1.5M-3M
1,000 commits 2M-5M ~500K ~200K ~3M-6M
5,000 commits 10M-25M ~2M ~500K ~13M-28M

// SaaS Architect

Enterprise multi-tenant, multi-product backend architect. NestJS + Drizzle ORM + PostgreSQL + TimescaleDB + BullMQ + Redis.

// What It Does

A senior enterprise backend architect skill that reads frontend code, extracts real backend intent (not naive CRUD mirrors), researches libraries before writing code, applies correct design patterns automatically, and enforces tenant hierarchy on every table, every query, every endpoint.

Frontend-to-Backend
Reads React/Vue components and extracts the real API contract — not a 1:1 CRUD mirror.
Library Research First
Compares 3+ options before choosing any new library. Pre-evaluated decisions included.
Auto Pattern Selection
Adapter, Manager, Strategy, Factory — picks the right pattern based on the feature shape.
Tenant-Aware Everything
Company/Workspace/Domain hierarchy enforced on every table, query, and endpoint.
Scale by Default
>1000 rows = BullMQ mandatory. SSE progress, job deduplication, dead letter queues.
Compliance Built In
Audit logging, admin panels, impersonation tracking, subscription enforcement.

// Tenant Hierarchy

The immutable foundation. Every table, every query, every endpoint respects this hierarchy.

Company (billing entity — subscriptions, plan limits, seats)
    Workspace (organizational unit — settings, custom field definitions, user roles)
        Domain (data partition — primary query pivot for all hot-path operations)
            Data (recipients, campaigns, events — scoped per domain)
Denormalization
Every Table = 3 IDs
company_id + workspace_id + domain_id on every data table. Domain migration is rare (~once/year), so redundancy is worth it.
Indexing Rule
Separate Per Level
Never one composite index with all 3. Start with domain_id only. Add workspace/company indexes when proven.
Shared Module
Recipients x 10+ Products
Core recipients table + extension tables per product (email, sms, whatsapp, push...). Extension = "enrolled in this product."
Redis Context
TenantContextGuard
Every request resolves hierarchy from Redis (not DB joins). Attached to request.tenantContext. 1hr TTL.

// 7-Phase Flow

Applied to every feature, from simple CRUD to complex enterprise workflows.

Phase 0
Library Selection
List 3+ candidates, compare maturity/TypeScript/NestJS compat/license. State recommendation with reasoning.
Phase 1
Context Extraction
Write user story with hierarchy context. Flag 14 complexity dimensions (tenant, shared, bulk, async, staging...).
Phase 2
Database Schema
Drizzle tables with all 3 IDs, domain_id index always, TimescaleDB for events, JSONB + GIN for custom fields.
Phase 3
NestJS Module
Controller (HTTP only) → Service (business logic) → Repository (Drizzle, domain_id first). DTOs for validation.
Phase 4
Async & Scale
>1000 rows = BullMQ. SSE progress via Redis. File imports: upload → staging → preview → commit.
Phase 5
Compliance
@Audit decorator on mutations. BaseProcessor for job logs. Admin panel with MFA. Impersonation tracking.
Phase 6
Caching Strategy
Domain context (1hr), custom field defs (1hr), counts (5min), filter results (5min). Invalidation rules per entity.

// Design Patterns

Seven core patterns applied automatically based on feature shape.

TenantContextGuard
Resolves company/workspace/domain from Redis on every request. Checks subscription status.
Adapter Pattern
Multiple external providers (SSO, email, SMS). Common interface, provider-specific implementations.
Manager Pattern
Runtime selection of the right adapter based on configuration or context.
Strategy Pattern
Plan-based limit enforcement. Different behavior per subscription tier.
BaseProcessor
All BullMQ jobs extend BaseProcessor. Automatic job logging on success and failure.
@Audit Decorator
Declarative audit logging on mutations. Admin actions use logSync() for guaranteed writes.
Repository Pattern
Pure Drizzle queries. domain_id always first WHERE. No business logic, no HTTP concerns.

// Master Checklist

Run before shipping any feature. Catches the hidden complexity that multi-tenancy introduces.

Hierarchy & Tenancy
Table has company_id, workspace_id, domain_id
Hot-path queries use domain_id (with index)
tenantContext resolved from Redis, not DB joins
Subscription limits checked before mutations
Shared Module
Touching recipients: core table or extension table?
Extension table has all 3 hierarchy IDs
No N+1: use JOIN or inArray, never loop
Async & Scale
>1000 rows = BullMQ + jobId return
File imports use staging table + preview + commit
SSE progress for long operations
Job deduplication via BullMQ jobId
Compliance
Every MUTATION has @Audit (skip GET/reads)
Processors extend BaseProcessor (auto job_logs)
Admin actions use logSync() (synchronous audit)
Additive limit check: existing + incoming ≤ limit
Custom Fields & Events
JSONB column + GIN index on entity table
Definitions cached per workspace in Redis
Time-series data uses TimescaleDB hypertable
Retention policy + continuous aggregates configured
Design Patterns
Multiple providers = Adapter pattern
Runtime selection = Manager pattern
Plan-based limits = Strategy pattern
New library = 3+ options compared first

// Reference Documents

Four comprehensive reference files loaded on-demand during skill execution.

5.5 KB
library-decisions.md
Pre-evaluated tech choices: job queues, identity, audit, file parsing, email, storage, observability, feature flags.
17 KB
schema-reference.md
Complete Drizzle table definitions for all core entities — companies, workspaces, domains, recipients, extensions, events, audit, SSO, admin.
15 KB
patterns-reference.md
Design pattern implementations: TenantContextGuard, Adapter, Manager, Strategy, BaseProcessor, @Audit decorator, Repository.
13 KB
enterprise-reference.md
Admin module, impersonation service, SSO end-to-end flow, file import flow, domain migration, BullMQ queue configuration.

// Plugin Structure

Complete file layout — two skills, runtime hooks, and documentation.

second-brain/
  .claude-plugin/
    plugin.json // Plugin manifest (v1.2.0)
    marketplace.json // Marketplace listing

  skills/build-second-brain/ // Skill 1
    SKILL.md // Main orchestrator (600+ lines)
    references/
      harvest-agent-prompt.md // Phase 1: commit analysis
      artifact-harvest-prompt.md // Phase 1A: artifact mining
      category-agent-prompt.md // Phase 2: category specialist
      brain-builder-prompt.md // Phase 3: knowledge base
      profile-generator-prompt.md // Phase 3: engineer profile
      memory-injector-prompt.md // Phase 3: memory injection
      progress-template.md // Progress tracking
    scripts/
      indexer.py // Category indexer (fuzzy matching)
      verify.py // Post-run verification (12+ checks)

  skills/saas-architect-skill/ // Skill 2
    SKILL.md // Enterprise SaaS architect (15KB)
    library-decisions.md // Pre-evaluated tech choices
    schema-reference.md // Drizzle table definitions
    patterns-reference.md // Design patterns & guards
    enterprise-reference.md // Admin, SSO, imports
    TEST_SCENARIOS.md // 5 evaluation scenarios
    TEST_RESULTS.md // Test execution results

  hooks/
    hooks.json // 6 runtime enforcement hooks
    scripts/
      validate-write-paths.sh // Path & filename validation
      validate-scratchpad-output.sh // Output structure validation
      validate-agent-completion.sh // Completion progress check

  index.html // This documentation page
  README.md
  LICENSE // MIT

03 Frontend Architect

Next.js 16 + React 19 + TypeScript 5 + Tailwind 4 + Zustand + TanStack Query + TanStack Table

Seven-Phase Flow

PHASE 0
Types & Contracts
Entity types + Zod schemas BEFORE any component
PHASE 1
Mock Data & API
fetchApi() adapter + mock handler + API service
PHASE 2
React Query Hooks
Query key hierarchy + cache invalidation
PHASE 3
Components
UnifiedDataTable, forms, detail panels
PHASE 4
Pages
Thin wrappers: fetch data, render components
PHASE 5
Wizard Patterns
Multi-step flows with centralized state
PHASE 6
Polish & Quality
Loading, empty, error states. Accessibility.

MSSP Frontend Patterns

Progressive complexity — UC1 users see simple UI, UC3 users see full MSSP features.

UC1: Zerodha
No workspace selector. No domain tabs. No Person column. Clean, simple UI. Zero multi-tenant complexity visible.
UC2: Reliance Jio
Domain tabs visible. Person column shows link count. Bulk ops show domain breakdown. Import asks target domain.
UC3: Tata Group
Workspace selector in nav. Company Library. Blueprint deployment. Settings inheritance badges. "All Workspaces" read-only view.

04 MSSP Audit

5-phase, 48-check quality gate covering data model, API, frontend, integration, and deployment

Five Audit Phases

1
Data Model — 10 checks: workspaceId, personId, companyId, indexes, cascades, soft deletes
2
API & Service — 10 checks: workspace scoping, CASL abilities, Person de-dup, Blueprint service
3
Frontend — 12 checks: workspace selector, domain tabs, Person column, pagination, React Query
4
Integration — 8 checks: campaign↔training, portal unification, gamification, risk score feeds
5
Deployment — 8 checks: non-breaking migration, backfill, feature flags, rollback, UC1 unaffected

Planning Gate (10 Mandatory Questions)

No code without answers. If any answer is "I don't know" — stop and research.

Q1 Which customer types affected? (UC1/UC2/UC3)
Q2 Which hierarchy level owns this data?
Q3 Needs Company Library tier?
Q4 Needs Blueprint pattern?
Q5 Touches Person/Recipient? De-dup needed?
Q6 What settings? Which inherit, which workspace-only?
Q7 Who can do what? (Company Admin vs Workspace Admin)
Q8 What does UC1 user see? (must be simple)
Q9 What does audit checklist say? (run BEFORE coding)
Q10 Migration path? (non-breaking? feature flag? backfill?)

05 Real-World Examples

20 situations showing which skill to use, what you say, and what outcome to expect

Building New Features

#1 "Build a phishing report module where employees report suspicious emails"
Audit SaaS Architect Frontend Architect
Outcome

Audit asks 10 planning questions. SaaS designs PhishingReport schema with workspaceId + personId. Frontend builds report form + list view with UnifiedDataTable.

Without Skills

Developer builds a simple form. No workspace scoping. No Person de-dup. No Company Library for report templates. Data leaks across workspaces. UC1 users see unnecessary complexity.

#2 "Add CSV import for vishing campaign phone numbers"
Frontend (wizard) + SaaS (import flow)
Outcome

Frontend wizard reference: 3-step flow with auto-mapper (7-strategy scoring), duplicate detection, chunked processing. SaaS: staging table → preview → commit pipeline with BullMQ.

Without Skills

Developer uploads CSV, parses all at once (UI freezes on 10K rows), no duplicate detection, no preview step, no undo capability. Phone numbers not validated.

#3 "Build company-wide dashboard showing risk scores across all subsidiaries"
Audit (UC3) SaaS (company endpoint) Frontend (MSSP)
Outcome

Audit catches: UC3-only, company-level, Person de-dup needed. SaaS: /companies/:id/dashboard endpoint aggregating across workspaces. Frontend: workspace selector + progressive complexity (hidden for UC1).

Without Skills

Developer builds dashboard that queries across workspaces without permission check. Workspace admin can see other subsidiaries' data. Person not de-duplicated — inflated headcount. UC1 users confused by empty workspace selector.

Auditing Existing Modules

#4 "Is the training module ready for Tata Group?"
Audit (5 phases)
Outcome

48-check audit: schema (personId? companyId?), API (workspace scoped?), frontend (domain tabs?), integration (campaign↔training?), deployment (non-breaking?). Gap report with severity + sprint estimates.

Without Skills

"Looks fine to me" — ship it. Tata Steel admin discovers they can see TCS training data. CISO can't see cross-workspace completion rates. Data leak reported. Trust lost.

#5 "Before releasing v3, check all modules for data leaks"
Audit (6 negative tests)
Outcome

6 negative tests per module: cross-WS data leak, bulk cross-WS, company admin scope, Person de-dup, UC1 complexity, settings inheritance. Concrete PASS/FAIL per test with reproduction steps.

Without Skills

Manual testing misses edge cases. "It works on my machine" with one workspace. First MSSP customer finds the bug in production.

Architecture Decisions

#6 "Should we use BullMQ or Temporal for the new email workflow?"
SaaS (Phase 0 + library-decisions)
Outcome: SaaS skill's Phase 0 library selection fires. Pre-evaluated: BullMQ for everything, Temporal only for multi-step durable sagas. Decision made in 2 minutes, not 2 days of research.
#7 "How should the JIT Coach data model look?"
Audit (planning) SaaS (Phase 2)
Outcome: Audit asks: hierarchy level? (Domain). Company Library? (Yes — company tips). SaaS Phase 2: JitTip + JitTriggerRule + JitTipDelivery tables with all 3 IDs + companyId. MSSP flags catch Blueprint need early.

Frontend Development

#8 "Build the campaign list page with filters, bulk actions, and inline editing"
Frontend (Phase 3 + table-reference)
Outcome: UnifiedDataTable with column persistence, DnD reorder, 3-layer filters, bulk actions with confirmation, editable cells. All from table-reference.md templates. Without: Custom table from scratch. No persistence. No DnD. Rebuilds what already exists.
#9 "The recipients page loads 10,000 records on mount — fix this"
Frontend (migration + Phase 2)
Outcome: Migration skill Phase 3: replace ?limit=10000 with React Query hooks + server-side pagination. Query key hierarchy for cache. Without: Someone adds useMemo and calls it "optimized." Still fetches 10K rows.

Migration & Refactoring

#10 "Migrate the frontend to the correct folder structure"
Frontend (migration-skill)
Outcome: 7-phase migration: src/ → feature modules → API layer → Zustand → route groups → auth → i18n. Each phase independently deployable. App keeps working throughout.
#11 "Add Drizzle ORM for the new reporting module alongside existing Prisma"
SaaS (ORM Migration section)
Outcome: SaaS skill's Prisma→Drizzle section: existing modules keep Prisma, new modules use Drizzle. Translation guide maps Prisma syntax to Drizzle. Patterns (tenant hierarchy, indexes) are ORM-agnostic. Without: Developer rewrites existing Prisma code to Drizzle. Breaks existing queries. Two weeks of regression fixing.
#12 "Add settings inheritance to the announcement module"
SaaS (mssp-patterns) + Frontend (MSSP UI)
Outcome: SaaS: CompanyDefaultAnnouncementSettings + useCompanyDefaults + overriddenFields[] + resolution algorithm. Frontend: COMPANY/WORKSPACE/OVERRIDE badge components per field. Without: Developer adds a "copy settings" button. No field-level override. Company admin changes default → overwrites workspace customizations.

Planning & Prevention

#13 "My boss wants a 'copy campaign to another workspace' feature"
Audit (planning gate)
Outcome

Audit's 10 questions fire: "Does this need Blueprint pattern?" — YES. "Who can do this?" — Company Admin only. "What does UC1 see?" — Nothing (hidden). Produces Planning Output Template. Correctly designs as Blueprint, not copy.

Without Skills

Developer builds a "clone" button that duplicates the campaign record. Workspace admin can copy campaigns INTO other workspaces they don't manage. Scenarios/templates don't exist in target workspace. Broken references everywhere.

#14 "I'm about to ship the portal module — what should I check?"
Audit (all 5 phases + 6 negative tests)
Outcome: Full 90-minute audit. 48 checks + 6 negative tests. Report: "UC1: PASS. UC2: PARTIAL (Person column missing). UC3: FAIL (no settings inheritance, no workspace selector)." Clear gap list with sprint estimates. Without: Ship and pray. First MSSP customer finds 12 issues in week 1.
#15 "New developer joined — show them how we build features"
Audit SaaS Frontend
Outcome: Full walkthrough: Audit planning (10 questions) → SaaS backend (7 phases) → Frontend (7 phases) → Audit verification (48 checks). New developer understands the entire flow on day 1. Without: "Read the codebase and figure it out." Three months of learning by breaking things.