Compilation Command

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

OptionAliasDefaultDescription
--depth <n>-d2Dependency traversal depth (0 = entry only, 1 = direct deps, 2 = nested components, etc.).
--include-code <mode>-cheaderInclude none, header, or full source snippets.
--format <fmt>-fjsonOutput format: json, pretty, ndjson, toon.
--out <file>-ocontext.jsonOutput 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>-m100Maximum graph nodes per bundle.
--profile <name>llm-chatPreset configuration (llm-chat, llm-safe, ci-strict, watch-fast).
--strict-sfalseFail when dependencies are missing.
--strict-missingfalseExit with error if any missing dependencies found.
--predict-behaviorfalseExperimental behavioral prediction annotations.
--dry-runfalseSkip writing the output; display summary only.
--statsfalseEmit single-line JSON stats (ideal for CI). When combined with --compare-modes, writes context_compare_modes.json for MCP integration.
--compare-modesfalseShow 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-stylefalseExtract style metadata (Tailwind, SCSS, Material UI, Ant Design, Chakra UI, animations, layout).
--style-mode <mode>leanStyle output format: lean (counts + flags, compact) or full (arrays + details, verbose). Default is lean for token efficiency.
--skip-gitignorefalseSkip .gitignore setup (never prompt or modify).
--quiet-qfalseSuppress verbose output (show only errors).
--verbosefalseShow detailed bundle output (checkmarks for each file written). By default, only shows summary messages.
--watch-wfalseWatch for file changes and regenerate automatically.
--strict-watchfalseEnable strict watch mode - automatically enables watch mode and tracks breaking changes and violations during development. Exits with code 1 if errors detected.
--debugfalseShow detailed hash information in watch mode.
--log-filefalseWrite structured change logs to file (watch mode only, for change notifications).
--help-hPrint 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 App uses Hero, and Hero uses Button, depth=1 only includes Hero in 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, AppHeroButton all 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 App and Hero, but Button is missing → no Button props/signatures
  • Depth 2: Bundle includes App, Hero, and Button → 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-nodes limits
  • 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-strict profile works well with git baseline comparison (v0.7.2). Use stamp context compare --baseline git:main for 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.json

File 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.json exists 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 context and stamp context style

Code inclusion modes and credentials:

  • none mode: No code is included, so credentials cannot appear in bundles
  • header mode: Only JSDoc @uif metadata blocks are included (not implementation code), so credentials in your source code will not appear in bundles
  • header+style mode: Same as header mode (only metadata), plus style information in contracts (not code), so credentials will not appear in bundles
  • full mode: 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:

  1. Run stamp security scan (or stamp init which runs it automatically)
  2. This creates stamp_security_report.json
  3. Subsequent stamp context runs 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; run stamp init or stamp security scan to 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 (nodes and edges)
  • meta.missing for 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 1

Watch 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 stop

Features:

  • 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-style for style metadata
  • Strict mode - Use --strict-watch to 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 --debug

For comprehensive watch mode documentation, see watch.md.

Tips

  • Combine --profile presets with manual flags for tailored runs (e.g., --profile llm-safe --format pretty).
  • Use --max-nodes to keep bundle size manageable before sharing with LLMs.
  • Run stamp context validate after generation to catch schema drift early.
  • Use stamp context clean to remove all context artifacts when resetting or switching branches.
  • Use stamp context style or --include-style to extract visual and layout metadata for design-aware context bundles. Use --style-mode lean (default) for compact output or --style-mode full for detailed arrays. See style.md for detailed documentation.
  • Use --compare-modes to 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 --watch during 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/tokenizer

If 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 context

Debug 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.

Next Steps

Learn how to use it with LLMs or explore watch mode for automatic updates.