Watch Mode

stamp context --watch

Monitor the codebase for changes and rebuild affected context bundles incrementally—ideal for tight edit-compile loops.

Watch mode monitors your codebase for file changes and automatically regenerates context bundles. It provides incremental rebuilds for fast feedback during development.

stamp context --watch stamp context -w

Quick Start

# Basic watch mode stamp context --watch # Watch with style metadata stamp context style --watch # Watch a specific directory stamp context ./src/components --watch # Watch with debug output (shows hash changes) stamp context --watch --debug # Watch with structured change logs written to .logicstamp/context_watch-mode-logs.json (for change notifications) stamp context --watch --log-file # Strict watch mode - track breaking changes and violations # (--strict-watch automatically enables watch mode) stamp context --strict-watch

How It Works

  1. Initial Build - Generates context files and initializes the watch cache
  2. File Monitoring - Uses chokidar to watch for file changes
  3. Debouncing - Waits 500ms after the last change before regenerating (batches rapid changes)
  4. Incremental Rebuild - Only rebuilds affected bundles, not the entire project
  5. Change Detection - Shows what changed (props, hooks, state, etc.)
  6. Strict Watch Mode - Optionally tracks breaking changes (removed props, events, functions) and reports violations in real-time with --strict-watch

Features

Incremental Rebuilds

Watch mode maintains a cache of contracts, AST data, and style metadata. When a file changes, it only rebuilds:

  • The contract for the changed file
  • Bundles that include the changed component in their dependency graph

This makes rebuilds significantly faster than full regeneration.

Errors and recovery

If an incremental rebuild throws (parse error, I/O, etc.), watch mode:

  1. Logs the error (and appends to the watch log when --log-file is set).
  2. Runs a full stamp context rebuild (same as the non-watch command) and reloads output from disk.
  3. Re-initializes the watch cache when that succeeds so later edits use incremental rebuilds again.

If step 2 or 3 fails, the in-memory cache is cleared. each subsequent change triggers a full rebuild until one completes successfully.

Diff / strict-watch baseline: The snapshot used for “what changed” and for strict violations is normally fixed for the session (from the first successful load). After a successful recovery, that baseline is updated to match the recovered output so comparisons stay aligned with what is on disk. Strict-watch session counters (errors/warnings detected, resolved count, etc.) are not reset by recovery.

Corrupted or missing context files: When the context index or a folder context file cannot be read or parsed, watch mode emits a warning (suppressed when --quiet is set), except a missing main index before any output exists (ENOENT), which still returns empty bundles without a warning.

Change Detection

Watch mode detects and displays what changed in your components (informational):

Note: Regular watch mode shows changes but doesn't classify them as "breaking". Use --strict-watch to detect breaking changes (removed props, events, etc.) with violation tracking and exit codes.

📝 Changed: src/components/Button.tsx 🔄 Regenerating (1 file changed)... ✏️ Modified contract: src/components/Button.tsx • Added props: `disabled` • Removed props: `loading` • Changed hooks: `useCallback` 📦 Modified bundle: src/components/Button.tsx • Dependency graph updated ✅ Regenerated

Change types detected:

  • Props - Added, removed, or changed prop signatures
  • Events - Added, removed, or changed event callbacks
  • State - Added, removed, or changed useState variables
  • Hooks - Added or removed hook usage
  • Components - Added or removed component dependencies
  • Variables - Added or removed module-level variables
  • Functions - Added or removed function exports

File Events

Watch mode responds to three file events:

EventDescription
changeFile content modified
addNew file created
unlinkFile deleted

Watched File Types

By default, watch mode monitors:

  • .ts files
  • .tsx files

When using --include-style, it also watches:

  • .css files
  • .scss files
  • .module.css files
  • .module.scss files

Ignored Paths

Watch mode automatically ignores:

  • node_modules/
  • dist/
  • build/
  • .next/
  • coverage/
  • context.json files (generated output)
  • context_main.json (generated output)

Options

OptionAliasDescription
--watch-wEnable watch mode
--strict-watchEnable strict watch mode - automatically enables watch mode and tracks breaking changes and violations
--debugShow detailed hash information on changes
--quiet-qSuppress verbose output (show only errors)
--include-styleWatch style files and include style metadata
--profile watch-fastUse lighter style extraction for faster rebuilds
--log-fileWrite structured change logs to .logicstamp/context_watch-mode-logs.json (for change notifications)

All other stamp context options are supported in watch mode.

Debug Mode

Use --debug to see detailed information about what changed:

stamp context --watch --debug

Debug output shows:

  • Which file triggered the rebuild
  • Semantic hash changes (API/logic changes)
  • File hash changes (any content change)
  • Bundle hash changes (dependency graph changes)
  • Detailed contract diffs
[DEBUG] Changed file: src/components/Button.tsx [DEBUG] Modified contracts (1): ~ src/components/Button.tsx semanticHash (API/logic): uif:abc123... → uif:def456... ↳ Detects: props, events, state, hooks, components, functions Detailed changes: + Props: disabled - Props: loading

Hash types explained:

  • semanticHash - Changes when the component's API changes (props, events, state, hooks)
  • fileHash - Changes when any file content changes (including comments, formatting)
  • bundleHash - Changes when the dependency graph structure changes

Watch Status & Logs

Watch mode can write status files for integration with other tools (like the MCP server).

Status File (.logicstamp/context_watch-status.json)

Written when watch mode starts, deleted when it stops:

{ "active": true, "projectRoot": "/path/to/project", "pid": 12345, "startedAt": "2025-01-19T10:30:00.000Z", "outputDir": "/path/to/project", "strictWatch": false }

Fields:

  • active - Always true when file exists (file is deleted on exit)
  • projectRoot - Absolute path to the watched project
  • pid - Process ID of the watch process (use to verify process is still running)
  • startedAt - ISO timestamp when watch mode started
  • outputDir - Directory where context files are written
  • strictWatch - Whether strict watch mode is enabled (true when --strict-watch flag is used, false otherwise)

Watch Log (.logicstamp/context_watch-mode-logs.json)

Opt-in with --log-file flag. When enabled, logs are appended after each regeneration:

# Enable watch mode with log file output stamp context --watch --log-file
{ "timestamp": "2025-01-19T10:30:05.000Z", "changedFiles": ["src/components/Button.tsx"], "fileCount": 1, "durationMs": 234, "modifiedContracts": [...], "modifiedBundles": [...], "summary": { "modifiedContractsCount": 1, "modifiedBundlesCount": 1, "addedContractsCount": 0, "removedContractsCount": 0 } }

By default, watch mode does not write log files. Use --log-file when you need structured change notifications (e.g., to display "what changed" in a UI or for debugging).

Strict Watch Mode

Strict watch mode (--strict-watch) tracks breaking changes and violations during development. It detects API changes in real-time as you code.

Note: --strict-watch automatically enables watch mode, so --watch is optional. Both stamp context --strict-watch and stamp context --watch --strict-watch are equivalent and fully supported for backward compatibility.

# Enable strict watch mode (--strict-watch automatically enables watch mode) stamp context --strict-watch # Alternative: explicitly enable both (equivalent to above, backward compatible) stamp context --watch --strict-watch # Combine with style metadata stamp context style --strict-watch

What It Detects

Strict watch mode identifies breaking changes that could affect consumers of your components:

Violation TypeSeverityDescription
contract_removedErrorA component/contract was deleted
breaking_change_prop_removedErrorA prop was removed from a component
breaking_change_event_removedErrorAn event callback was removed
breaking_change_function_removedErrorAn exported function was removed
breaking_change_variable_removedWarningA module-level variable was removed
breaking_change_state_removedWarningA state variable was removed
breaking_change_prop_typeWarningA prop's type signature changed

Output

When violations are detected, strict watch mode displays them after each regeneration:

🔄 Regenerating (1 file changed)... ✏️ Modified contract: src/components/Button.tsx • Removed props: `loading` ✅ Regenerated ⚠️ Strict Watch: 1 violation(s) detected ❌ Errors (1): Breaking change: prop 'loading' removed from src/components/Button.tsx 📊 Current state: 1 error(s), 0 warning(s) 📊 Session status: ❌ Errors detected: 1 ⚠️ Warnings detected: 0 🔧 Resolved: 0 📌 Active: 1

Note: The session status block only appears when violations change (not on every file change), keeping terminal output clean. It tracks cumulative statistics throughout the watch session:

  • Errors/Warnings detected: Total count of violations detected during the session (cumulative across all checks, only increments when new violations appear or count increases)
  • Resolved: Number of times all violations were completely resolved (increments only when ALL violations - both errors and warnings - go from >0 to 0, reverted back to baseline). Partial fixes (e.g., warnings decreasing from 2 to 1) do not increment this count.
  • Active: Current number of active violations (errors + warnings)

Violations Report File

When violations are detected, strict watch mode creates a structured JSON report at .logicstamp/strict_watch_violations.json. The file only exists when violations are present - if there are no violations, the file is not created (or is deleted if all violations are resolved):

{ "active": true, "startedAt": "2025-01-22T10:30:00.000Z", "cumulativeViolations": 1, "cumulativeErrors": 1, "cumulativeWarnings": 0, "regenerationCount": 5, "lastCheck": { "timestamp": "2025-01-22T10:35:00.000Z", "totalViolations": 1, "errors": 1, "warnings": 0, "violations": [ { "type": "breaking_change_prop_removed", "severity": "error", "entryId": "src/components/Button.tsx", "message": "Breaking change: prop 'loading' removed from src/components/Button.tsx", "details": { "name": "loading" } } ], "changedFiles": ["src/components/Button.tsx"] } }

State-based semantics (v0.5.5+): The violations report shows current violations relative to the baseline snapshot used for diffs (normally from the first successful rebuild in the session; updated after successful error recovery), not cumulative history:

  • cumulativeViolations/Errors/Warnings reflect the current state, not a running total
  • File lifecycle: The file is created when violations are detected and automatically deleted when all violations are resolved (reverted back to baseline)
  • This works like git diff - only shows what's currently different from baseline

Exit Behavior

Watch mode is designed for development awareness, not CI enforcement. When you stop watch mode (Ctrl+C), it exits with the standard signal code (130 for SIGINT) regardless of violations detected.

For CI/CD pipelines with exit codes based on contract drift, use the stamp compare command instead:

# CI: Exit code 1 if breaking changes detected stamp compare --baseline .logicstamp/baseline.json # Development: Awareness-only (no exit code enforcement) stamp context --strict-watch

The violations report (.logicstamp/strict_watch_violations.json) persists after watch mode stops, allowing you to review violations before committing.

Session Summary

When exiting, strict watch mode displays a session summary:

^C 👋 Watch mode stopped ❌ Strict Watch session complete - 3 errors, 2 warnings detected 📊 Session summary: ❌ Errors detected: 3 ⚠️ Warnings detected: 2 🔧 Resolved: 1 📌 Active: 5 Report saved to: .logicstamp/strict_watch_violations.json

If no violations were detected during the session:

^C 👋 Watch mode stopped ✅ Strict Watch session complete - no violations detected 📊 Session summary: ❌ Errors detected: 0 ⚠️ Warnings detected: 0 🔧 Resolved: 0 📌 Active: 0

If only warnings were detected:

^C 👋 Watch mode stopped ⚠️ Strict Watch session complete - 2 warnings detected 📊 Session summary: ❌ Errors detected: 0 ⚠️ Warnings detected: 2 🔧 Resolved: 0 📌 Active: 2

Use Cases

1. Active development Run strict watch mode while coding to catch breaking changes in real-time.

2. Refactoring sessions Track API changes during refactoring to understand impact.

3. Design system maintenance Monitor component contract stability across changes.

4. Pre-commit review Check the violations report before committing to understand what changed.

Examples

Basic Development Workflow

# Start watch mode in your project stamp context --watch # Output: # 👀 Watch mode enabled. Watching for file changes... # Press Ctrl+C to stop # # Watching: my-project # Ignoring: context.json files, node_modules, dist, build, etc. # Watching extensions: .ts, .tsx # # ✅ Watch mode active. Waiting for file changes...

Watch with Style Metadata

# Watch for style changes too stamp context style --watch # Or equivalently stamp context --include-style --watch # Now watches: .ts, .tsx, .css, .scss, .module.css, .module.scss

Watch a Subdirectory

# Only watch and rebuild a specific feature stamp context ./src/components/MyFeature --watch # Faster incremental rebuilds when focused on one area

Watch with Fast Profile

# Use lighter style extraction for faster rebuilds stamp context style --watch --profile watch-fast

CI/Development Server Integration

# Run in background (redirect output) stamp context --watch > watch.log 2>&1 & # Run with structured change logs (for change notifications) stamp context --watch --log-file # Or use in a development script (package.json) # "scripts": { # "context:watch": "stamp context --watch" # }

Performance Tips

  1. Focus on subdirectories - Watch a specific directory when working on one feature
  2. Use watch-fast profile - Lighter style extraction when you need faster rebuilds
  3. Skip style if not needed - Don't use --include-style if you don't need style metadata
  4. Check debug mode sparingly - Debug output adds overhead; use it for troubleshooting

Stopping Watch Mode

Press Ctrl+C to stop watch mode gracefully:

^C 👋 Watch mode stopped

Watch mode cleans up:

  • Closes file watcher
  • Deletes watch status file (.logicstamp/watch_status.json)
  • Flushes any pending logs

Graceful Shutdown (v0.5.4+)

Watch mode uses a centralized cleanup registry to ensure resources are properly cleaned up on any exit:

  • Signal handlers - SIGINT (Ctrl+C), SIGTERM, and SIGHUP all trigger graceful shutdown
  • Error exits - Even when errors occur, cleanup handlers run before the process exits
  • Priority ordering - Cleanup handlers run in priority order (watch mode cleanup runs first)

This prevents orphaned resources (file watchers, status files) that could occur if the process exits unexpectedly. The cleanup is automatic—no user action required.

Troubleshooting

Changes not detected

  1. Check if the file type is watched (.ts, .tsx, or style files with --include-style)
  2. Verify the file isn't in an ignored directory
  3. Enable debug logging: LOGICSTAMP_DEBUG=1 stamp context --watch

Slow rebuilds

  1. Use --profile watch-fast for lighter style extraction
  2. Focus on a subdirectory instead of the entire project
  3. Check if you're hitting max-nodes limits

Watch mode crashes

  1. Check available memory (large projects need more RAM)
  2. Enable debug mode to identify problematic files
  3. Report issues at https://github.com/LogicStamp/logicstamp-context/issues

See Also

Next Steps

Pair watch mode with style metadata or browse all CLI commands.