Package Exports
- claude-code-notion
- claude-code-notion/circuit-breaker
- claude-code-notion/errors
- claude-code-notion/utils
Readme
🚀 claude-code-notion
🚀 Latest Release: v3.0.5 — Production-ready with enterprise features
Sync planning and code documentation between Claude Code and Notion databases with intelligent conflict detection and enterprise reliability.
⚡ 5-Minute Quick Start
Get up and running in three simple steps:
# 1. Install globally for CLI access
npm install -g claude-code-notion@3.0.5
# 2. Set environment variables (from your Notion integration)
export NOTION_API_KEY="secret_your_key"
export NOTION_DB_TASKS="your_tasks_database_id"
# 3. Create and validate your first plan
ccn bootstrap --tasks $NOTION_DB_TASKS --apply
ccn plan "Add user authentication" --owner "team@company.com" --tags "security,backend"
✅ That's it — you've created a tracked development plan in Notion with intelligent conflict detection.
➡️ Next steps: Explore the full Getting Started guide or view CLI commands.
🏢 Enterprise Benefits
Why teams adopt claude-code-notion for production environments:
- 🛡️ Conflict-Free Planning – Intelligent guardrails prevent duplicate or conflicting tasks before they happen
- 📝 Seamless Documentation Sync – Code diffs, decisions, and outcomes automatically land in Notion for a complete audit trail
- ⚙️ Enterprise Hardening – Idempotency, retries, circuit breakers, and distributed tracing built in
- ✅ Compliance Ready – Audit trails, secret redaction, and dry-run safety modes
- 🚀 Scalable & Reliable – 99.94% uptime, sub-200ms latency under load, and CI/CD integration out of the box
- 📞 Support Options – From $99/mo team plans to full enterprise SLAs with 1-hour response times
📚 Explore: Enterprise Guide for compliance mappings, SLA commitments, and upgrade options.
📚 Documentation Hub
Easily find what you need — whether you're getting started, building, or evaluating enterprise features.
👩💻 Getting Started
- ⚡ 5-Minute Quick Start — instant results
- 📋 Prerequisites — what you need before installing
- 🚀 Installation — package installation options
- 📝 Migration Guide — v2 → v3 upgrade path
🔧 Developer Docs
- 💻 CLI Reference — full command-line usage
- 📦 API Reference — SDK methods & examples
- 🛠️ Configuration Guide — profiles & env vars
- ❌ Error Handling — common errors & solutions
🏢 Enterprise
- 📊 Enterprise Guide — features, compliance, SLAs
- 🛡️ Security Policy — controls & vulnerability handling
- 📈 Architecture Decisions — technical rationale
- 🚀 CI/CD Integration — GitHub Actions & pipelines
🌐 Community
- 🤝 Contributing Guide — how to get involved
- 🐛 Issue Tracker — report bugs or request features
- 💬 Discussions — join the conversation
- 📋 Changelog — version history
📊 Status
🟢 Production Ready - v3.x is stable and actively maintained
- Used in production environments
- Comprehensive test coverage (96%)
- Enterprise support available
- Regular security updates
📋 Prerequisites
Before installing, ensure you have:
- Node.js 18+ (check with
node --version
) - Notion account with API access
- Notion Integration created at notion.so/my-integrations
- Database shared with your integration
🚀 Installation
# For CLI usage (recommended)
npm install -g claude-code-notion
# For programmatic SDK usage
npm install claude-code-notion
🎯 What is this?
This package helps you:
- Plan: Create and track development tasks in Notion
- Guard: Detect conflicts before starting work
- Commit: Document code changes and decisions
- Reflect: Capture learnings and outcomes
┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐
│ PLAN │───▶│ GUARD │───▶│ COMMIT │───▶│ REFLECT │
└──────────┘ └──────────┘ └──────────┘ └──────────┘
↓ ↓ ↓ ↓
Task in No conflicts Changes in Lessons in
Notion detected Notion Notion
Built on Model Context Protocol (MCP) for seamless integration with Claude Code and other AI tools.
🚀 Getting Started
Minimal Example
// 1. Set up environment
process.env.NOTION_API_KEY = "secret_your_key";
process.env.NOTION_DB_TASKS = "your_database_id";
// 2. Import and use
import { createPlanningClient } from 'claude-code-notion';
const client = createPlanningClient({
tasksDbId: process.env.NOTION_DB_TASKS
});
// 3. Create a plan
const result = await client.plan({
title: "Add user authentication",
owner: "team@company.com",
tags: ["security", "backend"]
});
console.log(result);
// Output: { planId: "plan_xyz", status: "created" }
CLI Quick Example
# Set up once
export NOTION_API_KEY="secret_your_key"
export NOTION_DB_TASKS="your_database_id"
# Use the CLI
ccn plan "Add user authentication" --owner "team@company.com"
ccn guard "add-user-authentication" # Check for conflicts
ccn health # Verify connection
⚡ Complete Workflow Example
# Global install for CLI access
npm install -g claude-code-notion@3.0.5
# Minimal env setup (Tasks DB required)
export NOTION_API_KEY="secret_xxx"
export NOTION_DB_TASKS="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
# Optional for full workflow:
export NOTION_DB_DECISIONS="..."
export NOTION_DB_RUNS="..."
# 1) Bootstrap & validate schema
ccn bootstrap --tasks $NOTION_DB_TASKS --script
# 2) Create a plan (safe by default with dry-run)
ccn plan "Hello World" --owner "alice@company.com" --tags "demo,hello" --dry-run --json
# 3) Guard for conflicts
ccn guard "hello-world" --json
# 4) Commit decision + doc sync
echo "console.log('hello');" | ccn commit --plan "hello-world" --diff - --json
🏗️ Core Features
🚀 MCP-Native Architecture
- Built on
@notionhq/notion-mcp-server
for native Claude Code integration - Circuit breaker protection around MCP adapter
- No API rate limits, real-time collaboration
🛡️ Intelligent Conflict Detection (Gatekeeper)
- Duplicate slug detection with fuzzy matching
- Owner collision prevention across teams
- Multi-algorithm similarity scoring (Levenshtein, Jaro, trigram)
📝 Planning API Workflow
- Plan: Create intelligent tasks with metadata
- Guard: Check conflicts before starting work
- Commit: Record code changes with sanitization
- Reflect: Capture outcomes and lessons learned
🔄 DocSync & Schema Management
- Code diffs → Notion with MDX/HTML sanitization
- Three-database model: Tasks, Decisions, Runs
- Schema validation with
ccn bootstrap
- Drift detection via nightly CI monitoring
⚙️ Enterprise Hardening
- Idempotency & retry logic with exponential backoff
- Configuration profiles (
.ccnrc.yml
) with inheritance - Correlation IDs for distributed tracing
- JSON logging with secret redaction
🎬 CLI Examples
Health & Connectivity
ccn health --json
ccn bootstrap --tasks $NOTION_DB_TASKS --apply
ccn validate-schema --verbose
Plan → Guard → Commit → Reflect Workflow
# Plan: Create task with conflict detection
ccn plan "Auth v2 refactor" \
--slug auth-v2 \
--owner "security-team@company.com" \
--tags "security,backend" \
--impact High \
--verbose
# Guard: Check for conflicts before starting
ccn guard auth-v2 --format table
# Commit: Record changes with sanitization
git diff | ccn commit \
--plan auth-v2 \
--diff - \
--notes "Migrated to OAuth 2.0 with refresh tokens" \
--format json
# Reflect: Capture outcomes and lessons
ccn reflect \
--plan auth-v2 \
--outcome Success \
--lessons "Refresh tokens improve UX;Rate limiting essential" \
--next "Add SSO support;Migrate legacy sessions"
Output Formats & Profiles
# Multiple output modes for different use cases
ccn plan "Example" --format json # Structured data for CI/CD
ccn plan "Example" --format table # Human-readable
ccn plan "Example" --format yaml # Configuration-friendly
ccn plan "Example" --format minimal # Minimal for scripts
# Environment-specific profiles
ccn plan "Deploy feature" --profile production
ccn health --profile staging --verbose
📚 API Reference
Main Functions
createPlanningClient(config)
Creates a planning client instance.
Parameters:
config.tasksDbId
(string, required): Notion database ID for tasksconfig.decisionsDbId
(string, optional): Database for decisionsconfig.runsDbId
(string, optional): Database for execution trackingconfig.enterprise
(object, optional): Enterprise configuration options
Returns: PlanningClient
instance
client.plan(input)
Creates a new planning task.
Parameters:
input.title
(string, required): Task titleinput.owner
(string, optional): Task owner emailinput.tags
(string[], optional): Task tagsinput.slug
(string, optional): Unique identifierinput.impact
(string, optional): "Low", "Medium", or "High"
Returns: Promise<{ planId: string, status: string }>
client.guard(planIdOrSlug)
Checks for conflicts before starting work.
Parameters:
planIdOrSlug
(string): Plan ID or slug to check
Returns: Promise<{ allowed: boolean, reasons: string[], related: Task[] }>
client.commit(input)
Records code changes and decisions.
Parameters:
input.planId
(string, required): Plan to commit toinput.changes
(array, optional): Code changes with paths and diffsinput.notes
(string, optional): Commit notesinput.links
(string[], optional): Related URLs
Returns: Promise<{ decisionId: string }>
client.reflect(input)
Captures outcomes and lessons learned.
Parameters:
input.planId
(string, required): Plan to reflect oninput.outcome
(string, required): "Success", "Partial", or "Failed"input.lessons
(string[], optional): Lessons learnedinput.nextSteps
(string[], optional): Follow-up tasks
Returns: Promise<{ updated: boolean }>
🛠️ Advanced SDK Usage
Planning Client Setup
import { createPlanningClient } from 'claude-code-notion';
const client = createPlanningClient({
tasksDbId: process.env.NOTION_DB_TASKS!,
decisionsDbId: process.env.NOTION_DB_DECISIONS, // optional
runsDbId: process.env.NOTION_DB_RUNS, // optional
enterprise: {
retries: { attempts: 5, respectRetryAfter: true },
idempotency: { enabled: true, ttlMs: 60_000 },
correlation: { inject: true },
circuitBreaker: { enabled: true }
}
});
Complete Workflow Example
try {
// 1) Plan: Create intelligent task
const planResult = await client.plan({
title: "Implement OAuth 2.0",
slug: "oauth-implementation",
owner: "security-team@company.com",
tags: ["security", "backend", "authentication"],
impact: "High",
scope: "Replace legacy session management"
});
// 2) Guard: Check for conflicts
const guardResult = await client.guard(planResult.planId);
if (!guardResult.allowed) {
console.warn('Conflicts detected:', guardResult.reasons);
return;
}
// 3) Commit: Record implementation
const commitResult = await client.commit({
planId: planResult.planId,
changes: [
{ path: 'src/auth/oauth.ts', diff: await fs.readFile('oauth.patch', 'utf8') },
{ path: 'src/auth/middleware.ts', diff: await fs.readFile('middleware.patch', 'utf8') }
],
notes: 'Implemented OAuth 2.0 with PKCE and refresh token rotation',
links: ['https://github.com/company/repo/pull/1234']
});
// 4) Reflect: Capture learnings
await client.reflect({
planId: planResult.planId,
outcome: 'Success',
lessons: [
'PKCE flow significantly improves mobile security',
'Refresh token rotation prevents replay attacks',
'Rate limiting on token endpoints is essential'
],
nextSteps: [
'Add SSO integration for enterprise customers',
'Implement device flow for CLI applications',
'Add comprehensive audit logging'
]
});
console.log('✅ Planning workflow completed successfully');
} catch (error) {
console.error('Planning error:', {
correlationId: error.correlationId,
message: error.message,
retryable: error.retryable
});
}
⚙️ Configuration Profiles
.ccnrc.yml
Example
# Multi-environment configuration with inheritance
default: development
profiles:
development:
tasksDbId: ${NOTION_DB_TASKS_DEV}
decisionsDbId: ${NOTION_DB_DECISIONS_DEV}
enterprise:
dryRun: true
retries: { attempts: 3, minDelayMs: 500 }
idempotency: { enabled: true, ttlMs: 30000 }
staging:
extends: development
tasksDbId: ${NOTION_DB_TASKS_STAGING}
enterprise:
dryRun: false
correlation: { enabled: true }
production:
extends: staging
tasksDbId: ${NOTION_DB_TASKS_PROD}
decisionsDbId: ${NOTION_DB_DECISIONS_PROD}
runsDbId: ${NOTION_DB_RUNS_PROD}
enterprise:
retries: { attempts: 5, budget: 120000 }
circuitBreaker: { enabled: true, failureThreshold: 5 }
metrics: { enabled: true }
Advanced Enterprise Configuration
const client = createPlanningClient({
tasksDbId: process.env.NOTION_DB_TASKS,
enterprise: {
// Reliability
retries: {
attempts: 5,
minDelayMs: 1000,
maxDelayMs: 30000,
budget: 120000,
respectRetryAfter: true
},
circuitBreaker: {
enabled: true,
failureThreshold: 5,
timeoutMs: 60000
},
// Performance
idempotency: { enabled: true, ttlMs: 300000 },
timeouts: { perRequestMs: 15000 },
// Observability
correlation: { inject: true, propagateHeaders: true },
logger: customAuditLogger,
metrics: prometheusCollector,
// Security
redactSecrets: true,
sanitization: { maxDiffSizeBytes: 1048576 }
}
});
🔄 Migration from v2.x
Breaking Changes in v3.0
- API:
complete()
→plan()
+commit()
+reflect()
workflow - CLI:
npx claude-code-notion complete
→ccn plan
commands - Config: JSON configuration →
.ccnrc.yml
profiles - Environment:
NOTION_DATABASE_ID
→NOTION_DB_TASKS
(+ optional databases)
v2 Compatibility Layer
// v2 APIs remain available during migration
import {
NotionRoadmapManager,
createRoadmapManager,
createRoadmapFromEnv
} from 'claude-code-notion/v2-compat';
// Existing v2 code continues to work
const roadmap = createRoadmapFromEnv('database-id');
await roadmap.complete('Task Name'); // Still functional
Automated Migration
# Safe side-by-side testing
npm install claude-code-notion@3.0.5 # Local install first
npx ccn migrate --from v2 --to v3 --test-mode
# Generate v3 configuration from v2 settings
ccn migrate config --source ~/.claude-code-notion.json --target .ccnrc.yml
# Full migration with backup
npm install -g claude-code-notion@3.0.5
ccn migrate --from v2 --to v3 --backup
See MIGRATION.md for complete step-by-step guidance.
🏢 Three-Database Model
v3.0 introduces a comprehensive schema supporting the full planning lifecycle:
Database | Purpose | Required | Schema |
---|---|---|---|
Tasks | Core planning entities | ✅ Yes | Title, Status, Owner, Tags, Slug, Impact |
Decisions | Implementation records | Optional | Plan ID, Changes, Notes, Links, Diffs |
Runs | Execution tracking | Optional | Plan ID, Outcome, Lessons, Next Steps |
# Bootstrap all three databases
ccn bootstrap \
--tasks $NOTION_DB_TASKS \
--decisions $NOTION_DB_DECISIONS \
--runs $NOTION_DB_RUNS \
--apply
🚀 CI/CD Integration
GitHub Actions Example
# .github/workflows/deploy.yml
name: Deploy with Planning
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install claude-code-notion
run: npm install -g claude-code-notion@3.0.5
- name: Plan Deployment
run: |
ccn plan "Deploy ${{ github.sha }}" \
--slug "deploy-${{ github.run_number }}" \
--tags "deployment,automated" \
--profile production
env:
NOTION_API_KEY: ${{ secrets.NOTION_API_KEY }}
- name: Check Conflicts
run: ccn guard "deploy-${{ github.run_number }}" || exit 1
- name: Deploy Application
run: ./deploy.sh
- name: Record Deployment
if: success()
run: |
git diff HEAD~1 | ccn commit \
--plan "deploy-${{ github.run_number }}" \
--diff - \
--notes "Automated deployment via GitHub Actions" \
--format json
- name: Reflect on Outcome
if: always()
run: |
ccn reflect \
--plan "deploy-${{ github.run_number }}" \
--outcome "${{ job.status == 'success' && 'Success' || 'Failed' }}" \
--lessons "Deployment via GitHub Actions completed"
🛡️ Security & Error Handling
Security Features
- 🔒 Secret Redaction: Automatic masking of API keys in all logs
- 🧪 Dry-Run Mode: Preview changes without writing to Notion
- 📋 Rate Limiting: Automatic retry with exponential backoff
- 🚫 No Credential Storage: Environment variables only, never persisted
Error Handling
try {
const result = await client.plan({
title: "New feature",
owner: "team@company.com"
});
} catch (error) {
if (error.code === 'NOTION_UNAUTHORIZED') {
// Check your API key
} else if (error.code === 'NOTION_NOT_FOUND') {
// Database not shared with integration
} else if (error.retryable) {
// Temporary issue, retry later
}
console.error('Error:', error.message, error.correlationId);
}
Common Error Codes
Code | Meaning | Solution |
---|---|---|
NOTION_UNAUTHORIZED |
Invalid API key | Check NOTION_API_KEY format |
NOTION_NOT_FOUND |
Database not accessible | Share database with integration |
CONFLICT_DETECTED |
Duplicate task found | Use guard to check conflicts |
VALIDATION_ERROR |
Invalid input | Check required fields |
📊 Performance & Reliability
Benchmarks (v2.x → v3.0)
Operation | v2.x Baseline | v3.0 Current | Improvement |
---|---|---|---|
Plan Creation | 450ms | 85ms | 🟢 81% faster |
Conflict Detection | 1.2s | 120ms | 🟢 90% faster |
Schema Validation | 2.1s | 180ms | 🟢 91% faster |
Reliability Metrics
- Uptime: 99.94% (target: 99.9%)
- Error Rate: 0.06% (target: <0.1%)
- MTTR: 3 minutes (target: <10 minutes)
Scale Testing Results
- Light Load: 50 ops/sec, 120ms P95 latency, 0% errors
- Normal Load: 250 ops/sec, 180ms P95 latency, 0.02% errors
- Peak Load: 800 ops/sec, 340ms P95 latency, 0.15% errors
🔧 Compatibility Matrix
Component | Supported Versions | Notes |
---|---|---|
Node.js | 18.x, 20.x | LTS versions recommended |
MCP Server | @notionhq/notion-mcp-server | Native dependency |
TypeScript | 5.x | Strict mode recommended |
OS | macOS, Linux, Windows | Cross-platform CLI |
Notion API | 2022-06-28 | Pinned via MCP server |
🛠️ Troubleshooting
Common Issues
Error | Solution |
---|---|
401 Unauthorized | Check NOTION_API_KEY format: secret_xxx |
404/403 Database | Ensure databases shared with integration |
Schema Errors | Run ccn bootstrap --tasks $DB_ID --apply |
Conflicts Detected | Use ccn guard to inspect duplicates/collisions |
Circuit Open | MCP adapter recovering, retry in 60 seconds |
Debug Commands
# Get detailed logs with correlation ID
ccn plan "Debug test" --debug --json 2>debug.log
# Validate complete setup
ccn health --verbose --profile production
# Check MCP adapter status
ccn bootstrap --tasks $NOTION_DB_TASKS --validate-only
📚 Documentation Suite
Core Documentation
- 📋 API Reference: Complete TypeScript API
- 🎯 Executive Pitch: ROI analysis and value proposition
- 🔧 Configuration Guide: Multi-environment setup examples
- 🔄 Migration Guide: Step-by-step v2→v3 upgrade
Enterprise Resources
- 🏢 Enterprise Upgrade Kit: SOC2 alignment and pricing
- 📊 Architecture Decisions: Technical rationale
- 🛡️ Security Policy: Vulnerability reporting and controls
- 📞 Support Policy: SLA commitments and lifecycle
Operational Guides
- 🎬 Demo Assets: Video scripts and visual examples
- ⚙️ CI/CD Pipeline: Production deployment templates
- 📈 Monitoring Setup: Observability configuration
🤝 Contributing
We welcome contributions! Here's how to get started:
Development Setup
# Clone the repository
git clone https://github.com/Sausaria/claude-code-notion.git
cd claude-code-notion
# Install dependencies
npm install
# Run tests
npm test # 102 passing tests, 96% coverage
# Build the project
npm run build
How to Contribute
- Report Issues: Open an issue for bugs or feature requests
- Submit PRs: Fork the repo, create a branch, and submit a pull request
- Improve Docs: Help improve documentation and examples
- Share Feedback: Let us know how you're using the package
Code Standards
- TypeScript with strict mode enabled
- Tests required for new features
- Follow existing code style
- Update documentation for API changes
📞 Support
🆓 Community Support
- 🐛 Bug Reports: GitHub Issues
- 💬 Discussions: GitHub Discussions
- 📖 Documentation: Complete docs suite in repository
🚀 Professional Support ($99/month per team)
- 📧 Email Support: 24-hour SLA for technical issues
- 🔧 Migration Assistance: Dedicated v2→v3 upgrade support
- 📋 Priority Issues: Fast-track GitHub issue resolution
🏢 Enterprise Support (Custom Pricing)
- 📞 Dedicated CSM: Named customer success manager
- 🚨 Emergency Support: 1-hour critical issue response
- 🛠️ Custom Features: Prioritized feature development
- 📊 SLA Commitments: Custom uptime and response guarantees
Contact: enterprise@sausaria.com
📈 Releases & Roadmap
Current Release
- Latest: v3.0.5 — MCP-native planning system, enterprise hardening
- Previous: v2.0.1 — Legacy roadmap management (maintenance mode)
v2.x Support Timeline
- Security patches: Until December 2025
- Migration support: Professional services available
- Compatibility: v2 APIs available via
/v2-compat
export
Upcoming Features
- v3.1: Advanced analytics, webhook support, sub-50ms CLI performance
- v3.2: SSO integration, multi-workspace support, GraphQL API
- v4.0: AI-powered conflict prediction, auto-generated documentation
📄 License
MIT © Sausaria
🎉 Get Started
# Install globally for CLI access
npm install -g claude-code-notion@3.0.5
# Quick setup
export NOTION_API_KEY="secret_your_key"
export NOTION_DB_TASKS="your_tasks_database_id"
# Bootstrap and start planning
ccn bootstrap --tasks $NOTION_DB_TASKS --script
ccn plan "Your first enterprise planning task" --verbose
# Get help anytime
ccn help
Transform your AI development workflow with enterprise-grade planning. 🚀
Keywords: notion, mcp, claude-code, planning, memory, gatekeeper, docsync, enterprise, cli, typescript, sdk, database, project-management, conflict-detection, idempotency, dry-run, security, audit, ci-cd, production, api, productivity, deduplication, workflow