logicstamp-context 0.8.2 → 0.8.4

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 (51) hide show
  1. package/LICENSE +21 -21
  2. package/LLM_CONTEXT.md +703 -703
  3. package/README.md +404 -459
  4. package/dist/cli/commands/clean.d.ts.map +1 -1
  5. package/dist/cli/commands/clean.js +1 -6
  6. package/dist/cli/commands/clean.js.map +1 -1
  7. package/dist/cli/commands/context/fileWriter.js +2 -2
  8. package/dist/cli/commands/context/fileWriter.js.map +1 -1
  9. package/dist/cli/commands/context/statsCalculator.d.ts +3 -2
  10. package/dist/cli/commands/context/statsCalculator.d.ts.map +1 -1
  11. package/dist/cli/commands/context/statsCalculator.js +45 -104
  12. package/dist/cli/commands/context/statsCalculator.js.map +1 -1
  13. package/dist/cli/commands/context/watchMode/watchMode.d.ts.map +1 -1
  14. package/dist/cli/commands/context/watchMode/watchMode.js +124 -39
  15. package/dist/cli/commands/context/watchMode/watchMode.js.map +1 -1
  16. package/dist/cli/commands/init.js +20 -20
  17. package/dist/cli/commands/security.js +3 -3
  18. package/dist/cli/commands/security.js.map +1 -1
  19. package/dist/cli/commands/validate.d.ts.map +1 -1
  20. package/dist/cli/commands/validate.js +1 -6
  21. package/dist/cli/commands/validate.js.map +1 -1
  22. package/dist/cli/handlers/initHandler.js +5 -5
  23. package/dist/cli/index.d.ts +6 -2
  24. package/dist/cli/index.d.ts.map +1 -1
  25. package/dist/cli/index.js +100 -96
  26. package/dist/cli/index.js.map +1 -1
  27. package/dist/cli/parser/helpText.js +570 -570
  28. package/dist/cli/validate-index.js +26 -26
  29. package/dist/core/astParser/detectors.d.ts.map +1 -1
  30. package/dist/core/astParser/detectors.js +3 -2
  31. package/dist/core/astParser/detectors.js.map +1 -1
  32. package/dist/core/pack/loader.js +3 -3
  33. package/dist/core/pack/loader.js.map +1 -1
  34. package/dist/utils/codeSanitizer.d.ts.map +1 -1
  35. package/dist/utils/codeSanitizer.js +3 -2
  36. package/dist/utils/codeSanitizer.js.map +1 -1
  37. package/dist/utils/fsx.d.ts +5 -0
  38. package/dist/utils/fsx.d.ts.map +1 -1
  39. package/dist/utils/fsx.js +9 -2
  40. package/dist/utils/fsx.js.map +1 -1
  41. package/dist/utils/git.d.ts.map +1 -1
  42. package/dist/utils/git.js +2 -1
  43. package/dist/utils/git.js.map +1 -1
  44. package/dist/utils/gitignore.d.ts.map +1 -1
  45. package/dist/utils/gitignore.js +2 -1
  46. package/dist/utils/gitignore.js.map +1 -1
  47. package/dist/utils/secretDetector.d.ts.map +1 -1
  48. package/dist/utils/secretDetector.js +17 -10
  49. package/dist/utils/secretDetector.js.map +1 -1
  50. package/package.json +85 -84
  51. package/schema/logicstamp.context.schema.json +1250 -1250
package/LLM_CONTEXT.md CHANGED
@@ -1,703 +1,703 @@
1
- # LogicStamp Context – LLM Guide
2
-
3
- ## Overview
4
- - **The Context Compiler for TypeScript.** Compiles React/Next.js/Vue/TypeScript projects and backend frameworks (Express.js, NestJS) into deterministic architectural contracts and dependency graphs.
5
- - Ships as a global CLI (install with `npm install -g logicstamp-context`, then use `stamp context` command) that parses `.ts`/`.tsx` files via `ts-morph`, extracts component contracts, and emits structured JSON bundles.
6
- - Contracts are deterministic (same input = same output), diffable, and auditable. AI assistants consume contracts instead of parsing raw implementation code.
7
- - Works on Node.js ≥ 20 and requires access to the project's source tree.
8
- - **Framework support**: React, Next.js, Vue 3 (Composition API), TypeScript, Express.js, and NestJS. Vue support works with `.ts`/`.tsx` files only (JSX/TSX components, composables); Single File Components (`.vue` files) are not currently supported. Backend frameworks (Express.js, NestJS) are automatically detected and their routes, controllers, and API signatures are extracted.
9
-
10
- **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.
11
-
12
- ## Core Workflow
13
- - `src/cli/index.ts` and `src/cli/stamp.ts` orchestrate CLI execution: read CLI flags via `src/cli/parser/argumentParser.ts`, route to handlers in `src/cli/handlers/`, and coordinate command execution.
14
- - `src/cli/commands/compare.ts` implements drift detection for single-file and multi-file comparison modes, including ADDED/ORPHANED/DRIFT/PASS detection.
15
- - `src/core/astParser.ts` orchestrates AST parsing modules (`astParser/extractors/` and `astParser/detectors.ts`) that use `ts-morph` to parse source files, derive component metadata, and normalize type information. Supports React, Next.js, Vue 3 (Composition API) component detection, and backend framework detection (Express.js, NestJS) for API route and controller extraction.
16
- - `src/core/contractBuilder.ts` converts raw AST findings into UIF contracts and merges incremental updates.
17
- - `src/core/manifest.ts` and `src/core/pack.ts` (with modules in `pack/`) assemble dependency graphs, compute bundle hashes, and format final output entries.
18
- - `src/extractors/styling/` extracts style metadata from components:
19
- - **CSS frameworks**: Tailwind CSS (with categorization and breakpoint detection), SCSS/CSS modules (AST-based parsing)
20
- - **CSS-in-JS**: styled-components/Emotion, Styled JSX (CSS content, selectors, properties extraction)
21
- - **UI libraries**: Material UI, ShadCN/UI, Radix UI
22
- - **Animation**: framer-motion (components, variants, gestures, layout animations)
23
- - **Inline styles**: Enhanced extraction of property names and literal values
24
- - **Layout & visual**: Layout patterns (flex, grid), visual metadata (colors, spacing, typography, border radius)
25
- - `src/types/UIFContract.ts` defines the UIF contract schema; `src/utils/fsx.ts` and `src/utils/hash.ts` provide file and hashing utilities.
26
-
27
- ## CLI Usage Cheatsheet
28
- - Install globally: `npm install -g logicstamp-context`.
29
- - Show version: `stamp --version` or `stamp -v` displays the version number.
30
- - Default command `stamp context [target]` scans the current directory (or supplied path) and emits multiple `context.json` files (one per folder containing components) plus a `context_main.json` index file at the output root.
31
- - Key flags: `--depth` (dependency traversal), `--include-code none|header|full`, `--profile llm-chat|llm-safe|ci-strict|watch-fast`, `--out <file>` (output directory or file path), `--max-nodes <n>`, `--quiet` or `-q` (suppress verbose output, show only errors), `--watch` or `-w` (watch mode), `--strict-watch` (breaking change detection in watch mode).
32
- - Profiles tune defaults: `llm-chat` (balanced), `llm-safe` (token-conservative), `ci-strict` (validation-first), `watch-fast` (lighter style extraction for watch mode).
33
- - Supports multiple output formats via `--format`: `json` (default), `pretty`, `ndjson`, `toon`.
34
- - Compare command: `stamp context compare` compares all context files (multi-file mode) to detect drift, ADDED/ORPHANED folders, and component changes. Supports `--approve` for auto-updates, `--clean-orphaned` for cleanup, `--stats` for per-folder token deltas, and `--quiet` or `-q` to show only diffs.
35
- - Validate command: `stamp context validate [file]` checks context files for schema compliance. Supports `--quiet` or `-q` to show only errors. The JSON schema (`schema/logicstamp.context.schema.json`) supports both lean and full style mode variants (v0.7.0+).
36
- - Clean command: `stamp context clean [path]` removes context artifacts. Supports `--quiet` or `-q` to suppress verbose output.
37
- - Output structure: Context files are organized by folder, maintaining project directory hierarchy. Each folder gets its own `context.json` with bundles for that folder's components. The `context_main.json` index file provides metadata about all folders.
38
-
39
- ## Output Structure
40
-
41
- LogicStamp Context generates **folder-organized, multi-file output**:
42
-
43
- ### File Organization
44
- - Multiple `context.json` files, one per folder containing components
45
- - Directory structure mirrors your project layout
46
- - `context_main.json` index file at the output root with folder metadata
47
-
48
- **Example structure:**
49
- ```
50
- output/
51
- ├── context_main.json # Main index with folder metadata
52
- ├── context.json # Root folder bundles (if any)
53
- ├── src/
54
- │ └── context.json # Bundles from src/ folder
55
- ├── src/components/
56
- │ └── context.json # Bundles from src/components/
57
- └── src/utils/
58
- └── context.json # Bundles from src/utils/
59
- ```
60
-
61
- ### Main Index (`context_main.json`)
62
-
63
- The `context_main.json` file serves as a directory index:
64
-
65
- ```json
66
- {
67
- "type": "LogicStampIndex",
68
- "schemaVersion": "0.2",
69
- "projectRoot": ".",
70
- "createdAt": "2025-01-15T10:30:00.000Z",
71
- "summary": {
72
- "totalComponents": 42,
73
- "totalBundles": 15,
74
- "totalFolders": 5,
75
- "totalTokenEstimate": 13895
76
- },
77
- "folders": [
78
- {
79
- "path": "src/components",
80
- "contextFile": "src/components/context.json",
81
- "bundles": 3,
82
- "components": ["Button.tsx", "Card.tsx"],
83
- "isRoot": false,
84
- "tokenEstimate": 5234
85
- },
86
- {
87
- "path": ".",
88
- "contextFile": "context.json",
89
- "bundles": 2,
90
- "components": ["App.tsx"],
91
- "isRoot": true,
92
- "rootLabel": "Project Root",
93
- "tokenEstimate": 2134
94
- }
95
- ],
96
- "meta": {
97
- "source": "logicstamp-context@0.6.1"
98
- }
99
- }
100
- ```
101
-
102
- **Folder entry fields:**
103
- - `path` - Relative path from project root
104
- - `contextFile` - Path to this folder's context.json
105
- - `bundles` - Number of bundles in this folder
106
- - `components` - List of component file names
107
- - `isRoot` - Whether this is an application entry point
108
- - `rootLabel` - Label for root folders (e.g., "Next.js App", "Project Root")
109
- - `tokenEstimate` - Token count for this folder's context
110
-
111
- ### Folder Context Files (`context.json`)
112
-
113
- Each folder's `context.json` contains an array of LogicStamp bundles. Each bundle represents one entry point (component/module) plus its immediate dependency graph.
114
- - **Design note**: LogicStamp Context uses per-root bundles (one bundle per entry point) rather than per-component files. This means each bundle contains the root component plus its complete dependency graph—all related components and their relationships in one self-contained unit. This design is optimized for AI workflows: when you need help with a specific page or feature, share that root bundle and the AI has complete context.
115
- - Top-level fields: `position`, `type`, `schemaVersion`, `entryId`, `depth`, `createdAt`, `bundleHash`, `graph`, `meta`.
116
- - `graph.nodes` holds UIF contracts describing functions, props, events, imports, and semantic/file hashes. Optional `codeHeader` stores contract headers or code snippets when requested.
117
- - `graph.edges` lists dependency relationships between nodes (empty when analysis depth is 1).
118
- - `meta` section contains two critical fields:
119
- - `missing`: Array of unresolved dependencies. Each entry includes `name` (import path), `reason` (why it failed), and `referencedBy` (source component). Empty array indicates complete dependency resolution.
120
- - `source`: Generator version string (e.g., `"logicstamp-context@0.6.1"`) for compatibility tracking.
121
- - Example bundle skeleton:
122
-
123
- ```
124
- ```1:58:context.json
125
- [
126
- {
127
- "position": "1/9",
128
- "type": "LogicStampBundle",
129
- "schemaVersion": "0.1",
130
- "entryId": ".../src/cli/index.ts",
131
- "graph": {
132
- "nodes": [
133
- {
134
- "contract": {
135
- "kind": "node:cli",
136
- "composition": {
137
- "functions": ["generateContext", "main", "printHelp"],
138
- "imports": ["../core/astParser.js", "..."]
139
- }
140
- ```
141
-
142
- - Bundles may include behavioral `prediction` hints when heuristics detect notable logic (e.g., form handling, data access).
143
-
144
- ### Component Kinds
145
-
146
- LogicStamp Context detects and categorizes components into different kinds:
147
-
148
- - **`react:component`** - React functional components (with hooks, JSX, or React imports)
149
- - **`react:hook`** - Custom React hooks (functions starting with "use" and no JSX)
150
- - **`vue:component`** - Vue 3 components (detected via Vue imports and JSX/TSX syntax)
151
- - **`vue:composable`** - Vue 3 composables (functions using Vue Composition API like `ref`, `reactive`, `computed`, `watch`)
152
- - **`ts:module`** - TypeScript modules/utilities (non-React/Vue code)
153
- - **`node:cli`** - Node.js CLI scripts (files in `/cli/` directory or using `process.argv`)
154
- - **`node:api`** - Backend API routes/handlers (Express.js routes, NestJS controllers) with API signatures, route metadata, and framework-specific information
155
-
156
- **Vue.js Support (v0.3.4+):**
157
- - Detects Vue components and composables in `.ts`/`.tsx` files
158
- - Extracts Vue reactive state (`ref`, `reactive`, `computed`, `shallowRef`, `shallowReactive`)
159
- - Extracts Vue props from `defineProps` (supports both type-based and runtime props)
160
- - Extracts Vue emits from `defineEmits` (supports both type-based and runtime emits)
161
- - Detects Vue lifecycle hooks (`onMounted`, `onUnmounted`, `onUpdated`, etc.)
162
- - Framework detection priority: Vue takes priority over React when both are imported
163
- - **Note**: Works with Vue code in `.ts`/`.tsx` files (JSX/TSX components, extracted composables). Single File Components (`.vue` files) are not currently supported.
164
-
165
- ## Interpreting Missing Dependencies
166
- When `meta.missing` is non-empty, it signals incomplete dependency resolution:
167
-
168
- **Common scenarios:**
169
- 1. **External packages** (`reason: "external package"`) - Expected. LogicStamp only analyzes project source, not node_modules.
170
- 2. **File not found** (`reason: "file not found"`) - Component references a deleted/moved file. May indicate refactoring in progress or broken imports.
171
- 3. **Outside scan path** (`reason: "outside scan path"`) - Dependency exists but wasn't included in the scan directory. Consider widening scan scope.
172
- 4. **Max depth exceeded** (`reason: "max depth exceeded"`) - Dependency chain deeper than `--depth` setting. Increase depth for fuller analysis.
173
- 5. **Circular dependency** (`reason: "circular dependency"`) - Import cycle detected. LogicStamp breaks the cycle to prevent infinite loops.
174
-
175
- **Best practices for LLMs:**
176
- - Check `meta.missing` before making assumptions about complete component coverage
177
- - When missing deps exist, inform the user that analysis may be partial
178
- - Suggest running with `--depth 2` or higher if many "max depth exceeded" entries appear
179
- - Flag "file not found" entries as potential bugs in the codebase
180
-
181
- ## Why Compiled Contracts Are Better Than Raw Source
182
-
183
- LogicStamp compiles TypeScript into **structured context bundles** rather than passing raw source files to AI. This approach provides significant advantages for AI workflows:
184
-
185
- ### Semantic Density
186
-
187
- Raw code requires parsing and inference. Structured data is already parsed and categorized.
188
-
189
- **Raw code:**
190
- ```tsx
191
- className="flex items-center gap-2 px-4 py-2 rounded-lg bg-blue-500 text-white"
192
- ```
193
-
194
- **Structured:**
195
- ```json
196
- {
197
- "layout": { "type": "flex", "alignment": "items-center" },
198
- "spacing": ["gap-2", "px-4", "py-2"],
199
- "colors": ["bg-blue-500", "text-white"],
200
- "borders": ["rounded-lg"]
201
- }
202
- ```
203
-
204
- The structured form groups related concepts together. You can immediately answer "what colors are used?" without scanning strings. You can reason about spacing patterns without parsing className concatenations.
205
-
206
- ### Pre-Processed Relationships
207
-
208
- **Raw source approach:**
209
- - Scan imports to infer dependencies
210
- - Parse JSX to understand component hierarchy
211
- - Infer prop flows from usage patterns
212
- - Manually trace data flow
213
-
214
- **Structured approach:**
215
- - `graph.edges` explicitly shows `[ComponentA, ComponentB]` relationships
216
- - `interface.props` lists all inputs with types
217
- - `interface.state` shows reactive state
218
- - Dependency graph is pre-computed and traversable
219
-
220
- This eliminates inference work. You don't need to "figure out" relationships—they're already documented.
221
-
222
- ### Categorized Information
223
-
224
- Raw code scatters information across files. Structured data groups it by semantic meaning.
225
-
226
- **Example: Design System Analysis**
227
-
228
- To answer "What design patterns does the Hero component use?":
229
-
230
- **Raw Source Approach:**
231
- - Read 200+ lines of JSX
232
- - Parse className strings manually
233
- - Identify patterns through repeated scanning
234
- - Infer relationships from context
235
-
236
- **Structured Approach:**
237
- - Read `style.layout.type: "flex"`
238
- - Read `style.layout.hasHeroPattern: true`
239
- - Read `style.visual.colors: [...]`
240
- - Read `style.animation.type: "pulse"`
241
- - Answer in seconds
242
-
243
- The information is **already categorized**. Colors are in `visual.colors`, spacing in `visual.spacing`, layout patterns in `layout.type`. No scanning required.
244
-
245
- ### Contract-Based Understanding
246
-
247
- Raw code requires inferring component APIs from implementation. Structured data provides explicit contracts.
248
-
249
- **Raw:**
250
- ```tsx
251
- function Button({ onClick, children, variant }) {
252
- // ... 50 lines of implementation
253
- }
254
- ```
255
-
256
- **Structured:**
257
- ```json
258
- {
259
- "interface": {
260
- "props": [
261
- { "name": "onClick", "type": "() => void", "required": true },
262
- { "name": "children", "type": "ReactNode", "required": true },
263
- { "name": "variant", "type": "'primary' | 'secondary'", "required": false }
264
- ],
265
- "emits": ["click"],
266
- "state": []
267
- }
268
- }
269
- ```
270
-
271
- The contract is explicit. No need to read implementation to understand the API. You know exactly what inputs are expected, what outputs are produced, and what state is managed.
272
-
273
- ### Reduced Noise
274
-
275
- Raw code includes implementation details, comments, variable names, and boilerplate. Structured data focuses on **structure, relationships, and patterns**.
276
-
277
- **What's filtered out:**
278
- - Implementation details (how it works)
279
- - Comments and documentation (already processed)
280
- - Variable names (less relevant than types)
281
- - Boilerplate (repetitive patterns)
282
-
283
- **What's preserved:**
284
- - Component APIs (what it does)
285
- - Dependencies (what it uses)
286
- - Style patterns (how it looks)
287
- - Behavioral contracts (how it behaves)
288
-
289
- This reduces cognitive overhead. You can focus on **what matters** without parsing through implementation noise.
290
-
291
- ### Real-World Query Examples
292
-
293
- **Query: "What components use the same color palette?"**
294
- - **Raw source:** Scan all className strings, extract color utilities, group manually, compare across files
295
- - **Structured:** Read `visual.colors` arrays from each component contract, compare directly. Answer in one pass.
296
-
297
- **Query: "Which components depend on framer-motion?"**
298
- - **Raw source:** Search for `framer-motion` imports, check usage patterns, infer dependencies
299
- - **Structured:** Filter `style.styleSources.motion` objects, read `graph.edges` to see motion-dependent components. Immediate answer.
300
-
301
- **Query: "What's the spacing pattern across hero sections?"**
302
- - **Raw source:** Find hero components (pattern matching), extract spacing classes, analyze manually
303
- - **Structured:** Filter `layout.hasHeroPattern: true`, read `visual.spacing` arrays, compare patterns. Done.
304
-
305
- ### The Efficiency Multiplier
306
-
307
- Structured data provides:
308
- - **Faster parsing** (pre-processed, no AST traversal needed)
309
- - **Higher semantic density** (more meaning per token)
310
- - **Explicit relationships** (no inference required)
311
- - **Categorized information** (easier queries)
312
- - **Reduced noise** (focus on what matters)
313
-
314
- Even when token counts are similar, structured data is **significantly faster to process** because information is pre-categorized, relationships are explicit, contracts are clear, and patterns are extracted.
315
-
316
- ## Suggestions for LLM Consumers
317
-
318
- ### Loading Context Files
319
-
320
- 1. **Start with the index**: Load `context_main.json` to understand the project structure and locate relevant folders.
321
- 2. **Load folder contexts**: Based on the index, load specific folder `context.json` files for the modules you need to analyze.
322
- 3. **Filter by `entryId`**: Within a folder's context file, filter bundles by `entryId` to focus on relevant modules.
323
- 4. **Combine multiple folders**: When a task spans multiple folders, load the relevant folder context files and combine their bundles.
324
-
325
- ### Finding Components: Root vs Dependencies
326
-
327
- LogicStamp organizes components into two categories:
328
-
329
- - **Root components** - Components that have their own bundles (listed in `context_main.json` under each folder's `components` array). These are entry points that are **not imported by any other components** in the project. Each root component gets its own bundle.
330
- - **Dependencies** - Components that are imported by root components. They appear in the importing component's bundle as nodes in `graph.nodes[]`, not as separate root bundles. A dependency can appear in multiple bundles if it's imported by multiple root components.
331
-
332
- **Workflow for finding a component:**
333
-
334
- 1. **Check `context_main.json` first** - Look in the `folders[]` array for the component's file name in the `components` list. If found, it's a root component with its own bundle in that folder's `context.json`.
335
- 2. **If not found as a root** - The component is likely a dependency. Find which root component(s) import it:
336
- - Search for import statements in source code to identify importing components
337
- - Check bundles in the same folder (dependencies are often in the same folder as their importing component)
338
- - Search through bundle `graph.nodes[]` arrays to find which bundles include the dependency
339
- 3. **Read the importing root's bundle** - The dependency's contract will be in `graph.nodes[]` of that bundle. Each bundle in a folder's `context.json` is an array - find the bundle whose `entryId` matches the importing root component.
340
-
341
- **Example:**
342
-
343
- ```
344
- FAQ.tsx is imported by src/app/page.tsx
345
- → FAQ is NOT listed in context_main.json folders[].components (not a root)
346
- → FAQ IS in src/app/page.tsx bundle (as a dependency node in graph.nodes[])
347
- → To access FAQ:
348
- 1. Read src/app/context.json (array of bundles)
349
- 2. Find bundle with entryId: "src/app/page.tsx"
350
- 3. Look in that bundle's graph.nodes[] for FAQ.tsx contract
351
- ```
352
-
353
- **Why this matters:**
354
-
355
- - Root components = own bundles (e.g., `Features.tsx`, `Stats.tsx` in `src/components/sections/context.json`)
356
- - Dependencies = included in importing root component's bundle graph (e.g., `FAQ.tsx` in `src/app/page.tsx` bundle)
357
- - This structure matches how developers think: pages/features are entry points, their dependencies are included automatically
358
- - A component can be a dependency in multiple bundles if imported by multiple root components
359
-
360
- **Common mistake:** Looking for a component as a root when it's actually a dependency. Always check `context_main.json` first to see if it's listed as a root component.
361
-
362
- ### Working with the Index
363
-
364
- - Use `context_main.json` to:
365
- - Get an overview of all folders and their component counts
366
- - Identify root folders (application entry points) via `isRoot` and `rootLabel`
367
- - Estimate token costs per folder via `tokenEstimate`
368
- - Locate context files for specific directories via `contextFile` paths
369
-
370
- ### Bundle Analysis
371
-
372
- - Use `composition.functions` and `interface` to reason about available APIs without scanning full source.
373
- - Combine multiple bundles when a task spans related modules; respect `max-nodes` constraints to stay within token budgets.
374
- - For deeper understanding, rerun the CLI with `--include-code full` or higher `--depth` before querying the assistant.
375
- - **Always inspect `meta.missing`** in each bundle to understand analysis completeness before providing architectural guidance.
376
-
377
- ### Style Metadata (Optional)
378
-
379
- When using `stamp context style` or `stamp context --include-style`, bundles include a `style` field with visual and layout information.
380
-
381
- **Style Mode Variants (v0.7.0+):**
382
- - **Lean mode** (default): Compact format with count fields (`selectorCount`, `componentCount`, `colorCount`, etc.) and category names (`categoriesUsed`) instead of full arrays. Includes `summary.mode: 'lean'` and optional `summary.fullModeBytes` for size comparison. This is the default output format for `stamp context style` and `stamp context --include-style`.
383
- - **Full mode**: Verbose format with complete arrays (`selectors`, `components`, `colors`, `categories` objects, etc.). Includes `summary.mode: 'full'`. Use `--style-mode full` to generate this format.
384
-
385
- Both formats are valid and schema-compliant. The JSON schema supports both variants to ensure validation passes regardless of style mode.
386
-
387
- **Style Sources (`style.styleSources`):**
388
- - **Tailwind CSS**:
389
- - Full mode: `categories` object with arrays of classes per category, plus `classCount` and `breakpoints`
390
- - Lean mode: `categoriesUsed` array (category names), `classCount`, and `breakpoints`
391
- - **SCSS/CSS Modules**: File paths and parsed details (selectors, properties, SCSS features like variables, nesting, mixins)
392
- - **Styled JSX** (v0.3.5+):
393
- - Full mode: `css` string, `selectors` array, `properties` array, `global` boolean
394
- - Lean mode: `selectorCount`, `propertyCount`, `global` boolean
395
- - **styled-components/Emotion**:
396
- - Full mode: `components` array, `usesTheme`, `usesCssProp`
397
- - Lean mode: `componentCount`, `usesTheme`, `usesCssProp`
398
- - **framer-motion**: Motion components, variants, gesture handlers, layout animations, viewport animations
399
- - **Material UI**: Components, packages, theme usage, sx prop, styled API, makeStyles, system props
400
- - **ShadCN/UI**: Components, variants, sizes, form integration, theme usage, icon libraries, component density
401
- - **Radix UI**: Primitives (organized by package), patterns (controlled/uncontrolled, portals, asChild), accessibility features
402
- - **Inline Styles** (v0.3.5+): Enhanced extraction with both property names and literal values (e.g., `{ properties: ['color', 'padding'], values: { color: 'blue', padding: '1rem' } }`)
403
-
404
- **Layout Metadata (`style.layout`):**
405
- - Layout type (flex, grid, relative, absolute)
406
- - Grid column patterns
407
- - Hero section and feature card patterns
408
- - Page sections:
409
- - Full mode: `sections` array with section names
410
- - Lean mode: `sectionCount` number
411
-
412
- **Visual Metadata (`style.visual`):**
413
- - Color palettes:
414
- - Full mode: `colors` array (top 10 color utility classes)
415
- - Lean mode: `colorCount` number
416
- - Spacing patterns:
417
- - Full mode: `spacing` array (top 10 spacing utilities)
418
- - Lean mode: `spacingCount` number
419
- - Border radius tokens (`radius` string)
420
- - Typography classes:
421
- - Full mode: `typography` array (top 10)
422
- - Lean mode: `typographyCount` number
423
-
424
- **Style Summary (`style.summary`):**
425
- - `mode`: `'lean'` or `'full'` - indicates which format is used
426
- - `sources`: Array of detected style sources (e.g., `['tailwind', 'styled-jsx']`)
427
- - `fullModeBytes`: Optional, only in lean mode - estimated byte size if full mode were used
428
-
429
- **Animation Metadata (`style.animation`):**
430
- - Animation library type
431
- - Animation types and triggers
432
-
433
- ### Folder-Based Organization Benefits
434
-
435
- - **Targeted loading**: Load only the folder context files you need, reducing token usage
436
- - **Project structure alignment**: Folder structure mirrors your codebase, making it easier to navigate
437
- - **Incremental updates**: When code changes, only affected folder context files need regeneration
438
- - **Root detection**: Use `isRoot` and `rootLabel` to identify application entry points and framework-specific folders
439
-
440
- ## Context Drift Detection
441
-
442
- LogicStamp Context includes a `compare` command for detecting drift across all context files in a project:
443
-
444
- ### Multi-File Comparison Mode
445
-
446
- The compare command operates in multi-file mode when comparing `context_main.json` indices:
447
-
448
- ```bash
449
- stamp context compare # Auto-mode: compares all files
450
- stamp context compare old/context_main.json new/context_main.json # Manual mode
451
- ```
452
-
453
- **What it detects:**
454
- - **ADDED FILE** - New folders with context files (new features/modules added)
455
- - **ORPHANED FILE** - Folders removed from project (but context files still exist on disk)
456
- - **DRIFT** - Changed files with detailed component-level changes
457
- - **PASS** - Unchanged files
458
-
459
- **Three-tier output:**
460
- 1. **Folder-level summary** - Shows added/orphaned/changed/unchanged folder counts
461
- 2. **Component-level summary** - Total components added/removed/changed across all folders
462
- 3. **Detailed per-folder changes** - Component-by-component diffs for each folder with changes
463
-
464
- ### Use Cases for LLMs
465
-
466
- 1. **Change impact analysis**: When analyzing a codebase update, run `stamp context compare` to see exactly which folders and components changed
467
- 2. **Architectural drift**: Identify when new modules are added (`ADDED FILE`) or old ones removed (`ORPHANED FILE`)
468
- 3. **Per-folder token impact**: Use `--stats` to see token delta per folder, helping prioritize which changes to review
469
- 4. **Breaking change detection**: Check if component signatures (props, exports, hooks) changed, indicating potential breaking changes
470
-
471
- ### Key Features
472
-
473
- - **Jest-style workflow**: Use `--approve` to auto-update all context files (like `jest -u` for snapshots)
474
- - **Orphaned file cleanup**: Use `--clean-orphaned` with `--approve` to automatically delete stale context files
475
- - **CI integration**: Exit code 1 if drift detected, making it CI-friendly for validation
476
- - **Token statistics**: `--stats` shows per-folder token deltas to understand context size impact
477
-
478
- ### Example Output
479
-
480
- ```bash
481
- $ stamp context compare
482
-
483
- ⚠️ DRIFT
484
-
485
- 📁 Folder Summary:
486
- Total folders: 14
487
- ➕ Added folders: 1
488
- ~ Changed folders: 2
489
- ✓ Unchanged folders: 11
490
-
491
- 📦 Component Summary:
492
- + Added: 3
493
- ~ Changed: 2
494
-
495
- 📂 Folder Details:
496
-
497
- ➕ ADDED FILE: src/new-feature/context.json
498
- Path: src/new-feature
499
-
500
- ⚠️ DRIFT: src/cli/commands/context.json
501
- Path: src/cli/commands
502
- ~ Changed components (1):
503
- ~ compare.ts
504
- Δ hash
505
- old: uif:abc123...
506
- new: uif:def456...
507
- ```
508
-
509
- ### Implementation Details
510
-
511
- - **Truth from bundles**: Comparison is based on actual bundle content, not metadata (summary counts)
512
- - **Bundle→folder mapping**: Verifies folder structure from `context_main.json`
513
- - **Orphaned detection**: Checks disk for files that exist but aren't in the new index
514
- - **Metadata ignored**: `totalComponents`, `totalBundles` counts are derived stats, not compared for drift
515
-
516
- ## Watch Mode Integration
517
-
518
- Watch mode (`stamp context --watch`) monitors file changes and automatically regenerates context. This section explains how to integrate with watch mode from MCP servers or other tools.
519
-
520
- ### Detecting Watch Mode
521
-
522
- Check if watch mode is active by reading `.logicstamp/context_watch-status.json`:
523
-
524
- ```json
525
- {
526
- "active": true,
527
- "projectRoot": "/path/to/project",
528
- "pid": 12345,
529
- "startedAt": "2025-01-19T10:30:00.000Z",
530
- "outputDir": "/path/to/project",
531
- "strictWatch": false
532
- }
533
- ```
534
-
535
- **Fields:**
536
- - `active` - Always `true` when file exists (file is deleted on exit)
537
- - `projectRoot` - Absolute path to the watched project
538
- - `pid` - Process ID of the watch process (use to verify process is still running)
539
- - `startedAt` - ISO timestamp when watch mode started
540
- - `outputDir` - Directory where context files are written
541
- - `strictWatch` - Whether strict watch mode is enabled (`true` when `--strict-watch` flag is used, `false` otherwise)
542
-
543
- **Important**: The status file is deleted when watch mode exits. If the file exists but the process crashed, validate using the `pid` field:
544
-
545
- ```typescript
546
- // Pseudo-code for validating watch mode is truly active
547
- const status = JSON.parse(readFile('.logicstamp/context_watch-status.json'));
548
- try {
549
- process.kill(status.pid, 0); // Signal 0 checks if process exists
550
- // Watch mode is running
551
- } catch {
552
- // Process doesn't exist - stale status file
553
- }
554
- ```
555
-
556
- ### MCP Server Integration Patterns
557
-
558
- **Pattern 1: Direct Context Reading (Recommended)**
559
-
560
- When watch mode is active, `context_main.json` and folder `context.json` files are always up-to-date. Simply read them directly:
561
-
562
- ```typescript
563
- // 1. Check if watch mode is active
564
- const isWatching = await checkWatchStatus(projectRoot);
565
-
566
- // 2. Read context (always fresh when watch mode is running)
567
- const index = JSON.parse(readFile('context_main.json'));
568
- const bundles = JSON.parse(readFile(index.folders[0].contextFile));
569
- ```
570
-
571
- This is the simplest approach - no need to track changes, just read the latest context.
572
-
573
- **Pattern 2: Change-Aware Integration (with `--log-file`)**
574
-
575
- For MCP servers that need to know *what* changed (not just read fresh context), use the `--log-file` flag:
576
-
577
- ```bash
578
- stamp context --watch --log-file
579
- ```
580
-
581
- This writes structured change logs to `.logicstamp/context_watch-mode-logs.json`:
582
-
583
- ```json
584
- {
585
- "entries": [
586
- {
587
- "timestamp": "2025-01-19T10:30:05.000Z",
588
- "changedFiles": ["src/components/Button.tsx"],
589
- "fileCount": 1,
590
- "durationMs": 234,
591
- "modifiedContracts": [
592
- {
593
- "entryId": "src/components/Button.tsx",
594
- "semanticHashChanged": true,
595
- "fileHashChanged": true,
596
- "semanticHash": { "old": "uif:abc...", "new": "uif:def..." }
597
- }
598
- ],
599
- "modifiedBundles": [
600
- {
601
- "entryId": "src/components/Button.tsx",
602
- "bundleHash": { "old": "hash1...", "new": "hash2..." }
603
- }
604
- ],
605
- "addedContracts": [],
606
- "removedContracts": [],
607
- "summary": {
608
- "modifiedContractsCount": 1,
609
- "modifiedBundlesCount": 1,
610
- "addedContractsCount": 0,
611
- "removedContractsCount": 0
612
- }
613
- }
614
- ]
615
- }
616
- ```
617
-
618
- **Log entry fields:**
619
- - `timestamp` - When regeneration completed
620
- - `changedFiles` - Source files that triggered regeneration
621
- - `fileCount` - Number of changed files
622
- - `durationMs` - Regeneration time in milliseconds
623
- - `modifiedContracts` - Contracts with changed hashes (API or content changes)
624
- - `modifiedBundles` - Bundles with changed dependency graphs
625
- - `addedContracts` - New components added
626
- - `removedContracts` - Components removed
627
- - `summary` - Quick counts for each change type
628
- - `error` - Error message if regeneration failed
629
-
630
- **When to use `--log-file`:**
631
- - MCP server needs to notify users about specific changes
632
- - Building a UI that shows "what changed" information
633
- - Debugging or auditing context regeneration
634
- - Integration tests that verify specific changes
635
-
636
- **When NOT to use `--log-file`:**
637
- - Just need fresh context (Pattern 1 is simpler)
638
- - Concerned about disk I/O overhead
639
- - Log file maintenance is a concern
640
-
641
- ### Hash Types in Change Logs
642
-
643
- When `--log-file` is enabled, change logs include hash information:
644
-
645
- | Hash Type | What It Detects | When It Changes |
646
- |-----------|-----------------|-----------------|
647
- | `semanticHash` | API/logic changes | Props, events, state, hooks, components, functions change |
648
- | `fileHash` | Any content change | Any file modification (including comments, formatting) |
649
- | `bundleHash` | Dependency graph changes | Components added/removed from bundle, edges change |
650
-
651
- **Interpreting changes:**
652
- - `semanticHash` changed → API breaking change likely, consumers may need updates
653
- - `fileHash` changed but not `semanticHash` → Cosmetic change (comments, formatting)
654
- - `bundleHash` changed → Dependency structure changed, may affect bundle consumers
655
-
656
- ### File Locations Summary
657
-
658
- | File | Location | Purpose |
659
- |------|----------|---------|
660
- | Watch status | `.logicstamp/context_watch-status.json` | Detect if watch mode is running |
661
- | Watch logs | `.logicstamp/context_watch-mode-logs.json` | Change history (requires `--log-file`) |
662
- | Main index | `context_main.json` | Project structure and folder index |
663
- | Folder context | `<folder>/context.json` | Component bundles per folder |
664
-
665
- ### CLI Reference
666
-
667
- ```bash
668
- # Start watch mode (no log file)
669
- stamp context --watch
670
-
671
- # Start watch mode with change logging
672
- stamp context --watch --log-file
673
-
674
- # Watch with breaking change detection (strict mode)
675
- stamp context --watch --strict-watch
676
-
677
- # Watch with style metadata
678
- stamp context --watch --include-style
679
-
680
- # Watch with debug output (shows hash details in console)
681
- stamp context --watch --debug
682
-
683
- # Watch specific directory
684
- stamp context ./src/components --watch
685
- ```
686
-
687
- ### Strict Watch Mode
688
-
689
- Strict watch mode (`--strict-watch`) detects breaking changes in real-time:
690
-
691
- **Violation types:**
692
- - `breaking_change_prop_removed` - Prop removed from component
693
- - `breaking_change_event_removed` - Event/callback removed
694
- - `breaking_change_function_removed` - Exported function removed
695
- - `breaking_change_state_removed` - State variable removed
696
- - `breaking_change_prop_type` - Prop type changed (warning)
697
- - `contract_removed` - Entire component/module removed
698
-
699
- **Output files:**
700
- - `.logicstamp/strict_watch_violations.json` - Current violations (only exists when violations are present; automatically deleted when all resolved)
701
-
702
- **CI integration:** Exits with code 1 if errors detected during session.
703
-
1
+ # LogicStamp Context – LLM Guide
2
+
3
+ ## Overview
4
+ - **The Context Compiler for TypeScript.** Compiles React/Next.js/Vue/TypeScript projects and backend frameworks (Express.js, NestJS) into deterministic architectural contracts and dependency graphs.
5
+ - Ships as a global CLI (install with `npm install -g logicstamp-context`, then use `stamp context` command) that parses `.ts`/`.tsx` files via `ts-morph`, extracts component contracts, and emits structured JSON bundles.
6
+ - Contracts are deterministic (same input = same output), diffable, and auditable. AI assistants consume contracts instead of parsing raw implementation code.
7
+ - Works on Node.js ≥ 20 and requires access to the project's source tree.
8
+ - **Framework support**: React, Next.js, Vue 3 (Composition API), TypeScript, Express.js, and NestJS. Vue support works with `.ts`/`.tsx` files only (JSX/TSX components, composables); Single File Components (`.vue` files) are not currently supported. Backend frameworks (Express.js, NestJS) are automatically detected and their routes, controllers, and API signatures are extracted.
9
+
10
+ **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.
11
+
12
+ ## Core Workflow
13
+ - `src/cli/index.ts` and `src/cli/stamp.ts` orchestrate CLI execution: read CLI flags via `src/cli/parser/argumentParser.ts`, route to handlers in `src/cli/handlers/`, and coordinate command execution.
14
+ - `src/cli/commands/compare.ts` implements drift detection for single-file and multi-file comparison modes, including ADDED/ORPHANED/DRIFT/PASS detection.
15
+ - `src/core/astParser.ts` orchestrates AST parsing modules (`astParser/extractors/` and `astParser/detectors.ts`) that use `ts-morph` to parse source files, derive component metadata, and normalize type information. Supports React, Next.js, Vue 3 (Composition API) component detection, and backend framework detection (Express.js, NestJS) for API route and controller extraction.
16
+ - `src/core/contractBuilder.ts` converts raw AST findings into UIF contracts and merges incremental updates.
17
+ - `src/core/manifest.ts` and `src/core/pack.ts` (with modules in `pack/`) assemble dependency graphs, compute bundle hashes, and format final output entries.
18
+ - `src/extractors/styling/` extracts style metadata from components:
19
+ - **CSS frameworks**: Tailwind CSS (with categorization and breakpoint detection), SCSS/CSS modules (AST-based parsing)
20
+ - **CSS-in-JS**: styled-components/Emotion, Styled JSX (CSS content, selectors, properties extraction)
21
+ - **UI libraries**: Material UI, ShadCN/UI, Radix UI
22
+ - **Animation**: framer-motion (components, variants, gestures, layout animations)
23
+ - **Inline styles**: Enhanced extraction of property names and literal values
24
+ - **Layout & visual**: Layout patterns (flex, grid), visual metadata (colors, spacing, typography, border radius)
25
+ - `src/types/UIFContract.ts` defines the UIF contract schema; `src/utils/fsx.ts` and `src/utils/hash.ts` provide file and hashing utilities.
26
+
27
+ ## CLI Usage Cheatsheet
28
+ - Install globally: `npm install -g logicstamp-context`.
29
+ - Show version: `stamp --version` or `stamp -v` displays the version number.
30
+ - Default command `stamp context [target]` scans the current directory (or supplied path) and emits multiple `context.json` files (one per folder containing components) plus a `context_main.json` index file at the output root.
31
+ - Key flags: `--depth` (dependency traversal), `--include-code none|header|full`, `--profile llm-chat|llm-safe|ci-strict|watch-fast`, `--out <file>` (output directory or file path), `--max-nodes <n>`, `--quiet` or `-q` (suppress verbose output, show only errors), `--watch` or `-w` (watch mode), `--strict-watch` (breaking change detection in watch mode).
32
+ - Profiles tune defaults: `llm-chat` (balanced), `llm-safe` (token-conservative), `ci-strict` (validation-first), `watch-fast` (lighter style extraction for watch mode).
33
+ - Supports multiple output formats via `--format`: `json` (default), `pretty`, `ndjson`, `toon`.
34
+ - Compare command: `stamp context compare` compares all context files (multi-file mode) to detect drift, ADDED/ORPHANED folders, and component changes. Supports `--approve` for auto-updates, `--clean-orphaned` for cleanup, `--stats` for per-folder token deltas, and `--quiet` or `-q` to show only diffs.
35
+ - Validate command: `stamp context validate [file]` checks context files for schema compliance. Supports `--quiet` or `-q` to show only errors. The JSON schema (`schema/logicstamp.context.schema.json`) supports both lean and full style mode variants (v0.7.0+).
36
+ - Clean command: `stamp context clean [path]` removes context artifacts. Supports `--quiet` or `-q` to suppress verbose output.
37
+ - Output structure: Context files are organized by folder, maintaining project directory hierarchy. Each folder gets its own `context.json` with bundles for that folder's components. The `context_main.json` index file provides metadata about all folders.
38
+
39
+ ## Output Structure
40
+
41
+ LogicStamp Context generates **folder-organized, multi-file output**:
42
+
43
+ ### File Organization
44
+ - Multiple `context.json` files, one per folder containing components
45
+ - Directory structure mirrors your project layout
46
+ - `context_main.json` index file at the output root with folder metadata
47
+
48
+ **Example structure:**
49
+ ```
50
+ output/
51
+ ├── context_main.json # Main index with folder metadata
52
+ ├── context.json # Root folder bundles (if any)
53
+ ├── src/
54
+ │ └── context.json # Bundles from src/ folder
55
+ ├── src/components/
56
+ │ └── context.json # Bundles from src/components/
57
+ └── src/utils/
58
+ └── context.json # Bundles from src/utils/
59
+ ```
60
+
61
+ ### Main Index (`context_main.json`)
62
+
63
+ The `context_main.json` file serves as a directory index:
64
+
65
+ ```json
66
+ {
67
+ "type": "LogicStampIndex",
68
+ "schemaVersion": "0.2",
69
+ "projectRoot": ".",
70
+ "createdAt": "2025-01-15T10:30:00.000Z",
71
+ "summary": {
72
+ "totalComponents": 42,
73
+ "totalBundles": 15,
74
+ "totalFolders": 5,
75
+ "totalTokenEstimate": 13895
76
+ },
77
+ "folders": [
78
+ {
79
+ "path": "src/components",
80
+ "contextFile": "src/components/context.json",
81
+ "bundles": 3,
82
+ "components": ["Button.tsx", "Card.tsx"],
83
+ "isRoot": false,
84
+ "tokenEstimate": 5234
85
+ },
86
+ {
87
+ "path": ".",
88
+ "contextFile": "context.json",
89
+ "bundles": 2,
90
+ "components": ["App.tsx"],
91
+ "isRoot": true,
92
+ "rootLabel": "Project Root",
93
+ "tokenEstimate": 2134
94
+ }
95
+ ],
96
+ "meta": {
97
+ "source": "logicstamp-context@0.6.1"
98
+ }
99
+ }
100
+ ```
101
+
102
+ **Folder entry fields:**
103
+ - `path` - Relative path from project root
104
+ - `contextFile` - Path to this folder's context.json
105
+ - `bundles` - Number of bundles in this folder
106
+ - `components` - List of component file names
107
+ - `isRoot` - Whether this is an application entry point
108
+ - `rootLabel` - Label for root folders (e.g., "Next.js App", "Project Root")
109
+ - `tokenEstimate` - Token count for this folder's context
110
+
111
+ ### Folder Context Files (`context.json`)
112
+
113
+ Each folder's `context.json` contains an array of LogicStamp bundles. Each bundle represents one entry point (component/module) plus its immediate dependency graph.
114
+ - **Design note**: LogicStamp Context uses per-root bundles (one bundle per entry point) rather than per-component files. This means each bundle contains the root component plus its complete dependency graph—all related components and their relationships in one self-contained unit. This design is optimized for AI workflows: when you need help with a specific page or feature, share that root bundle and the AI has complete context.
115
+ - Top-level fields: `position`, `type`, `schemaVersion`, `entryId`, `depth`, `createdAt`, `bundleHash`, `graph`, `meta`.
116
+ - `graph.nodes` holds UIF contracts describing functions, props, events, imports, and semantic/file hashes. Optional `codeHeader` stores contract headers or code snippets when requested.
117
+ - `graph.edges` lists dependency relationships between nodes (empty when analysis depth is 1).
118
+ - `meta` section contains two critical fields:
119
+ - `missing`: Array of unresolved dependencies. Each entry includes `name` (import path), `reason` (why it failed), and `referencedBy` (source component). Empty array indicates complete dependency resolution.
120
+ - `source`: Generator version string (e.g., `"logicstamp-context@0.6.1"`) for compatibility tracking.
121
+ - Example bundle skeleton:
122
+
123
+ ```
124
+ ```1:58:context.json
125
+ [
126
+ {
127
+ "position": "1/9",
128
+ "type": "LogicStampBundle",
129
+ "schemaVersion": "0.1",
130
+ "entryId": ".../src/cli/index.ts",
131
+ "graph": {
132
+ "nodes": [
133
+ {
134
+ "contract": {
135
+ "kind": "node:cli",
136
+ "composition": {
137
+ "functions": ["generateContext", "main", "printHelp"],
138
+ "imports": ["../core/astParser.js", "..."]
139
+ }
140
+ ```
141
+
142
+ - Bundles may include behavioral `prediction` hints when heuristics detect notable logic (e.g., form handling, data access).
143
+
144
+ ### Component Kinds
145
+
146
+ LogicStamp Context detects and categorizes components into different kinds:
147
+
148
+ - **`react:component`** - React functional components (with hooks, JSX, or React imports)
149
+ - **`react:hook`** - Custom React hooks (functions starting with "use" and no JSX)
150
+ - **`vue:component`** - Vue 3 components (detected via Vue imports and JSX/TSX syntax)
151
+ - **`vue:composable`** - Vue 3 composables (functions using Vue Composition API like `ref`, `reactive`, `computed`, `watch`)
152
+ - **`ts:module`** - TypeScript modules/utilities (non-React/Vue code)
153
+ - **`node:cli`** - Node.js CLI scripts (files in `/cli/` directory or using `process.argv`)
154
+ - **`node:api`** - Backend API routes/handlers (Express.js routes, NestJS controllers) with API signatures, route metadata, and framework-specific information
155
+
156
+ **Vue.js Support (v0.3.4+):**
157
+ - Detects Vue components and composables in `.ts`/`.tsx` files
158
+ - Extracts Vue reactive state (`ref`, `reactive`, `computed`, `shallowRef`, `shallowReactive`)
159
+ - Extracts Vue props from `defineProps` (supports both type-based and runtime props)
160
+ - Extracts Vue emits from `defineEmits` (supports both type-based and runtime emits)
161
+ - Detects Vue lifecycle hooks (`onMounted`, `onUnmounted`, `onUpdated`, etc.)
162
+ - Framework detection priority: Vue takes priority over React when both are imported
163
+ - **Note**: Works with Vue code in `.ts`/`.tsx` files (JSX/TSX components, extracted composables). Single File Components (`.vue` files) are not currently supported.
164
+
165
+ ## Interpreting Missing Dependencies
166
+ When `meta.missing` is non-empty, it signals incomplete dependency resolution:
167
+
168
+ **Common scenarios:**
169
+ 1. **External packages** (`reason: "external package"`) - Expected. LogicStamp only analyzes project source, not node_modules.
170
+ 2. **File not found** (`reason: "file not found"`) - Component references a deleted/moved file. May indicate refactoring in progress or broken imports.
171
+ 3. **Outside scan path** (`reason: "outside scan path"`) - Dependency exists but wasn't included in the scan directory. Consider widening scan scope.
172
+ 4. **Max depth exceeded** (`reason: "max depth exceeded"`) - Dependency chain deeper than `--depth` setting. Increase depth for fuller analysis.
173
+ 5. **Circular dependency** (`reason: "circular dependency"`) - Import cycle detected. LogicStamp breaks the cycle to prevent infinite loops.
174
+
175
+ **Best practices for LLMs:**
176
+ - Check `meta.missing` before making assumptions about complete component coverage
177
+ - When missing deps exist, inform the user that analysis may be partial
178
+ - Suggest running with `--depth 2` or higher if many "max depth exceeded" entries appear
179
+ - Flag "file not found" entries as potential bugs in the codebase
180
+
181
+ ## Why Compiled Contracts Are Better Than Raw Source
182
+
183
+ LogicStamp compiles TypeScript into **structured context bundles** rather than passing raw source files to AI. This approach provides significant advantages for AI workflows:
184
+
185
+ ### Semantic Density
186
+
187
+ Raw code requires parsing and inference. Structured data is already parsed and categorized.
188
+
189
+ **Raw code:**
190
+ ```tsx
191
+ className="flex items-center gap-2 px-4 py-2 rounded-lg bg-blue-500 text-white"
192
+ ```
193
+
194
+ **Structured:**
195
+ ```json
196
+ {
197
+ "layout": { "type": "flex", "alignment": "items-center" },
198
+ "spacing": ["gap-2", "px-4", "py-2"],
199
+ "colors": ["bg-blue-500", "text-white"],
200
+ "borders": ["rounded-lg"]
201
+ }
202
+ ```
203
+
204
+ The structured form groups related concepts together. You can immediately answer "what colors are used?" without scanning strings. You can reason about spacing patterns without parsing className concatenations.
205
+
206
+ ### Pre-Processed Relationships
207
+
208
+ **Raw source approach:**
209
+ - Scan imports to infer dependencies
210
+ - Parse JSX to understand component hierarchy
211
+ - Infer prop flows from usage patterns
212
+ - Manually trace data flow
213
+
214
+ **Structured approach:**
215
+ - `graph.edges` explicitly shows `[ComponentA, ComponentB]` relationships
216
+ - `interface.props` lists all inputs with types
217
+ - `interface.state` shows reactive state
218
+ - Dependency graph is pre-computed and traversable
219
+
220
+ This eliminates inference work. You don't need to "figure out" relationships—they're already documented.
221
+
222
+ ### Categorized Information
223
+
224
+ Raw code scatters information across files. Structured data groups it by semantic meaning.
225
+
226
+ **Example: Design System Analysis**
227
+
228
+ To answer "What design patterns does the Hero component use?":
229
+
230
+ **Raw Source Approach:**
231
+ - Read 200+ lines of JSX
232
+ - Parse className strings manually
233
+ - Identify patterns through repeated scanning
234
+ - Infer relationships from context
235
+
236
+ **Structured Approach:**
237
+ - Read `style.layout.type: "flex"`
238
+ - Read `style.layout.hasHeroPattern: true`
239
+ - Read `style.visual.colors: [...]`
240
+ - Read `style.animation.type: "pulse"`
241
+ - Answer in seconds
242
+
243
+ The information is **already categorized**. Colors are in `visual.colors`, spacing in `visual.spacing`, layout patterns in `layout.type`. No scanning required.
244
+
245
+ ### Contract-Based Understanding
246
+
247
+ Raw code requires inferring component APIs from implementation. Structured data provides explicit contracts.
248
+
249
+ **Raw:**
250
+ ```tsx
251
+ function Button({ onClick, children, variant }) {
252
+ // ... 50 lines of implementation
253
+ }
254
+ ```
255
+
256
+ **Structured:**
257
+ ```json
258
+ {
259
+ "interface": {
260
+ "props": [
261
+ { "name": "onClick", "type": "() => void", "required": true },
262
+ { "name": "children", "type": "ReactNode", "required": true },
263
+ { "name": "variant", "type": "'primary' | 'secondary'", "required": false }
264
+ ],
265
+ "emits": ["click"],
266
+ "state": []
267
+ }
268
+ }
269
+ ```
270
+
271
+ The contract is explicit. No need to read implementation to understand the API. You know exactly what inputs are expected, what outputs are produced, and what state is managed.
272
+
273
+ ### Reduced Noise
274
+
275
+ Raw code includes implementation details, comments, variable names, and boilerplate. Structured data focuses on **structure, relationships, and patterns**.
276
+
277
+ **What's filtered out:**
278
+ - Implementation details (how it works)
279
+ - Comments and documentation (already processed)
280
+ - Variable names (less relevant than types)
281
+ - Boilerplate (repetitive patterns)
282
+
283
+ **What's preserved:**
284
+ - Component APIs (what it does)
285
+ - Dependencies (what it uses)
286
+ - Style patterns (how it looks)
287
+ - Behavioral contracts (how it behaves)
288
+
289
+ This reduces cognitive overhead. You can focus on **what matters** without parsing through implementation noise.
290
+
291
+ ### Real-World Query Examples
292
+
293
+ **Query: "What components use the same color palette?"**
294
+ - **Raw source:** Scan all className strings, extract color utilities, group manually, compare across files
295
+ - **Structured:** Read `visual.colors` arrays from each component contract, compare directly. Answer in one pass.
296
+
297
+ **Query: "Which components depend on framer-motion?"**
298
+ - **Raw source:** Search for `framer-motion` imports, check usage patterns, infer dependencies
299
+ - **Structured:** Filter `style.styleSources.motion` objects, read `graph.edges` to see motion-dependent components. Immediate answer.
300
+
301
+ **Query: "What's the spacing pattern across hero sections?"**
302
+ - **Raw source:** Find hero components (pattern matching), extract spacing classes, analyze manually
303
+ - **Structured:** Filter `layout.hasHeroPattern: true`, read `visual.spacing` arrays, compare patterns. Done.
304
+
305
+ ### The Efficiency Multiplier
306
+
307
+ Structured data provides:
308
+ - **Faster parsing** (pre-processed, no AST traversal needed)
309
+ - **Higher semantic density** (more meaning per token)
310
+ - **Explicit relationships** (no inference required)
311
+ - **Categorized information** (easier queries)
312
+ - **Reduced noise** (focus on what matters)
313
+
314
+ Even when token counts are similar, structured data is **significantly faster to process** because information is pre-categorized, relationships are explicit, contracts are clear, and patterns are extracted.
315
+
316
+ ## Suggestions for LLM Consumers
317
+
318
+ ### Loading Context Files
319
+
320
+ 1. **Start with the index**: Load `context_main.json` to understand the project structure and locate relevant folders.
321
+ 2. **Load folder contexts**: Based on the index, load specific folder `context.json` files for the modules you need to analyze.
322
+ 3. **Filter by `entryId`**: Within a folder's context file, filter bundles by `entryId` to focus on relevant modules.
323
+ 4. **Combine multiple folders**: When a task spans multiple folders, load the relevant folder context files and combine their bundles.
324
+
325
+ ### Finding Components: Root vs Dependencies
326
+
327
+ LogicStamp organizes components into two categories:
328
+
329
+ - **Root components** - Components that have their own bundles (listed in `context_main.json` under each folder's `components` array). These are entry points that are **not imported by any other components** in the project. Each root component gets its own bundle.
330
+ - **Dependencies** - Components that are imported by root components. They appear in the importing component's bundle as nodes in `graph.nodes[]`, not as separate root bundles. A dependency can appear in multiple bundles if it's imported by multiple root components.
331
+
332
+ **Workflow for finding a component:**
333
+
334
+ 1. **Check `context_main.json` first** - Look in the `folders[]` array for the component's file name in the `components` list. If found, it's a root component with its own bundle in that folder's `context.json`.
335
+ 2. **If not found as a root** - The component is likely a dependency. Find which root component(s) import it:
336
+ - Search for import statements in source code to identify importing components
337
+ - Check bundles in the same folder (dependencies are often in the same folder as their importing component)
338
+ - Search through bundle `graph.nodes[]` arrays to find which bundles include the dependency
339
+ 3. **Read the importing root's bundle** - The dependency's contract will be in `graph.nodes[]` of that bundle. Each bundle in a folder's `context.json` is an array - find the bundle whose `entryId` matches the importing root component.
340
+
341
+ **Example:**
342
+
343
+ ```
344
+ FAQ.tsx is imported by src/app/page.tsx
345
+ → FAQ is NOT listed in context_main.json folders[].components (not a root)
346
+ → FAQ IS in src/app/page.tsx bundle (as a dependency node in graph.nodes[])
347
+ → To access FAQ:
348
+ 1. Read src/app/context.json (array of bundles)
349
+ 2. Find bundle with entryId: "src/app/page.tsx"
350
+ 3. Look in that bundle's graph.nodes[] for FAQ.tsx contract
351
+ ```
352
+
353
+ **Why this matters:**
354
+
355
+ - Root components = own bundles (e.g., `Features.tsx`, `Stats.tsx` in `src/components/sections/context.json`)
356
+ - Dependencies = included in importing root component's bundle graph (e.g., `FAQ.tsx` in `src/app/page.tsx` bundle)
357
+ - This structure matches how developers think: pages/features are entry points, their dependencies are included automatically
358
+ - A component can be a dependency in multiple bundles if imported by multiple root components
359
+
360
+ **Common mistake:** Looking for a component as a root when it's actually a dependency. Always check `context_main.json` first to see if it's listed as a root component.
361
+
362
+ ### Working with the Index
363
+
364
+ - Use `context_main.json` to:
365
+ - Get an overview of all folders and their component counts
366
+ - Identify root folders (application entry points) via `isRoot` and `rootLabel`
367
+ - Estimate token costs per folder via `tokenEstimate`
368
+ - Locate context files for specific directories via `contextFile` paths
369
+
370
+ ### Bundle Analysis
371
+
372
+ - Use `composition.functions` and `interface` to reason about available APIs without scanning full source.
373
+ - Combine multiple bundles when a task spans related modules; respect `max-nodes` constraints to stay within token budgets.
374
+ - For deeper understanding, rerun the CLI with `--include-code full` or higher `--depth` before querying the assistant.
375
+ - **Always inspect `meta.missing`** in each bundle to understand analysis completeness before providing architectural guidance.
376
+
377
+ ### Style Metadata (Optional)
378
+
379
+ When using `stamp context style` or `stamp context --include-style`, bundles include a `style` field with visual and layout information.
380
+
381
+ **Style Mode Variants (v0.7.0+):**
382
+ - **Lean mode** (default): Compact format with count fields (`selectorCount`, `componentCount`, `colorCount`, etc.) and category names (`categoriesUsed`) instead of full arrays. Includes `summary.mode: 'lean'` and optional `summary.fullModeBytes` for size comparison. This is the default output format for `stamp context style` and `stamp context --include-style`.
383
+ - **Full mode**: Verbose format with complete arrays (`selectors`, `components`, `colors`, `categories` objects, etc.). Includes `summary.mode: 'full'`. Use `--style-mode full` to generate this format.
384
+
385
+ Both formats are valid and schema-compliant. The JSON schema supports both variants to ensure validation passes regardless of style mode.
386
+
387
+ **Style Sources (`style.styleSources`):**
388
+ - **Tailwind CSS**:
389
+ - Full mode: `categories` object with arrays of classes per category, plus `classCount` and `breakpoints`
390
+ - Lean mode: `categoriesUsed` array (category names), `classCount`, and `breakpoints`
391
+ - **SCSS/CSS Modules**: File paths and parsed details (selectors, properties, SCSS features like variables, nesting, mixins)
392
+ - **Styled JSX** (v0.3.5+):
393
+ - Full mode: `css` string, `selectors` array, `properties` array, `global` boolean
394
+ - Lean mode: `selectorCount`, `propertyCount`, `global` boolean
395
+ - **styled-components/Emotion**:
396
+ - Full mode: `components` array, `usesTheme`, `usesCssProp`
397
+ - Lean mode: `componentCount`, `usesTheme`, `usesCssProp`
398
+ - **framer-motion**: Motion components, variants, gesture handlers, layout animations, viewport animations
399
+ - **Material UI**: Components, packages, theme usage, sx prop, styled API, makeStyles, system props
400
+ - **ShadCN/UI**: Components, variants, sizes, form integration, theme usage, icon libraries, component density
401
+ - **Radix UI**: Primitives (organized by package), patterns (controlled/uncontrolled, portals, asChild), accessibility features
402
+ - **Inline Styles** (v0.3.5+): Enhanced extraction with both property names and literal values (e.g., `{ properties: ['color', 'padding'], values: { color: 'blue', padding: '1rem' } }`)
403
+
404
+ **Layout Metadata (`style.layout`):**
405
+ - Layout type (flex, grid, relative, absolute)
406
+ - Grid column patterns
407
+ - Hero section and feature card patterns
408
+ - Page sections:
409
+ - Full mode: `sections` array with section names
410
+ - Lean mode: `sectionCount` number
411
+
412
+ **Visual Metadata (`style.visual`):**
413
+ - Color palettes:
414
+ - Full mode: `colors` array (top 10 color utility classes)
415
+ - Lean mode: `colorCount` number
416
+ - Spacing patterns:
417
+ - Full mode: `spacing` array (top 10 spacing utilities)
418
+ - Lean mode: `spacingCount` number
419
+ - Border radius tokens (`radius` string)
420
+ - Typography classes:
421
+ - Full mode: `typography` array (top 10)
422
+ - Lean mode: `typographyCount` number
423
+
424
+ **Style Summary (`style.summary`):**
425
+ - `mode`: `'lean'` or `'full'` - indicates which format is used
426
+ - `sources`: Array of detected style sources (e.g., `['tailwind', 'styled-jsx']`)
427
+ - `fullModeBytes`: Optional, only in lean mode - estimated byte size if full mode were used
428
+
429
+ **Animation Metadata (`style.animation`):**
430
+ - Animation library type
431
+ - Animation types and triggers
432
+
433
+ ### Folder-Based Organization Benefits
434
+
435
+ - **Targeted loading**: Load only the folder context files you need, reducing token usage
436
+ - **Project structure alignment**: Folder structure mirrors your codebase, making it easier to navigate
437
+ - **Incremental updates**: When code changes, only affected folder context files need regeneration
438
+ - **Root detection**: Use `isRoot` and `rootLabel` to identify application entry points and framework-specific folders
439
+
440
+ ## Context Drift Detection
441
+
442
+ LogicStamp Context includes a `compare` command for detecting drift across all context files in a project:
443
+
444
+ ### Multi-File Comparison Mode
445
+
446
+ The compare command operates in multi-file mode when comparing `context_main.json` indices:
447
+
448
+ ```bash
449
+ stamp context compare # Auto-mode: compares all files
450
+ stamp context compare old/context_main.json new/context_main.json # Manual mode
451
+ ```
452
+
453
+ **What it detects:**
454
+ - **ADDED FILE** - New folders with context files (new features/modules added)
455
+ - **ORPHANED FILE** - Folders removed from project (but context files still exist on disk)
456
+ - **DRIFT** - Changed files with detailed component-level changes
457
+ - **PASS** - Unchanged files
458
+
459
+ **Three-tier output:**
460
+ 1. **Folder-level summary** - Shows added/orphaned/changed/unchanged folder counts
461
+ 2. **Component-level summary** - Total components added/removed/changed across all folders
462
+ 3. **Detailed per-folder changes** - Component-by-component diffs for each folder with changes
463
+
464
+ ### Use Cases for LLMs
465
+
466
+ 1. **Change impact analysis**: When analyzing a codebase update, run `stamp context compare` to see exactly which folders and components changed
467
+ 2. **Architectural drift**: Identify when new modules are added (`ADDED FILE`) or old ones removed (`ORPHANED FILE`)
468
+ 3. **Per-folder token impact**: Use `--stats` to see token delta per folder, helping prioritize which changes to review
469
+ 4. **Breaking change detection**: Check if component signatures (props, exports, hooks) changed, indicating potential breaking changes
470
+
471
+ ### Key Features
472
+
473
+ - **Jest-style workflow**: Use `--approve` to auto-update all context files (like `jest -u` for snapshots)
474
+ - **Orphaned file cleanup**: Use `--clean-orphaned` with `--approve` to automatically delete stale context files
475
+ - **CI integration**: Exit code 1 if drift detected, making it CI-friendly for validation
476
+ - **Token statistics**: `--stats` shows per-folder token deltas to understand context size impact
477
+
478
+ ### Example Output
479
+
480
+ ```bash
481
+ $ stamp context compare
482
+
483
+ ⚠️ DRIFT
484
+
485
+ 📁 Folder Summary:
486
+ Total folders: 14
487
+ ➕ Added folders: 1
488
+ ~ Changed folders: 2
489
+ ✓ Unchanged folders: 11
490
+
491
+ 📦 Component Summary:
492
+ + Added: 3
493
+ ~ Changed: 2
494
+
495
+ 📂 Folder Details:
496
+
497
+ ➕ ADDED FILE: src/new-feature/context.json
498
+ Path: src/new-feature
499
+
500
+ ⚠️ DRIFT: src/cli/commands/context.json
501
+ Path: src/cli/commands
502
+ ~ Changed components (1):
503
+ ~ compare.ts
504
+ Δ hash
505
+ old: uif:abc123...
506
+ new: uif:def456...
507
+ ```
508
+
509
+ ### Implementation Details
510
+
511
+ - **Truth from bundles**: Comparison is based on actual bundle content, not metadata (summary counts)
512
+ - **Bundle→folder mapping**: Verifies folder structure from `context_main.json`
513
+ - **Orphaned detection**: Checks disk for files that exist but aren't in the new index
514
+ - **Metadata ignored**: `totalComponents`, `totalBundles` counts are derived stats, not compared for drift
515
+
516
+ ## Watch Mode Integration
517
+
518
+ Watch mode (`stamp context --watch`) monitors file changes and automatically regenerates context. This section explains how to integrate with watch mode from MCP servers or other tools.
519
+
520
+ ### Detecting Watch Mode
521
+
522
+ Check if watch mode is active by reading `.logicstamp/context_watch-status.json`:
523
+
524
+ ```json
525
+ {
526
+ "active": true,
527
+ "projectRoot": "/path/to/project",
528
+ "pid": 12345,
529
+ "startedAt": "2025-01-19T10:30:00.000Z",
530
+ "outputDir": "/path/to/project",
531
+ "strictWatch": false
532
+ }
533
+ ```
534
+
535
+ **Fields:**
536
+ - `active` - Always `true` when file exists (file is deleted on exit)
537
+ - `projectRoot` - Absolute path to the watched project
538
+ - `pid` - Process ID of the watch process (use to verify process is still running)
539
+ - `startedAt` - ISO timestamp when watch mode started
540
+ - `outputDir` - Directory where context files are written
541
+ - `strictWatch` - Whether strict watch mode is enabled (`true` when `--strict-watch` flag is used, `false` otherwise)
542
+
543
+ **Important**: The status file is deleted when watch mode exits. If the file exists but the process crashed, validate using the `pid` field:
544
+
545
+ ```typescript
546
+ // Pseudo-code for validating watch mode is truly active
547
+ const status = JSON.parse(readFile('.logicstamp/context_watch-status.json'));
548
+ try {
549
+ process.kill(status.pid, 0); // Signal 0 checks if process exists
550
+ // Watch mode is running
551
+ } catch {
552
+ // Process doesn't exist - stale status file
553
+ }
554
+ ```
555
+
556
+ ### MCP Server Integration Patterns
557
+
558
+ **Pattern 1: Direct Context Reading (Recommended)**
559
+
560
+ When watch mode is active, `context_main.json` and folder `context.json` files are always up-to-date. Simply read them directly:
561
+
562
+ ```typescript
563
+ // 1. Check if watch mode is active
564
+ const isWatching = await checkWatchStatus(projectRoot);
565
+
566
+ // 2. Read context (always fresh when watch mode is running)
567
+ const index = JSON.parse(readFile('context_main.json'));
568
+ const bundles = JSON.parse(readFile(index.folders[0].contextFile));
569
+ ```
570
+
571
+ This is the simplest approach - no need to track changes, just read the latest context.
572
+
573
+ **Pattern 2: Change-Aware Integration (with `--log-file`)**
574
+
575
+ For MCP servers that need to know *what* changed (not just read fresh context), use the `--log-file` flag:
576
+
577
+ ```bash
578
+ stamp context --watch --log-file
579
+ ```
580
+
581
+ This writes structured change logs to `.logicstamp/context_watch-mode-logs.json`:
582
+
583
+ ```json
584
+ {
585
+ "entries": [
586
+ {
587
+ "timestamp": "2025-01-19T10:30:05.000Z",
588
+ "changedFiles": ["src/components/Button.tsx"],
589
+ "fileCount": 1,
590
+ "durationMs": 234,
591
+ "modifiedContracts": [
592
+ {
593
+ "entryId": "src/components/Button.tsx",
594
+ "semanticHashChanged": true,
595
+ "fileHashChanged": true,
596
+ "semanticHash": { "old": "uif:abc...", "new": "uif:def..." }
597
+ }
598
+ ],
599
+ "modifiedBundles": [
600
+ {
601
+ "entryId": "src/components/Button.tsx",
602
+ "bundleHash": { "old": "hash1...", "new": "hash2..." }
603
+ }
604
+ ],
605
+ "addedContracts": [],
606
+ "removedContracts": [],
607
+ "summary": {
608
+ "modifiedContractsCount": 1,
609
+ "modifiedBundlesCount": 1,
610
+ "addedContractsCount": 0,
611
+ "removedContractsCount": 0
612
+ }
613
+ }
614
+ ]
615
+ }
616
+ ```
617
+
618
+ **Log entry fields:**
619
+ - `timestamp` - When regeneration completed
620
+ - `changedFiles` - Source files that triggered regeneration
621
+ - `fileCount` - Number of changed files
622
+ - `durationMs` - Regeneration time in milliseconds
623
+ - `modifiedContracts` - Contracts with changed hashes (API or content changes)
624
+ - `modifiedBundles` - Bundles with changed dependency graphs
625
+ - `addedContracts` - New components added
626
+ - `removedContracts` - Components removed
627
+ - `summary` - Quick counts for each change type
628
+ - `error` - Error message if regeneration failed
629
+
630
+ **When to use `--log-file`:**
631
+ - MCP server needs to notify users about specific changes
632
+ - Building a UI that shows "what changed" information
633
+ - Debugging or auditing context regeneration
634
+ - Integration tests that verify specific changes
635
+
636
+ **When NOT to use `--log-file`:**
637
+ - Just need fresh context (Pattern 1 is simpler)
638
+ - Concerned about disk I/O overhead
639
+ - Log file maintenance is a concern
640
+
641
+ ### Hash Types in Change Logs
642
+
643
+ When `--log-file` is enabled, change logs include hash information:
644
+
645
+ | Hash Type | What It Detects | When It Changes |
646
+ |-----------|-----------------|-----------------|
647
+ | `semanticHash` | API/logic changes | Props, events, state, hooks, components, functions change |
648
+ | `fileHash` | Any content change | Any file modification (including comments, formatting) |
649
+ | `bundleHash` | Dependency graph changes | Components added/removed from bundle, edges change |
650
+
651
+ **Interpreting changes:**
652
+ - `semanticHash` changed → API breaking change likely, consumers may need updates
653
+ - `fileHash` changed but not `semanticHash` → Cosmetic change (comments, formatting)
654
+ - `bundleHash` changed → Dependency structure changed, may affect bundle consumers
655
+
656
+ ### File Locations Summary
657
+
658
+ | File | Location | Purpose |
659
+ |------|----------|---------|
660
+ | Watch status | `.logicstamp/context_watch-status.json` | Detect if watch mode is running |
661
+ | Watch logs | `.logicstamp/context_watch-mode-logs.json` | Change history (requires `--log-file`) |
662
+ | Main index | `context_main.json` | Project structure and folder index |
663
+ | Folder context | `<folder>/context.json` | Component bundles per folder |
664
+
665
+ ### CLI Reference
666
+
667
+ ```bash
668
+ # Start watch mode (no log file)
669
+ stamp context --watch
670
+
671
+ # Start watch mode with change logging
672
+ stamp context --watch --log-file
673
+
674
+ # Watch with breaking change detection (strict mode)
675
+ stamp context --watch --strict-watch
676
+
677
+ # Watch with style metadata
678
+ stamp context --watch --include-style
679
+
680
+ # Watch with debug output (shows hash details in console)
681
+ stamp context --watch --debug
682
+
683
+ # Watch specific directory
684
+ stamp context ./src/components --watch
685
+ ```
686
+
687
+ ### Strict Watch Mode
688
+
689
+ Strict watch mode (`--strict-watch`) detects breaking changes in real-time:
690
+
691
+ **Violation types:**
692
+ - `breaking_change_prop_removed` - Prop removed from component
693
+ - `breaking_change_event_removed` - Event/callback removed
694
+ - `breaking_change_function_removed` - Exported function removed
695
+ - `breaking_change_state_removed` - State variable removed
696
+ - `breaking_change_prop_type` - Prop type changed (warning)
697
+ - `contract_removed` - Entire component/module removed
698
+
699
+ **Output files:**
700
+ - `.logicstamp/strict_watch_violations.json` - Current violations (only exists when violations are present; automatically deleted when all resolved)
701
+
702
+ **CI integration:** Exits with code 1 if errors detected during session.
703
+