A tiny CLI that compiles your React/TypeScript codebase into machine-readable context bundles for AI and CI. Fast, deterministic, zero-config.
npm install -g logicstamp-context
cd your-project
stamp contextThat's it! LogicStamp Context will scan your project and generate context.json files organized by folder, plus a context_main.json index file. Share these files with AI assistants for instant codebase understanding.
Note: This is a beta release (v0.1.0). We're actively improving the tool based on user feedback. If you encounter any issues or have suggestions, please open an issue on GitHub.
LogicStamp Context is a lightweight tool that scans your React/TypeScript codebase and generates structured context bundles optimized for AI tools like Claude, ChatGPT, and other LLMs.
No setup, no configuration, no pre-compilation required. Just point it at your code and get instant, AI-ready documentation.
npm install -g logicstamp-contextAfter installation, the stamp command will be available globally.
Note: "Global CLI" means the tool is installed globally on your system (via npm install -g), making the stamp command available from any directory in your terminal, not just within a specific project folder.
- Local install:
npm install logicstamp-contextβ only available in that project - Global install:
npm install -g logicstamp-contextβ available everywhere viastampcommand
π Token Cost Optimization
- Automatic token estimates for GPT-4o-mini and Claude
- Mode comparison showing savings (none/header/full)
--compare-modesflag for detailed token analysis
π Multi-File Context Drift Detection
- New
comparecommand with multi-file support - Compares all context files using
context_main.jsonas index - Detects ADDED folders, ORPHANED folders, per-folder DRIFT, and PASS status
- Three-tier output: folder summary β component summary β detailed changes
--clean-orphanedflag to automatically remove stale context files- CI-friendly exit codes and per-folder token delta stats
βοΈ Next.js App Router Support
- Detects
'use client'and'use server'directives - Identifies files in Next.js App Router (
/appdirectory) - Adds metadata to contracts for framework-aware analysis
β Enhanced Component Detection
- Fixed React component detection for HTML-only JSX
- Improved dependency resolution (relative paths prioritized)
- Better handling of cross-directory component references
π‘οΈ CI/CD Improvements
--strict-missingflag for dependency validation- Enhanced
--statsoutput with mode estimates - JSON output optimized for CI parsing
# Install globally
npm i -g logicstamp-context
# Generate context.json (llm-chat profile)
stamp context
# Preview stats without writing files
stamp context --dry-run --stats
# Compare token costs across modes
stamp context --compare-modes
# Generate minimal API documentation
stamp context --include-code none --format pretty --out docs/api.json
# Compare all context files for drift (multi-file mode)
stamp context compare
# Auto-approve and update all drifted files (like jest -u)
stamp context compare --approve
# Compare with per-folder token stats
stamp context compare --stats
# Compare two specific context files
stamp context compare old.json new.json --stats
# Validate generated context
stamp context validate context.json
# Clean all context artifacts (dry run)
stamp context clean
# Actually delete all context files
stamp context clean --all --yesWhy? Generate AI-ready context from your React/TS codebase in seconds with built-in token cost optimization.
LogicStamp Context analyzes your React components and outputs a structured JSON file containing:
- Component structure: variables, hooks, components, functions
- Logic signatures: props, events, state types
- Dependency graph: how components relate to each other
- Code snippets: headers or full source (configurable)
- Semantic hashes: for tracking changes
- Next.js metadata: App Router directives and file location (when applicable)
This output is designed to be easily understood by AI assistants, helping them provide better suggestions and understand your codebase architecture.
LogicStamp Context automatically detects and annotates Next.js App Router components:
'use client'directive - Marks Client Components'use server'directive - Marks Server Actions- App Router location - Identifies files in
/appdirectory
{
"type": "UIFContract",
"kind": "react:component",
"entryId": "app/dashboard/page.tsx",
"nextjs": {
"directive": "client",
"isInAppDir": true
}
}- Framework-aware suggestions - AI knows which APIs are available (client vs server)
- Better refactoring - AI understands boundaries between client/server code
- Accurate recommendations - AI won't suggest client-only hooks in Server Components
β
Client Components with 'use client'
β
Server Actions with 'use server'
β
Server Components in /app directory (no directive)
β
Regular components outside /app (no metadata)
Note: The nextjs field is only added when relevant, keeping contracts clean for non-Next.js projects.
stamp --version # Show version number
stamp --help # Show help
stamp init [path] [options]
stamp context [path] [options]
stamp context compare <old.json> <new.json> [options]
stamp context validate [file] [options]
stamp context clean [path] [options]-
stamp init [path]- Initialize LogicStamp in a project by creating or updating.gitignorewith patterns for context files (context.json,context_*.json,.logicstamp/, etc.), generatingLLM_CONTEXT.mdin the project root, and saving preferences to.logicstamp/config.json. Optional - thestamp contextcommand includes smart detection and will prompt you interactively on first run.See docs/cli/INIT.md for detailed documentation.
-
stamp context [path]- Scans a directory and writes AI-ready context files organized by folder. Generates multiplecontext.jsonfiles (one per folder containing components) plus acontext_main.jsonindex file at the output root. Shows token estimates and mode comparison in output. Automatically validates the generated context before writing. On first run (interactive mode), prompts to add.gitignorepatterns and generateLLM_CONTEXT.md, saving your preferences - subsequent runs respect your choices.See docs/cli/CONTEXT.md for detailed documentation.
-
stamp context compare [options]- Compares all context files (multi-file mode) or two specific files to detect drift. In multi-file mode, usescontext_main.jsonas index to compare all folder context files and detect ADDED/ORPHANED folders, per-folder DRIFT, and unchanged files (PASS). Shows three-tier output: folder summary, component summary, and detailed changes. Supports--approvefor auto-updates (Jest-style),--clean-orphanedto remove stale files, and--statsfor per-folder token deltas. Exits with code 1 if drift is detected (CI-friendly).See docs/cli/COMPARE.md for detailed documentation.
-
stamp context validate [file]- Checks an existing context file for schema and structural issues before sharing it with an AI or committing it to a repo. When no file is specified it looks forcontext.jsonin the current directory.See docs/cli/VALIDATE.md for detailed documentation.
-
stamp context clean [path]- Removes all generated context artifacts (context_main.json, all foldercontext.jsonfiles, and.logicstamp/directory if present). Safe by default (dry run), requires--all --yesto actually delete. Useful for resetting context files or cleaning before switching branches.See docs/cli/CLEAN.md for detailed documentation.
[path]- Target directory to initialize (default: current directory)--skip-gitignore- Skip.gitignoresetup--help,-h- Show help message
See docs/cli/INIT.md for detailed documentation.
[path]- Directory to scan (default: current directory)
| Option | Alias | Description | Default |
|---|---|---|---|
--depth <n> |
-d |
Dependency traversal depth | 1 |
--include-code <mode> |
-c |
Code inclusion: none|header|full |
header |
--format <format> |
-f |
Output format: json|pretty|ndjson |
json |
--out <file> |
-o |
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. |
context.json (creates output directory) |
--max-nodes <n> |
-m |
Maximum nodes per bundle | 100 |
--profile <profile> |
Profile preset (see below) | llm-chat |
|
--strict |
-s |
Fail on missing dependencies | false |
--strict-missing |
Exit with error code 1 if any missing dependencies found (CI-friendly) | false |
|
--predict-behavior |
Include experimental behavior predictions in contracts | false |
|
--dry-run |
Skip writing output; show on-screen summary only | false |
|
--stats |
Emit single-line JSON stats with token estimates (intended for CI) | false |
|
--compare-modes |
Show detailed token comparison table across modes (none/header/full) | false |
|
--skip-gitignore |
Skip .gitignore setup (never prompt or modify) |
false |
|
--quiet |
-q |
Suppress verbose output (show only errors) | false |
--help |
-h |
Show help message |
| Option | Description | Default |
|---|---|---|
--stats |
Show token count statistics and delta | false |
--approve |
Auto-approve updates (non-interactive, CI-safe) | false |
--clean-orphaned |
Auto-delete orphaned files with --approve |
false |
--quiet |
-q |
Suppress verbose output (show only diffs) |
--help, -h |
Show help message |
[file]β Optional path to a generatedcontext.jsonfile to validate. Defaults to./context.json. You can validate individual folder context files or the main index file.--quiet|-qβ Suppress verbose output (show only errors)- Exits with code
0on success,1on invalid structure or read/parse errors. - Prints bundle counts, node totals, and highlights schema mismatches.
Profiles are preset configurations optimized for different use cases:
Balanced mode for AI chat interfaces
- Depth: 1
- Code: headers only
- Max nodes: 100
- Behavioral predictions: disabled by default (enable with
--predict-behavior)
Conservative mode for token-limited contexts
- Depth: 1
- Code: headers only
- Max nodes: 30
- Behavioral predictions: disabled by default (enable with
--predict-behavior)
Strict validation mode for CI/CD
- Code: none
- Strict dependencies enabled
- Behavioral predictions: not applicable (metadata-only mode)
The --predict-behavior flag enables experimental behavioral analysis that adds predicted component behaviors to the contract output. These predictions include:
- Form validation patterns
- Side effect management (useEffect)
- Data fetching/mutation patterns
- Memoization usage
- Context consumption
- Ref usage for DOM access
- Loading/error state handling
Note: Behavioral predictions are disabled by default in all profiles to minimize token usage. Enable them explicitly when you need richer semantic information about component behavior.
Example:
# Enable predictions with the default profile
stamp context --predict-behavior
# Enable predictions with a specific profile
stamp context --profile llm-safe --predict-behaviorLogicStamp Context includes built-in token cost analysis and optimization features:
Every context generation shows token costs for both GPT-4o-mini and Claude:
π Token Estimates (header mode):
GPT-4o-mini: 13,895 | Full code: ~39,141 (~65% savings)
Claude: 12,351 | Full code: ~34,792 (~65% savings)
π Mode Comparison:
none: ~8,337 tokens
header: ~13,895 tokens
full: ~39,141 tokens
This helps you:
- Understand costs at a glance
- Choose the right mode for your budget
- See savings compared to including full source code
Use --compare-modes for a detailed comparison:
stamp context --compare-modesOutput:
π Mode Comparison
Mode | Tokens GPT-4o | Tokens Claude | Savings vs Full
---------|---------------|---------------|------------------
none | 8,337 | 7,411 | 79%
header | 13,895 | 12,351 | 65%
full | 39,141 | 34,792 | 0%
When to use each mode:
none- API documentation, CI validation (no code snippets)header- AI chat, code review (JSDoc headers + contracts)full- Deep analysis, debugging (complete source code)
Use --stats to get machine-readable token data:
stamp context --statsOutput JSON includes:
{
"tokensGPT4": 13895,
"tokensClaude": 12351,
"modeEstimates": {
"none": {"gpt4": 8337, "claude": 7411},
"header": {"gpt4": 13895, "claude": 12351},
"full": {"gpt4": 39141, "claude": 34792}
},
"savingsGPT4": "65",
"savingsClaude": "65"
}The compare command helps you track changes between context versions:
stamp context compare old.json new.jsonOutput:
β
PASS
# or if changes detected:
β οΈ DRIFT
Added components: 2
+ src/components/NewButton.tsx
+ src/utils/helpers.ts
Removed components: 1
- src/components/OldButton.tsx
Changed components: 3
~ src/components/Card.tsx
Ξ imports, hooks
~ src/App.tsx
Ξ hash
stamp context compare old.json new.json --statsShows token cost changes:
Token Stats:
Old: 8,484 (GPT-4o-mini) | 7,542 (Claude)
New: 9,125 (GPT-4o-mini) | 8,111 (Claude)
Ξ +641 (+7.56%)
0- No drift (PASS)1- Drift detected or error
Perfect for CI/CD validation:
# In your CI pipeline
stamp context compare base.json pr.json || echo "Context drift detected!"# Generate context for entire project
stamp context
# CLI output:
# π Scanning /path/to/project...
# βοΈ Analyzing components...
# π Building dependency graph...
# π¦ Generating context...
# π Validating generated context...
# β
Validation passed
# π Writing context files for 5 folders...
# β context.json (2 bundles)
# β src/context.json (3 bundles)
# β src/components/context.json (5 bundles)
# β src/utils/context.json (2 bundles)
# β app/context.json (3 bundles)
# π Writing main context index...
# β context_main.json (index of 5 folders)
# β
6 context files written successfully
#
# π Summary:
# Total components: 15
# Root components: 3
# ...# Analyze only the src directory
stamp context ./src
# Analyze with custom output directory
stamp context --out ./output
# Or specify a .json file to use its directory
stamp context --out ./output/context.json # Uses ./output as directory# Include 2 levels of dependencies
stamp context --depth 2
# Include full source code
stamp context --include-code full# Show detailed mode comparison
stamp context --compare-modes
# Get JSON stats for CI
stamp context --stats
# See token costs for specific mode
stamp context --include-code none
stamp context --include-code full# Basic drift detection
stamp context compare old.json new.json
# With token delta stats
stamp context compare base.json pr.json --stats
# In CI pipeline
stamp context compare base.json pr.json || exit 1# Show what would be removed (dry run)
stamp context clean
# Actually delete all context artifacts
stamp context clean --all --yes
# Clean specific directory
stamp context clean ./output --all --yes
# Suppress verbose output (quiet mode)
stamp context --quiet
stamp context validate --quiet
stamp context compare --quiet
stamp context clean --all --yes --quiet
# Show version number
stamp --version# Use llm-safe profile for smaller output
stamp context --profile llm-safe --out safe-context.json
# Strict mode: fail if any dependencies missing
stamp context --strict-missing
# Generate stats for CI monitoring
stamp context --stats > stats.json
# Validate generated context
stamp context validate context.jsonLogicStamp Context generates a folder-organized, multi-file output structure that maintains your project's directory hierarchy:
The tool writes multiple context.json files, one per folder containing components, plus a context_main.json index file at the output root:
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's context.json contains bundles for components in that folder. This organization:
- Matches your project structure - Easy to locate context for specific directories
- Enables incremental updates - Only regenerate context for changed folders
- Improves AI context loading - Load only relevant folder contexts
- Maintains relative paths - Folder structure mirrors your project layout
The context_main.json file serves as a directory index with:
{
"type": "LogicStampIndex",
"schemaVersion": "0.1",
"projectRoot": ".",
"projectRootResolved": "/absolute/path/to/project",
"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", "Modal.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.1.0"
}
}Key fields in folder entries:
path- Relative path from project rootcontextFile- Path to the folder's context.json filebundles- Number of bundles in this foldercomponents- List of component files in this folderisRoot- Whether this folder is an application entry pointrootLabel- Human-readable label for root folders (e.g., "Next.js App", "Project Root")tokenEstimate- Estimated token count for this folder's context
Each folder's context.json contains an array of bundles (one bundle per entry point). Each bundle represents a root component plus its complete dependency graph, with all related components and their contracts included within that bundle. This per-root bundle design is optimized for how developers and LLMs workβwhen you need help with a specific page or feature, the root bundle contains everything related to that feature in one self-contained unit.
π Full Schema Reference: See schema/logicstamp.context.schema.json for the complete JSON Schema definition.
Example: src/components/context.json
[
{
"$schema": "https://logicstamp.dev/schemas/context/v0.1.json",
"position": "1/3",
"type": "LogicStampBundle",
"schemaVersion": "0.1",
"entryId": "src/components/Button.tsx",
"depth": 1,
"createdAt": "2025-01-15T10:30:00.000Z",
"bundleHash": "uifb:abc123...",
"graph": {
"nodes": [
{
"entryId": "src/components/Button.tsx",
"contract": {
"type": "UIFContract",
"schemaVersion": "0.3",
"kind": "react:component",
"description": "Button - Interactive component",
"version": {
"variables": ["variant", "size"],
"hooks": ["useState"],
"components": [],
"functions": ["handleClick"]
},
"logicSignature": {
"props": {
"onClick": { "type": "function", "signature": "() => void" },
"variant": { "type": "literal-union", "literals": ["primary", "secondary"] }
},
"events": {},
"state": {}
},
"nextjs": {
"directive": "client",
"isInAppDir": true
}
}
}
],
"edges": []
},
"meta": {
"missing": [],
"source": "logicstamp-context@0.1.0"
}
}
]π Full Schema Reference: See schema/logicstamp.context.schema.json for the complete JSON Schema definition.
The meta section provides metadata about bundle generation and dependency resolution:
Tracks dependencies that couldn't be resolved during analysis. An empty array [] means all dependencies were successfully found.
When dependencies are missing, each entry contains:
name- The import specifier that couldn't be resolved (e.g.,"./MissingComponent")reason- Why it couldn't be found (e.g.,"file not found","external package")referencedBy- The component that tried to import it
Example with missing dependencies:
{
"meta": {
"missing": [
{
"name": "./components/DeletedComponent",
"reason": "file not found",
"referencedBy": "src/App.tsx"
},
{
"name": "@external/ui-lib",
"reason": "external package",
"referencedBy": "src/components/Button.tsx"
}
],
"source": "logicstamp-context@0.1.0"
}
}Common reasons for missing dependencies:
file not found- Referenced file doesn't exist (deleted or moved)external package- Third-party npm package (intentionally excluded)outside scan path- File exists but outside the specified scan directorycircular dependency- Circular import detected and skippedmax depth exceeded- Dependency beyond--depthlimit
Using --strict-missing for CI/CD:
# Exit with error code 1 if ANY missing dependencies found
stamp context --strict-missing
# Perfect for CI validation
stamp context --strict-missing || exit 1Identifies the generator and version (e.g., "logicstamp-context@0.1.0"). Useful for:
- Debugging context generation issues
- Ensuring compatibility with consuming tools
- Tracking which version generated historical contexts
Share context with Claude or ChatGPT to get:
- Architecture suggestions
- Refactoring recommendations
- Bug fixes based on full component understanding
Generate up-to-date component documentation automatically:
- API contracts
- Dependency trees
- Component relationships
Quickly understand component structure and dependencies:
- Identify circular dependencies
- Find unused components
- Track component complexity
If your generated context shows missing dependencies in the meta.missing array:
{
"name": "@mui/material",
"reason": "external package"
}Solution: This is normal. LogicStamp only analyzes your source code, not node_modules. External packages are intentionally excluded.
{
"name": "./components/OldButton",
"reason": "file not found",
"referencedBy": "src/App.tsx"
}Solutions:
- Check if the file was deleted or moved
- Update the import path in the referencing component
- Use
--strict-missingin CI to catch these issues early
{
"name": "../../shared/utils",
"reason": "outside scan path"
}Solutions:
- Expand your scan path:
stamp context ../(parent directory) - Or scan from project root:
stamp context .(from root)
{
"name": "./deeply/nested/component",
"reason": "max depth exceeded"
}Solutions:
- Increase depth:
stamp context --depth 2or--depth 3 - Note: Higher depth = more tokens consumed
{
"name": "./ComponentA",
"reason": "circular dependency"
}Solutions:
- Refactor to break the circular import
- Extract shared logic to a separate module
- This is a code smell that should be addressed
Q: Why is my context.json huge?
- Use
--include-code noneto exclude all source code (smallest) - Use
--include-code header(default) for balanced output - Use
--profile llm-safefor token-constrained scenarios - Check
--compare-modesto see token savings
Q: Validation failed - what went wrong?
stamp context validate context.json
# Or validate the main index
stamp context validate context_main.json- Check for schema mismatches (outdated schema version)
- Verify JSON is well-formed (no trailing commas, proper escaping)
- Ensure all required fields are present
- Each folder's context.json should be a valid bundle array
- The context_main.json should have the LogicStampIndex structure
Q: How do I ignore certain directories?
- LogicStamp respects
.gitignoreautomatically node_modules/and common build directories are excluded by default- Scan specific directories:
stamp context ./src
- Scan: Finds all
.tsand.tsxfiles in your project - Analyze: Parses React components using TypeScript AST
- Extract: Builds component contracts with structure and signatures
- Graph: Creates dependency graph showing relationships
- Bundle: Packages context bundles optimized for AI consumption
- Organize: Groups bundles by folder and writes
context.jsonfiles maintaining directory structure - Index: Creates
context_main.jsonindex with folder metadata and summary statistics
All in one command, no pre-compilation needed!
logicstamp-context is the primary CLI available today. A higher-level orchestrator package @logicstamp/cli is planned as an optional wrapper.
| Feature | logicstamp-context | LogicStamp Orchestrator (planned) |
|---|---|---|
| Standalone | β Yes | β No (wraps underlying tools) |
| Pre-compilation required | β No | β Yes (for verification) |
| Context generation | β Yes | β Yes |
| UIF contracts per file | β Yes (embedded in bundles) | β
Yes (as .uif.json sidecar files) |
| Contract compilation | β Built-in | β Separate command |
| Contract verification | β No | β Yes (planned) |
| Size | Focused | Orchestrator |
TL;DR: Use stamp context (logicstamp-context) for AI context generation today. The future @logicstamp/cli orchestrator will provide optional higher-level workflows once it's released.
The current Next.js support (v0.1) provides foundational directive and App Router detection. Future versions may include:
App Router Advanced Features
roledetection - Identifypage,layout,route,loading,errorfilessegmentPathextraction - Capture dynamic route segments (e.g.,[id],[...slug])- Route dependency graph - Map App Router file relationships
- Metadata exports - Detect
generateMetadata,generateStaticParams
Server Actions & RPC
- Server Action signature extraction from
'use server'blocks - Form action detection and validation
- RPC call graph (client β server action relationships)
Streaming & Suspense
- Suspense boundary detection
- Streaming component identification
- Loading states and error boundaries
Example Future Contract
{
"nextjs": {
"directive": "client",
"isInAppDir": true,
"role": "page",
"segmentPath": "dashboard/[userId]",
"hasMetadata": true
}
}Note: These features will be added incrementally based on community feedback and real-world usage patterns. The current implementation prioritizes the 80/20 rule - maximum value with minimal complexity.
- Vue.js Support - Extend to Vue 3 Composition API components
- Svelte Support - Component analysis for Svelte files
- Custom Contract Fields - User-defined metadata via config
- Performance Metrics - Bundle size and render performance estimates
- Node.js >= 18.0.0
- TypeScript/React codebase
MIT
Issues and PRs welcome! This is an open-source project.
See CONTRIBUTING.md for detailed guidelines, including:
- Branching strategy (feature β
main, nodevelopbranch) - Branch naming conventions (
feature/*,fix/*,docs/*) - Commit message format (Conventional Commits)
- Development workflow and best practices
#TEST: CI Workflow