stamp context Command
Compile AI-ready bundles that describe your TypeScript codebase.
Generate bundles organized by folder that describe your TypeScript codebase.
stamp context [path] [options][path](optional) – Directory to scan. Defaults to the current working directory. Paths can be relative (./src) or absolute.
Output Structure: Generates multiple context.json files (one per folder containing components) plus a context_main.json index file at the output root, keeping your project's directory structure.
Setup: stamp context respects preferences saved in .logicstamp/config.json and never prompts. On first run (no config), it defaults to skipping both .gitignore and LLM_CONTEXT.md setup for CI-friendly behavior. Use stamp init to configure these options (non-interactive by default; use --no-secure for interactive mode).
File Exclusion: stamp context respects .stampignore and excludes those files from context compilation. You'll see how many files were excluded (unless using --quiet). Use stamp ignore <file> to add files to .stampignore. .stampignore is completely optional and independent of security scanning. See stampignore.md for details.
Secret Sanitization: If a security report (stamp_security_report.json) exists, stamp context automatically replaces detected secrets with "PRIVATE_DATA" in the generated JSON files. Your source code files are never modified - only the generated context files contain sanitized values. See security-scan.md for details.
Options
| Option | Alias | Default | Description |
|---|---|---|---|
--depth <n> | -d | 2 | Dependency traversal depth (0 = entry only, 1 = direct deps, 2 = nested components, etc.). |
--include-code <mode> | -c | header | Include none, header, or full source snippets. |
--format <fmt> | -f | json | Output format: json, pretty, ndjson, toon. |
--out <file> | -o | context.json | Output directory or file path. If a .json file is specified, its directory is used as the output directory. Otherwise, the path is used as the output directory. All context files will be written within this directory structure. |
--max-nodes <n> | -m | 100 | Maximum graph nodes per bundle. |
--profile <name> | llm-chat | Preset configuration (llm-chat, llm-safe, ci-strict, watch-fast). | |
--strict | -s | false | Fail when dependencies are missing. |
--strict-missing | false | Exit with error if any missing dependencies found. | |
--predict-behavior | false | Experimental behavioral prediction annotations. | |
--dry-run | false | Skip writing the output; display summary only. | |
--stats | false | Emit single-line JSON stats (ideal for CI). When combined with --compare-modes, writes context_compare_modes.json for MCP integration. | |
--compare-modes | false | Show detailed token comparison table across all modes (none/header/header+style/full) with accurate style metadata impact. When combined with --stats, writes context_compare_modes.json for MCP (Model Context Protocol) integration. See compare-modes.md for comprehensive guide. | |
--include-style | false | Extract style metadata (Tailwind, SCSS, Material UI, Ant Design, Chakra UI, animations, layout). | |
--style-mode <mode> | lean | Style output format: lean (counts + flags, compact) or full (arrays + details, verbose). Default is lean for token efficiency. | |
--skip-gitignore | false | Skip .gitignore setup (never prompt or modify). | |
--quiet | -q | false | Suppress verbose output (show only errors). |
--verbose | false | Show detailed bundle output (checkmarks for each file written). By default, only shows summary messages. | |
--watch | -w | false | Watch for file changes and regenerate automatically. |
--strict-watch | false | Enable strict watch mode - automatically enables watch mode and tracks breaking changes and violations during development. Exits with code 1 if errors detected. | |
--debug | false | Show detailed hash information in watch mode. | |
--log-file | false | Write structured change logs to file (watch mode only, for change notifications). | |
--help | -h | Print usage help. |
Depth Parameter
The --depth option controls how many levels deep the dependency graph includes. The default is 2 to ensure proper signature extraction for TypeScript projects.
Why Depth 2 is the Default
Problem with Depth 1:
- Only includes direct dependencies (components directly imported/used)
- Missing nested component signatures: If
AppusesHero, andHerousesButton, depth=1 only includesHeroin the bundle—Button's contract and signatures are missing - This leads to incomplete signature extraction, making it harder for AI assistants to understand component APIs
Why Depth 2 Works Better:
- Includes nested components (components used by components)
- Complete signature extraction: With depth=2,
App→Hero→Buttonall appear in the bundle with their full contracts - Better for React projects with component hierarchies
- Still efficient: header mode saves ~70% vs raw source even with depth=2
Example:
// App.tsx
import { Hero } from './Hero'
export function App() {
return <Hero />
}
// Hero.tsx
import { Button } from './Button'
export function Hero() {
return <Button>Click me</Button>
}
// Button.tsx
export function Button({ onClick, children }: ButtonProps) {
return <button onClick={onClick}>{children}</button>
}- Depth 1: Bundle includes
AppandHero, butButtonis missing → noButtonprops/signatures - Depth 2: Bundle includes
App,Hero, andButton→ complete component tree with all signatures ✅
When to Adjust Depth
Reduce to depth=1 if:
- You only need direct dependencies
- Bundle size is a concern and you're hitting
max-nodeslimits - You're analyzing simple projects without component hierarchies
Increase to depth=3+ if:
- You have deeply nested component trees
- You need to see dependencies 3+ levels deep
- You're doing comprehensive architecture analysis
Note: The max-nodes limit (default 100) prevents bundles from growing too large. If you hit this limit with depth=2, consider reducing depth or increasing max-nodes.
Profiles
- llm-chat (default) – Depth 2, header-only source, max 100 nodes. Balanced output for AI chat.
- llm-safe – Depth 2, header-only source, max 30 nodes, allows missing dependencies. Smaller footprint.
- ci-strict – No source code, strict dependency checks. Fails when contracts are missing.
Note: The
ci-strictprofile works well with git baseline comparison (v0.7.2). Usestamp context compare --baseline git:mainfor CI/CD workflows to detect changes against git refs. See compare.md for complete documentation.
Example workflows
# Scan entire repo and write context files (defaults)
stamp context
# Creates: context_main.json + context.json files in each folder
# Generate context for ./src with pretty-printed output
stamp context ./src --format pretty
# Include full source for deep AI reviews (limit nodes for safety)
stamp context --include-code full --max-nodes 20
# Gather metrics without writing files (e.g., CI dashboards)
stamp context --stats >> .ci/context-stats.jsonl
# Dry run to confirm counts before generating files
stamp context ./packages/ui --dry-run
# Suppress verbose output (quiet mode)
stamp context --quiet
# Show detailed bundle output (verbose mode)
stamp context --verbose
# Generate context with style metadata
stamp context style
# Or use the flag (equivalent)
stamp context --include-style
# Compare token costs across all modes (including style)
stamp context --compare-modes
# See compare-modes.md for comprehensive guide
# Generate comparison data file for MCP integration
stamp context --compare-modes --stats
# Creates: context_compare_modes.json with structured comparison data
# Watch mode - auto-regenerate on file changes
stamp context --watch
# Watch with style metadata
stamp context style --watch
# Watch a specific directory for fast incremental rebuilds
stamp context ./src/components --watch
# Watch with debug output (shows hash changes)
stamp context --watch --debug
# Strict watch mode - track breaking changes and violations
# (--strict-watch automatically enables watch mode)
stamp context --strict-watch
# Alternative: explicitly enable both (equivalent to above)
stamp context --watch --strict-watch
# Custom output directory
stamp context --out ./output
# Or specify a file to use its directory
stamp context --out ./output/context.jsonFile Exclusion with .stampignore
Files in .stampignore are excluded from context compilation (no flags needed). You'll see how many files were excluded (unless using --quiet). Supports glob patterns and exact file paths.
Example .stampignore:
{
"ignore": [
"src/config/secrets.ts",
"src/api/keys.ts",
"**/*.secret.ts"
]
}.stampignore is completely optional and can be created manually. It's independent of security scanning. See stampignore.md for complete documentation.
For complete documentation on .stampignore file format, see stampignore.md.
Secret Sanitization
When generating context files, LogicStamp automatically sanitizes secrets if a security report exists.
How it works:
- If
stamp_security_report.jsonexists in your project root, it's automatically used - Secrets detected in the security report are replaced with
"PRIVATE_DATA"in generated JSON files - Your source code files are never modified - only the generated context files are affected
Example:
Source code:
const apiKey = 'PLACEHOLDER_KEY_1234567890abcdef';
const password = 'FAKE_PASSWORD_FOR_DOCS_12345678';Generated context.json:
{
"code": "const apiKey = 'PRIVATE_DATA';\nconst password = 'PRIVATE_DATA';"
}Important:
- ✅ Source files remain unchanged
- ✅ Sanitization happens automatically (no flags needed)
- ✅ Works with all code inclusion modes (
--include-code none,header,full) - ✅ Applies to both
stamp contextandstamp context style
Code inclusion modes and credentials:
nonemode: No code is included, so credentials cannot appear in bundlesheadermode: Only JSDoc@uifmetadata blocks are included (not implementation code), so credentials in your source code will not appear in bundlesheader+stylemode: Same asheadermode (only metadata), plus style information in contracts (not code), so credentials will not appear in bundlesfullmode: Full source code is included, so credentials could appear unless sanitized. Sanitization automatically replaces detected secrets with"PRIVATE_DATA"when a security report exists
Even if credentials exist in your source files (which they shouldn't), they can only be included in generated bundles when using --include-code full mode. The other modes (none, header, header+style) only include metadata and contracts, not actual implementation code where credentials would typically be found.
To enable secret sanitization:
- Run
stamp security scan(orstamp initwhich runs it automatically) - This creates
stamp_security_report.json - Subsequent
stamp contextruns will automatically sanitize secrets
Completion messages:
✅ Generated context verified - no secret patterns detected- Security report exists and no secrets were found⚠️ Secret sanitization: Replaced X secret(s) in Y file(s)- Secrets were detected and sanitizedℹ️ Security scan skipped (no security report found)- No security report exists; runstamp initorstamp security scanto enable secret detection
See security-scan.md for more information about security scanning.
Output Structure
LogicStamp Context creates a folder-organized, multi-file output:
File Organization
output/
├── context_main.json # Main index with folder metadata
├── context.json # Root folder bundles (if any)
├── src/
│ └── context.json # Bundles from src/ folder
├── src/components/
│ └── context.json # Bundles from src/components/
└── src/utils/
└── context.json # Bundles from src/utils/Each folder containing components gets its own context.json file with bundles for that folder's components. The directory structure mirrors your project layout.
Main Index (context_main.json)
The context_main.json file provides a complete directory index:
{
"type": "LogicStampIndex",
"schemaVersion": "0.2",
"projectRoot": ".",
"createdAt": "2025-01-15T10:30:00.000Z",
"summary": {
"totalComponents": 42,
"totalBundles": 15,
"totalFolders": 5,
"totalTokenEstimate": 13895
},
"folders": [
{
"path": "src/components",
"contextFile": "src/components/context.json",
"bundles": 3,
"components": ["Button.tsx", "Card.tsx"],
"isRoot": false,
"tokenEstimate": 5234
},
{
"path": ".",
"contextFile": "context.json",
"bundles": 2,
"components": ["App.tsx"],
"isRoot": true,
"rootLabel": "Project Root",
"tokenEstimate": 2134
}
],
"meta": {
"source": "logicstamp-context@0.4.x"
}
}Each folder entry includes: path, contextFile, bundles, components, isRoot, rootLabel, and tokenEstimate.
Each folder's context.json contains bundles with:
- Contracts (UIFContract schema v0.4)
- Dependency graph (
nodesandedges) meta.missingfor unresolved dependencies:file not found,external package,outside scan path,max depth exceeded,circular dependency
Understanding meta.missing
An empty missing array means all dependencies were resolved. Non-empty means some couldn't be found.
Expected (safe to ignore): External packages (React, lodash, etc.)
Actionable: "file not found" (broken imports), "outside scan path" (expand scan directory), "max depth exceeded" (increase --depth)
Use --strict-missing in CI to catch unexpected missing dependencies:
stamp context --strict-missing || exit 1Watch Mode
Watch mode monitors your codebase for file changes and automatically regenerates context bundles with incremental rebuilds.
# Start watch mode
stamp context --watch
# Press Ctrl+C to stopFeatures:
- Incremental rebuilds - Only rebuilds affected bundles, not the entire project
- Change detection - Shows what changed (props added/removed, hooks, state, etc.)
- Debouncing - Batches rapid changes (500ms delay)
- Style support - Works with
--include-stylefor style metadata - Strict mode - Use
--strict-watchto detect breaking changes (removed props, events, etc.) with violation tracking
Watched file types:
.ts,.tsx(always).css,.scss,.module.css,.module.scss(with--include-style)
Debug mode shows detailed hash information:
stamp context --watch --debugFor comprehensive watch mode documentation, see watch.md.
Tips
- Combine
--profilepresets with manual flags for tailored runs (e.g.,--profile llm-safe --format pretty). - Use
--max-nodesto keep bundle size manageable before sharing with LLMs. - Run
stamp context validateafter generation to catch schema drift early. - Use
stamp context cleanto remove all context artifacts when resetting or switching branches. - Use
stamp context styleor--include-styleto extract visual and layout metadata for design-aware context bundles. Use--style-mode lean(default) for compact output or--style-mode fullfor detailed arrays. See style.md for detailed documentation. - Use
--compare-modesto see tokenizer-based or approximate token estimates across all modes (none/header/header+style/full) and understand the cost impact of including style metadata. - Use
--watchduring development for automatic context regeneration on file changes. See watch.md for details.
Token Estimation
Token counts are estimated using character-based approximations by default (~4 characters per token for GPT-4o, ~4.5 for Claude).
Optional Tokenizers: LogicStamp Context includes @dqbd/tiktoken (GPT-4o encoding) and @anthropic-ai/tokenizer (Claude) as optional dependencies. npm installs them automatically when you install logicstamp-context. When load succeeds, GPT-4o counts follow that tiktoken encoding. Claude: Anthropic’s package is documented as aligned with older models; for Claude 3+ it is only a rough local approximation—use usage in API responses when you need billing-accurate counts. If optional install fails or is skipped, the tool falls back to character-based estimation (~4 chars/token GPT-4o, ~4.5 Claude).
If the automatic installation failed, you can manually install them:
# GPT-4o-aligned counts (tiktoken)
npm install @dqbd/tiktoken
# Claude: rough local estimate (see @anthropic-ai/tokenizer readme)
npm install @anthropic-ai/tokenizerIf these packages are installed and load successfully, --compare-modes and token summaries use them instead of the character fallback.
Error Handling
The parser handles errors gracefully—malformed code returns empty AST structures instead of crashing, so it keeps processing other files.
Error handling is silent by default. Enable debug logging:
LOGICSTAMP_DEBUG=1 stamp contextDebug logs show file paths, failed extraction steps (hooks, props, components, state, events), and error messages with module-specific prefixes.
Files with syntax errors return empty AST structures but won't crash the tool. Use --strict-missing in CI to catch missing dependencies early.
Related Commands
init command →
Configure .gitignore, project config, and onboarding files
Watch Mode →
Incremental rebuilds while you work
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
Learn how to use it with LLMs or explore watch mode for automatic updates.