Skip to content

Latest commit

Β 

History

History
781 lines (606 loc) Β· 36.6 KB

File metadata and controls

781 lines (606 loc) Β· 36.6 KB

CLAUDE.md

Purpose: AI-optimized execution guide for Claude Code agents working with the CodeMie Code codebase

Note: CodeMie Code is an umbrella project with multiple agent plugins (Claude, Gemini, OpenCode, etc.) and provider integrations.


πŸ“š GUIDE IMPORTS

This document references detailed guides stored in .codemie/guides/. Key references:

🚨 MANDATORY RULE: Check Guides First

BEFORE searching files or codebase for information, you MUST:

  1. Always check if the guides referenced below contain relevant information for the prompt or task
  2. Use the Task Classifier in Instant Start to identify which guides are relevant
  3. Load and review the appropriate P0 (required) guides BEFORE performing direct file searches
  4. Only proceed to codebase searches after confirming guides don't contain the needed patterns/information

This rule is MANDATORY and must be followed without exceptions.

Why: Guides contain curated patterns, best practices, and architectural decisions. Checking them first:

  • Prevents reinventing existing patterns
  • Ensures consistency with established conventions
  • Saves time by providing direct answers to common questions
  • Reduces risk of introducing anti-patterns

Workflow: Prompt β†’ Task Classifier β†’ Load Relevant Guides β†’ Check Guide Content β†’ Then Search Codebase (if needed)


πŸ“– Guide References by Category

Architecture:

Development Practices:

Testing:

Standards & Workflows:

Integration & Security:


⚑ INSTANT START (Read First)

1. Critical Rules (MANDATORY - Always Check)

Rule Trigger Action Required
🚨 Check Guides First ANY new prompt/task ALWAYS check relevant guides BEFORE searching codebase β†’ Guide Imports
🚨 Testing User says "write tests", "run tests" ONLY then work on tests β†’ Testing Policy
🚨 Git Ops User says "commit", "push", "create PR" ONLY then do git operations β†’ Git Policy
🚨 Node Environment ANY TypeScript/npm command No activation needed (Node.js >=20.0.0) β†’ Env Policy
🚨 Shell ANY shell command ONLY bash/Linux syntax β†’ Shell Policy

Emergency Recovery: If commands fail β†’ Check Troubleshooting

2. Task Classifier (What am I doing?)

Scan user request for keywords β†’ Load guides β†’ Execute

Keywords Complexity Load Guide (P0=Required) Also Load (P1=Optional)
plugin, registry, agent, adapter Medium-High .codemie/guides/architecture/architecture.md .codemie/guides/integration/external-integrations.md
architecture, layer, structure, pattern Medium .codemie/guides/architecture/architecture.md .codemie/guides/development/development-practices.md
test, vitest, mock, coverage Medium .codemie/guides/testing/testing-patterns.md .codemie/guides/development/development-practices.md
error, exception, validation Medium .codemie/guides/development/development-practices.md .codemie/guides/security/security-practices.md
security, sanitize, credential High .codemie/guides/security/security-practices.md .codemie/guides/development/development-practices.md
provider, sso, bedrock, litellm, langgraph Medium-High .codemie/guides/integration/external-integrations.md .codemie/guides/architecture/architecture.md
cli, command, commander Medium .codemie/guides/architecture/architecture.md .codemie/guides/development/development-practices.md
workflow, ci/cd, github, gitlab Medium .codemie/guides/standards/git-workflow.md -
lint, eslint, format, code quality Simple .codemie/guides/standards/code-quality.md -
commit, branch, pr, git Simple .codemie/guides/standards/git-workflow.md -

Guide Path: All guides in .codemie/guides/<category>/

Complexity Guide:

  • Simple: 1 file, < 5 min, obvious pattern β†’ Use direct tools (Grep/Glob/Read)
  • Medium: 2-5 files, 5-15 min, standard patterns β†’ Use direct tools + guide reference
  • High: 6+ files, 15+ min, architectural decisions β†’ Consider EnterPlanMode or Task tool

3. Self-Check Before Starting

Before any action:

  • Did I check relevant guides FIRST (before searching codebase)?
  • Which critical rules apply? (guides/testing/git/env/shell)
  • What keywords did I identify?
  • What's the complexity level?
  • Which guides do I need to load (P0 first)?
  • Am I 80%+ confident about approach?

Decision Gates:

  • ❌ NO to any above β†’ ASK USER or READ MORE before proceeding
  • ❌ Confidence < 80% β†’ Load P0 guides, then re-assess
  • βœ… YES to all + Confidence 80%+ β†’ Proceed to execution

πŸ”„ EXECUTION WORKFLOW (Step-by-Step)

Follow this sequence for every task:

START
  β”‚
  β”œβ”€> STEP 1: Parse Request
  β”‚   β”œβ”€ Identify task keywords (see Task Classifier above)
  β”‚   β”œβ”€ Check which Critical Rules apply
  β”‚   β”œβ”€ Assess complexity level
  β”‚   └─ Gate: Can I identify 1+ relevant guides? NO β†’ Ask user | YES β†’ Continue
  β”‚
  β”œβ”€> STEP 2: Confidence Check
  β”‚   β”œβ”€ Am I 80%+ confident about approach?
  β”‚   β”œβ”€ YES β†’ Continue | NO β†’ Load P0 guides
  β”‚   └─ Gate: After reading, confidence 80%+? NO β†’ Load P1 guides or ask user | YES β†’ Continue
  β”‚
  β”œβ”€> STEP 3: Load Documentation (Selective, Not Everything)
  β”‚   β”œβ”€ Load P0 guides from Task Classifier (REQUIRED for Medium/High complexity)
  β”‚   β”œβ”€ Scan P1 guides - load only if confidence still < 80% (OPTIONAL)
  β”‚   └─ Gate: Do I have enough context? NO β†’ Load more or ask user | YES β†’ Continue
  β”‚
  β”œβ”€> STEP 4: Pattern Match (Use Quick References)
  β”‚   β”œβ”€ Check Pattern Tables below (error handling, logging, architecture)
  β”‚   β”œβ”€ Check Common Pitfalls table
  β”‚   └─ Gate: Do I know the correct pattern? NO β†’ Read guide detail | YES β†’ Continue
  β”‚
  β”œβ”€> STEP 5: Execute (Apply Patterns)
  β”‚   β”œβ”€ Apply patterns from loaded guides
  β”‚   β”œβ”€ Follow Critical Rules (test/git/env/shell)
  β”‚   β”œβ”€ Track progress with success indicators
  β”‚   └─ Cross-check with Quick Validation (below)
  β”‚
  └─> STEP 6: Validate (Before Delivery)
      β”œβ”€ Run through Quick Validation checklist
      β”œβ”€ Check Success Indicators
      β”œβ”€ Gate: All checks pass? NO β†’ Fix issues | YES β†’ Deliver
      └─ END

Success Indicators (Am I on track?)

Stage Good Signs Warning Signs
Parse Request Keywords match Task Classifier No matching keywords β†’ ask user
Confidence Check 80%+ confident after reading Still confused after P0 guides β†’ need clarification
Load Docs Patterns clear, examples match task Multiple conflicting patterns β†’ ask user preference
Pattern Match Found exact pattern in quick ref No matching pattern β†’ read full guide
Execute Code compiles, follows architecture Errors, missing imports β†’ check guide again
Validate All checks pass, tests work Any check fails β†’ fix before delivery

Quick Validation (Run Before Delivery)

Priority Check How to Verify Fix If Failed
🚨 Functionality Does it meet user request? Re-read requirements
🚨 Critical Rules Did I follow test/git/env/shell rules? Review policies below
🚨 Security No hardcoded secrets? Input validated? See Security Patterns
🚨 Error Handling Using proper exceptions? See Error Handling
🚨 Logging Following logging patterns? See Logging Patterns
⚠️ Architecture Followed layered architecture? See guides in .codemie/guides/architecture/
⚠️ Async/Concurrency Used appropriate patterns? See Common Pitfalls
βœ… Type Safety All functions typed? See code quality guide
βœ… Code Quality No TODOs, unused imports? Run linter

πŸ“Š PATTERN QUICK REFERENCE

Error Handling (Use These Patterns)

When Pattern/Exception Import From Related Patterns
Configuration failed ConfigurationError src/utils/errors.ts Logging
Agent not found AgentNotFoundError src/utils/errors.ts API Patterns
Agent install failed AgentInstallationError src/utils/errors.ts Process Execution
Tool execution failed ToolExecutionError src/utils/errors.ts Security
Path security issue PathSecurityError src/utils/errors.ts Security
npm operation failed NpmError src/utils/errors.ts Process Execution
Generic CodeMie error CodeMieError src/utils/errors.ts Base class for all errors

Error Context:

// Always provide context for errors
import { createErrorContext, formatErrorForUser } from 'src/utils/errors.js';

try {
  await riskyOperation();
} catch (error) {
  const context = createErrorContext(error, { sessionId, agent: 'claude' });
  logger.error('Operation failed', context);
  console.error(formatErrorForUser(context));
}

Detail: .codemie/guides/development/development-practices.md

Logging Patterns (MANDATORY)

βœ… DO ❌ DON'T Why Related
Use logger.debug() for internal details Use console.log() directly Debug logs go to file, controlled by CODEMIE_DEBUG Error Handling
Use logger.info() for non-console logs Log sensitive data (tokens, keys) Auto-sanitization prevents leaks Security
Use logger.success() for user feedback Skip session/agent context Context required for debugging Session Management
Sanitize before logging Log raw API responses Prevents credential exposure Security

Session Context:

// Set session context at agent startup
logger.setSessionId(sessionId);
logger.setAgentName('claude');
logger.setProfileName('work');

// All subsequent logs include context automatically
logger.debug('Processing request'); // [DEBUG] [claude] [session-id] [work] Processing request

Detail: .codemie/guides/development/development-practices.md

Architecture Patterns (Core Rules)

Layer Responsibility Example Path Related Guide
CLI User interface, Commander.js commands src/cli/commands/ .codemie/guides/architecture/architecture.md
Registry Plugin discovery, routing src/agents/registry.ts .codemie/guides/architecture/architecture.md
Plugin Concrete implementations (agents, providers) src/agents/plugins/claude/ .codemie/guides/architecture/architecture.md
Core Base classes, interfaces, contracts src/agents/core/ .codemie/guides/architecture/architecture.md
Utils Shared utilities (errors, logging, security) src/utils/ .codemie/guides/development/development-practices.md

Flow: CLI β†’ Registry β†’ Plugin β†’ Core β†’ Utils (Never skip layers)

Detail: .codemie/guides/architecture/architecture.md

Security Patterns (MANDATORY)

Rule Implementation Related Guide
No hardcoded credentials Use environment variables + CredentialStore .codemie/guides/security/security-practices.md
Input validation Validate all file paths with security utilities .codemie/guides/security/security-practices.md
Data sanitization Use sanitizeValue(), sanitizeLogArgs() before logging .codemie/guides/security/security-practices.md
Credential storage CredentialStore with keychain + encrypted fallback .codemie/guides/security/security-practices.md

Security Utilities:

import { sanitizeValue, sanitizeLogArgs, CredentialStore } from 'src/utils/security.js';

// Sanitize before logging
logger.debug('Request data', ...sanitizeLogArgs(requestData));

// Store/retrieve credentials securely
const store = CredentialStore.getInstance();
await store.storeSSOCredentials(credentials, baseUrl);
const retrieved = await store.retrieveSSOCredentials(baseUrl);

Detail: .codemie/guides/security/security-practices.md

Project-Level Configuration (Use These Patterns)

Pattern When to Use Implementation Related Guide
Global Config Settings across all repositories codemie setup β†’ Select "Global" .codemie/guides/usage/project-config.md
Local Config Repository-specific overrides codemie setup β†’ Select "Local" .codemie/guides/usage/project-config.md
Field Override Override specific fields only Use initProjectConfig() with overrides .codemie/guides/usage/project-config.md
Source Tracking Debug config sources codemie profile status --show-sources .codemie/guides/usage/project-config.md
2-Level Lookup Access both local and global profiles codemie profile shows all profiles .codemie/guides/usage/project-config.md

Priority System: CLI args > Env vars > Project config > Global config > Defaults

2-Level Profile Lookup: Local configs don't isolate from global - you get access to BOTH:

  • codemie profile lists profiles from both local and global configs (marked with [Local] or [Global])
  • You can switch to any profile (local or global) even when local config exists
  • Profile loading merges: global profile (base) + local overrides (if any)

Common Use Cases:

// Initialize local config with project overrides
await ConfigLoader.initProjectConfig(workingDir, {
  codeMieProject: 'frontend-app',
  codeMieIntegration: { id: 'frontend-123', alias: 'frontend-team' }
});

// Check if local config exists
const hasLocal = await ConfigLoader.hasLocalConfig(workingDir);

// Load with source tracking
const { config, hasLocalConfig, sources } = await ConfigLoader.loadWithSources(workingDir);

File Locations:

  • Global: ~/.codemie/codemie-cli.config.json
  • Local: .codemie/codemie-cli.config.json (in repository root)

Detail: .codemie/guides/usage/project-config.md

Process Patterns (npm, git, exec)

Operation Function Import From
Execute command exec(command, args, options) src/utils/processes.ts
Check command exists commandExists(command) src/utils/processes.ts
Install npm package installGlobal(packageName) src/utils/processes.ts
Run with npx npxRun(command, args) src/utils/processes.ts
Detect git branch detectGitBranch(cwd) src/utils/processes.ts

Detail: .codemie/guides/development/development-practices.md

Common Pitfalls (Avoid These)

Category 🚨 Never Do This βœ… Do This Instead Guide Reference
TypeScript Use require() or __dirname Use ES modules: import and getDirname(import.meta.url) .codemie/guides/development/development-practices.md
Imports Import without .js extension Always use .js extension: import x from './file.js' .codemie/guides/standards/code-quality.md
Testing Write tests unless requested Only write tests when user explicitly asks .codemie/guides/testing/testing-patterns.md
Process Execution Use child_process.exec directly Use exec() from src/utils/processes.ts .codemie/guides/development/development-practices.md
Logging Use console.log() for debug info Use logger.debug() (file-only, controlled) .codemie/guides/development/development-practices.md
Security Log sensitive data (tokens, keys) Use sanitizeLogArgs() before logging .codemie/guides/security/security-practices.md
Error Handling Throw generic Error Throw specific error classes (ConfigurationError, etc.) .codemie/guides/development/development-practices.md
Paths Hardcode ~/.codemie/ paths Use getCodemiePath() from src/utils/paths.ts .codemie/guides/development/development-practices.md
Architecture CLI directly calls plugin code CLI β†’ Registry β†’ Plugin (never skip layers) .codemie/guides/architecture/architecture.md
Async Use callbacks or Promise chaining Use async/await consistently .codemie/guides/standards/code-quality.md

πŸ› οΈ DEVELOPMENT COMMANDS

🚨 CRITICAL: No virtual environment needed - Node.js >=20.0.0 required

Common Commands

Task Command Env? Notes
Setup npm install N/A First time setup, installs all dependencies
Build npm run build N/A Compile TypeScript to dist/
Dev Watch npm run dev N/A Watch mode (tsc --watch)
Lint npm run lint N/A ESLint check (zero warnings required)
Lint Fix npm run lint:fix N/A Auto-fix ESLint issues
Test ⚠️ npm test N/A Run all tests - ONLY if user requests
Test Unit ⚠️ npm run test:unit N/A Unit tests only - ONLY if user requests
Test Integration ⚠️ npm run test:integration N/A Integration tests only - ONLY if user requests
CI Full npm run ci N/A Full CI pipeline (lint + build + tests)
Doctor codemie doctor N/A System health check (after npm link)
Link Global npm link N/A Link for local testing (after build)

Build + Link Workflow:

npm run build && npm link
codemie doctor  # Verify installation
codemie-code health  # Test built-in agent

Additional Info:

  • Package manager: npm (no yarn/pnpm)
  • Test framework: Vitest
  • Build output: dist/ (gitignored)
  • Entry points: bin/codemie.js, bin/agent-executor.js

πŸ”§ TROUBLESHOOTING QUICK REFERENCE

Common Issues & Fixes

Symptom Likely Cause Fix Prevention
command not found: codemie Not installed globally or not linked Run npm install -g @codemieai/code or npm link Use global install for CLI tools
Cannot find module './file' Missing .js extension in import Add .js extension to all imports ESLint rule enforces this
Module not found: @codemieai/code Dependencies not installed Run npm install Always run after clone/pull
Tests failing with dynamic imports Static imports before spy setup Use dynamic imports after beforeEach See testing patterns guide
CODEMIE_DEBUG=true not working Environment variable not set Export in shell: export CODEMIE_DEBUG=true Use .env file for persistent settings
ESLint warnings > 0 Code quality issues Run npm run lint:fix to auto-fix Run lint before commit
TypeScript compilation errors Type issues or missing declarations Check tsconfig.json settings Use strict mode, avoid any
Permission denied on global install Insufficient permissions Use sudo npm install -g (Unix) or run as admin (Windows) Use nvm for user-local Node.js
Agent not found after install Registry not updated or cache issue Check ~/.codemie/agents/ directory Verify installation with codemie doctor

Diagnostic Commands

Need to Check Command What to Look For
Node.js version node --version >=20.0.0 required
npm version npm --version Should be bundled with Node.js
Global packages npm list -g --depth=0 Should show @codemieai/code if installed
CodeMie health codemie doctor All checks should pass
Build output ls -la dist/ Should contain compiled .js files
TypeScript config cat tsconfig.json Verify ES2022 target, NodeNext module

Emergency Recovery

Situation Action
Commands failing 1. Verify Node.js >=20.0.0 (node --version)
2. Reinstall dependencies (rm -rf node_modules && npm install)
3. Rebuild project (npm run build)
4. Re-link global (npm link)
Build errors 1. Clean dist directory (rm -rf dist/)
2. Check TypeScript errors (npx tsc --noEmit)
3. Fix import paths (.js extensions required)
4. Rebuild (npm run build)
Pattern unclear 1. Search .codemie/guides/ for pattern
2. Check related patterns in Quick Reference
3. Ask user if ambiguous
Tests failing 1. Check if using dynamic imports for mocking
2. Verify test isolation (no shared state)
3. Check if environment variables are set
4. Run single test file to isolate issue

πŸ—οΈ PROJECT CONTEXT

Technology Stack

Component Tool Version Purpose
Language TypeScript 5.3+ Type-safe development
Runtime Node.js 20.0.0+ JavaScript execution environment
Framework LangGraph 1.0.2+ Agent orchestration and state management
Framework LangChain 1.0.4+ LLM integration and tool calling
Testing Vitest 4.0.10+ Fast unit testing framework
Linting ESLint 9.38.0+ Code quality enforcement (flat config)
CLI Commander.js 11.1.0+ Command-line argument parsing
UI Inquirer 9.2.12+ Interactive CLI prompts
Package Manager npm - Dependency management

Core Components

Component Path Purpose Guide
CLI Commands src/cli/commands/ User interface (setup, doctor, install, etc.) .codemie/guides/architecture/architecture.md
Agent System src/agents/ Plugin-based agent management (registry, core, plugins) .codemie/guides/architecture/architecture.md
Provider System src/providers/ LLM provider integrations (OpenAI, Bedrock, SSO, LiteLLM) .codemie/guides/integration/external-integrations.md
Analytics src/analytics/ Usage tracking and metrics (JSONL-based) .codemie/guides/development/development-practices.md
Workflows src/workflows/ CI/CD workflow templates (GitHub, GitLab) .codemie/guides/integration/external-integrations.md
Utilities src/utils/ Shared utilities (errors, logging, security, processes) .codemie/guides/development/development-practices.md
Configuration src/env/ Environment and profile management .codemie/guides/development/development-practices.md

Key Integrations

Integration Purpose Guide
LangGraph Agent orchestration, state machines, tool calling .codemie/guides/integration/external-integrations.md
LangChain LLM abstractions, provider integrations .codemie/guides/integration/external-integrations.md
AWS Bedrock Enterprise LLM access (Claude via AWS) .codemie/guides/integration/external-integrations.md
Azure OpenAI Enterprise OpenAI access .codemie/guides/integration/external-integrations.md
LiteLLM Unified LLM proxy (100+ providers) .codemie/guides/integration/external-integrations.md
Ollama Local LLM execution .codemie/guides/integration/external-integrations.md
Enterprise SSO Corporate authentication (SAML, OAuth) .codemie/guides/security/security-practices.md

Architecture Overview

Plugin-Based 5-Layer Architecture:

  • CLI Layer: User interface and command handling (Commander.js)
  • Registry Layer: Plugin discovery, routing, and orchestration
  • Plugin Layer: Concrete implementations (agents, providers, frameworks)
  • Core Layer: Base classes, interfaces, contracts (abstract base classes)
  • Utils Layer: Shared utilities and foundation code

Key Characteristics:

  • Separation of concerns (each layer has distinct responsibility)
  • Dependency inversion (plugins depend on core, not vice versa)
  • Open/Closed principle (extend via plugins, no core modification)
  • Testability (each layer tested independently)

Detail: .codemie/guides/architecture/architecture.md


πŸ“ CODING STANDARDS

TypeScript Features (Use These)

Feature Use For Guide Reference
ES Modules All imports/exports (no CommonJS) .codemie/guides/standards/code-quality.md
async/await All asynchronous operations .codemie/guides/standards/code-quality.md
interface/type Type definitions (prefer interface for objects) .codemie/guides/standards/code-quality.md
Generics Reusable type-safe functions/classes .codemie/guides/standards/code-quality.md
Optional chaining Safe property access (obj?.prop) .codemie/guides/standards/code-quality.md
Nullish coalescing Default values (val ?? default) .codemie/guides/standards/code-quality.md
Destructuring Clean parameter/return handling .codemie/guides/standards/code-quality.md

Detail: .codemie/guides/standards/code-quality.md

Type Safety (REQUIRED)

  • All exported functions must have explicit return types
  • Prefer interfaces over types for object shapes
  • Avoid any (use unknown if type truly unknown)
  • Use strict TypeScript settings (see tsconfig.json)
  • @typescript-eslint/no-explicit-any disabled project-wide (use any when needed, but document why)
  • Unused variables should be prefixed with _ if intentional

Async/Concurrency Patterns (CRITICAL)

βœ… DO ❌ DON'T Guide
Use async/await for all async operations Use callbacks or .then() chains .codemie/guides/standards/code-quality.md
Handle errors with try/catch in async functions Let errors bubble without context .codemie/guides/development/development-practices.md
Use Promise.all() for parallel operations Await in loops (sequential bottleneck) .codemie/guides/standards/code-quality.md
Avoid blocking operations in CLI Use synchronous fs operations in async contexts .codemie/guides/development/development-practices.md

πŸ“š DETAILED POLICIES

Testing Policy

MANDATORY RULE: Tests ONLY when user EXPLICITLY requests

Triggers (work on tests ONLY if user says):

  • βœ… "write tests"
  • βœ… "run the tests"
  • βœ… "create unit tests"
  • βœ… "add test coverage"
  • βœ… "execute test suite"

Never Do:

  • ❌ Proactively write tests
  • ❌ Suggest running tests
  • ❌ Run tests unless asked

Framework: Vitest with dynamic imports for mocking

Test Commands:

  • npm test - All tests
  • npm run test:unit - Unit tests only (src/)
  • npm run test:integration - Integration tests only (tests/)
  • npm run test:watch - Watch mode
  • npm run test:coverage - Coverage report

Rationale: Testing requires time and context. Only implement when explicitly needed.

If Unsure: Ask user for clarification

Testing Details: .codemie/guides/testing/testing-patterns.md

Git Operations Policy

MANDATORY RULE: Git operations ONLY when user EXPLICITLY requests

Triggers (do git ops ONLY if user says):

  • βœ… "commit these changes"
  • βœ… "create a commit"
  • βœ… "push to remote"
  • βœ… "create a branch"
  • βœ… "create a pull request"

Never Do:

  • ❌ Proactively commit/push/branch
  • ❌ Suggest git operations

Branch Pattern: <type>/<description> (e.g., feat/add-gemini-support, fix/npm-install-error)

Commit Message Format: Conventional Commits (feat:, fix:, refactor:, test:, docs:, chore:)

Rationale: Git affects version control history. Only perform when explicitly requested.

If Unsure: Ask user for clarification

Git Details: .codemie/guides/standards/git-workflow.md

Environment Policy

MANDATORY RULE: No activation needed (Node.js environment)

Why: CodeMie Code is a Node.js CLI tool that runs in the system Node.js environment

Requirements:

  • Node.js >=20.0.0 installed
  • npm bundled with Node.js
  • No virtual environment or activation step

How to Verify: node --version should show >=20.0.0

Alternative: Use nvm (Node Version Manager) for managing Node.js versions

Rule of Thumb: If commands fail with "command not found", check Node.js installation and PATH

Recovery: See Troubleshooting

Detail: .codemie/guides/development/development-practices.md

Shell Environment Policy

MANDATORY RULE: Use bash/Linux commands ONLY

Requirements:

  • βœ… Bash/shell syntax for all commands
  • βœ… Linux-compatible commands
  • ❌ No Windows commands (PowerShell, cmd.exe)

Rationale: Ensures consistency across development environments (macOS, Linux, Windows WSL)


🎯 REMEMBER

Critical Workflow

  1. ⚑ Read Instant Start
  2. βœ… Run Self-Check (check confidence level)
  3. πŸ”„ Follow Execution Workflow (step-by-step with gates)
  4. πŸ“Š Use Pattern Quick Reference (fast lookups)
  5. πŸ” Track Success Indicators (am I on track?)
  6. βœ… Validate before delivery (all checks must pass)

Critical Rules (Check EVERY Time)

  • 🚨 Check Guides First: ALWAYS check relevant guides BEFORE searching codebase
  • 🚨 Testing: Only when explicitly requested
  • 🚨 Git: Only when explicitly requested
  • 🚨 Environment: No activation needed (Node.js >=20.0.0)
  • 🚨 Shell: Bash/Linux only

Decision Making Framework

  1. Parse: Use Task Classifier to identify keywords β†’ guides β†’ complexity
  2. Confidence: Am I 80%+ confident? NO β†’ Load P0 guides
  3. Load: P0 (required) first, then P1 (optional) only if needed
  4. Execute: Apply patterns, follow critical rules, track success indicators
  5. Validate: All checks must pass before delivery
  6. Stuck?: Check Troubleshooting, load more guides, or ask user

Quality Standards (Non-Negotiable)

  • No hardcoded secrets (use environment variables or CredentialStore)
  • No placeholders/TODOs in delivered code
  • All imports must use .js extensions
  • Security: sanitize logs, validate paths, encrypt credentials
  • Architecture: follow 5-layer pattern (CLI β†’ Registry β†’ Plugin β†’ Core β†’ Utils)
  • Error handling: use specific error classes with context
  • Type safety on all exported functions (explicit return types)
  • Specific exception handling (use try/catch with error context)

When to Ask User

  • Ambiguous requirements: Multiple valid approaches possible
  • Low confidence: < 80% after reading P0+P1 guides
  • Missing information: Need clarification on scope/approach
  • High complexity: Task involves architectural decisions
  • Policy unclear: Unsure if testing/git/other policy applies

Confidence Calibration

  • 90%+ confident: Proceed with execution, minimal guide lookup
  • 80-89% confident: Review quick reference tables, proceed
  • 70-79% confident: Load P0 guides, then re-assess
  • < 70% confident: Load P0+P1 guides, ask user if still unclear

Production Ready: Deliver complete, tested, secure solutions without shortcuts.

Questions? Always better to ask than assume - ask for clarification when unsure.

RTK (Rust Token Killer) - Token-Optimized Commands

Golden Rule

Always prefix commands with rtk. If RTK has a dedicated filter, it uses it. If not, it passes through unchanged. This means RTK is always safe to use.

Important: Even in command chains with &&, use rtk:

# ❌ Wrong
git add . && git commit -m "msg" && git push

# βœ… Correct
rtk git add . && rtk git commit -m "msg" && rtk git push

RTK Commands by Workflow

Build & Compile (80-90% savings)

rtk cargo build         # Cargo build output
rtk cargo check         # Cargo check output
rtk cargo clippy        # Clippy warnings grouped by file (80%)
rtk tsc                 # TypeScript errors grouped by file/code (83%)
rtk lint                # ESLint/Biome violations grouped (84%)
rtk prettier --check    # Files needing format only (70%)
rtk next build          # Next.js build with route metrics (87%)

Test (90-99% savings)

rtk cargo test          # Cargo test failures only (90%)
rtk vitest run          # Vitest failures only (99.5%)
rtk playwright test     # Playwright failures only (94%)
rtk test <cmd>          # Generic test wrapper - failures only

Git (59-80% savings)

rtk git status          # Compact status
rtk git log             # Compact log (works with all git flags)
rtk git diff            # Compact diff (80%)
rtk git show            # Compact show (80%)
rtk git add             # Ultra-compact confirmations (59%)
rtk git commit          # Ultra-compact confirmations (59%)
rtk git push            # Ultra-compact confirmations
rtk git pull            # Ultra-compact confirmations
rtk git branch          # Compact branch list
rtk git fetch           # Compact fetch
rtk git stash           # Compact stash
rtk git worktree        # Compact worktree

Note: Git passthrough works for ALL subcommands, even those not explicitly listed.

GitHub (26-87% savings)

rtk gh pr view <num>    # Compact PR view (87%)
rtk gh pr checks        # Compact PR checks (79%)
rtk gh run list         # Compact workflow runs (82%)
rtk gh issue list       # Compact issue list (80%)
rtk gh api              # Compact API responses (26%)

JavaScript/TypeScript Tooling (70-90% savings)

rtk pnpm list           # Compact dependency tree (70%)
rtk pnpm outdated       # Compact outdated packages (80%)
rtk pnpm install        # Compact install output (90%)
rtk npm run <script>    # Compact npm script output
rtk npx <cmd>           # Compact npx command output
rtk prisma              # Prisma without ASCII art (88%)

Files & Search (60-75% savings)

rtk ls <path>           # Tree format, compact (65%)
rtk read <file>         # Code reading with filtering (60%)
rtk grep <pattern>      # Search grouped by file (75%)
rtk find <pattern>      # Find grouped by directory (70%)

Analysis & Debug (70-90% savings)

rtk err <cmd>           # Filter errors only from any command
rtk log <file>          # Deduplicated logs with counts
rtk json <file>         # JSON structure without values
rtk deps                # Dependency overview
rtk env                 # Environment variables compact
rtk summary <cmd>       # Smart summary of command output
rtk diff                # Ultra-compact diffs

Infrastructure (85% savings)

rtk docker ps           # Compact container list
rtk docker images       # Compact image list
rtk docker logs <c>     # Deduplicated logs
rtk kubectl get         # Compact resource list
rtk kubectl logs        # Deduplicated pod logs

Network (65-70% savings)

rtk curl <url>          # Compact HTTP responses (70%)
rtk wget <url>          # Compact download output (65%)

Meta Commands

rtk gain                # View token savings statistics
rtk gain --history      # View command history with savings
rtk discover            # Analyze Claude Code sessions for missed RTK usage
rtk proxy <cmd>         # Run command without filtering (for debugging)
rtk init                # Add RTK instructions to CLAUDE.md
rtk init --global       # Add RTK to ~/.claude/CLAUDE.md

Token Savings Overview

Category Commands Typical Savings
Tests vitest, playwright, cargo test 90-99%
Build next, tsc, lint, prettier 70-87%
Git status, log, diff, add, commit 59-80%
GitHub gh pr, gh run, gh issue 26-87%
Package Managers pnpm, npm, npx 70-90%
Files ls, read, grep, find 60-75%
Infrastructure docker, kubectl 85%
Network curl, wget 65-70%

Overall average: 60-90% token reduction on common development operations.