logicstamp-context 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/LICENSE +21 -0
  2. package/LLM_CONTEXT.md +260 -0
  3. package/README.md +949 -0
  4. package/dist/cli/commands/clean.d.ts +15 -0
  5. package/dist/cli/commands/clean.d.ts.map +1 -0
  6. package/dist/cli/commands/clean.js +142 -0
  7. package/dist/cli/commands/clean.js.map +1 -0
  8. package/dist/cli/commands/compare.d.ts +88 -0
  9. package/dist/cli/commands/compare.d.ts.map +1 -0
  10. package/dist/cli/commands/compare.js +519 -0
  11. package/dist/cli/commands/compare.js.map +1 -0
  12. package/dist/cli/commands/context.d.ts +24 -0
  13. package/dist/cli/commands/context.d.ts.map +1 -0
  14. package/dist/cli/commands/context.js +576 -0
  15. package/dist/cli/commands/context.js.map +1 -0
  16. package/dist/cli/commands/init.d.ts +14 -0
  17. package/dist/cli/commands/init.d.ts.map +1 -0
  18. package/dist/cli/commands/init.js +71 -0
  19. package/dist/cli/commands/init.js.map +1 -0
  20. package/dist/cli/commands/validate.d.ts +52 -0
  21. package/dist/cli/commands/validate.d.ts.map +1 -0
  22. package/dist/cli/commands/validate.js +368 -0
  23. package/dist/cli/commands/validate.js.map +1 -0
  24. package/dist/cli/index.d.ts +7 -0
  25. package/dist/cli/index.d.ts.map +1 -0
  26. package/dist/cli/index.js +223 -0
  27. package/dist/cli/index.js.map +1 -0
  28. package/dist/cli/stamp.d.ts +7 -0
  29. package/dist/cli/stamp.d.ts.map +1 -0
  30. package/dist/cli/stamp.js +961 -0
  31. package/dist/cli/stamp.js.map +1 -0
  32. package/dist/cli/validate-index.d.ts +7 -0
  33. package/dist/cli/validate-index.d.ts.map +1 -0
  34. package/dist/cli/validate-index.js +55 -0
  35. package/dist/cli/validate-index.js.map +1 -0
  36. package/dist/core/astParser.d.ts +47 -0
  37. package/dist/core/astParser.d.ts.map +1 -0
  38. package/dist/core/astParser.js +417 -0
  39. package/dist/core/astParser.js.map +1 -0
  40. package/dist/core/contractBuilder.d.ts +48 -0
  41. package/dist/core/contractBuilder.d.ts.map +1 -0
  42. package/dist/core/contractBuilder.js +120 -0
  43. package/dist/core/contractBuilder.js.map +1 -0
  44. package/dist/core/manifest.d.ts +75 -0
  45. package/dist/core/manifest.d.ts.map +1 -0
  46. package/dist/core/manifest.js +173 -0
  47. package/dist/core/manifest.js.map +1 -0
  48. package/dist/core/pack.d.ts +190 -0
  49. package/dist/core/pack.d.ts.map +1 -0
  50. package/dist/core/pack.js +438 -0
  51. package/dist/core/pack.js.map +1 -0
  52. package/dist/core/signature.d.ts +47 -0
  53. package/dist/core/signature.d.ts.map +1 -0
  54. package/dist/core/signature.js +208 -0
  55. package/dist/core/signature.js.map +1 -0
  56. package/dist/index.d.ts +27 -0
  57. package/dist/index.d.ts.map +1 -0
  58. package/dist/index.js +23 -0
  59. package/dist/index.js.map +1 -0
  60. package/dist/types/UIFContract.d.ts +112 -0
  61. package/dist/types/UIFContract.d.ts.map +1 -0
  62. package/dist/types/UIFContract.js +36 -0
  63. package/dist/types/UIFContract.js.map +1 -0
  64. package/dist/utils/config.d.ts +34 -0
  65. package/dist/utils/config.d.ts.map +1 -0
  66. package/dist/utils/config.js +62 -0
  67. package/dist/utils/config.js.map +1 -0
  68. package/dist/utils/fsx.d.ts +85 -0
  69. package/dist/utils/fsx.d.ts.map +1 -0
  70. package/dist/utils/fsx.js +181 -0
  71. package/dist/utils/fsx.js.map +1 -0
  72. package/dist/utils/gitignore.d.ts +62 -0
  73. package/dist/utils/gitignore.d.ts.map +1 -0
  74. package/dist/utils/gitignore.js +183 -0
  75. package/dist/utils/gitignore.js.map +1 -0
  76. package/dist/utils/hash.d.ts +73 -0
  77. package/dist/utils/hash.d.ts.map +1 -0
  78. package/dist/utils/hash.js +159 -0
  79. package/dist/utils/hash.js.map +1 -0
  80. package/dist/utils/llmContext.d.ts +34 -0
  81. package/dist/utils/llmContext.d.ts.map +1 -0
  82. package/dist/utils/llmContext.js +136 -0
  83. package/dist/utils/llmContext.js.map +1 -0
  84. package/dist/utils/tokens.d.ts +23 -0
  85. package/dist/utils/tokens.d.ts.map +1 -0
  86. package/dist/utils/tokens.js +29 -0
  87. package/dist/utils/tokens.js.map +1 -0
  88. package/package.json +69 -0
  89. package/schema/logicstamp.context.schema.json +430 -0
package/README.md ADDED
@@ -0,0 +1,949 @@
1
+ # LogicStamp Context
2
+
3
+ <div align="center">
4
+ <img src="assets/logicstamp-fox.svg" alt="LogicStamp Fox Mascot" width="120" height="120">
5
+ </div>
6
+
7
+ ![Version](https://img.shields.io/badge/version-0.1.0-blue.svg)
8
+ ![Beta](https://img.shields.io/badge/status-beta-orange.svg)
9
+ ![License](https://img.shields.io/badge/license-MIT-green.svg)
10
+ ![Node](https://img.shields.io/badge/node-%3E%3D18.0.0-brightgreen.svg)
11
+ [![CI](https://github.com/LogicStamp/logicstamp-context/workflows/CI/badge.svg)](https://github.com/LogicStamp/logicstamp-context/actions)
12
+
13
+ **A tiny CLI that compiles your React/TypeScript codebase into machine-readable context bundles for AI and CI. Fast, deterministic, zero-config.**
14
+
15
+ ## Quick Start
16
+
17
+ ```bash
18
+ npm install -g logicstamp-context
19
+ cd your-project
20
+ stamp context
21
+ ```
22
+
23
+ That'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.
24
+
25
+ > **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](https://github.com/LogicStamp/logicstamp-context/issues).
26
+
27
+ ## What is this?
28
+
29
+ **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.
30
+
31
+ No setup, no configuration, no pre-compilation required. Just point it at your code and get instant, AI-ready documentation.
32
+
33
+ ## Installation
34
+
35
+ ```bash
36
+ npm install -g logicstamp-context
37
+ ```
38
+
39
+ After installation, the `stamp` command will be available globally.
40
+
41
+ **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.
42
+ - **Local install**: `npm install logicstamp-context` → only available in that project
43
+ - **Global install**: `npm install -g logicstamp-context` → available everywhere via `stamp` command
44
+
45
+ ## What's New in v0.1.0
46
+
47
+ 🎉 **Token Cost Optimization**
48
+ - Automatic token estimates for GPT-4o-mini and Claude
49
+ - Mode comparison showing savings (none/header/full)
50
+ - `--compare-modes` flag for detailed token analysis
51
+
52
+ 🔍 **Multi-File Context Drift Detection**
53
+ - New `compare` command with multi-file support
54
+ - Compares **all context files** using `context_main.json` as index
55
+ - Detects ADDED folders, ORPHANED folders, per-folder DRIFT, and PASS status
56
+ - Three-tier output: folder summary → component summary → detailed changes
57
+ - `--clean-orphaned` flag to automatically remove stale context files
58
+ - CI-friendly exit codes and per-folder token delta stats
59
+
60
+ ⚛️ **Next.js App Router Support**
61
+ - Detects `'use client'` and `'use server'` directives
62
+ - Identifies files in Next.js App Router (`/app` directory)
63
+ - Adds metadata to contracts for framework-aware analysis
64
+
65
+ ✅ **Enhanced Component Detection**
66
+ - Fixed React component detection for HTML-only JSX
67
+ - Improved dependency resolution (relative paths prioritized)
68
+ - Better handling of cross-directory component references
69
+
70
+ 🛡️ **CI/CD Improvements**
71
+ - `--strict-missing` flag for dependency validation
72
+ - Enhanced `--stats` output with mode estimates
73
+ - JSON output optimized for CI parsing
74
+
75
+ ## Quick Start
76
+
77
+ ```bash
78
+ # Install globally
79
+ npm i -g logicstamp-context
80
+
81
+ # Generate context.json (llm-chat profile)
82
+ stamp context
83
+
84
+ # Preview stats without writing files
85
+ stamp context --dry-run --stats
86
+
87
+ # Compare token costs across modes
88
+ stamp context --compare-modes
89
+
90
+ # Generate minimal API documentation
91
+ stamp context --include-code none --format pretty --out docs/api.json
92
+
93
+ # Compare all context files for drift (multi-file mode)
94
+ stamp context compare
95
+
96
+ # Auto-approve and update all drifted files (like jest -u)
97
+ stamp context compare --approve
98
+
99
+ # Compare with per-folder token stats
100
+ stamp context compare --stats
101
+
102
+ # Compare two specific context files
103
+ stamp context compare old.json new.json --stats
104
+
105
+ # Validate generated context
106
+ stamp context validate context.json
107
+
108
+ # Clean all context artifacts (dry run)
109
+ stamp context clean
110
+
111
+ # Actually delete all context files
112
+ stamp context clean --all --yes
113
+ ```
114
+
115
+ **Why?** Generate AI-ready context from your React/TS codebase in seconds with built-in token cost optimization.
116
+
117
+ ## What does it generate?
118
+
119
+ LogicStamp Context analyzes your React components and outputs a structured JSON file containing:
120
+
121
+ - **Component structure**: variables, hooks, components, functions
122
+ - **Logic signatures**: props, events, state types
123
+ - **Dependency graph**: how components relate to each other
124
+ - **Code snippets**: headers or full source (configurable)
125
+ - **Semantic hashes**: for tracking changes
126
+ - **Next.js metadata**: App Router directives and file location (when applicable)
127
+
128
+ This output is designed to be easily understood by AI assistants, helping them provide better suggestions and understand your codebase architecture.
129
+
130
+ ## Next.js App Router Support
131
+
132
+ LogicStamp Context automatically detects and annotates Next.js App Router components:
133
+
134
+ ### Detected Features
135
+
136
+ - **`'use client'` directive** - Marks Client Components
137
+ - **`'use server'` directive** - Marks Server Actions
138
+ - **App Router location** - Identifies files in `/app` directory
139
+
140
+ ### Example Contract Output
141
+
142
+ ```json
143
+ {
144
+ "type": "UIFContract",
145
+ "kind": "react:component",
146
+ "entryId": "app/dashboard/page.tsx",
147
+ "nextjs": {
148
+ "directive": "client",
149
+ "isInAppDir": true
150
+ }
151
+ }
152
+ ```
153
+
154
+ ### Benefits for AI Analysis
155
+
156
+ - **Framework-aware suggestions** - AI knows which APIs are available (client vs server)
157
+ - **Better refactoring** - AI understands boundaries between client/server code
158
+ - **Accurate recommendations** - AI won't suggest client-only hooks in Server Components
159
+
160
+ ### Supported Scenarios
161
+
162
+ ✅ Client Components with `'use client'`
163
+ ✅ Server Actions with `'use server'`
164
+ ✅ Server Components in `/app` directory (no directive)
165
+ ✅ Regular components outside `/app` (no metadata)
166
+
167
+ **Note:** The `nextjs` field is only added when relevant, keeping contracts clean for non-Next.js projects.
168
+
169
+ ## Usage
170
+
171
+ ```bash
172
+ stamp --version # Show version number
173
+ stamp --help # Show help
174
+ stamp init [path] [options]
175
+ stamp context [path] [options]
176
+ stamp context compare <old.json> <new.json> [options]
177
+ stamp context validate [file] [options]
178
+ stamp context clean [path] [options]
179
+ ```
180
+
181
+ ### Commands
182
+
183
+ - **`stamp init [path]`** - Initialize LogicStamp in a project by creating or updating `.gitignore` with patterns for context files (`context.json`, `context_*.json`, `.logicstamp/`, etc.), generating `LLM_CONTEXT.md` in the project root, and saving preferences to `.logicstamp/config.json`. Optional - the `stamp context` command includes smart detection and will prompt you interactively on first run.
184
+
185
+ See [docs/cli/INIT.md](docs/cli/INIT.md) for detailed documentation.
186
+
187
+ - **`stamp context [path]`** - Scans a directory and writes AI-ready context files organized by folder. Generates multiple `context.json` files (one per folder containing components) plus a `context_main.json` index 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 `.gitignore` patterns and generate `LLM_CONTEXT.md`, saving your preferences - subsequent runs respect your choices.
188
+
189
+ See [docs/cli/CONTEXT.md](docs/cli/CONTEXT.md) for detailed documentation.
190
+
191
+ - **`stamp context compare [options]`** - Compares all context files (multi-file mode) or two specific files to detect drift. In multi-file mode, uses `context_main.json` as 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 `--approve` for auto-updates (Jest-style), `--clean-orphaned` to remove stale files, and `--stats` for per-folder token deltas. Exits with code 1 if drift is detected (CI-friendly).
192
+
193
+ See [docs/cli/COMPARE.md](docs/cli/COMPARE.md) for detailed documentation.
194
+
195
+ - **`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 for `context.json` in the current directory.
196
+
197
+ See [docs/cli/VALIDATE.md](docs/cli/VALIDATE.md) for detailed documentation.
198
+
199
+ - **`stamp context clean [path]`** - Removes all generated context artifacts (`context_main.json`, all folder `context.json` files, and `.logicstamp/` directory if present). Safe by default (dry run), requires `--all --yes` to actually delete. Useful for resetting context files or cleaning before switching branches.
200
+
201
+ See [docs/cli/CLEAN.md](docs/cli/CLEAN.md) for detailed documentation.
202
+
203
+ ### Arguments & Options (`init` command)
204
+
205
+ - `[path]` - Target directory to initialize (default: current directory)
206
+ - `--skip-gitignore` - Skip `.gitignore` setup
207
+ - `--help`, `-h` - Show help message
208
+
209
+ See [docs/cli/INIT.md](docs/cli/INIT.md) for detailed documentation.
210
+
211
+ ### Arguments (`context` command)
212
+
213
+ - `[path]` - Directory to scan (default: current directory)
214
+
215
+ ### Options (`context` command)
216
+
217
+ | Option | Alias | Description | Default |
218
+ |--------|-------|-------------|---------|
219
+ | `--depth <n>` | `-d` | Dependency traversal depth | `1` |
220
+ | `--include-code <mode>` | `-c` | Code inclusion: `none\|header\|full` | `header` |
221
+ | `--format <format>` | `-f` | Output format: `json\|pretty\|ndjson` | `json` |
222
+ | `--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) |
223
+ | `--max-nodes <n>` | `-m` | Maximum nodes per bundle | `100` |
224
+ | `--profile <profile>` | | Profile preset (see below) | `llm-chat` |
225
+ | `--strict` | `-s` | Fail on missing dependencies | `false` |
226
+ | `--strict-missing` | | Exit with error code 1 if any missing dependencies found (CI-friendly) | `false` |
227
+ | `--predict-behavior` | | Include experimental behavior predictions in contracts | `false` |
228
+ | `--dry-run` | | Skip writing output; show on-screen summary only | `false` |
229
+ | `--stats` | | Emit single-line JSON stats with token estimates (intended for CI) | `false` |
230
+ | `--compare-modes` | | Show detailed token comparison table across modes (none/header/full) | `false` |
231
+ | `--skip-gitignore` | | Skip `.gitignore` setup (never prompt or modify) | `false` |
232
+ | `--quiet` | `-q` | Suppress verbose output (show only errors) | `false` |
233
+ | `--help` | `-h` | Show help message | |
234
+
235
+ ### Options (`compare` command)
236
+
237
+ | Option | Description | Default |
238
+ |--------|-------------|---------|
239
+ | `--stats` | Show token count statistics and delta | `false` |
240
+ | `--approve` | Auto-approve updates (non-interactive, CI-safe) | `false` |
241
+ | `--clean-orphaned` | Auto-delete orphaned files with `--approve` | `false` |
242
+ | `--quiet` | `-q` | Suppress verbose output (show only diffs) | `false` |
243
+ | `--help`, `-h` | Show help message | |
244
+
245
+ ### Options (`validate` command)
246
+
247
+ - `[file]` – Optional path to a generated `context.json` file to validate. Defaults to `./context.json`. You can validate individual folder context files or the main index file.
248
+ - `--quiet` | `-q` – Suppress verbose output (show only errors)
249
+ - Exits with code `0` on success, `1` on invalid structure or read/parse errors.
250
+ - Prints bundle counts, node totals, and highlights schema mismatches.
251
+
252
+ ### Profiles
253
+
254
+ Profiles are preset configurations optimized for different use cases:
255
+
256
+ #### `llm-chat` (default)
257
+ Balanced mode for AI chat interfaces
258
+ - Depth: 1
259
+ - Code: headers only
260
+ - Max nodes: 100
261
+ - Behavioral predictions: disabled by default (enable with `--predict-behavior`)
262
+
263
+ #### `llm-safe`
264
+ Conservative mode for token-limited contexts
265
+ - Depth: 1
266
+ - Code: headers only
267
+ - Max nodes: 30
268
+ - Behavioral predictions: disabled by default (enable with `--predict-behavior`)
269
+
270
+ #### `ci-strict`
271
+ Strict validation mode for CI/CD
272
+ - Code: none
273
+ - Strict dependencies enabled
274
+ - Behavioral predictions: not applicable (metadata-only mode)
275
+
276
+ ### Behavioral Predictions
277
+
278
+ The `--predict-behavior` flag enables experimental behavioral analysis that adds predicted component behaviors to the contract output. These predictions include:
279
+
280
+ - Form validation patterns
281
+ - Side effect management (useEffect)
282
+ - Data fetching/mutation patterns
283
+ - Memoization usage
284
+ - Context consumption
285
+ - Ref usage for DOM access
286
+ - Loading/error state handling
287
+
288
+ **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.
289
+
290
+ **Example:**
291
+ ```bash
292
+ # Enable predictions with the default profile
293
+ stamp context --predict-behavior
294
+
295
+ # Enable predictions with a specific profile
296
+ stamp context --profile llm-safe --predict-behavior
297
+ ```
298
+
299
+ ## Token Optimization
300
+
301
+ LogicStamp Context includes built-in token cost analysis and optimization features:
302
+
303
+ ### Automatic Token Estimates
304
+
305
+ Every context generation shows token costs for both GPT-4o-mini and Claude:
306
+
307
+ ```
308
+ 📏 Token Estimates (header mode):
309
+ GPT-4o-mini: 13,895 | Full code: ~39,141 (~65% savings)
310
+ Claude: 12,351 | Full code: ~34,792 (~65% savings)
311
+
312
+ 📊 Mode Comparison:
313
+ none: ~8,337 tokens
314
+ header: ~13,895 tokens
315
+ full: ~39,141 tokens
316
+ ```
317
+
318
+ This helps you:
319
+ - **Understand costs** at a glance
320
+ - **Choose the right mode** for your budget
321
+ - **See savings** compared to including full source code
322
+
323
+ ### Mode Comparison Table
324
+
325
+ Use `--compare-modes` for a detailed comparison:
326
+
327
+ ```bash
328
+ stamp context --compare-modes
329
+ ```
330
+
331
+ Output:
332
+ ```
333
+ 📊 Mode Comparison
334
+
335
+ Mode | Tokens GPT-4o | Tokens Claude | Savings vs Full
336
+ ---------|---------------|---------------|------------------
337
+ none | 8,337 | 7,411 | 79%
338
+ header | 13,895 | 12,351 | 65%
339
+ full | 39,141 | 34,792 | 0%
340
+ ```
341
+
342
+ **When to use each mode:**
343
+ - **`none`** - API documentation, CI validation (no code snippets)
344
+ - **`header`** - AI chat, code review (JSDoc headers + contracts)
345
+ - **`full`** - Deep analysis, debugging (complete source code)
346
+
347
+ ### Stats for CI/CD
348
+
349
+ Use `--stats` to get machine-readable token data:
350
+
351
+ ```bash
352
+ stamp context --stats
353
+ ```
354
+
355
+ Output JSON includes:
356
+ ```json
357
+ {
358
+ "tokensGPT4": 13895,
359
+ "tokensClaude": 12351,
360
+ "modeEstimates": {
361
+ "none": {"gpt4": 8337, "claude": 7411},
362
+ "header": {"gpt4": 13895, "claude": 12351},
363
+ "full": {"gpt4": 39141, "claude": 34792}
364
+ },
365
+ "savingsGPT4": "65",
366
+ "savingsClaude": "65"
367
+ }
368
+ ```
369
+
370
+ ## Context Drift Detection
371
+
372
+ The `compare` command helps you track changes between context versions:
373
+
374
+ ### Basic Comparison
375
+
376
+ ```bash
377
+ stamp context compare old.json new.json
378
+ ```
379
+
380
+ Output:
381
+ ```
382
+ ✅ PASS
383
+
384
+ # or if changes detected:
385
+
386
+ ⚠️ DRIFT
387
+
388
+ Added components: 2
389
+ + src/components/NewButton.tsx
390
+ + src/utils/helpers.ts
391
+
392
+ Removed components: 1
393
+ - src/components/OldButton.tsx
394
+
395
+ Changed components: 3
396
+ ~ src/components/Card.tsx
397
+ Δ imports, hooks
398
+ ~ src/App.tsx
399
+ Δ hash
400
+ ```
401
+
402
+ ### With Token Stats
403
+
404
+ ```bash
405
+ stamp context compare old.json new.json --stats
406
+ ```
407
+
408
+ Shows token cost changes:
409
+ ```
410
+ Token Stats:
411
+ Old: 8,484 (GPT-4o-mini) | 7,542 (Claude)
412
+ New: 9,125 (GPT-4o-mini) | 8,111 (Claude)
413
+ Δ +641 (+7.56%)
414
+ ```
415
+
416
+ ### Exit Codes
417
+
418
+ - `0` - No drift (PASS)
419
+ - `1` - Drift detected or error
420
+
421
+ Perfect for CI/CD validation:
422
+ ```bash
423
+ # In your CI pipeline
424
+ stamp context compare base.json pr.json || echo "Context drift detected!"
425
+ ```
426
+
427
+ ## Examples
428
+
429
+ ### Basic usage
430
+
431
+ ```bash
432
+ # Generate context for entire project
433
+ stamp context
434
+
435
+ # CLI output:
436
+ # 🔍 Scanning /path/to/project...
437
+ # ⚙️ Analyzing components...
438
+ # 🔗 Building dependency graph...
439
+ # 📦 Generating context...
440
+ # 🔍 Validating generated context...
441
+ # ✅ Validation passed
442
+ # 📝 Writing context files for 5 folders...
443
+ # ✓ context.json (2 bundles)
444
+ # ✓ src/context.json (3 bundles)
445
+ # ✓ src/components/context.json (5 bundles)
446
+ # ✓ src/utils/context.json (2 bundles)
447
+ # ✓ app/context.json (3 bundles)
448
+ # 📝 Writing main context index...
449
+ # ✓ context_main.json (index of 5 folders)
450
+ # ✅ 6 context files written successfully
451
+ #
452
+ # 📊 Summary:
453
+ # Total components: 15
454
+ # Root components: 3
455
+ # ...
456
+ ```
457
+
458
+ ### Focused analysis
459
+
460
+ ```bash
461
+ # Analyze only the src directory
462
+ stamp context ./src
463
+
464
+ # Analyze with custom output directory
465
+ stamp context --out ./output
466
+
467
+ # Or specify a .json file to use its directory
468
+ stamp context --out ./output/context.json # Uses ./output as directory
469
+ ```
470
+
471
+ ### Deep traversal
472
+
473
+ ```bash
474
+ # Include 2 levels of dependencies
475
+ stamp context --depth 2
476
+
477
+ # Include full source code
478
+ stamp context --include-code full
479
+ ```
480
+
481
+ ### Token cost analysis
482
+
483
+ ```bash
484
+ # Show detailed mode comparison
485
+ stamp context --compare-modes
486
+
487
+ # Get JSON stats for CI
488
+ stamp context --stats
489
+
490
+ # See token costs for specific mode
491
+ stamp context --include-code none
492
+ stamp context --include-code full
493
+ ```
494
+
495
+ ### Context comparison
496
+
497
+ ```bash
498
+ # Basic drift detection
499
+ stamp context compare old.json new.json
500
+
501
+ # With token delta stats
502
+ stamp context compare base.json pr.json --stats
503
+
504
+ # In CI pipeline
505
+ stamp context compare base.json pr.json || exit 1
506
+ ```
507
+
508
+ ### Clean context files
509
+
510
+ ```bash
511
+ # Show what would be removed (dry run)
512
+ stamp context clean
513
+
514
+ # Actually delete all context artifacts
515
+ stamp context clean --all --yes
516
+
517
+ # Clean specific directory
518
+ stamp context clean ./output --all --yes
519
+
520
+ # Suppress verbose output (quiet mode)
521
+ stamp context --quiet
522
+ stamp context validate --quiet
523
+ stamp context compare --quiet
524
+ stamp context clean --all --yes --quiet
525
+
526
+ # Show version number
527
+ stamp --version
528
+ ```
529
+
530
+ ### CI/CD validation
531
+
532
+ ```bash
533
+ # Use llm-safe profile for smaller output
534
+ stamp context --profile llm-safe --out safe-context.json
535
+
536
+ # Strict mode: fail if any dependencies missing
537
+ stamp context --strict-missing
538
+
539
+ # Generate stats for CI monitoring
540
+ stamp context --stats > stats.json
541
+
542
+ # Validate generated context
543
+ stamp context validate context.json
544
+ ```
545
+
546
+ ## Output Format
547
+
548
+ LogicStamp Context generates a **folder-organized, multi-file output structure** that maintains your project's directory hierarchy:
549
+
550
+ ### File Structure
551
+
552
+ The tool writes multiple `context.json` files, one per folder containing components, plus a `context_main.json` index file at the output root:
553
+
554
+ ```
555
+ output/
556
+ ├── context_main.json # Main index with folder metadata
557
+ ├── context.json # Root folder bundles (if any)
558
+ ├── src/
559
+ │ └── context.json # Bundles from src/ folder
560
+ ├── src/components/
561
+ │ └── context.json # Bundles from src/components/
562
+ └── src/utils/
563
+ └── context.json # Bundles from src/utils/
564
+ ```
565
+
566
+ ### Folder-Based Organization
567
+
568
+ Each folder's `context.json` contains bundles for components in that folder. This organization:
569
+ - **Matches your project structure** - Easy to locate context for specific directories
570
+ - **Enables incremental updates** - Only regenerate context for changed folders
571
+ - **Improves AI context loading** - Load only relevant folder contexts
572
+ - **Maintains relative paths** - Folder structure mirrors your project layout
573
+
574
+ ### Main Index File (`context_main.json`)
575
+
576
+ The `context_main.json` file serves as a directory index with:
577
+
578
+ ```json
579
+ {
580
+ "type": "LogicStampIndex",
581
+ "schemaVersion": "0.1",
582
+ "projectRoot": ".",
583
+ "projectRootResolved": "/absolute/path/to/project",
584
+ "createdAt": "2025-01-15T10:30:00.000Z",
585
+ "summary": {
586
+ "totalComponents": 42,
587
+ "totalBundles": 15,
588
+ "totalFolders": 5,
589
+ "totalTokenEstimate": 13895
590
+ },
591
+ "folders": [
592
+ {
593
+ "path": "src/components",
594
+ "contextFile": "src/components/context.json",
595
+ "bundles": 3,
596
+ "components": ["Button.tsx", "Card.tsx", "Modal.tsx"],
597
+ "isRoot": false,
598
+ "tokenEstimate": 5234
599
+ },
600
+ {
601
+ "path": ".",
602
+ "contextFile": "context.json",
603
+ "bundles": 2,
604
+ "components": ["App.tsx"],
605
+ "isRoot": true,
606
+ "rootLabel": "Project Root",
607
+ "tokenEstimate": 2134
608
+ }
609
+ ],
610
+ "meta": {
611
+ "source": "logicstamp-context@0.1.0"
612
+ }
613
+ }
614
+ ```
615
+
616
+ **Key fields in folder entries:**
617
+ - `path` - Relative path from project root
618
+ - `contextFile` - Path to the folder's context.json file
619
+ - `bundles` - Number of bundles in this folder
620
+ - `components` - List of component files in this folder
621
+ - `isRoot` - Whether this folder is an application entry point
622
+ - `rootLabel` - Human-readable label for root folders (e.g., "Next.js App", "Project Root")
623
+ - `tokenEstimate` - Estimated token count for this folder's context
624
+
625
+ ### Bundle Structure
626
+
627
+ 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.
628
+
629
+ **📋 Full Schema Reference:** See [`schema/logicstamp.context.schema.json`](schema/logicstamp.context.schema.json) for the complete JSON Schema definition.
630
+
631
+ **Example: `src/components/context.json`**
632
+
633
+ ```json
634
+ [
635
+ {
636
+ "$schema": "https://logicstamp.dev/schemas/context/v0.1.json",
637
+ "position": "1/3",
638
+ "type": "LogicStampBundle",
639
+ "schemaVersion": "0.1",
640
+ "entryId": "src/components/Button.tsx",
641
+ "depth": 1,
642
+ "createdAt": "2025-01-15T10:30:00.000Z",
643
+ "bundleHash": "uifb:abc123...",
644
+ "graph": {
645
+ "nodes": [
646
+ {
647
+ "entryId": "src/components/Button.tsx",
648
+ "contract": {
649
+ "type": "UIFContract",
650
+ "schemaVersion": "0.3",
651
+ "kind": "react:component",
652
+ "description": "Button - Interactive component",
653
+ "version": {
654
+ "variables": ["variant", "size"],
655
+ "hooks": ["useState"],
656
+ "components": [],
657
+ "functions": ["handleClick"]
658
+ },
659
+ "logicSignature": {
660
+ "props": {
661
+ "onClick": { "type": "function", "signature": "() => void" },
662
+ "variant": { "type": "literal-union", "literals": ["primary", "secondary"] }
663
+ },
664
+ "events": {},
665
+ "state": {}
666
+ },
667
+ "nextjs": {
668
+ "directive": "client",
669
+ "isInAppDir": true
670
+ }
671
+ }
672
+ }
673
+ ],
674
+ "edges": []
675
+ },
676
+ "meta": {
677
+ "missing": [],
678
+ "source": "logicstamp-context@0.1.0"
679
+ }
680
+ }
681
+ ]
682
+ ```
683
+
684
+ **📋 Full Schema Reference:** See [`schema/logicstamp.context.schema.json`](schema/logicstamp.context.schema.json) for the complete JSON Schema definition.
685
+
686
+ ### Understanding the Meta Field
687
+
688
+ The `meta` section provides metadata about bundle generation and dependency resolution:
689
+
690
+ #### `missing` Array
691
+
692
+ Tracks dependencies that couldn't be resolved during analysis. An empty array `[]` means all dependencies were successfully found.
693
+
694
+ When dependencies are missing, each entry contains:
695
+ - `name` - The import specifier that couldn't be resolved (e.g., `"./MissingComponent"`)
696
+ - `reason` - Why it couldn't be found (e.g., `"file not found"`, `"external package"`)
697
+ - `referencedBy` - The component that tried to import it
698
+
699
+ **Example with missing dependencies:**
700
+ ```json
701
+ {
702
+ "meta": {
703
+ "missing": [
704
+ {
705
+ "name": "./components/DeletedComponent",
706
+ "reason": "file not found",
707
+ "referencedBy": "src/App.tsx"
708
+ },
709
+ {
710
+ "name": "@external/ui-lib",
711
+ "reason": "external package",
712
+ "referencedBy": "src/components/Button.tsx"
713
+ }
714
+ ],
715
+ "source": "logicstamp-context@0.1.0"
716
+ }
717
+ }
718
+ ```
719
+
720
+ **Common reasons for missing dependencies:**
721
+ - `file not found` - Referenced file doesn't exist (deleted or moved)
722
+ - `external package` - Third-party npm package (intentionally excluded)
723
+ - `outside scan path` - File exists but outside the specified scan directory
724
+ - `circular dependency` - Circular import detected and skipped
725
+ - `max depth exceeded` - Dependency beyond `--depth` limit
726
+
727
+ **Using `--strict-missing` for CI/CD:**
728
+ ```bash
729
+ # Exit with error code 1 if ANY missing dependencies found
730
+ stamp context --strict-missing
731
+
732
+ # Perfect for CI validation
733
+ stamp context --strict-missing || exit 1
734
+ ```
735
+
736
+ #### `source` Field
737
+
738
+ Identifies the generator and version (e.g., `"logicstamp-context@0.1.0"`). Useful for:
739
+ - Debugging context generation issues
740
+ - Ensuring compatibility with consuming tools
741
+ - Tracking which version generated historical contexts
742
+
743
+ ## Use Cases
744
+
745
+ ### AI-Assisted Development
746
+
747
+ Share context with Claude or ChatGPT to get:
748
+ - Architecture suggestions
749
+ - Refactoring recommendations
750
+ - Bug fixes based on full component understanding
751
+
752
+ ### Documentation
753
+
754
+ Generate up-to-date component documentation automatically:
755
+ - API contracts
756
+ - Dependency trees
757
+ - Component relationships
758
+
759
+ ### Code Review
760
+
761
+ Quickly understand component structure and dependencies:
762
+ - Identify circular dependencies
763
+ - Find unused components
764
+ - Track component complexity
765
+
766
+ ## Troubleshooting
767
+
768
+ ### Handling Missing Dependencies
769
+
770
+ If your generated context shows missing dependencies in the `meta.missing` array:
771
+
772
+ #### 1. External Packages (Expected)
773
+ ```json
774
+ {
775
+ "name": "@mui/material",
776
+ "reason": "external package"
777
+ }
778
+ ```
779
+ **Solution:** This is normal. LogicStamp only analyzes your source code, not node_modules. External packages are intentionally excluded.
780
+
781
+ #### 2. File Not Found (Action Required)
782
+ ```json
783
+ {
784
+ "name": "./components/OldButton",
785
+ "reason": "file not found",
786
+ "referencedBy": "src/App.tsx"
787
+ }
788
+ ```
789
+ **Solutions:**
790
+ - Check if the file was deleted or moved
791
+ - Update the import path in the referencing component
792
+ - Use `--strict-missing` in CI to catch these issues early
793
+
794
+ #### 3. Outside Scan Path
795
+ ```json
796
+ {
797
+ "name": "../../shared/utils",
798
+ "reason": "outside scan path"
799
+ }
800
+ ```
801
+ **Solutions:**
802
+ - Expand your scan path: `stamp context ../` (parent directory)
803
+ - Or scan from project root: `stamp context .` (from root)
804
+
805
+ #### 4. Max Depth Exceeded
806
+ ```json
807
+ {
808
+ "name": "./deeply/nested/component",
809
+ "reason": "max depth exceeded"
810
+ }
811
+ ```
812
+ **Solutions:**
813
+ - Increase depth: `stamp context --depth 2` or `--depth 3`
814
+ - Note: Higher depth = more tokens consumed
815
+
816
+ #### 5. Circular Dependencies
817
+ ```json
818
+ {
819
+ "name": "./ComponentA",
820
+ "reason": "circular dependency"
821
+ }
822
+ ```
823
+ **Solutions:**
824
+ - Refactor to break the circular import
825
+ - Extract shared logic to a separate module
826
+ - This is a code smell that should be addressed
827
+
828
+ ### Common Issues
829
+
830
+ **Q: Why is my context.json huge?**
831
+ - Use `--include-code none` to exclude all source code (smallest)
832
+ - Use `--include-code header` (default) for balanced output
833
+ - Use `--profile llm-safe` for token-constrained scenarios
834
+ - Check `--compare-modes` to see token savings
835
+
836
+ **Q: Validation failed - what went wrong?**
837
+ ```bash
838
+ stamp context validate context.json
839
+ # Or validate the main index
840
+ stamp context validate context_main.json
841
+ ```
842
+ - Check for schema mismatches (outdated schema version)
843
+ - Verify JSON is well-formed (no trailing commas, proper escaping)
844
+ - Ensure all required fields are present
845
+ - Each folder's context.json should be a valid bundle array
846
+ - The context_main.json should have the LogicStampIndex structure
847
+
848
+ **Q: How do I ignore certain directories?**
849
+ - LogicStamp respects `.gitignore` automatically
850
+ - `node_modules/` and common build directories are excluded by default
851
+ - Scan specific directories: `stamp context ./src`
852
+
853
+ ## How it Works
854
+
855
+ 1. **Scan**: Finds all `.ts` and `.tsx` files in your project
856
+ 2. **Analyze**: Parses React components using TypeScript AST
857
+ 3. **Extract**: Builds component contracts with structure and signatures
858
+ 4. **Graph**: Creates dependency graph showing relationships
859
+ 5. **Bundle**: Packages context bundles optimized for AI consumption
860
+ 6. **Organize**: Groups bundles by folder and writes `context.json` files maintaining directory structure
861
+ 7. **Index**: Creates `context_main.json` index with folder metadata and summary statistics
862
+
863
+ All in one command, no pre-compilation needed!
864
+
865
+ ## Planned Orchestrator (@logicstamp/cli)
866
+
867
+ `logicstamp-context` is the primary CLI available today. A higher-level orchestrator package `@logicstamp/cli` is planned as an optional wrapper.
868
+
869
+ | Feature | logicstamp-context | LogicStamp Orchestrator (planned) |
870
+ |---------|-------------------|----------------------------------|
871
+ | Standalone | ✅ Yes | ❌ No (wraps underlying tools) |
872
+ | Pre-compilation required | ❌ No | ✅ Yes (for verification) |
873
+ | Context generation | ✅ Yes | ✅ Yes |
874
+ | UIF contracts per file | ✅ Yes (embedded in bundles) | ✅ Yes (as `.uif.json` sidecar files) |
875
+ | Contract compilation | ✅ Built-in | ✅ Separate command |
876
+ | Contract verification | ❌ No | ✅ Yes (planned) |
877
+ | Size | Focused | Orchestrator |
878
+
879
+ **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.
880
+
881
+ ## Future Roadmap
882
+
883
+ ### Next.js Enhancements (Planned)
884
+
885
+ The current Next.js support (v0.1) provides foundational directive and App Router detection. Future versions may include:
886
+
887
+ **App Router Advanced Features**
888
+ - `role` detection - Identify `page`, `layout`, `route`, `loading`, `error` files
889
+ - `segmentPath` extraction - Capture dynamic route segments (e.g., `[id]`, `[...slug]`)
890
+ - Route dependency graph - Map App Router file relationships
891
+ - Metadata exports - Detect `generateMetadata`, `generateStaticParams`
892
+
893
+ **Server Actions & RPC**
894
+ - Server Action signature extraction from `'use server'` blocks
895
+ - Form action detection and validation
896
+ - RPC call graph (client → server action relationships)
897
+
898
+ **Streaming & Suspense**
899
+ - Suspense boundary detection
900
+ - Streaming component identification
901
+ - Loading states and error boundaries
902
+
903
+ **Example Future Contract**
904
+ ```json
905
+ {
906
+ "nextjs": {
907
+ "directive": "client",
908
+ "isInAppDir": true,
909
+ "role": "page",
910
+ "segmentPath": "dashboard/[userId]",
911
+ "hasMetadata": true
912
+ }
913
+ }
914
+ ```
915
+
916
+ **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.
917
+
918
+ ### Other Planned Features
919
+
920
+ - **Vue.js Support** - Extend to Vue 3 Composition API components
921
+ - **Svelte Support** - Component analysis for Svelte files
922
+ - **Custom Contract Fields** - User-defined metadata via config
923
+ - **Performance Metrics** - Bundle size and render performance estimates
924
+
925
+ ## Requirements
926
+
927
+ - Node.js >= 18.0.0
928
+ - TypeScript/React codebase
929
+
930
+ ## License
931
+
932
+ MIT
933
+
934
+ ## Contributing
935
+
936
+ Issues and PRs welcome! This is an open-source project.
937
+
938
+ **See [CONTRIBUTING.md](CONTRIBUTING.md) for detailed guidelines**, including:
939
+ - Branching strategy (feature → `main`, no `develop` branch)
940
+ - Branch naming conventions (`feature/*`, `fix/*`, `docs/*`)
941
+ - Commit message format (Conventional Commits)
942
+ - Development workflow and best practices
943
+
944
+ ## Links
945
+
946
+ - [LogicStamp Main Project](https://github.com/LogicStamp/logicstamp)
947
+ - [Report Issues](https://github.com/LogicStamp/logicstamp-context/issues)
948
+
949
+ #TEST: CI Workflow