Skip to content

Conversation

@prosdev
Copy link
Collaborator

@prosdev prosdev commented Dec 12, 2025

Summary

Enhances the dev stats command with rich formatted output including tables, colors, and detailed statistics breakdowns. Adds dev dashboard as an alias command for easy access.

Key Improvements:

  • 📊 Language breakdown table (TypeScript, JavaScript, Go, Markdown)
  • 🔧 Component type counts with percentages
  • 💚 Color-coded health indicators (green/yellow/red)
  • 📦 Package-level stats (auto-detected for monorepos)
  • 🎨 Rich terminal formatting with cli-table3
  • 🔍 Maintains --json flag for programmatic access

Changes

New Files:

  • packages/cli/src/utils/formatters.ts - Table formatting utilities (279 lines)
  • packages/cli/src/utils/__tests__/formatters.test.ts - Comprehensive tests (325 lines, 19 tests)
  • packages/cli/src/commands/dashboard.ts - Dashboard alias command

Modified Files:

  • packages/cli/package.json - Added cli-table3 (^0.6.5), terminal-size (^4.0.0)
  • packages/cli/src/commands/stats.ts - Enhanced with DetailedIndexStats and formatted output
  • packages/cli/src/cli.ts - Registered dashboard command
  • pnpm-lock.yaml - Updated dependencies

Stats:

  • +674 lines, -31 lines
  • 19 tests (all passing ✅)
  • Full typecheck passing ✅

Test Plan

  • All 19 formatter unit tests pass
  • TypeScript compilation succeeds
  • Biome linting passes
  • Formatted tables render correctly with various data
  • Health indicators show correct colors
  • --json flag maintains backward compatibility
  • Package detection works for monorepos
  • Manual testing: Run dev stats and dev dashboard on indexed repository
  • Visual verification: Tables align properly in various terminal widths

Related Issues

Resolves #147 (Enhanced CLI Statistics)
Part of Epic #145 (Dashboard & Visualization System)

Dependencies

Builds on #146 (Data Collection Infrastructure) which added DetailedIndexStats to core package.

Enhance the `dev stats` command with formatted tables, colors, and
detailed breakdowns. Add `dev dashboard` as an alias command.

Features:
- Language breakdown table with files, components, LOC
- Component type counts with percentages
- Color-coded health indicators (green/yellow/red)
- Package-level stats for monorepos
- Terminal-aware formatting with cli-table3
- Maintained --json flag for programmatic access

New utilities:
- formatters.ts: Table creation and formatting functions
- dashboard.ts: Alias command for enhanced stats display

Dependencies added: cli-table3, terminal-size

Tests: 19 formatter tests (all passing)

Resolves #147
Fix critical bug where detailed statistics (byLanguage, byComponentType,
byPackage) were collected during indexing but not persisted to state or
returned by getStats().

Changes:
- Update IndexerState.stats type to include optional detailed fields
- Modify updateState() to accept and persist detailed stats parameter
- Update getStats() to return DetailedIndexStats with all fields
- Fix index() method to pass detailed stats to updateState
- Fix update() method to preserve existing stats (incremental updates)

For incremental updates (dev update), existing detailed stats are
preserved from the last full index. Users should run full re-index
periodically for accurate stats.

This ensures the enhanced CLI stats command displays rich formatted
tables with language breakdown and component types.

Related: #147
- Add StatsMetadata to track full vs incremental index updates
- Extract pure stat merging functions (stats-merger.ts, 17 tests, 100% coverage)
- Extract pure date utilities (date-utils.ts, 18 tests, 100% coverage)
- Add test factories for DRY test data creation
- Implement smart stat merging: incremental updates now merge into full stats
- Users see complete picture in 'dev stats' after incremental updates
- Add TypeScript Standards manifesto (consolidates TESTABILITY.md)

User Experience:
- update() returns incremental stats (what changed)
- getStats() returns full repository stats (complete picture)
- CLI shows freshness metadata and warnings after 10+ updates

Technical Improvements:
- Reduced stat merging from 102 lines to 25 lines (75% reduction)
- Eliminated mutations in favor of pure functions
- Changed byLanguage from Record to Partial<Record> (more accurate)
- All 1667 tests passing (+35 new pure function tests)

Fixes failing CI test: packages/core/src/indexer/__tests__/detailed-stats.integration.test.ts
- Install Zod for runtime type validation (following TypeScript Standards Rule #2)
- Create comprehensive schemas for all 9 adapters (247 lines, 33 tests)
- Create validation utilities with Result type pattern (68 lines)
- Migrate 5 adapters to Zod validation (eliminates ~150 lines of manual checks)

Migrated adapters:
- HealthAdapter: 2 lines validation → type-safe
- StatusAdapter: 24 lines validation → type-safe
- RefsAdapter: 32 lines validation → type-safe
- SearchAdapter: 58 lines validation → type-safe
- MapAdapter: 34 lines validation → type-safe

Benefits:
- Zero type assertions (no more 'as unknown as')
- Automatic TypeScript type inference from schemas
- Better error messages with field paths
- Schemas are pure functions (100% test coverage)
- Cleaner adapter tests (focus on logic, not validation)

Remaining: HistoryAdapter, PlanAdapter, ExploreAdapter, GitHubAdapter

All tests passing, build successful
Add comprehensive guidance on when to commit during development:

- 5 checkpoint signals (green state, logical boundary,
  before complexity, demonstrable value, context limits)
- Real examples from Zod migration
- Anti-patterns to avoid
- Quick checklist before committing
- Why it matters for teams, AI collaboration, and developers

Context limit threshold: 150K tokens (updated from 100K)

This codifies the instinct to commit at safe checkpoints
before tackling complexity, improving collaboration and
reducing risk.
Migrate remaining 4 adapters to Zod validation:
- HistoryAdapter: 30 lines validation → type-safe
- PlanAdapter: 20 lines validation → type-safe
- ExploreAdapter: 54 lines validation → type-safe
- GitHubAdapter: 55 lines validation → type-safe

Total impact across all adapters:
- Eliminated ~330 lines of manual validation code
- Zero type assertions (no more 'as unknown as')
- Automatic TypeScript type inference from schemas
- All 33 schema tests passing
- Build successful, all tests green

All 9 MCP adapters now follow TypeScript Standards Rule #2:
No Type Assertions Without Validation
Update Rule #2 with real example from MCP adapter migration:
- Show before/after with actual code from codebase
- Demonstrate automatic type inference benefits
- Link to test files as reference
- Show 63% code reduction metric

This completes the Zod migration documentation.
Following TypeScript Standards Rule #2: No Type Assertions Without Validation

Changes:
- Added GitHub CLI output validation (packages/subagents/src/schemas/github-cli.ts)
  * GitHubIssueSchema, GitHubPullRequestSchema, GitHubCommentSchema
  * 17 comprehensive tests with 100% coverage
  * Eliminates ~50 lines of type assertions in github.ts

- Updated all MCP adapter tests to expect INVALID_PARAMS error code
  * Zod returns consistent INVALID_PARAMS for all validation failures
  * Tests now check error.message for specific field names
  * Aligns with Zod migration completed in previous commits

Impact:
- Zero type assertions in GitHub CLI parsing (HIGH RISK boundary)
- Better error messages: 'Invalid GitHub CLI response: body: Expected string'
- Bulletproof against gh CLI format changes
- All 1717 tests passing ✅

Scope: External data validation at system boundaries
Following TypeScript Standards Rule #2: No Type Assertions Without Validation

Changes:
- Created message schemas (packages/subagents/src/schemas/messages.ts)
  * PlanningRequestSchema for planner agent
  * ExplorationRequestSchema (discriminated union) for explorer agent
  * GitHubContextRequestSchema for GitHub agent
  * 22 comprehensive tests with 100% coverage

- Replaced 3 type assertions with validated functions:
  * planner/index.ts: validatePlanningRequest()
  * explorer/index.ts: validateExplorationRequest()
  * github/agent.ts: validateGitHubContextRequest()

- Updated 3 tests to expect 'error' messages for invalid requests
  * planner/__tests__/index.test.ts
  * explorer/__tests__/index.test.ts
  * coordinator/__tests__/coordinator.integration.test.ts

Impact:
- Zero type assertions in inter-agent communication (MEDIUM RISK boundary)
- Better error messages: 'Invalid planning request: issueNumber: ...'
- Bulletproof against malformed coordinator messages
- All 1739 tests passing ✅

Scope: Inter-agent message validation
Following TypeScript Standards Rule #2: No Type Assertions Without Validation

Changes:
- Created validation schema (packages/core/src/storage/validation.ts)
  * RepositoryMetadataSchema with nested objects
  * validateRepositoryMetadata() helper

- Replaced type assertion in metadata.ts
  * Before: JSON.parse(content) as RepositoryMetadata
  * After: validateRepositoryMetadata(JSON.parse(content))

Impact:
- Protects against corrupted metadata.json files
- Returns null on validation failure (existing error handling)
- All 1739 tests passing ✅

Scope: State file validation (metadata only, LOW RISK boundary)

Note: Indexer state files are more complex and would require significant
refactoring. This completes validation for the primary metadata file.
Following UX best practices for developer CLI tools to improve DX:

## New Output System

Created packages/cli/src/utils/output.ts:
- Clean output functions without logger timestamps
- Compact, scannable formatters for all commands
- Progressive disclosure (compact by default, --verbose for details)
- Follows patterns from gh CLI, npm, git

## Updated Commands

**stats**: One-line summary + optional verbose tables
  Before: 20+ lines with [timestamp] INFO prefixes
  After:  📊 dev-agent • 212 files • 2,205 components • Indexed 10m ago • ✓ Healthy

**index**: Compact success summary
  Before: Multi-section breakdown with timestamps
  After:  📊 Indexed: 1 files • 3 components • Duration: 0.11s • Storage: 11 KB

**update**: Single-line status
  Before: Section headers with detailed stats
  After:  ✓ Updated 6 files • 19 components • 3.19s

**search**: Scannable results (compact or verbose)
  Compact: One line per result with score and location
  Verbose: Multi-line with signatures and docs (--verbose flag)

**gh index**: Compact GitHub summary
  After:  ✓ Indexed 155 GitHub documents • 67 issues • 88 PRs • 7.44s

**init**: Clean welcome message
  Before: [timestamp] INFO for each line
  After:  Clean bullet points with next steps

## Test Improvements

Suppressed intentional error logs in tests:
- ExplorerAgent error handling tests
- Coordinator integration tests
- GitHub agent error tests
- Config loading error tests

Prevents test output pollution while maintaining error validation.

## Benefits

1. **Glanceable** - Key metrics visible at a glance
2. **Respects terminal space** - No unnecessary scrolling
3. **Actionable** - Shows next steps when needed
4. **Familiar** - Matches conventions from popular CLI tools
5. **Progressive disclosure** - --verbose flag for detailed output

## Testing

- Updated commands.test.ts to mock console.log
- All 1,739 tests passing ✅
- Clean test output (error logs only where intended)

Addresses user feedback on "awful" logger timestamps cluttering CLI output.
@prosdev prosdev merged commit 989f5d1 into main Dec 12, 2025
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Story: Enhanced CLI Statistics with Rich Formatting

1 participant