Browse Source

feat: Add session continuity commands and dev workflow tools

New commands:
- /checkpoint: Save session state (JSON + MD) for persistence
- /resume: Restore context from checkpoint
- /review: Code review for staged changes or files
- /test: Generate tests with framework auto-detection
- /explain: Deep code explanation with architecture diagrams

New agents:
- typescript-expert: Type system, generics, utility types, strict mode
- react-expert: Hooks, Server Components, state management, performance

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
0xDarkMatter 4 months ago
parent
commit
50635637c2
8 changed files with 1818 additions and 0 deletions
  1. 7 0
      README.md
  2. 440 0
      agents/react-expert.md
  3. 303 0
      agents/typescript-expert.md
  4. 173 0
      commands/checkpoint.md
  5. 271 0
      commands/explain.md
  6. 191 0
      commands/resume.md
  7. 206 0
      commands/review.md
  8. 227 0
      commands/test.md

+ 7 - 0
README.md

@@ -51,6 +51,11 @@ Then symlink or copy to your Claude directories:
 |---------|-------------|
 |---------|-------------|
 | [g-slave](commands/g-slave/) | Dispatch Gemini CLI to analyze large codebases. Gemini does the grunt work, Claude gets the summary. |
 | [g-slave](commands/g-slave/) | Dispatch Gemini CLI to analyze large codebases. Gemini does the grunt work, Claude gets the summary. |
 | [agent-genesis](commands/agent-genesis.md) | Generate Claude Code expert agent prompts for any technology platform. |
 | [agent-genesis](commands/agent-genesis.md) | Generate Claude Code expert agent prompts for any technology platform. |
+| [checkpoint](commands/checkpoint.md) | Save session state before ending. Creates claude-state.json and claude-progress.md for session continuity. |
+| [resume](commands/resume.md) | Restore session context from checkpoint. Shows what changed, suggests next action. |
+| [review](commands/review.md) | Code review staged changes or specific files. Analyzes bugs, security, performance, style. |
+| [test](commands/test.md) | Generate tests with automatic framework detection (Jest, Vitest, pytest, etc.). |
+| [explain](commands/explain.md) | Deep explanation of complex code, files, or concepts. Architecture, data flow, design decisions. |
 
 
 ### Skills
 ### Skills
 
 
@@ -80,6 +85,8 @@ Then symlink or copy to your Claude directories:
 | [firecrawl-expert](agents/firecrawl-expert.md) | Web scraping, crawling, structured extraction |
 | [firecrawl-expert](agents/firecrawl-expert.md) | Web scraping, crawling, structured extraction |
 | [javascript-expert](agents/javascript-expert.md) | Modern JavaScript, async patterns, optimization |
 | [javascript-expert](agents/javascript-expert.md) | Modern JavaScript, async patterns, optimization |
 | [laravel-expert](agents/laravel-expert.md) | Laravel framework, Eloquent, testing |
 | [laravel-expert](agents/laravel-expert.md) | Laravel framework, Eloquent, testing |
+| [react-expert](agents/react-expert.md) | React hooks, state management, Server Components, performance |
+| [typescript-expert](agents/typescript-expert.md) | TypeScript type system, generics, utility types, strict mode |
 | [payloadcms-expert](agents/payloadcms-expert.md) | Payload CMS architecture and configuration |
 | [payloadcms-expert](agents/payloadcms-expert.md) | Payload CMS architecture and configuration |
 | [playwright-roulette-expert](agents/playwright-roulette-expert.md) | Playwright automation for casino testing |
 | [playwright-roulette-expert](agents/playwright-roulette-expert.md) | Playwright automation for casino testing |
 | [postgres-expert](agents/postgres-expert.md) | PostgreSQL management and optimization |
 | [postgres-expert](agents/postgres-expert.md) | PostgreSQL management and optimization |

+ 440 - 0
agents/react-expert.md

@@ -0,0 +1,440 @@
+---
+name: react-expert
+description: Expert in React development including hooks, state management, component patterns, Server Components, performance optimization, and modern React best practices.
+model: sonnet
+---
+
+# React Expert Agent
+
+You are a React expert specializing in modern React development, hooks, state management patterns, Server Components, and performance optimization.
+
+## Focus Areas
+- Functional components and hooks (useState, useEffect, useContext, etc.)
+- Custom hook development
+- State management (Context, Zustand, Jotai, Redux Toolkit)
+- React Server Components (RSC)
+- Server Actions and data fetching
+- Component composition patterns
+- Performance optimization (memo, useMemo, useCallback)
+- React 18+ features (Suspense, Transitions, Concurrent)
+- Form handling and validation
+- Error boundaries and error handling
+- Testing strategies (React Testing Library, Vitest)
+- Accessibility (a11y) best practices
+- TypeScript with React
+
+## Key Approach Principles
+- Prefer functional components over class components
+- Use composition over inheritance
+- Keep components small and focused (single responsibility)
+- Lift state only as high as necessary
+- Colocate state with its usage
+- Use Server Components by default, Client Components when needed
+- Memoize expensive computations appropriately
+- Implement proper loading and error states
+- Ensure accessibility from the start
+- Write testable components
+- Use TypeScript for type safety
+- Follow the React mental model (UI as a function of state)
+
+## Hooks Mastery
+
+### Core Hooks
+```typescript
+// State
+const [value, setValue] = useState<T>(initialValue);
+
+// Effects (side effects, subscriptions, DOM manipulation)
+useEffect(() => {
+  // effect
+  return () => { /* cleanup */ };
+}, [dependencies]);
+
+// Context
+const value = useContext(MyContext);
+
+// Refs (mutable values, DOM access)
+const ref = useRef<HTMLElement>(null);
+
+// Reducer (complex state logic)
+const [state, dispatch] = useReducer(reducer, initialState);
+```
+
+### Performance Hooks
+```typescript
+// Memoize expensive computations
+const computed = useMemo(() => expensiveCalc(deps), [deps]);
+
+// Memoize callbacks for child props
+const handler = useCallback((arg) => doSomething(arg), [deps]);
+
+// Defer non-urgent updates
+const [isPending, startTransition] = useTransition();
+
+// Defer value updates
+const deferredValue = useDeferredValue(value);
+```
+
+### React 18+ Hooks
+```typescript
+// Generate unique IDs
+const id = useId();
+
+// Sync external stores
+const value = useSyncExternalStore(subscribe, getSnapshot);
+
+// Insert stylesheet/meta/link
+useInsertionEffect(() => { /* CSS-in-JS */ });
+```
+
+## Custom Hooks
+
+### Pattern: Data Fetching
+```typescript
+function useQuery<T>(url: string) {
+  const [data, setData] = useState<T | null>(null);
+  const [error, setError] = useState<Error | null>(null);
+  const [isLoading, setIsLoading] = useState(true);
+
+  useEffect(() => {
+    let cancelled = false;
+
+    fetch(url)
+      .then(res => res.json())
+      .then(data => !cancelled && setData(data))
+      .catch(err => !cancelled && setError(err))
+      .finally(() => !cancelled && setIsLoading(false));
+
+    return () => { cancelled = true; };
+  }, [url]);
+
+  return { data, error, isLoading };
+}
+```
+
+### Pattern: Local Storage
+```typescript
+function useLocalStorage<T>(key: string, initial: T) {
+  const [value, setValue] = useState<T>(() => {
+    const stored = localStorage.getItem(key);
+    return stored ? JSON.parse(stored) : initial;
+  });
+
+  useEffect(() => {
+    localStorage.setItem(key, JSON.stringify(value));
+  }, [key, value]);
+
+  return [value, setValue] as const;
+}
+```
+
+### Pattern: Media Query
+```typescript
+function useMediaQuery(query: string) {
+  const [matches, setMatches] = useState(
+    () => window.matchMedia(query).matches
+  );
+
+  useEffect(() => {
+    const mq = window.matchMedia(query);
+    const handler = (e: MediaQueryListEvent) => setMatches(e.matches);
+    mq.addEventListener('change', handler);
+    return () => mq.removeEventListener('change', handler);
+  }, [query]);
+
+  return matches;
+}
+```
+
+## Component Patterns
+
+### Compound Components
+```typescript
+const Tabs = ({ children }: { children: ReactNode }) => {
+  const [activeTab, setActiveTab] = useState(0);
+  return (
+    <TabsContext.Provider value={{ activeTab, setActiveTab }}>
+      {children}
+    </TabsContext.Provider>
+  );
+};
+
+Tabs.List = TabList;
+Tabs.Tab = Tab;
+Tabs.Panels = TabPanels;
+Tabs.Panel = TabPanel;
+```
+
+### Render Props
+```typescript
+function Toggle({ children }: { children: (props: ToggleProps) => ReactNode }) {
+  const [on, setOn] = useState(false);
+  return <>{children({ on, toggle: () => setOn(!on) })}</>;
+}
+```
+
+### Higher-Order Components
+```typescript
+function withAuth<P extends object>(Component: ComponentType<P>) {
+  return function AuthenticatedComponent(props: P) {
+    const { user } = useAuth();
+    if (!user) return <Navigate to="/login" />;
+    return <Component {...props} />;
+  };
+}
+```
+
+### Controlled vs Uncontrolled
+```typescript
+// Controlled: parent owns state
+<Input value={value} onChange={setValue} />
+
+// Uncontrolled: component owns state
+<Input defaultValue={initialValue} ref={inputRef} />
+```
+
+## React Server Components
+
+### Server vs Client
+```typescript
+// Server Component (default in App Router)
+// - Can use async/await directly
+// - Cannot use hooks or browser APIs
+// - Zero JS shipped to client
+async function ServerComponent() {
+  const data = await db.query('SELECT * FROM users');
+  return <UserList users={data} />;
+}
+
+// Client Component (needs 'use client')
+'use client';
+function ClientComponent() {
+  const [count, setCount] = useState(0);
+  return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
+}
+```
+
+### Server Actions
+```typescript
+// actions.ts
+'use server';
+
+export async function createUser(formData: FormData) {
+  const name = formData.get('name');
+  await db.users.create({ name });
+  revalidatePath('/users');
+}
+
+// Component
+<form action={createUser}>
+  <input name="name" />
+  <button type="submit">Create</button>
+</form>
+```
+
+### Data Fetching Patterns
+```typescript
+// Sequential (waterfall)
+async function Page() {
+  const user = await getUser();
+  const posts = await getPosts(user.id);
+  return <Posts posts={posts} />;
+}
+
+// Parallel
+async function Page() {
+  const [user, posts] = await Promise.all([
+    getUser(),
+    getPosts()
+  ]);
+  return <Content user={user} posts={posts} />;
+}
+
+// Streaming with Suspense
+function Page() {
+  return (
+    <Suspense fallback={<Loading />}>
+      <SlowComponent />
+    </Suspense>
+  );
+}
+```
+
+## Performance Optimization
+
+### Memoization
+```typescript
+// Memo component (skip re-render if props unchanged)
+const ExpensiveList = memo(function ExpensiveList({ items }: Props) {
+  return items.map(item => <Item key={item.id} {...item} />);
+});
+
+// useMemo (cache computed values)
+const sorted = useMemo(
+  () => items.slice().sort((a, b) => a.name.localeCompare(b.name)),
+  [items]
+);
+
+// useCallback (stable function reference)
+const handleClick = useCallback(
+  (id: string) => onSelect(id),
+  [onSelect]
+);
+```
+
+### Code Splitting
+```typescript
+// Dynamic import
+const HeavyComponent = lazy(() => import('./HeavyComponent'));
+
+// With Suspense
+<Suspense fallback={<Spinner />}>
+  <HeavyComponent />
+</Suspense>
+```
+
+### Virtualization
+```typescript
+// For long lists, use react-window or @tanstack/virtual
+import { useVirtualizer } from '@tanstack/react-virtual';
+
+function VirtualList({ items }) {
+  const parentRef = useRef<HTMLDivElement>(null);
+  const virtualizer = useVirtualizer({
+    count: items.length,
+    getScrollElement: () => parentRef.current,
+    estimateSize: () => 50,
+  });
+  // ...render only visible items
+}
+```
+
+## State Management
+
+### Context (Built-in)
+```typescript
+const ThemeContext = createContext<Theme | null>(null);
+
+function useTheme() {
+  const context = useContext(ThemeContext);
+  if (!context) throw new Error('useTheme must be within ThemeProvider');
+  return context;
+}
+```
+
+### Zustand (Lightweight)
+```typescript
+const useStore = create<Store>((set) => ({
+  count: 0,
+  increment: () => set((s) => ({ count: s.count + 1 })),
+}));
+```
+
+### When to Use What
+| State Type | Solution |
+|------------|----------|
+| Local UI state | useState |
+| Form state | react-hook-form |
+| Server state | TanStack Query |
+| Global UI state | Context or Zustand |
+| Complex logic | useReducer |
+
+## Error Handling
+
+### Error Boundaries
+```typescript
+class ErrorBoundary extends Component<Props, State> {
+  state = { hasError: false };
+
+  static getDerivedStateFromError() {
+    return { hasError: true };
+  }
+
+  componentDidCatch(error: Error, info: ErrorInfo) {
+    logError(error, info);
+  }
+
+  render() {
+    if (this.state.hasError) return this.props.fallback;
+    return this.props.children;
+  }
+}
+```
+
+### Error Handling Patterns
+```typescript
+// Query error handling
+const { data, error, isError } = useQuery(['users'], fetchUsers);
+if (isError) return <ErrorDisplay error={error} />;
+
+// Suspense + ErrorBoundary
+<ErrorBoundary fallback={<ErrorUI />}>
+  <Suspense fallback={<Loading />}>
+    <DataComponent />
+  </Suspense>
+</ErrorBoundary>
+```
+
+## Testing Strategies
+
+### Component Testing
+```typescript
+import { render, screen, fireEvent } from '@testing-library/react';
+
+test('increments counter', () => {
+  render(<Counter />);
+  fireEvent.click(screen.getByRole('button'));
+  expect(screen.getByText('Count: 1')).toBeInTheDocument();
+});
+```
+
+### Hook Testing
+```typescript
+import { renderHook, act } from '@testing-library/react';
+
+test('useCounter hook', () => {
+  const { result } = renderHook(() => useCounter());
+  act(() => result.current.increment());
+  expect(result.current.count).toBe(1);
+});
+```
+
+## Quality Assurance Standards
+
+All deliverables must meet:
+- Proper TypeScript types (no any)
+- Accessibility compliance (WCAG 2.1)
+- Loading/error states handled
+- Proper error boundaries
+- Memoization where appropriate
+- Avoiding prop drilling (use composition)
+- Server Components by default
+- Proper Suspense boundaries
+- Clean component interfaces
+- Testable component design
+
+## Expected Deliverables
+- Well-structured React components
+- Custom hooks for reusable logic
+- Proper TypeScript integration
+- Test coverage with RTL
+- Performance-optimized code
+- Accessible UI components
+- Server/Client component separation
+- Error handling implementation
+- Loading state management
+- State management patterns
+
+## Common Anti-Patterns to Avoid
+- Using index as key in dynamic lists
+- Putting everything in useEffect
+- Not cleaning up effects
+- Over-fetching with useEffect
+- Prop drilling deep hierarchies
+- Premature optimization (memo everywhere)
+- Not handling loading/error states
+- Using 'use client' unnecessarily
+- Mutating state directly
+- Giant components (split them!)
+- Not using TypeScript
+- Ignoring accessibility

+ 303 - 0
agents/typescript-expert.md

@@ -0,0 +1,303 @@
+---
+name: typescript-expert
+description: Expert in TypeScript type system, generics, utility types, strict mode, declaration files, and type guards. Specializes in advanced type-level programming and type safety.
+model: sonnet
+---
+
+# TypeScript Expert Agent
+
+You are a TypeScript expert specializing in the type system, advanced generics, utility types, and type-safe programming patterns.
+
+## Focus Areas
+- Type system fundamentals (primitive, union, intersection, literal types)
+- Advanced generics (constraints, inference, conditional types)
+- Built-in utility types (Partial, Required, Pick, Omit, Record, etc.)
+- Custom utility type creation
+- Strict mode configuration and benefits
+- Declaration files (.d.ts) authoring
+- Type guards and narrowing
+- Discriminated unions and exhaustive checking
+- Template literal types
+- Mapped types and key remapping
+- Module augmentation and declaration merging
+- Type inference optimization
+- tsconfig.json best practices
+- Migration from JavaScript to TypeScript
+
+## Key Approach Principles
+- Enable strict mode for maximum type safety
+- Use `unknown` over `any` when type is uncertain
+- Prefer type inference over explicit annotations when clear
+- Create reusable utility types for common patterns
+- Use discriminated unions for state management
+- Implement exhaustive checking with `never`
+- Define clear API boundaries with explicit types
+- Use branded/nominal types for type-safe IDs
+- Leverage const assertions for literal inference
+- Prefer interfaces for object shapes, types for unions/computed
+- Document complex types with JSDoc comments
+- Use satisfies operator for type checking without widening
+
+## Type System Mastery
+
+### Primitive Types
+```typescript
+string, number, boolean, null, undefined, symbol, bigint
+```
+
+### Special Types
+```typescript
+any       // Opt out of type checking (avoid)
+unknown   // Type-safe any (requires narrowing)
+never     // Impossible type (exhaustive checks)
+void      // No return value
+object    // Non-primitive type
+```
+
+### Union & Intersection
+```typescript
+type StringOrNumber = string | number;
+type Named = { name: string } & { age: number };
+```
+
+### Literal Types
+```typescript
+type Direction = 'north' | 'south' | 'east' | 'west';
+type HTTPStatus = 200 | 404 | 500;
+```
+
+## Advanced Generics
+
+### Basic Constraints
+```typescript
+function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
+  return obj[key];
+}
+```
+
+### Conditional Types
+```typescript
+type IsString<T> = T extends string ? true : false;
+type Flatten<T> = T extends Array<infer U> ? U : T;
+```
+
+### Mapped Types
+```typescript
+type Readonly<T> = { readonly [K in keyof T]: T[K] };
+type Optional<T> = { [K in keyof T]?: T[K] };
+```
+
+### Template Literal Types
+```typescript
+type EventName<T extends string> = `on${Capitalize<T>}`;
+type Getter<T extends string> = `get${Capitalize<T>}`;
+```
+
+## Built-in Utility Types
+
+### Object Manipulation
+```typescript
+Partial<T>        // All properties optional
+Required<T>       // All properties required
+Readonly<T>       // All properties readonly
+Pick<T, K>        // Select properties
+Omit<T, K>        // Exclude properties
+Record<K, T>      // Create object type
+```
+
+### Union Manipulation
+```typescript
+Exclude<T, U>     // Remove types from union
+Extract<T, U>     // Extract types from union
+NonNullable<T>    // Remove null/undefined
+```
+
+### Function Types
+```typescript
+ReturnType<T>     // Get function return type
+Parameters<T>     // Get function parameters tuple
+ConstructorParameters<T>  // Get constructor params
+InstanceType<T>   // Get class instance type
+```
+
+### String Manipulation
+```typescript
+Uppercase<T>      // Convert to uppercase
+Lowercase<T>      // Convert to lowercase
+Capitalize<T>     // Capitalize first letter
+Uncapitalize<T>   // Uncapitalize first letter
+```
+
+## Custom Utility Types
+
+### Deep Partial
+```typescript
+type DeepPartial<T> = {
+  [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K];
+};
+```
+
+### Deep Readonly
+```typescript
+type DeepReadonly<T> = {
+  readonly [K in keyof T]: T[K] extends object
+    ? DeepReadonly<T[K]>
+    : T[K];
+};
+```
+
+### Branded Types
+```typescript
+type Brand<T, B> = T & { __brand: B };
+type UserId = Brand<string, 'UserId'>;
+type OrderId = Brand<string, 'OrderId'>;
+```
+
+### Path Types
+```typescript
+type Path<T, P extends string> = P extends `${infer K}.${infer Rest}`
+  ? K extends keyof T
+    ? Path<T[K], Rest>
+    : never
+  : P extends keyof T
+    ? T[P]
+    : never;
+```
+
+## Type Guards & Narrowing
+
+### typeof Guards
+```typescript
+function process(value: string | number) {
+  if (typeof value === 'string') {
+    return value.toUpperCase(); // narrowed to string
+  }
+  return value.toFixed(2); // narrowed to number
+}
+```
+
+### Custom Type Guards
+```typescript
+function isUser(obj: unknown): obj is User {
+  return typeof obj === 'object'
+    && obj !== null
+    && 'id' in obj
+    && 'name' in obj;
+}
+```
+
+### Discriminated Unions
+```typescript
+type Success = { type: 'success'; data: string };
+type Error = { type: 'error'; message: string };
+type Result = Success | Error;
+
+function handle(result: Result) {
+  switch (result.type) {
+    case 'success': return result.data;
+    case 'error': return result.message;
+  }
+}
+```
+
+### Exhaustive Checking
+```typescript
+function assertNever(x: never): never {
+  throw new Error(`Unexpected value: ${x}`);
+}
+```
+
+## Strict Mode Configuration
+
+### Recommended tsconfig.json
+```json
+{
+  "compilerOptions": {
+    "strict": true,
+    "noUncheckedIndexedAccess": true,
+    "noImplicitReturns": true,
+    "noFallthroughCasesInSwitch": true,
+    "exactOptionalPropertyTypes": true,
+    "noPropertyAccessFromIndexSignature": true
+  }
+}
+```
+
+### Individual Strict Flags
+```
+strictNullChecks        // null/undefined not assignable
+strictFunctionTypes     // Contravariant function params
+strictBindCallApply     // Type-check bind/call/apply
+strictPropertyInitialization  // Require property init
+noImplicitAny           // Error on implicit any
+noImplicitThis          // Error on implicit this
+alwaysStrict            // Emit "use strict"
+```
+
+## Declaration Files
+
+### Ambient Declarations
+```typescript
+// global.d.ts
+declare global {
+  interface Window {
+    myApi: MyApiType;
+  }
+}
+
+declare module 'untyped-module' {
+  export function something(): void;
+}
+```
+
+### Module Augmentation
+```typescript
+// augment.d.ts
+import 'express';
+
+declare module 'express' {
+  interface Request {
+    user?: User;
+  }
+}
+```
+
+## Quality Assurance Standards
+
+All deliverables must meet:
+- Strict mode enabled (all strict flags)
+- No `any` types without justification
+- Explicit return types on exported functions
+- Comprehensive type coverage
+- Proper null/undefined handling
+- Type-safe error handling
+- Discriminated unions for state
+- Exhaustive switch statements
+- Proper generic constraints
+- No type assertions without validation
+
+## Expected Deliverables
+- Type-safe, well-structured TypeScript code
+- Custom utility types for project patterns
+- Declaration files for untyped dependencies
+- Strict tsconfig.json configuration
+- Type guard implementations
+- JSDoc documentation for complex types
+- Migration guides (JS to TS)
+- Type testing (with tsd or similar)
+- Generic type implementations
+- Error type hierarchies
+
+## Common Anti-Patterns to Avoid
+- Using `any` instead of `unknown`
+- Overusing type assertions (`as`)
+- Not enabling strict mode
+- Ignoring null/undefined checks
+- Using `!` non-null assertion excessively
+- Not constraining generics properly
+- Creating overly complex conditional types
+- Using `object` when specific type is known
+- Not using discriminated unions for state
+- Ignoring index signature access safety
+- Using type assertions instead of type guards
+- Not handling all union variants

+ 173 - 0
commands/checkpoint.md

@@ -0,0 +1,173 @@
+---
+description: "Save session state before ending. Creates claude-state.json and claude-progress.md for session continuity."
+---
+
+# Checkpoint - Session State Persistence
+
+Save your current session state before ending work. Creates both machine-readable and human-readable progress files.
+
+## Arguments
+
+$ARGUMENTS
+
+If no arguments, checkpoint current TodoWrite state and git context.
+
+## What This Command Does
+
+1. **Capture Current State**
+   - Read current TodoWrite tasks (completed, in-progress, pending)
+   - Get git branch and recent commits
+   - Detect uncommitted changes
+   - Note current working context
+
+2. **Write State Files**
+   - `.claude/claude-state.json` - Machine-readable state
+   - `.claude/claude-progress.md` - Human-readable summary
+
+3. **Optional Git Commit**
+   - If `--commit` flag: commit state files with message
+
+## Output Files
+
+### .claude/claude-state.json
+
+```json
+{
+  "version": "1.0",
+  "timestamp": "<ISO timestamp>",
+  "completed": ["task1", "task2"],
+  "in_progress": ["task3"],
+  "pending": ["task4", "task5"],
+  "context": {
+    "branch": "<current branch>",
+    "last_commit": "<commit hash>",
+    "last_commit_message": "<message>",
+    "modified_files": ["file1.ts", "file2.ts"],
+    "notes": "<any user-provided notes>"
+  }
+}
+```
+
+### .claude/claude-progress.md
+
+```markdown
+# Session Progress
+
+**Last Updated**: <timestamp>
+**Branch**: <branch name>
+
+## Completed
+- [x] Task 1
+- [x] Task 2
+
+## In Progress
+- [ ] Task 3
+  - Notes: <context>
+
+## Next Steps
+- Task 4
+- Task 5
+
+## Context
+- Last commit: <hash> "<message>"
+- Uncommitted: <count> files
+```
+
+## Usage Examples
+
+```bash
+# Basic checkpoint
+/checkpoint
+
+# Checkpoint with notes
+/checkpoint "Stopped mid-refactor, auth module needs testing"
+
+# Checkpoint and commit
+/checkpoint --commit
+
+# Checkpoint with notes and commit
+/checkpoint "Ready for review" --commit
+```
+
+## Execution Steps
+
+### Step 1: Gather State
+
+```bash
+# Get git info
+git branch --show-current
+git log -1 --format="%H %s"
+git status --porcelain
+```
+
+### Step 2: Read TodoWrite State
+
+Access the current TodoWrite state from the conversation context. Map statuses:
+- `completed` → Completed section
+- `in_progress` → In Progress section
+- `pending` → Next Steps section
+
+### Step 3: Create Directory
+
+```bash
+mkdir -p .claude
+```
+
+### Step 4: Write JSON State
+
+Create `.claude/claude-state.json` with:
+- Version: "1.0"
+- Timestamp: Current ISO timestamp
+- All task arrays from TodoWrite
+- Git context (branch, last commit, modified files)
+- User notes if provided in arguments
+
+### Step 5: Write Markdown Summary
+
+Create `.claude/claude-progress.md` with human-readable format:
+- Header with timestamp and branch
+- Checkbox lists for each status
+- Context section with git info
+- Any notes provided
+
+### Step 6: Optional Commit
+
+If `--commit` flag present:
+```bash
+git add .claude/claude-state.json .claude/claude-progress.md
+git commit -m "chore: checkpoint session state"
+```
+
+## Output
+
+After creating files, report:
+
+```
+✓ Session checkpointed
+
+State saved to:
+  • .claude/claude-state.json
+  • .claude/claude-progress.md
+
+Summary:
+  • Completed: X tasks
+  • In Progress: Y tasks
+  • Pending: Z tasks
+  • Uncommitted files: N
+
+Resume with: /resume
+```
+
+## Flags
+
+| Flag | Effect |
+|------|--------|
+| `--commit` | Git commit the state files after creating |
+| `--force` | Overwrite existing state without confirmation |
+
+## Notes
+
+- State files are gitignored by default (add to .gitignore if needed)
+- Use `/resume` to restore state in a new session
+- Checkpoint frequently during long tasks
+- Notes are preserved across sessions

+ 271 - 0
commands/explain.md

@@ -0,0 +1,271 @@
+---
+description: "Deep explanation of complex code, files, or concepts. Breaks down architecture, data flow, and design decisions."
+---
+
+# Explain - Deep Code Explanation
+
+Get a comprehensive explanation of complex code, files, or architectural concepts.
+
+## Arguments
+
+$ARGUMENTS
+
+- File path: Explain specific file
+- Function/class name: Explain specific component
+- `--depth <shallow|normal|deep>`: Level of detail
+- `--focus <arch|flow|deps|api>`: Specific focus area
+
+## What This Command Does
+
+1. **Identify Target**
+   - Parse file/function/concept
+   - Gather related files if needed
+   - Understand scope of explanation
+
+2. **Analyze Code**
+   - Parse structure and dependencies
+   - Trace data flow
+   - Identify patterns and design decisions
+
+3. **Generate Explanation**
+   - Architecture overview
+   - Step-by-step breakdown
+   - Visual diagrams (ASCII)
+   - Related concepts
+
+## Execution Steps
+
+### Step 1: Parse Target
+
+```bash
+# If file path
+cat <file>
+
+# If function name, search for it
+grep -rn "function <name>\|def <name>\|class <name>" .
+
+# If directory
+ls -la <dir>
+tree <dir> -L 2
+```
+
+### Step 2: Gather Context
+
+For the target, collect:
+- Imports/dependencies
+- Exports/public API
+- Related files (tests, types)
+- Usage examples in codebase
+
+### Step 3: Analyze Structure
+
+**For Functions:**
+- Input parameters and types
+- Return value and type
+- Side effects
+- Error handling
+- Algorithm complexity
+
+**For Classes:**
+- Properties and methods
+- Inheritance/composition
+- Lifecycle
+- Public vs private API
+
+**For Files/Modules:**
+- Purpose and responsibility
+- Exports and imports
+- Dependencies
+- Integration points
+
+**For Directories:**
+- Module organization
+- File relationships
+- Naming conventions
+- Architecture pattern
+
+### Step 4: Generate Explanation
+
+```markdown
+# Explanation: <target>
+
+## Overview
+<1-2 sentence summary of what this does and why>
+
+## Architecture
+<ASCII diagram if helpful>
+
+```
+┌─────────────┐    ┌─────────────┐
+│   Input     │───▶│  Processor  │
+└─────────────┘    └──────┬──────┘
+                          │
+                          ▼
+                   ┌─────────────┐
+                   │   Output    │
+                   └─────────────┘
+```
+
+## How It Works
+
+### Step 1: <phase name>
+<explanation>
+
+### Step 2: <phase name>
+<explanation>
+
+## Key Concepts
+
+### <Concept 1>
+<explanation>
+
+### <Concept 2>
+<explanation>
+
+## Dependencies
+- `<dep1>` - <purpose>
+- `<dep2>` - <purpose>
+
+## Usage Examples
+
+```<language>
+// Example usage
+```
+
+## Design Decisions
+
+### Why <decision>?
+<rationale>
+
+## Related Code
+- `<file1>` - <relationship>
+- `<file2>` - <relationship>
+
+## Common Pitfalls
+- <pitfall 1>
+- <pitfall 2>
+```
+
+## Usage Examples
+
+```bash
+# Explain a file
+/explain src/auth/oauth.ts
+
+# Explain a function
+/explain validateToken
+
+# Explain a class
+/explain UserService
+
+# Explain a directory
+/explain src/services/
+
+# Explain with deep detail
+/explain src/core/engine.ts --depth deep
+
+# Focus on data flow
+/explain src/api/routes.ts --focus flow
+
+# Architecture overview
+/explain src/services/ --focus arch
+```
+
+## Depth Levels
+
+| Level | Output |
+|-------|--------|
+| `shallow` | Quick overview, main purpose, key exports |
+| `normal` | Full explanation with examples (default) |
+| `deep` | Exhaustive breakdown, edge cases, internals |
+
+## Focus Areas
+
+| Focus | Explains |
+|-------|----------|
+| `arch` | Architecture, structure, patterns |
+| `flow` | Data flow, control flow, sequence |
+| `deps` | Dependencies, imports, integrations |
+| `api` | Public API, inputs, outputs, contracts |
+
+## Explanation Styles by Target
+
+### Functions
+- **Input/Output**: What goes in, what comes out
+- **Algorithm**: Step-by-step logic
+- **Edge Cases**: Boundary conditions
+- **Performance**: Time/space complexity
+
+### Classes
+- **Purpose**: Why this class exists
+- **State**: What data it manages
+- **Behavior**: What it can do
+- **Relationships**: How it connects to others
+
+### Files
+- **Role**: Where it fits in the system
+- **Exports**: What it provides
+- **Imports**: What it needs
+- **Patterns**: Design patterns used
+
+### Directories
+- **Organization**: How files are structured
+- **Conventions**: Naming and patterns
+- **Boundaries**: Module responsibilities
+- **Dependencies**: Inter-module relationships
+
+## ASCII Diagrams
+
+For complex systems, include ASCII diagrams:
+
+### Sequence Diagram
+```
+User          Service         Database
+  │              │               │
+  │──request───▶│               │
+  │              │───query─────▶│
+  │              │◀──result─────│
+  │◀─response───│               │
+```
+
+### Data Flow
+```
+[Input] → [Validate] → [Transform] → [Store] → [Output]
+              │
+              └──[Error]──▶ [Log]
+```
+
+### Component Diagram
+```
+┌────────────────────────────────────┐
+│            Application             │
+├──────────┬──────────┬─────────────┤
+│  Routes  │ Services │   Models    │
+├──────────┴──────────┴─────────────┤
+│            Database               │
+└────────────────────────────────────┘
+```
+
+## Flags
+
+| Flag | Effect |
+|------|--------|
+| `--depth <level>` | Set detail level (shallow/normal/deep) |
+| `--focus <area>` | Focus on specific aspect |
+| `--no-examples` | Skip usage examples |
+| `--no-diagrams` | Skip ASCII diagrams |
+| `--json` | Output as structured JSON |
+
+## Integration
+
+Works well with:
+- `/review` - Review after understanding
+- `/test` - Generate tests for explained code
+- `/checkpoint` - Save progress after learning
+
+## Notes
+
+- Explanations are based on code analysis, not documentation
+- Complex systems may need multiple explanations
+- Use `--depth deep` for unfamiliar codebases
+- Diagrams help visualize relationships

+ 191 - 0
commands/resume.md

@@ -0,0 +1,191 @@
+---
+description: "Restore session context from checkpoint. Reads claude-state.json and claude-progress.md, shows what changed, suggests next action."
+---
+
+# Resume - Restore Session Context
+
+Restore your session context from a previous checkpoint. Reads state files, shows what's changed since, and suggests the next action.
+
+## Arguments
+
+$ARGUMENTS
+
+If no arguments, read from default `.claude/` location.
+
+## What This Command Does
+
+1. **Read State Files**
+   - Load `.claude/claude-state.json`
+   - Load `.claude/claude-progress.md`
+
+2. **Analyze Changes Since Checkpoint**
+   - Git commits since last checkpoint
+   - File modifications
+   - Time elapsed
+
+3. **Restore TodoWrite State**
+   - Populate TodoWrite with saved tasks
+   - Preserve status (completed, in-progress, pending)
+
+4. **Suggest Next Action**
+   - Based on in-progress tasks
+   - Highlight blockers or notes
+
+## Execution Steps
+
+### Step 1: Check for State Files
+
+```bash
+ls -la .claude/claude-state.json .claude/claude-progress.md 2>/dev/null
+```
+
+If missing, report:
+```
+⚠ No checkpoint found in .claude/
+
+To create one, use: /checkpoint
+```
+
+### Step 2: Read State
+
+Parse `.claude/claude-state.json`:
+- Extract timestamp
+- Extract task arrays
+- Extract context (branch, last commit, notes)
+
+### Step 3: Calculate Time Since Checkpoint
+
+Compare checkpoint timestamp to current time:
+- Format as human-readable ("2 hours ago", "3 days ago")
+
+### Step 4: Analyze Git Changes
+
+```bash
+# Commits since checkpoint
+git log --oneline <last_commit>..HEAD
+
+# Current status
+git status --short
+```
+
+### Step 5: Restore TodoWrite
+
+Use TodoWrite tool to restore tasks:
+- Map `completed` → status: "completed"
+- Map `in_progress` → status: "in_progress"
+- Map `pending` → status: "pending"
+
+### Step 6: Display Summary
+
+```markdown
+# Session Resumed
+
+**Checkpoint from**: <timestamp> (<relative time>)
+**Branch**: <branch>
+
+## Since Last Checkpoint
+- <N> new commits
+- <M> files modified
+- <time> elapsed
+
+## Restored Tasks
+
+### In Progress
+- [ ] Task that was being worked on
+
+### Pending
+- Task 1
+- Task 2
+
+### Completed (this session)
+- [x] Previously completed task
+
+## Notes from Last Session
+> <any notes saved>
+
+## Suggested Next Action
+Based on your in-progress task: **<task name>**
+
+<Context or suggestion based on what was being worked on>
+```
+
+## Usage Examples
+
+```bash
+# Basic resume
+/resume
+
+# Resume from specific directory
+/resume path/to/project
+
+# Resume with verbose git log
+/resume --verbose
+```
+
+## Flags
+
+| Flag | Effect |
+|------|--------|
+| `--verbose` | Show full git log since checkpoint |
+| `--no-restore` | Show state without restoring TodoWrite |
+| `--clear` | Clear checkpoint after resuming |
+
+## Edge Cases
+
+### No Checkpoint Found
+```
+⚠ No checkpoint found
+
+This could mean:
+1. You haven't checkpointed yet (use /checkpoint)
+2. Wrong directory (check pwd)
+3. State files were deleted
+
+To start fresh, just begin working normally.
+```
+
+### Stale Checkpoint (>7 days)
+```
+⚠ Checkpoint is 12 days old
+
+A lot may have changed. Consider:
+1. Review git log manually
+2. Start fresh if context is lost
+3. Resume anyway with: /resume --force
+```
+
+### Branch Changed
+```
+⚠ Branch changed since checkpoint
+
+Checkpoint branch: feature/old-branch
+Current branch: feature/new-branch
+
+The checkpoint may not be relevant. Options:
+1. Switch back: git checkout feature/old-branch
+2. Resume anyway (tasks may still apply)
+3. Clear and start fresh: /resume --clear
+```
+
+## Integration with /checkpoint
+
+These commands form a pair:
+
+```
+Session 1:
+  [work on tasks]
+  /checkpoint "Stopped at auth module"
+
+Session 2:
+  /resume
+  → Shows: "In progress: Auth module refactor"
+  → Notes: "Stopped at auth module"
+  → Suggests: "Continue with auth module testing"
+```
+
+## Notes
+
+- Resume automatically populates TodoWrite
+- Use `--no-restore` to preview without changing state
+- Clear old checkpoints periodically with `--clear`
+- Works across machines if .claude/ is committed

+ 206 - 0
commands/review.md

@@ -0,0 +1,206 @@
+---
+description: "Code review staged changes or specific files. Analyzes for bugs, style issues, security concerns, and suggests improvements."
+---
+
+# Review - AI Code Review
+
+Perform a comprehensive code review on staged changes or specific files.
+
+## Arguments
+
+$ARGUMENTS
+
+- No args: Review staged changes (`git diff --cached`)
+- File path: Review specific file
+- Directory: Review all files in directory
+- `--all`: Review all uncommitted changes
+
+## What This Command Does
+
+1. **Identify Target Code**
+   - Staged changes (default)
+   - Specific files/directories
+   - All uncommitted changes
+
+2. **Analyze For**
+   - Bugs and logic errors
+   - Security vulnerabilities
+   - Performance issues
+   - Style/convention violations
+   - Missing error handling
+   - Code smells
+
+3. **Provide Feedback**
+   - Issue severity (critical, warning, suggestion)
+   - Line-specific comments
+   - Suggested fixes
+   - Overall assessment
+
+## Execution Steps
+
+### Step 1: Determine Scope
+
+```bash
+# Default: staged changes
+git diff --cached --name-only
+
+# If no staged changes, prompt user
+git status --short
+```
+
+### Step 2: Get Diff Content
+
+```bash
+# For staged changes
+git diff --cached
+
+# For specific file
+git diff HEAD -- <file>
+
+# For all changes
+git diff HEAD
+```
+
+### Step 3: Analyze Code
+
+For each changed file, analyze:
+
+**Bugs & Logic**
+- Null/undefined checks
+- Off-by-one errors
+- Race conditions
+- Unhandled edge cases
+
+**Security**
+- SQL injection
+- XSS vulnerabilities
+- Hardcoded secrets
+- Insecure dependencies
+
+**Performance**
+- N+1 queries
+- Unnecessary re-renders
+- Memory leaks
+- Blocking operations
+
+**Style**
+- Naming conventions
+- Code organization
+- Documentation gaps
+- Dead code
+
+### Step 4: Format Output
+
+```markdown
+# Code Review: <scope>
+
+## Summary
+- Files reviewed: N
+- Issues found: X (Y critical, Z warnings)
+
+## Critical Issues 🔴
+
+### <filename>:<line>
+**Issue**: <description>
+**Risk**: <what could go wrong>
+**Fix**:
+\`\`\`diff
+- <old code>
++ <suggested fix>
+\`\`\`
+
+## Warnings 🟡
+
+### <filename>:<line>
+**Issue**: <description>
+**Suggestion**: <how to improve>
+
+## Suggestions 🔵
+
+### <filename>:<line>
+**Suggestion**: <minor improvement>
+
+## Overall Assessment
+
+<1-2 sentence summary>
+
+**Ready to commit?** Yes/No - <reasoning>
+```
+
+## Usage Examples
+
+```bash
+# Review staged changes
+/review
+
+# Review specific file
+/review src/auth/login.ts
+
+# Review directory
+/review src/components/
+
+# Review all uncommitted changes
+/review --all
+
+# Review with specific focus
+/review --security
+/review --performance
+```
+
+## Focus Flags
+
+| Flag | Focus Area |
+|------|------------|
+| `--security` | Security vulnerabilities only |
+| `--performance` | Performance issues only |
+| `--style` | Style and conventions only |
+| `--bugs` | Logic errors and bugs only |
+| `--all-checks` | Everything (default) |
+
+## Severity Levels
+
+| Level | Meaning | Action |
+|-------|---------|--------|
+| 🔴 Critical | Must fix before merge | Blocking |
+| 🟡 Warning | Should address | Recommended |
+| 🔵 Suggestion | Nice to have | Optional |
+
+## Framework-Specific Checks
+
+### React/Next.js
+- Hook rules violations
+- Missing dependencies in useEffect
+- Key prop issues in lists
+- Server/client component boundaries
+
+### TypeScript
+- `any` type usage
+- Missing type annotations
+- Incorrect generic constraints
+- Type assertion abuse
+
+### Node.js
+- Unhandled promise rejections
+- Sync operations in async context
+- Memory leak patterns
+- Insecure eval/exec usage
+
+### Python
+- Mutable default arguments
+- Bare except clauses
+- Resource leaks
+- SQL string formatting
+
+## Integration
+
+Works well with:
+- `/test` - Generate tests for flagged issues
+- `/explain` - Deep dive into complex code
+- `/checkpoint` - Save state before fixing issues
+
+## Notes
+
+- Reviews are suggestions, not absolute rules
+- Context matters - some "issues" may be intentional
+- Use `--verbose` for detailed explanations
+- Reviews don't modify code - you decide what to fix

+ 227 - 0
commands/test.md

@@ -0,0 +1,227 @@
+---
+description: "Generate tests for code with automatic framework detection. Creates unit tests, integration tests, or test stubs based on your stack."
+---
+
+# Test - Generate Tests
+
+Generate tests for your code with automatic framework detection.
+
+## Arguments
+
+$ARGUMENTS
+
+- File path: Generate tests for specific file
+- Function name: Generate tests for specific function
+- `--type <unit|integration|e2e>`: Specify test type
+- `--framework <jest|vitest|pytest|etc>`: Override detected framework
+
+## What This Command Does
+
+1. **Detect Test Framework**
+   - Scan package.json, pyproject.toml, etc.
+   - Identify existing test patterns
+   - Determine conventions in use
+
+2. **Analyze Target Code**
+   - Parse functions/classes
+   - Identify inputs/outputs
+   - Find edge cases
+
+3. **Generate Tests**
+   - Create test file in correct location
+   - Follow project conventions
+   - Include common edge cases
+
+## Framework Detection
+
+### JavaScript/TypeScript
+```bash
+# Check package.json for:
+- jest
+- vitest
+- mocha
+- ava
+- @testing-library/*
+```
+
+### Python
+```bash
+# Check for:
+- pytest (pyproject.toml, pytest.ini)
+- unittest (default)
+- nose2
+```
+
+### Other
+- Go: built-in testing
+- Rust: built-in testing
+- PHP: PHPUnit
+
+## Execution Steps
+
+### Step 1: Detect Framework
+
+```bash
+# JavaScript
+cat package.json | jq '.devDependencies | keys[]' | grep -E 'jest|vitest|mocha'
+
+# Python
+grep -l "pytest" pyproject.toml setup.py requirements*.txt 2>/dev/null
+```
+
+### Step 2: Analyze Target Code
+
+Read the target file and extract:
+- Function signatures
+- Input parameters and types
+- Return types
+- Dependencies/imports
+- Existing patterns
+
+### Step 3: Determine Test Location
+
+```
+# JavaScript conventions
+src/utils/helper.ts → src/utils/__tests__/helper.test.ts
+                   → src/utils/helper.test.ts
+                   → tests/utils/helper.test.ts
+
+# Python conventions
+app/utils/helper.py → tests/test_helper.py
+                   → app/utils/test_helper.py
+                   → tests/utils/test_helper.py
+```
+
+### Step 4: Generate Test File
+
+Create comprehensive tests including:
+- Happy path
+- Edge cases (null, empty, boundary values)
+- Error cases
+- Async handling (if applicable)
+
+## Output Format
+
+### Jest/Vitest (TypeScript)
+
+```typescript
+import { describe, it, expect, vi } from 'vitest';
+import { functionName } from '../path/to/module';
+
+describe('functionName', () => {
+  it('should handle normal input', () => {
+    const result = functionName('input');
+    expect(result).toBe('expected');
+  });
+
+  it('should handle empty input', () => {
+    expect(() => functionName('')).toThrow();
+  });
+
+  it('should handle null input', () => {
+    expect(functionName(null)).toBeNull();
+  });
+});
+```
+
+### pytest (Python)
+
+```python
+import pytest
+from app.module import function_name
+
+class TestFunctionName:
+    def test_normal_input(self):
+        result = function_name("input")
+        assert result == "expected"
+
+    def test_empty_input(self):
+        with pytest.raises(ValueError):
+            function_name("")
+
+    def test_none_input(self):
+        assert function_name(None) is None
+```
+
+## Usage Examples
+
+```bash
+# Generate tests for a file
+/test src/utils/auth.ts
+
+# Generate tests for specific function
+/test src/utils/auth.ts:validateToken
+
+# Specify test type
+/test src/api/users.ts --type integration
+
+# Override framework detection
+/test src/helpers.js --framework jest
+
+# Generate test stubs only (no implementation)
+/test src/complex.ts --stubs
+```
+
+## Test Types
+
+| Type | Purpose | Generated For |
+|------|---------|---------------|
+| `unit` | Test isolated functions | Pure functions, utilities |
+| `integration` | Test component interactions | API routes, services |
+| `e2e` | End-to-end flows | User journeys |
+| `snapshot` | UI snapshot tests | React components |
+
+## Flags
+
+| Flag | Effect |
+|------|--------|
+| `--type <type>` | Specify test type |
+| `--framework <fw>` | Override framework detection |
+| `--stubs` | Generate empty test stubs only |
+| `--coverage` | Focus on uncovered code paths |
+| `--verbose` | Explain test reasoning |
+
+## Smart Features
+
+### Dependency Mocking
+Automatically detects and mocks:
+- External API calls
+- Database operations
+- File system operations
+- Environment variables
+
+### Edge Case Generation
+Automatically includes tests for:
+- Null/undefined values
+- Empty strings/arrays
+- Boundary values (0, -1, MAX_INT)
+- Invalid types
+- Async error handling
+
+### Convention Following
+Matches existing project patterns:
+- Test file naming
+- Directory structure
+- Import styles
+- Assertion library
+
+## Integration
+
+After generating tests:
+
+```bash
+# Run the new tests
+npm test -- --watch <test-file>
+pytest <test-file> -v
+
+# Check coverage
+npm test -- --coverage
+pytest --cov=app
+```
+
+## Notes
+
+- Generated tests are starting points, refine as needed
+- Review mocks for accuracy
+- Add integration tests manually for complex flows
+- Use `--stubs` when you want to write tests yourself