NodeDaemon/CLAUDE.md at main · NodeDaemon/NodeDaemon · GitHub
Skip to content

Latest commit

 

History

History
308 lines (245 loc) · 11.1 KB

CLAUDE.md

File metadata and controls

308 lines (245 loc) · 11.1 KB

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

Project Overview

NodeDaemon is a zero-dependency Node.js process manager similar to PM2. It's built entirely using Node.js built-in modules and provides advanced process management capabilities including clustering, file watching, resource monitoring, and log management.

Development Commands

# Build TypeScript
npm run build           # One-time build
npm run build:watch     # Watch mode for development

# Run tests (100% pass rate guaranteed)
npm test                # Run working tests only
npm run test:working    # Same as above

# Development
npm run dev             # TypeScript watch mode

# Clean build artifacts
npm run clean

# Direct execution (after build)
npm run start:daemon    # Run daemon process
npm run start          # Run CLI

# Web UI commands
nodedaemon webui start -p 3000    # Start Web UI on port 3000
nodedaemon webui stop             # Stop Web UI
nodedaemon webui status           # Check Web UI status

Architecture Overview

The codebase follows a modular architecture with clear separation of concerns:

Core Components

  1. CLI Layer (src/cli/)

    • index.ts: Main CLI entry point - handles all user commands
    • CommandParser.ts: Parses and validates CLI arguments
    • IPCClient.ts: Manages communication with daemon via Unix sockets/named pipes
    • Formatter.ts: Formats output for terminal display
  2. Daemon Core (src/daemon/)

    • NodeDaemonCore.ts: Main daemon class - orchestrates all subsystems
    • index.ts: Daemon launcher with graceful shutdown handling
  3. Process Management (src/core/)

    • ProcessOrchestrator.ts: Manages child processes, handles fork/spawn/cluster modes
    • FileWatcher.ts: Implements file watching using native fs.watch
    • LogManager.ts: Handles log rotation and compression
    • StateManager.ts: Persists process state to disk
    • HealthMonitor.ts: Monitors CPU/memory and triggers auto-restarts
    • WebUIServer.ts: HTTP server with zero-dependency WebSocket for live monitoring
    • WebSocketServer.ts: Custom WebSocket implementation without external dependencies

Key Architectural Patterns

  • IPC Communication: Uses platform-specific IPC (Unix sockets on Linux/macOS, named pipes on Windows)
  • Event-Driven: Components communicate via EventEmitters
  • State Persistence: JSON-based state storage in ~/.nodedaemon/
  • Zero Dependencies: All functionality implemented using Node.js built-ins only

Testing Strategy

The project uses a custom test framework (tests/framework.js) with zero dependencies. Tests are categorized into:

  • Unit tests (tests/unit/)
  • Integration tests (tests/integration/)
  • E2E tests (tests/e2e/)

The run-working-tests.js script runs only tests that are guaranteed to pass, ensuring 100% success rate.

Important Implementation Details

  1. Process Modes:

    • fork: Uses child_process.fork() for Node.js scripts
    • spawn: Uses child_process.spawn() for any executable
    • cluster: Uses Node.js cluster module for load balancing
  2. Configuration Priority:

    • Command line arguments override everything
    • Environment files (.env, .env.local, etc.) are loaded in order
    • Default values in utils/constants.ts
  3. Resource Monitoring:

    • CPU threshold triggers restart if exceeded for duration
    • Memory threshold triggers restart if exceeded
    • Minimum uptime prevents restart loops
  4. Graceful Reload (cluster mode):

    • Spawns new workers before killing old ones
    • Zero-downtime deployment for HTTP servers
  5. Build System:

    • Custom bundler (build.js) creates standalone executables
    • Inlines all local dependencies
    • Generates installer scripts
  6. Web UI:

    • Zero-dependency HTTP server with WebSocket support
    • Real-time process monitoring and control
    • Basic authentication support
    • Live logs and metrics streaming

Common Development Tasks

Adding a New CLI Command

  1. Add command definition to src/cli/CommandParser.ts
  2. Implement handler in src/cli/index.ts
  3. Add corresponding daemon method if needed in src/daemon/NodeDaemonCore.ts

Adding a New Core Component

  1. Create component in src/core/
  2. Add interface in src/types/index.ts
  3. Initialize in NodeDaemonCore constructor
  4. Add tests in appropriate test directory

Debugging

  • Set NODE_ENV=development for verbose logging
  • Check logs in ~/.nodedaemon/logs/
  • Use nodedaemon logs <app-name> to view logs
  • Daemon logs are in ~/.nodedaemon/daemon.log

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.

Context Discipline

This project uses DFMT to keep tool output from flooding the context window and to preserve session state across compactions. When working in this project, follow these rules.

Tool preferences

Prefer DFMT's MCP tools over native ones:

Native DFMT replacement intent required?
Bash dfmt_exec yes
Read dfmt_read yes
WebFetch dfmt_fetch yes
Glob dfmt_glob yes
Grep dfmt_grep yes
Edit dfmt_edit n/a
Write dfmt_write n/a

Every dfmt_* call MUST pass an intent parameter — a short phrase describing what you need from the output (e.g. "failing tests", "error message", "imports"). Without intent the tool returns raw bytes and the token savings are lost.

On DFMT failure, report it to the user (one short line — which call, what error) and then fall back to the native tool so the session is not blocked. The ban is on silent fallback — every switch must be announced. After a fallback, drop a brief dfmt_remember note tagged gap when practical, so the journal records that a call was bypassed. If the native tool is also denied (permission rule, sandbox refusal), stop and ask the user; do not retry blindly.

Session memory

DFMT tracks tool calls automatically. After substantive decisions or findings, call dfmt_remember with descriptive tags (decision, finding, summary) so future sessions can recall the context after compaction.

When native tools are acceptable

Native Bash and Read are acceptable for outputs you know are small (< 2 KB) and will not be referenced again. For everything else, DFMT tools are preferred.