@kb-labs/devkit
v1.0.0
Published
Shared developer toolkit for KB Labs projects: TS/ESLint/Prettier/Vitest/Tsup presets and reusable GitHub Actions.
Readme
KB Labs DevKit (@kb-labs/devkit)
A cohesive set of presets and configurations for the
@kb-labsecosystem. TypeScripttsconfig, ESLint, Prettier, Vitest, Tsup, and reusable GitHub Actions. The goal is to maximize automation, enforce consistent standards, and eliminate copy-paste across new projects.
🎯 Vision
KB Labs DevKit provides a cohesive set of presets and configurations for the @kb-labs ecosystem: TypeScript tsconfig, ESLint, Prettier, Vitest, Tsup, and reusable GitHub Actions. The goal is to maximize automation, enforce consistent standards, and eliminate copy-paste across new projects.
The project solves the problem of inconsistent tooling configurations across KB Labs projects by providing a single source of truth for all development tooling. Instead of copying configs between projects, developers can simply extend DevKit presets, ensuring consistency and reducing maintenance overhead.
This project is the foundation for all KB Labs tooling and is used by every project in the ecosystem. It includes a powerful sync system that automatically keeps projects up-to-date with the latest DevKit assets.
🚀 Quick Start
Installation
pnpm add -D @kb-labs/devkit
# or
npm i -D @kb-labs/devkitBasic Setup
Node Project (TS + Tsup + Vitest + ESLint + Prettier)
tsconfig.json:
{
"extends": "@kb-labs/devkit/tsconfig/node.json"
}tsup.config.ts:
import config from '@kb-labs/devkit/tsup/node.js'
export default configvitest.config.ts:
import config from '@kb-labs/devkit/vitest/node.js'
export default configeslint.config.js (ESLint 9 flat config):
import config from '@kb-labs/devkit/eslint/node.js'
export default config.prettierrc.json:
"@kb-labs/devkit/prettier/index.json"package.json (example):
{
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"import": "./dist/index.js",
"types": "./dist/index.d.ts"
}
},
"scripts": {
"build": "tsup",
"lint": "eslint .",
"test": "vitest",
"format": "prettier -w ."
}
}Build Convention: All KB Labs packages use
"build": "tsup"as the standard convention. Thetsuppreset handles both JavaScript bundling and TypeScript declaration generation (dts: true). TypeScripttsconfig.jsonwithreferencesis for IDE support and type-checking only, not for build orchestration. See ADR-0009 for details.
Workspace Aliases
For monorepos, DevKit ships with kb-devkit-paths – a generator that scans the pnpm workspace and writes tsconfig.paths.json with all @kb-labs/* aliases. Recommended setup:
{
"extends": [
"@kb-labs/devkit/tsconfig/node.json",
"./tsconfig.paths.json"
],
"compilerOptions": {
"baseUrl": "."
}
}Add scripts to your package.json so aliases stay fresh whenever DevKit sync runs:
{
"scripts": {
"devkit:paths": "pnpm exec kb-devkit-paths",
"predevkit:sync": "pnpm devkit:paths",
"predevkit:sync:ci": "pnpm devkit:paths",
"predevkit:check": "pnpm devkit:paths",
"predevkit:force": "pnpm devkit:paths"
}
}Then generate aliases once:
pnpm run devkit:pathsRepository Synchronization
Sync DevKit assets into your project:
# Run sync (creates/updates files)
npx kb-devkit-sync
# Check for drift without making changes
npx kb-devkit-sync --check
# Force overwrite existing files
npx kb-devkit-sync --forceNaming Convention Validation
Validate that all packages follow the Pyramid Rule (@kb-labs/{repo}-{package}):
# Validate naming convention
npx kb-devkit-validate-naming
# Run from monorepo root (validates all kb-labs-* repos)
cd /path/to/kb-labs
npx kb-devkit-validate-namingOutput:
- ✅ Lists all valid packages
- ❌ Reports violations with specific suggestions
- Exits with code 1 if violations found (CI-friendly)
See docs/naming-convention.md for the complete Pyramid Rule guide.
Import Checker
Check for broken imports, unused dependencies, and circular dependencies across all packages:
# Check all packages for import issues
npx kb-devkit-check-imports
# Check specific package
npx kb-devkit-check-imports --package core-cli
# Show all packages (including clean ones)
npx kb-devkit-check-imports --verbose
# Auto-fix unused dependencies (coming soon)
npx kb-devkit-check-imports --fixWhat it checks:
Broken imports (🔴): Files that are imported but don't exist
- Detects typos in import paths
- Finds missing files after refactoring
- Reports exact file and line number
Missing workspace dependencies (🟡): Packages used in code but not in
package.json- Finds
@kb-labs/*imports not declared as dependencies - Shows which files use the missing package
- Critical for proper workspace resolution
- Finds
Unused dependencies (🟠): Dependencies in
package.jsonbut never imported- Excludes build tools (
typescript,tsup,vitest, etc.) - Excludes type definitions (
@types/*) - Helps keep dependencies clean
- Excludes build tools (
Circular dependencies (🔄): Packages that depend on each other in a cycle
- Detects circular dependency chains
- Shows full cycle path (A → B → C → A)
- Can cause build and runtime issues
Output:
- ✅ Clean packages (only with
--verbose) - ❌ Packages with issues
- 📊 Summary with counts by issue type
- Exits with code 1 if issues found (CI-friendly)
Example output:
🔍 KB Labs Import Checker
Found 188 package(s) to check
❌ @kb-labs/core-cli
kb-labs-core/packages/core-cli
🔴 Broken imports (2):
src/commands/run.ts:15
└─ Cannot resolve: ../utils/missing-file
🟡 Missing workspace dependencies (1):
@kb-labs/core-config
└─ Used in 3 file(s)
🟠 Unused dependencies (2):
lodash
axios
🔄 Circular Dependencies (1):
1. @kb-labs/cli-core → @kb-labs/cli-commands → @kb-labs/cli-core
📊 Summary:
🔴 2 broken import(s)
🟡 1 missing workspace dep(s)
🟠 2 unused dependency(ies)
🔄 1 circular dependency cycle(s)Export Checker
Check for unused exports, dead code in public APIs, and package.json export inconsistencies:
# Check all packages for export issues
npx kb-devkit-check-exports
# Check specific package
npx kb-devkit-check-exports --package core-cli
# Include internal exports (more thorough)
npx kb-devkit-check-exports --strict
# Show all packages (including clean ones)
npx kb-devkit-check-exports --verboseWhat it checks:
Unused exports (🟠): Exports that are never imported by other packages
- Identifies dead code in public APIs
- Finds exports that can be safely removed
- Helps reduce API surface area
- Distinguishes between public (index.ts) and internal exports
Missing barrel exports (🟡): Files with exports not re-exported from index.ts
- Only shown in
--strictmode - Finds files that may need to be added to public API
- Or identifies files that should be marked as internal
- Only shown in
Inconsistent package.json exports (🔴): Exports field pointing to non-existent files
- Validates package.json
exportsfield - Finds broken export paths
- Critical for package consumers
- Validates package.json
Output:
- ✅ Clean packages (only with
--verbose) - ❌ Packages with unused exports
- 📊 Summary with counts by issue type
- Exits with code 1 if issues found (CI-friendly)
Example output:
📤 KB Labs Export Checker
Found 188 package(s) to check
❌ @kb-labs/core-cli
kb-labs-core/packages/core-cli
🟠 Unused exports (3):
src/index.ts
└─ oldFunction (public API)
└─ deprecatedUtil (public API)
src/internal/helpers.ts
└─ internalHelper (internal)
💡 These exports are never imported by other packages
💡 Consider removing them to reduce API surface
🔴 Inconsistent package.json exports (1):
"./utils" → ./dist/utils.js
└─ File does not exist
💡 Update package.json exports field to match actual files
📊 Summary:
🟠 3 unused export(s)
🔴 1 inconsistent package.json export(s)Duplicate Checker
Check for duplicate dependencies with different versions and code duplication patterns:
# Check for duplicate dependencies
npx kb-devkit-check-duplicates
# Include code duplication analysis
npx kb-devkit-check-duplicates --code
# Show detailed info (outdated deps, full package lists)
npx kb-devkit-check-duplicates --verboseWhat it checks:
- Duplicate dependencies (🔴): Same package with multiple versions
- Outdated common dependencies (🟡): Packages using older versions (with
--verbose) - Code duplication (🟠): Similar file names across packages (with
--code)
Structure Checker
Validate package structure, required files, and package.json fields:
# Check all packages
npx kb-devkit-check-structure
# Include recommendations
npx kb-devkit-check-structure --strict
# Check specific package
npx kb-devkit-check-structure --package core-cliWhat it checks:
- Missing critical files (package.json, src/, tsconfig.json, README.md)
- Missing package.json fields (name, version, type, exports, etc.)
- Structure issues (missing index.ts, tests in src/, missing scripts)
- Documentation quality (README length, missing sections)
- Configuration consistency (tsconfig using devkit presets)
Path Validator
Validate all paths and references in package.json, tsconfig.json, and dependencies:
# Check all paths
npx kb-devkit-check-paths
# Check specific package
npx kb-devkit-check-paths --package=cli-core
# JSON output for CI
npx kb-devkit-check-paths --jsonWhat it validates:
- Workspace dependencies:
workspace:*references to non-existent packages - Link references:
link:../pathpointing to non-existent directories - Package.json exports: Export paths pointing to non-existent files
- Bin scripts: Bin entries pointing to non-existent scripts
- Entry points:
main,module,typesfields pointing to missing files - Files field: Items in
filesarray that don't exist - tsconfig.json: Broken
extends,references, andpathsaliases
Severity levels:
- 🔴 Errors: Critical issues (broken links, missing workspace packages)
- ⚠️ Warnings: Build-dependent issues (
./dist/*files that needpnpm build)
Example output:
🔗 KB Labs Path Validator
📦 Missing Workspace Packages (2):
kb-labs-plugin/
@kb-labs/ai-docs-plugin
Workspace package "@kb-labs/setup-engine-operations" does not exist
🔗 Broken Link References (1):
kb-labs-ai-docs/
@kb-labs/ai-docs-plugin
Link path does not exist: ../../../kb-labs-setup-engine/packages/setup-operations
📊 Summary:
Packages checked: 91
❌ Errors: 107
⚠️ Warnings: 185Visualizer
Generate dependency graphs, statistics, and visualizations:
# Show all visualizations
npx kb-devkit-visualize
# Show dependency graph only
npx kb-devkit-visualize --graph
# Show package statistics
npx kb-devkit-visualize --stats
# Show dependency tree for package
npx kb-devkit-visualize --tree --package cli-coreWhat it shows:
- Dependency graph: Visual representation of dependencies
- Package statistics: By repository, most depended-on, largest packages
- Dependency tree: Hierarchical view with
--tree
Quick Statistics
Get comprehensive monorepo statistics and health scores:
# Show all statistics
npx kb-devkit-stats
# Show health score
npx kb-devkit-stats --health
# Output JSON for parsing
npx kb-devkit-stats --json
# Output Markdown table
npx kb-devkit-stats --mdWhat it shows:
- Overview: Total packages, repositories, files, LOC, size
- Dependencies: Workspace vs external, duplicates count
- By repository: Package count, LOC breakdown
- Health score: Grade A-F based on issues
- Largest packages: Top 5 by lines of code
Example output:
📊 KB Labs Monorepo Statistics
📦 Overview:
Packages: 90
Repositories: 18
Lines of Code: 226,514
Total Size: 6.22 MB
🔗 Dependencies:
Total: 1,085
Workspace: 340
External: 745
Duplicates: 30 ⚠️
💚 Health Score:
Score: 68/100 (Grade D)
Issues:
🔴 30 duplicate dependencies (-20)
🟡 12 packages missing README (-12)Dependency Auto-Fixer
Automatically fix common dependency issues and analyze dependency usage:
# Show dependency statistics
npx kb-devkit-fix-deps --stats
# Remove unused dependencies (dry-run first!)
npx kb-devkit-fix-deps --remove-unused --dry-run
npx kb-devkit-fix-deps --remove-unused
# Add missing workspace dependencies
npx kb-devkit-fix-deps --add-missing
# Align duplicate dependency versions
npx kb-devkit-fix-deps --align-versions
# Apply all fixes
npx kb-devkit-fix-deps --all
# Fix specific package only
npx kb-devkit-fix-deps --remove-unused --package=core-cli
# Show why dependencies were kept (debug mode)
npx kb-devkit-fix-deps --remove-unused --dry-run --verboseWhat it fixes:
- Removes unused dependencies: Safely removes deps not found in source code
- Scans
src/,test/,tests/,__tests__/,scripts/directories - Checks config files (
tsup.config.ts,vitest.config.ts, etc.) - Respects peer dependencies
- Scans
- Adds missing workspace deps: Adds
@kb-labs/*packages imported but not declared - Aligns duplicate versions: Picks most common version and aligns all packages
Statistics mode (--stats):
📊 Dependency Statistics
📦 Total packages: 91
📚 Total dependencies: 353
🔧 Total devDependencies: 586
🔗 Total peerDependencies: 4
🔝 Top 10 Most Used Dependencies:
1. tsup (91 packages)
2. typescript (84 packages)
3. @types/node (83 packages)
...Safety features:
- Always use
--dry-runfirst to preview changes - Excludes build tools (typescript, tsup, vitest, esbuild, vite, rimraf, etc.)
- Excludes testing tools (vitest, jest, playwright, @vitest/, @testing-library/)
- Excludes type definitions (@types/*)
- Excludes linting tools (eslint-, @eslint/, @typescript-eslint/, prettier-plugin-)
- Respects peer dependencies (won't remove if listed in peerDependencies)
- Use
--verboseto see why dependencies were kept - Sorts dependencies alphabetically after changes
Orphan packages analysis (--orphans):
Find packages that no other package depends on (potential dead code):
# Find orphan packages
npx kb-devkit-fix-deps --orphans
# JSON output for CI
npx kb-devkit-fix-deps --orphans --jsonOutput categorizes orphans into:
- ✅ CLI Entry Points - Expected orphans (entry points like @kb-labs/cli-bin)
- ✅ Plugin Packages - Usually standalone (@kb-labs/plugin-*, *-plugin)
- ✅ External Libraries - Consumed externally (@kb-labs/-core, ui-, etc.)
- ⚠️ Internal Packages - Review needed (might be dead code!)
Example output:
👻 Orphan Packages Analysis
📦 Total @kb-labs/* packages: 90
🔗 Packages with dependents: 70
👻 Orphan packages: 25
✅ CLI Entry Points (4) - Expected orphans:
@kb-labs/cli-bin
@kb-labs/analytics-cli
...
📦 Plugin Packages (6) - Usually standalone:
@kb-labs/ai-docs-plugin
...
📤 External/Library Packages (9) - Consumed externally:
@kb-labs/devlink-core
...
⚠️ Internal Packages Without Dependents (6) - Review needed:
kb-labs-shared/
@kb-labs/shared-boundaries
@kb-labs/shared-repo
@kb-labs/shared-textops
📊 Summary:
Expected orphans: 19
Review needed: 6CI Combo Tool
Run all DevKit checks in one command for CI/CD pipelines:
# Run all checks
npx kb-devkit-ci
# Skip specific checks
npx kb-devkit-ci --skip=exports,duplicates
# Run only specific checks
npx kb-devkit-ci --only=naming,imports
# JSON output for CI parsing
npx kb-devkit-ci --jsonChecks performed:
- ✅ Naming convention validation
- ✅ Import analysis (broken imports, unused deps, circular deps)
- ✅ Export analysis (unused exports, dead code)
- ✅ Duplicate dependencies
- ✅ Package structure validation
- ✅ Path validation (workspace deps, exports, bin)
- ✅ TypeScript types (dts generation, types field)
CI-friendly features:
- Exits with code 1 on failures
- JSON output for parsing
- Per-check timing information
- Summary with passed/failed counts
Example GitHub Actions integration:
name: DevKit Checks
on: [pull_request]
jobs:
devkit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run DevKit CI
run: npx kb-devkit-ci --json > devkit-report.json
- name: Upload Report
uses: actions/upload-artifact@v4
with:
name: devkit-report
path: devkit-report.jsonQA Runner
⚡ NEW: Comprehensive quality assurance with incremental builds
Run all quality checks across the entire monorepo (build, lint, type-check, tests):
# Run all QA checks
npx kb-devkit-qa
# Skip specific checks
npx kb-devkit-qa --skip-build --skip-tests
# JSON mode for AI agents
npx kb-devkit-qa --jsonWhat it checks:
- Build - All packages in correct layer order (13 layers, 125 packages)
- ⚡ Incremental: Only rebuilds when
src/is newer thandist/ - 🚀 Speed: ~10-20 seconds when up-to-date (vs 5-10 minutes full rebuild)
- ⚡ Incremental: Only rebuilds when
- Lint - ESLint on all packages
- Type Check - TypeScript type checking on all packages
- Tests - Vitest tests on all packages (with
--passWithNoTests)
Key features:
- ✅ Continues on errors (shows all failures, not just first)
- ✅ Progress indicators:
.= passed,F= failed,-= skipped (up-to-date) - ✅ Comprehensive summary report at the end
- ✅ JSON mode for CI/CD and AI agents
- ⚡ 30x faster with incremental builds
Example output:
🚀 KB Labs QA Runner
🔨 Building all packages in correct dependency order...
Found 13 layers to build
🔨 Building Layer 1/13 (21 packages)...
--------------------- (all skipped, up-to-date)
✅ Build complete: 0 passed, 0 failed, 100 skipped (up-to-date)
📊 QA Summary Report
✅ Build: 100 skipped (up-to-date)
❌ Lint: 70/125 passed (56%)
❌ Type Check: 60/125 passed (48%)
❌ Tests: 78/125 passed (62%)
Total: 208 passed, 167 failed, 100 skippedRoot commands (package.json):
pnpm qa # Run all checks
pnpm qa:quick # Skip tests
pnpm qa:full # With baseline comparisonHow incremental builds work:
- Compares modification times of
src/vsdist/ - Rebuilds only if source is newer than build output
- Skips packages that are already up-to-date
- First run builds all, subsequent runs ~20 seconds
JSON mode example:
{
"status": "failed",
"summary": {
"build": { "passed": 0, "failed": 0, "skipped": 100 },
"lint": { "passed": 70, "failed": 55, "skipped": 0 }
},
"failures": {
"lint": ["@kb-labs/cli", "@kb-labs/core", ...]
}
}Build Order Calculator
Calculate the correct build order for packages based on dependencies:
# Show sequential build order
npx kb-devkit-build-order
# Show parallel build layers
npx kb-devkit-build-order --layers
# Build order for specific package
npx kb-devkit-build-order --package=workflow-runtime
# Generate build script
npx kb-devkit-build-order --script > build.sh
npx kb-devkit-build-order --layers --script > build-parallel.sh
# JSON output
npx kb-devkit-build-order --jsonWhat it does:
- Builds dependency graph: Analyzes all workspace dependencies
- Topological sort: Determines correct build order using Kahn's algorithm
- Detects circular dependencies: Shows packages involved in cycles
- Parallel build layers: Groups packages that can build in parallel
- Generates build scripts: Creates executable bash scripts for automation
Example output:
📦 Build order for @kb-labs/workflow-runtime:
1. @kb-labs/cli-contracts
2. @kb-labs/shared-cli-ui
3. @kb-labs/core-sys
...
16. @kb-labs/workflow-runtime ⬅ targetWith --layers:
Layer 1 (15 packages):
@kb-labs/core-types
@kb-labs/cli-contracts
...
Layer 2 (23 packages):
@kb-labs/core-sys
@kb-labs/plugin-manifest
...
Total layers: 5
Max parallelism: 23 packagesCommand Health Checker
Automatically check all CLI commands in the ecosystem:
# Check all commands
npx kb-devkit-check-commands
# Quick check (faster)
npx kb-devkit-check-commands --fast
# Verbose output
npx kb-devkit-check-commands --verbose
# Custom timeout
npx kb-devkit-check-commands --timeout=10
# JSON output for CI
npx kb-devkit-check-commands --jsonWhat it checks:
- Command discovery: Finds all commands from plugin manifests
- Help output: Tests each command with
--help - Exit codes: Verifies commands exit with code 0
- Timeouts: Detects slow or hanging commands
- Error detection: Identifies broken commands with detailed errors
Example output:
🔍 KB Labs Command Health Checker
Found 107 commands to check
✅ Working commands (103):
kb plugins:list
kb workflow:run
...
❌ Broken commands (4):
kb ai:analyze --help
└─ Error: Cannot find module '@kb-labs/ai-core'
📊 Summary:
✅ 103 working (96%)
❌ 4 broken (4%)TypeScript Types Checker
Ensure all packages properly generate TypeScript declaration files:
# Check all packages for types generation
npx kb-devkit-check-types
# Auto-fix dts: false → dts: true
npx kb-devkit-check-types --fix
# Check specific package
npx kb-devkit-check-types --package=mind-engine
# Verbose output
npx kb-devkit-check-types --verbose
# Show types dependency graph
npx kb-devkit-check-types --graph
# JSON output for CI
npx kb-devkit-check-types --jsonWhat it checks:
- Technical debt detection: Finds
dts: falsein tsup configs (bad practice!) - Missing configuration: Detects packages without dts settings
- package.json types field: Validates "types" field exists
- Actual .d.ts files: Checks if declaration files exist in dist/
- Auto-fix capability: Can automatically change
dts: falsetodts: true
Example output:
🔍 KB Labs TypeScript Types Checker
Found 90 packages to check
🔴 Technical Debt: 7 package(s) with dts: false
@kb-labs/cli-core
/path/to/tsup.config.ts
└─ Has "dts: false" - types not being generated!
✅ Fixed: Changed to "dts: true"
📊 Summary:
Total packages: 90
With TypeScript: 90
✅ Clean: 21
🔴 dts: false: 7 (technical debt!)
⚠️ Other issues: 62Why this matters:
In a monorepo, TypeScript types form a dependency chain:
Project A uses type G from Package B
Package B uses type L from Package M
...If any package in the chain has dts: false or missing types, TypeScript compilation breaks. This tool helps identify and fix those broken chains automatically.
TypeScript Types Order
Calculate the correct order for types generation (separate from build order):
# Show types generation order
npx kb-devkit-types-order
# Show parallel generation layers
npx kb-devkit-types-order --layers
# Types order for specific package
npx kb-devkit-types-order --package=workflow-runtime
# Show only broken type chains
npx kb-devkit-types-order --broken
# JSON output
npx kb-devkit-types-order --jsonWhat it does:
- Types dependency analysis: Tracks which packages import types from which other packages
- Broken chain detection: Finds packages that import types from packages with
dts: false - Circular type dependencies: Detects cycles in type imports
- Topological sort: Determines correct order for .d.ts generation
- Parallel layers: Groups packages whose types can be generated in parallel
Example output:
📘 Types generation order for @kb-labs/workflow-runtime:
1. ✅ @kb-labs/plugin-manifest
2. ✅ @kb-labs/shared-cli-ui
3. ✅ @kb-labs/core-types
...
18. ✅ @kb-labs/workflow-runtime ⬅ targetDifference from build-order:
build-order: Tracks runtime dependencies (what needs to be built first)types-order: Tracks type dependencies (what types are imported from where)
TypeScript Types Audit
Centralized type safety audit for entire monorepo using TypeScript Compiler API:
# Full audit report
npx kb-devkit-types-audit
# Audit specific package
npx kb-devkit-types-audit --package=workflow-runtime
# Show only critical errors
npx kb-devkit-types-audit --errors-only
# Detailed coverage report
npx kb-devkit-types-audit --coverage
# JSON output
npx kb-devkit-types-audit --jsonWhat it does:
- Deep type analysis: Uses TypeScript Compiler API for semantic analysis
- Type errors: Finds all type errors across monorepo (what
tscwould show) - Type coverage: Calculates coverage % for each package
- Impact analysis: Shows which packages are affected by type errors
- Safety issues: Detects
anyusage,@ts-ignorecomments, missing types
Example output:
📊 TypeScript Type Safety Audit Report
❌ Critical Issues (12 packages with type errors):
@kb-labs/workflow-runtime
45 error(s) - impacts 8 package(s)
└─ ./src/auth.ts:45:10
Type 'any' is not assignable to 'string[]'
🔍 Type Safety Issues:
127 usage(s) of 'any' type
45 @ts-ignore comment(s)
📈 Type Coverage:
✅ Excellent (≥90%): 56 packages
⚠️ Good (70-90%): 28 packages
❌ Poor (<70%): 6 packages
📊 Summary:
Total packages: 90
❌ Type errors: 234
📈 Avg coverage: 84.3%Why this is powerful:
Instead of running tsc in each package separately, you get:
- Single centralized report for entire monorepo
- Impact analysis: See which packages break if type X has errors
- Type coverage metrics: Track type safety over time
- Dependency chains: Understand type inheritance relationships
See USAGE_GUIDE.md for comprehensive usage examples, real-world use cases, and best practices.
Automatic Build Configuration:
After sync, DevKit automatically generates tsconfig.build.json for all packages with tsup.config.ts. This ensures proper bundling configuration without manual setup.
To generate tsup.external.json manually (if needed):
npx kb-devkit-tsup-external --generate✨ Features
- TypeScript: Ready-to-use
tsconfigfor libraries, Node services, and CLIs - ESLint: ESLint 9 flat config with TypeScript support
- Prettier: Single opinionated formatting profile
- Vitest: Base test/coverage profile with lib/node overlays
- Tsup: Standard builds for libraries and Node services
- GitHub Actions: Reusable CI/PR/Release workflows
- AI Agents: Standardized Cursor agents for common development tasks
- Fixtures: Validation fixtures to ensure DevKit changes don't break downstream consumers
- Repository Sync: Automated synchronization system to keep projects up-to-date
📁 Repository Structure
kb-labs-devkit/
├── agents/ # AI agent definitions
│ ├── devkit-maintainer/ # DevKit maintainer agent
│ ├── test-generator/ # Test generator agent
│ ├── docs-crafter/ # Documentation drafter agent
│ └── release-manager/ # Release manager agent
├── bin/ # Executable scripts
│ └── devkit-sync.mjs # Sync tool binary
├── eslint/ # ESLint presets
├── fixtures/ # Validation fixtures
│ ├── lib/ # Library fixture
│ ├── cli/ # CLI fixture
│ ├── web/ # Web app fixture
│ └── monorepo/ # Monorepo fixture
├── prettier/ # Prettier config
├── scripts/ # Utility scripts
├── sync/ # Sync system
├── tsconfig/ # TypeScript configs
├── tsup/ # Tsup configs
├── vite/ # Vite configs
├── vitest/ # Vitest configs
└── docs/ # Documentation
└── adr/ # Architecture Decision RecordsDirectory Descriptions
agents/- Pre-configured AI agent definitions for Cursor and other IDE assistantsbin/- Executable scripts (sync tool)fixtures/- Validation fixtures that act as minimal, real-world consumer projectsdocs/- Documentation including ADRs and guides- Preset directories (
tsconfig/,eslint/,prettier/,vitest/,tsup/) - Tooling presets
📦 Presets
TypeScript (tsconfig)
Available configs:
base.json: strict base (ES2022, NodeNext, strict typing, isolatedModules)cli.json: CLI application presetlib.json: library presetnode.json: Node service – declarations, source maps,include: ["src"]react-lib.json: React library presetreact-app.json: React application presettest.json: Test configuration preset
All configs use module: "NodeNext" and moduleResolution: "NodeNext" for proper ESM support.
Usage:
{
"extends": "@kb-labs/devkit/tsconfig/node.json"
}ESLint
eslint/node.js: ESLint 9 flat config with TypeScript supporteslint/react.js: ESLint 9 flat config with React support
Features:
- Uses
typescript-eslintrecommended rules - Ignores
dist/,coverage/,node_modules/,.yalc/ - Allows unused variables with
_prefix - Consistent type imports
Prettier
prettier/index.json: shared style (no semicolons, single quotes, width 100)
Tsup
tsup/node.js: ESM-only build (target ES2022, sourcemap, clean, treeshake)tsup/react-lib.js: React library build preset
Automatic Configuration:
DevKit automatically handles bundling configuration to prevent workspace packages from being bundled:
tsconfig.build.json: Automatically generated bykb-devkit-syncfor all packages withtsup.config.ts. This file extends your basetsconfig.jsonbut setspaths: {}to prevent tsup from resolving workspace packages to their source files.tsup.external.json: Automatically generated bykb-devkit-tsup-external(runs inpostinstall). This file lists all workspace packages and dependencies that should be treated as external by tsup.
Usage:
Your tsup.config.ts should reference tsconfig.build.json:
import { defineConfig } from 'tsup';
import nodePreset from '@kb-labs/devkit/tsup/node.js';
export default defineConfig({
...nodePreset,
entry: { index: "src/index.ts" },
tsconfig: "tsconfig.build.json", // Use build-specific tsconfig without paths
});The nodePreset automatically reads tsup.external.json and marks all workspace packages as external, ensuring they are not bundled.
Features:
- ESM format only
- ES2022 target
- Source maps enabled
- Tree shaking enabled
- Clean output directory
- Automatic
externallist generated fromdependencies+peerDependencies
Vitest
vitest/node.js: Node environment with coverage supportvitest/react.js: React environment with coverage support
Features:
- Node/React environment
- Coverage with V8 provider (disabled by default)
- Excludes
node_modules/,dist/, etc. - Strict coverage thresholds when enabled
🛠️ Available Scripts
| Script | Description |
|--------|-------------|
| kb-devkit-health | ⚡ NEW: Comprehensive monorepo health check - detects missing deps, build failures, type errors |
| kb-devkit-ci | Run all critical checks (naming, imports, exports, duplicates, paths, types) |
| kb-devkit-fix-deps | Auto-fix dependency issues (unused deps, missing deps, version alignment) |
| kb-devkit-stats | Get monorepo health score and statistics |
| kb-devkit-check-imports | Check for broken imports, unused deps, circular deps |
| kb-devkit-check-exports | Find unused exports and dead code |
| kb-devkit-types-audit | Deep TypeScript type safety analysis for entire monorepo |
| pnpm fixtures:check | Check all fixtures (recommended for CI) |
| pnpm fixtures:lint | Lint all fixtures |
| pnpm fixtures:test | Test all fixtures |
| pnpm fixtures:build | Build all fixtures |
| pnpm fixtures:bootstrap | Bootstrap all fixtures |
| pnpm fixtures:clean | Clean all fixtures |
| pnpm fixtures:ci | Run fixtures check for CI |
🏥 Health Check Tool
The kb-devkit-health tool is a comprehensive monorepo health check that catches critical issues early:
# Full health check (recommended before major changes)
npx kb-devkit-health
# Quick check (skips slow build and type checks)
npx kb-devkit-health --quick
# JSON output for CI/CD or AI agents
npx kb-devkit-health --json
# Check specific package
npx kb-devkit-health --package cli-coreWhat it checks:
- ✅ Missing runtime dependencies (imports not in package.json)
- ✅ Cross-repo workspace vs link inconsistencies
- ✅ Build failures across all packages
- ✅ TypeScript type errors
- ✅ Circular dependencies
- ✅ Orphan packages
Example output:
🏥 KB Labs Monorepo Health Check
Analyzing 208 package(s)...
❌ CRITICAL ISSUES (blocking)
• 4 package(s) with missing runtime dependencies
@kb-labs/cli-commands: @kb-labs/plugin-contracts, @kb-labs/devkit
• 2 cross-repo dep(s) using workspace:* instead of link:
@kb-labs/core-sys → @kb-labs/shared-cli-ui
Health Score: 50/100 (Grade F)
Recommended Actions:
1. Fix missing runtime dependencies:
kb-devkit-fix-deps --add-missing📋 Development Policies
- Code Style: ESLint + Prettier, TypeScript strict mode
- Testing: Vitest with fixtures for integration testing
- Versioning: SemVer with automated releases through Changesets
- Architecture: Document decisions in ADRs (see
docs/adr/) - Preset Stability: Presets maintain backward compatibility
- Sync System: Automated drift detection and synchronization
🔧 Requirements
- Node.js: >= 18.18.0
- pnpm: >= 9.0.0
⚙️ Configuration
Repository Synchronization
The DevKit includes a powerful sync system that allows you to keep your project up-to-date with the latest DevKit assets. This is especially useful for maintaining consistent tooling across KB Labs projects.
Quick Sync
# Run sync (creates/updates files)
npx kb-devkit-sync
# Check for drift without making changes
npx kb-devkit-sync --check
# Force overwrite existing files
npx kb-devkit-sync --forceSync Configuration
Create a kb-labs.config.json file in your project root to customize sync behavior:
{
"sync": {
"enabled": true,
"disabled": ["vscode"],
"only": ["ci", "agents"],
"scope": "managed-only",
"force": false,
"overrides": {
"cursorrules": { "to": ".config/cursor/rules.json" }
},
"targets": {
"workflows": {
"from": ".github/workflows",
"to": ".github/workflows",
"type": "dir"
}
}
}
}Configuration Options
enabled: Boolean to enable/disable sync entirely (default: true)disabled: Array of target names to skip during synconly: Array of target names to sync (if empty, syncs all enabled targets)scope: Drift detection mode:"managed-only"(default),"strict", or"all"force: Boolean to force overwrite existing files (can be set in config or via--forceflag)overrides: Override source paths, destination paths, or types for existing targetstargets: Add custom sync targets withfrom,to, andtypeproperties
Available Targets
By default, the sync tool includes these targets:
agents: AI agent definitions →.kb/devkit/agents/cursorrules: Cursor AI rules →.cursorrulesvscode: VS Code settings →.vscode/settings.json
Drift Detection Modes
The sync tool supports three drift detection modes:
managed-only(default): Compare only files explicitly synced from DevKit. Safe for repositories with additional project-specific files.strict: Compare entire target directories and flag unmanaged files as drift. Use when you want to ensure no extra files exist.all: Legacy mode that combines strict checking with unmanaged file detection.
GitHub Actions Integration
Add a drift check to your CI to ensure your project stays in sync:
name: CI
on: [push, pull_request]
jobs:
ci:
uses: kb-labs/devkit/.github/workflows/ci.yml@main
with:
enable-drift-check: trueOr use the dedicated drift check workflow:
name: Drift Check
on:
workflow_dispatch: {}
schedule:
- cron: '0 3 * * *' # nightly
jobs:
drift:
uses: kb-labs/devkit/.github/workflows/drift-check.yml@main🤖 AI Agents
This DevKit includes pre-configured AI agents that can be synced into any KB Labs project. These agents are opinionated around KB Labs workflows (pnpm, devkit presets, monorepo). Outside this ecosystem, adapt accordingly.
| Agent | Purpose | |-------|---------| | DevKit Maintainer | Enforce unified tooling (tsconfig, eslint, prettier, vitest, tsup, CI) | | Test Generator | Generate and maintain pragmatic unit tests | | Docs Drafter | Draft and update README/CONTRIBUTING/ADR docs | | Release Manager | Prepare release plans, changelog, and GitHub releases |
Each agent includes:
- Prompt: AI instructions and context
- Runbook: step-by-step procedures
- Context: file patterns and permissions
To sync agents into your project:
# Copy agent definitions from this DevKit
npx kb-devkit-sync agentsThey are designed for Cursor AI agents, but can also be adapted for GitHub Copilot Chat or other IDE assistants.
See AGENTS.md for detailed agent documentation.
🧪 Validation Fixtures
This DevKit includes fixtures (/fixtures/*) that act as minimal, real-world consumer projects to validate DevKit changes:
fixtures/lib: A simple TypeScript library using DevKit presetsfixtures/cli: A CLI application with Commander.jsfixtures/web: A web application with DOM API and fetchfixtures/monorepo: A monorepo with shared library and app packages
Each fixture has its own package.json and extends DevKit via imports/extends (no relative paths).
Fixture Management
Use the automated fixture management script:
# Check all fixtures (recommended for CI)
pnpm fixtures:check
# Check specific fixture
pnpm fixtures lib check
pnpm fixtures cli test
pnpm fixtures web build
pnpm fixtures monorepo lint
# Run specific action on all fixtures
pnpm fixtures:lint # Lint all fixtures
pnpm fixtures:test # Test all fixtures
pnpm fixtures:build # Build all fixtures
# Show help
pnpm fixturesThe fixtures:check script runs all validation steps and is used in CI to ensure DevKit changes don't break downstream consumers.
See scripts/README.md for detailed fixture management documentation.
📚 Documentation
- Documentation Standard - Full documentation guidelines
- Contributing Guide - How to contribute
- Architecture Decisions - ADRs for this project
Guides:
- AI Agents - AI agent documentation
- Fixture Management - Fixture management documentation
Architecture:
- ADR 0001: Repository Synchronization via DevKit - Strategy for maintaining consistent tooling
- ADR 0002: ESM-only and NodeNext - ESM-only modules with NodeNext resolution
- ADR 0003: Validation Fixtures Strategy - Testing DevKit presets with realistic consumer projects
- ADR 0004: Testing Strategy and Quality Gates - Comprehensive testing approach
- ADR 0005: Build & Types Strategy - Unified approach to build and type generation
- ADR 0006: Sequential Build & Type Safety - Build order and dependency resolution
- ADR 0007: Reusable Workflow Strategy - Centralized CI workflows and drift check
- ADR 0008: Flexible Sync and Drift Management - Managed-only drift strategy with provenance tracking
- ADR 0011: Preventing Workspace Package Bundling - Automatic externalization of workspace packages in tsup builds
Migration Guides
- Migrating to Workspace External Bundling - Step-by-step guide for preventing workspace package bundling
🔗 Related Packages
Dependencies
- None (devkit is a foundation package)
Used By
- @kb-labs/core - Core utilities
- @kb-labs/cli - CLI framework
- @kb-labs/audit - Audit framework
- @kb-labs/ai-review - AI Review
- All other KB Labs projects
Ecosystem
- KB Labs - Main ecosystem repository
💡 Use Cases
- Bootstrap new packages/services without copying configs
- Enforce consistent style and rules across the ecosystem
- Provide a single minimal CI for PRs and releases
- Migrate existing projects to shared presets with minimal effort
- Validate DevKit changes against real-world usage patterns
📖 Migration Guide
Updating to Latest DevKit
To update your project to the latest DevKit version:
- Update the package:
pnpm update @kb-labs/devkit- Check for drift:
npx kb-devkit-sync --check- Sync changes (if drift found):
npx kb-devkit-sync --force- Review and commit changes:
git add .
git commit -m "chore: update devkit to latest version"Migrating from Manual Setup
If you're migrating from manually copied configs to the sync system:
- Install DevKit:
pnpm add -D @kb-labs/devkit- Create sync configuration:
{
"sync": {
"disabled": ["vscode"],
"overrides": {
"cursorrules": { "to": ".cursorrules" }
}
}
}- Run initial sync:
npx kb-devkit-sync --forceRemove old config files and update imports to use DevKit presets
Add drift check to CI:
jobs:
ci:
uses: kb-labs/devkit/.github/workflows/ci.yml@main
with:
enable-drift-check: true❓ FAQ
General
- Can I override rules? — Yes. Extend locally and add your overrides on top.
- How do I update? — Bump
@kb-labs/devkitand runnpx kb-devkit-sync --checkto see what changed. - ESLint 9 flat config? — Yes, all ESLint configs use the new flat config format.
- ESM only? — Yes, all presets assume ESM. For CJS, add dual builds/transpilation in your project.
- TypeScript errors with module resolution? — Ensure you're using
module: "NodeNext"in your tsconfig. - Importing specific files vs folders? — Both are supported. Use
@kb-labs/devkit/tsconfig/node.jsonfor specific files or `
📦 Complete Tools Summary
DevKit provides 19 tools for monorepo management and quality assurance:
Analysis Tools (8)
- Import Checker - Find broken imports, unused dependencies, circular deps
- Export Checker - Find unused exports and dead code
- Duplicate Checker - Find duplicate dependencies
- Structure Checker - Validate package structure
- Naming Validator - Enforce Pyramid Rule naming convention
- Path Validator - Validate workspace deps, exports, bin paths
- TypeScript Types Audit - Deep type safety analysis across monorepo
- Visualizer - Generate dependency graphs and stats
Automation Tools (8)
- ⚡ QA Runner - Comprehensive quality checks with incremental builds (NEW!)
- Quick Statistics - Get health scores and metrics
- Dependency Auto-Fixer - Auto-fix dependency issues
- CI Combo Tool - Run all checks in one command
- Build Order Calculator - Determine correct build order
- Types Order Calculator - Calculate types generation order
- Command Health Checker - Verify all CLI commands work
- TypeScript Types Checker - Ensure all packages generate types
Infrastructure Tools (3)
- Repository Sync - Sync DevKit assets across projects
- Path Aliases Generator - Generate workspace path aliases
- Tsup External Generator - Generate external dependencies list
Quick Access
# Quality Assurance (recommended)
npx kb-devkit-qa # ⚡ Incremental builds (~20s)
npx kb-devkit-ci # All static checks
# Analysis
npx kb-devkit-check-imports # Imports
npx kb-devkit-check-exports # Exports
npx kb-devkit-types-audit # Type safety
# Automation
npx kb-devkit-fix-deps --dry-run # Fix dependencies
npx kb-devkit-build-order --layers # Build order
npx kb-devkit-stats --health # Health scoreLicense
MIT License - see LICENSE for details.
