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 -wQuick 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-watchHow It Works
- Initial Build - Generates context files and initializes the watch cache
- File Monitoring - Uses chokidar to watch for file changes
- Debouncing - Waits 500ms after the last change before regenerating (batches rapid changes)
- Incremental Rebuild - Only rebuilds affected bundles, not the entire project
- Change Detection - Shows what changed (props, hooks, state, etc.)
- 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:
- Logs the error (and appends to the watch log when
--log-fileis set). - Runs a full
stamp contextrebuild (same as the non-watch command) and reloads output from disk. - 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-watchto 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
✅ RegeneratedChange 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:
| Event | Description |
|---|---|
change | File content modified |
add | New file created |
unlink | File deleted |
Watched File Types
By default, watch mode monitors:
.tsfiles.tsxfiles
When using --include-style, it also watches:
.cssfiles.scssfiles.module.cssfiles.module.scssfiles
Ignored Paths
Watch mode automatically ignores:
node_modules/dist/build/.next/coverage/context.jsonfiles (generated output)context_main.json(generated output)
Options
| Option | Alias | Description |
|---|---|---|
--watch | -w | Enable watch mode |
--strict-watch | Enable strict watch mode - automatically enables watch mode and tracks breaking changes and violations | |
--debug | Show detailed hash information on changes | |
--quiet | -q | Suppress verbose output (show only errors) |
--include-style | Watch style files and include style metadata | |
--profile watch-fast | Use lighter style extraction for faster rebuilds | |
--log-file | Write 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 --debugDebug 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: loadingHash 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- Alwaystruewhen file exists (file is deleted on exit)projectRoot- Absolute path to the watched projectpid- Process ID of the watch process (use to verify process is still running)startedAt- ISO timestamp when watch mode startedoutputDir- Directory where context files are writtenstrictWatch- Whether strict watch mode is enabled (truewhen--strict-watchflag is used,falseotherwise)
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-watchWhat It Detects
Strict watch mode identifies breaking changes that could affect consumers of your components:
| Violation Type | Severity | Description |
|---|---|---|
contract_removed | Error | A component/contract was deleted |
breaking_change_prop_removed | Error | A prop was removed from a component |
breaking_change_event_removed | Error | An event callback was removed |
breaking_change_function_removed | Error | An exported function was removed |
breaking_change_variable_removed | Warning | A module-level variable was removed |
breaking_change_state_removed | Warning | A state variable was removed |
breaking_change_prop_type | Warning | A 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: 1Note: 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/Warningsreflect 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-watchThe 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.jsonIf 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: 0If 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: 2Use 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.scssWatch a Subdirectory
# Only watch and rebuild a specific feature
stamp context ./src/components/MyFeature --watch
# Faster incremental rebuilds when focused on one areaWatch with Fast Profile
# Use lighter style extraction for faster rebuilds
stamp context style --watch --profile watch-fastCI/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
- Focus on subdirectories - Watch a specific directory when working on one feature
- Use
watch-fastprofile - Lighter style extraction when you need faster rebuilds - Skip style if not needed - Don't use
--include-styleif you don't need style metadata - 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 stoppedWatch 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
- Check if the file type is watched (
.ts,.tsx, or style files with--include-style) - Verify the file isn't in an ignored directory
- Enable debug logging:
LOGICSTAMP_DEBUG=1 stamp context --watch
Slow rebuilds
- Use
--profile watch-fastfor lighter style extraction - Focus on a subdirectory instead of the entire project
- Check if you're hitting
max-nodeslimits
Watch mode crashes
- Check available memory (large projects need more RAM)
- Enable debug mode to identify problematic files
- Report issues at https://github.com/LogicStamp/logicstamp-context/issues
See Also
- context.md - Complete
stamp contextcommand reference - style.md - Style metadata extraction guide
- compare.md - Context drift detection
Related Commands
init command →
Configure .gitignore, project config, and onboarding files
context command →
Generate AI-ready context bundles
style command →
Compile bundles with Tailwind and style metadata
validate command →
Validate bundles, contracts, and missing dependencies
compare command →
Detect drift between snapshots or git baselines
Next Steps
Pair watch mode with style metadata or browse all CLI commands.