Metadata-Version: 2.4
Name: baseplain
Version: 3.0.0
Summary: Ultra-compressed code mapping and static analysis for TypeScript/JavaScript codebases
Author: Piotr Tamulewicz
License: MIT
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: tree-sitter>=0.22.0
Requires-Dist: tree-sitter-typescript>=0.23.0
Requires-Dist: networkx>=3.0
Requires-Dist: matplotlib>=3.7
Provides-Extra: all
Requires-Dist: apted>=1.0; extra == "all"
Requires-Dist: gitpython>=3.1; extra == "all"
Dynamic: license-file

# baseplain

Ultra-compressed code mapping and static analysis tool for TypeScript/TSX codebases. Gives an LLM (or a human) the complete structural, contractual, and dependency picture of a codebase in a single call.

## What it does

Scans a TypeScript/TSX project and produces:

1. **Compressed code map** - one line per file: path, imports, exports, annotations
2. **Dependency graph** - interactive text/JSON/PNG showing how files connect
3. **Static analysis** - dead exports, impact analysis, call graphs, variable tracing, type flow, structural diff, annotation queries, domain grouping, AI artifact extraction

All output is designed to be LLM-readable. Progress goes to stderr, data goes to stdout.

## Installation

```bash
# Required
pip install tree-sitter tree-sitter-typescript

# For dependency graphs
pip install networkx matplotlib

# For structural diff
pip install apted

# For diff-aware mode
pip install gitpython
```

The tool is a single executable Python script at `/Users/piotr/Desktop/GlobalScripts/baseplain` with library modules in `baseplain_lib/`.

---

## Quick Start

```bash
# Scan current directory
baseplain

# Scan a specific project
baseplain /path/to/project/src

# Save to file (progress stays on screen, data goes to file)
baseplain ./src -o baseplain.txt

# Fast/light mode: no graph, compact header
baseplain ./src --light

# Pipe to an LLM
baseplain ./src --light | pbcopy
```

---

## Output Format

Each file becomes one pipe-separated line:

```
path | imports | content | annotations
```

### Path Compression

Common directories are replaced with Unicode symbols:

| Symbol | Directory    |
|--------|-------------|
| `/`    | /src/       |
| `/a/`  | /app/       |
| `/b/`  | /api/       |
| `/c/`  | /components/|
| `/f/`  | /features/  |
| `/h/`  | /hooks/     |
| `/l/`  | /lib/       |
| `/s/`  | /services/  |
| `/t/`  | /types/     |
| `/u/`  | /utils/     |

### Import Compression

```
{useState,useEffect}<react          # named imports
{z}<zod                              # single named
*utils<@/u/helpers                   # namespace import
React<react                          # default import
t{User,Post}<./types                 # type-only import
```

### Content Codes

| Code     | Meaning                  |
|----------|--------------------------|
| `s[...]` | Zod schemas              |
| `t[...]` | TypeScript type definitions |
| `m[...]` | Methods/functions        |
| `c[...]` | Constants                |
| `e[...]` | General exports          |
| `@[...]` | Annotation tags from JSDoc |

### Annotation Tags

Extracted from the first `/** ... */` JSDoc block in each file:

| Tag        | Meaning                              |
|------------|--------------------------------------|
| @PATTERN   | What the file implements             |
| @CRITICAL  | Inviolable rules                     |
| @REQUIRE   | What consumers of this file must do  |
| @COMPLEX   | Subtle logic needing careful handling|
| @DEPENDS   | What this file reads from            |
| @AFFECTS   | What reads from this file            |
| @DOMAIN    | Business domain (billing, auth, etc.)|

### Example Output Line

```
a/b/ai/generate/route.ts | {NextRequest,NextResponse}<next/server {z}<zod | m[POST,handleCardGeneration] | @[PATTERN:"Consume-first dual-counter quota enforcement",CRITICAL:"User never pays for a failed generation",DEPENDS:"ai-route-guard,website-generator",DOMAIN:"billing,builder"]
```

---

## Core Options

```
baseplain [directory] [options]
```

| Flag | Default | Description |
|------|---------|-------------|
| `directory` | `.` | Directory to scan |
| `-o, --output FILE` | stdout | Save output to file |
| `-e, --extensions EXT [EXT ...]` | `.ts .tsx .jsx` | File extensions to process |
| `-w, --workers N` | `64` | Number of parallel worker threads |
| `--no-gitignore` | off | Ignore .gitignore and .aiignore patterns |
| `--no-annotations` | off | Skip annotation extraction from JSDoc blocks |
| `--verbose-header` | off | Full header with format explanations and examples |
| `--light` | off | No graph, compact header (fastest mode) |

---

## Filtering

Filtering controls which files appear in the output. Filename and content filters combine with AND logic (file must match both). Within each filter type, patterns combine with OR by default.

### Basic Filtering

```bash
# Files with "auth" or "user" in the path
baseplain --filter-filename '["auth","user"]'

# Files containing "prisma" or "database" in source code
baseplain --filter-content '["prisma","database"]'

# Combine: filename must match AND content must match
baseplain --filter-filename '["auth"]' --filter-content '["prisma"]'

# Enable regex mode
baseplain --filter-filename '["route\\.ts$"]' --regex
```

### Content Mode: AND vs OR

```bash
# OR (default): files matching ANY content pattern
baseplain --filter-content '["useCardStore","getCachedForms"]'
# Returns 26 files (any file mentioning either term)

# AND: files matching ALL content patterns
baseplain --filter-content '["useCardStore","getCachedForms"]' --content-mode AND
# Returns 1 file (only files mentioning both terms)
```

### JSON Filter (full control)

```bash
# Everything in one flag
baseplain --filter '{
  "filename": ["auth", "user"],
  "content": ["prisma"],
  "contentMode": "AND",
  "regex": false
}'
```

| Flag | Type | Description |
|------|------|-------------|
| `--filter JSON` | string | Full JSON filter config (overrides individual flags) |
| `--filter-filename JSON` | string | JSON array of filename/path patterns |
| `--filter-content JSON` | string | JSON array of content patterns |
| `--content-mode OR\|AND` | string | Content filter logic (default: OR) |
| `--regex` | flag | Treat patterns as regular expressions |

---

## Dependency Graph

When you filter files, baseplain automatically generates a scoped dependency graph showing how those files connect to the rest of the codebase.

### Graph Options

| Flag | Default | Description |
|------|---------|-------------|
| `--no-graph` | off | Disable graph generation entirely |
| `--graph-depth N` | `2` | Expansion depth in hops from matched files (max: 4) |
| `--graph-direction both\|out\|in` | `both` | Direction: `out` = dependencies, `in` = dependents, `both` = both |
| `--graph-image-depth N` | none | Generate a PNG; set max depth rendered (triggers PNG generation) |

### Graph Outputs

Graphs are saved to `.baseplain/` directory with deterministic filenames:

- `.baseplain/graph_*.txt` - Human-readable text summary with cycles and hotspots
- `.baseplain/graph_*.json` - Machine-readable node/edge data
- `.baseplain/graph_*.png` - Visual graph (only when `--graph-image-depth` is set)

### Examples

```bash
# Graph for auth files, 3 hops deep
baseplain --filter-filename '["auth"]' --graph-depth 3

# Only show what depends ON auth files
baseplain --filter-filename '["auth"]' --graph-direction in

# Generate a PNG visualization
baseplain --filter-filename '["auth"]' --graph-image-depth 2

# Skip graph entirely for speed
baseplain --no-graph
# or equivalently:
baseplain --light
```

---

## Advanced Analysis

All advanced features build a cross-file symbol table (exports, imports, references) on first use. This adds ~3 seconds for a 1700-file codebase.

### Dead Export Finder

Find exports that nothing imports anywhere in the codebase.

```bash
baseplain ./src --dead-exports
```

Output:
```
DEAD EXPORTS: 1382 unused out of 4718 total
============================================================

  lib/auth/helpers.ts:
    :45    validateToken (function)
    :89    refreshSession (function)
  types/user.ts:
    :12    AdminRole (type/interface)
```

Automatically excludes Next.js framework entry points (`page.tsx`, `route.ts`, `layout.tsx`, etc.) and framework-consumed exports (`GET`, `POST`, `metadata`, `generateMetadata`, etc.).

| Flag | Description |
|------|-------------|
| `--dead-exports` | Run dead export analysis |

---

### Impact Analysis

Find all call sites of a specific export. Shows where it's called, with what arguments, what the caller does with the return value, and which function contains the call.

```bash
baseplain ./src --impact "createFieldConfig" --from "features/builder/lib/field-registry.ts"
```

Output:
```
IMPACT ANALYSIS: createFieldConfig
============================================================
  Source:    field-registry.ts:282
  Kind:      function
  Signature: createFieldConfig(fieldType, zoneId, sortOrder, data) -> FieldConfig | null
  Consumers: 4 files, 7 references

  features/builder/components/builder/BuilderChatDrawer.tsx:
    :978   [call] in BuilderChatDrawer()
           const fieldConfig = createFieldConfig(
    :1361  [call] in BuilderChatDrawer()
           const galleryConfig = createFieldConfig('gallery', 'fields',
  features/builder/components/builder/RightPanel.tsx:
    :315   [call] in handleAddField()
           const newField = createFieldConfig(fieldDef.id, zoneId, 999)
```

| Flag | Description |
|------|-------------|
| `--impact EXPORT_NAME` | Name of the export to analyze |
| `--from FILE_PATH` | File containing the export (relative to scan root) |

---

### Trace Mode

Follow a variable/identifier through the codebase: where it's exported, imported, called, assigned, and used.

```bash
baseplain ./src --trace "useCardStore"
```

Output:
```
TRACE: useCardStore
============================================================
  Found 51 references across 21 files

  features/builder/store/cardStore.tsx:
    :738   [EXPORT    ]  (function -> CardContextValue)
           export function useCardStore

  features/builder/components/builder/BuilderChatDrawer.tsx:
    :52    [IMPORT    ]
           import { useCardStore } from '@/features/builder/store/cardStore'
    :298   [CALL      ]  in BuilderChatDrawer()
           const { card, addField, removeField } = useCardStore()
```

| Flag | Description |
|------|-------------|
| `--trace VARIABLE` | Name of the variable/export to trace |

---

### Call Graph

Build a depth-limited call tree from a specific function. Resolves cross-file function calls via imports. Filters out all noise: JS/TS builtins, React hooks, common library utilities, string/array methods, DOM APIs, etc.

```bash
baseplain ./src --call-graph "POST" --file "app/api/ai/generate/route.ts" --call-depth 3
```

Output:
```
CALL GRAPH: POST (app/api/ai/generate/route.ts)
============================================================
  Internal calls: 20  Cycles: 4
  (builtins, React hooks, library utils filtered out)

  POST()  app/api/ai/generate/route.ts:219
      +-- getCurrentUser()  lib/auth/utils.ts:132
      |   +-- getSession()  lib/auth/utils.ts:58
      +-- resolveCredentials()  lib/integrations/credential-resolver.ts:75
      |   +-- getIntegrationManifest()  integrations/registry.ts:80
      |   +-- getUserTier()  lib/features/get-user-tier.ts:58
      |       +-- getUserSnapshot()  lib/features/snapshot-service.ts:265
      +-- guardAiRouteQuotas()  lib/features/ai-route-guard.ts:151
      |   +-- checkQuota()  lib/features/feature-service.ts:233
      |   +-- consumeFeature()  lib/features/feature-service.ts:409
      |   +-- releaseFeature()  lib/features/feature-service.ts:545
      +-- releaseAiRouteQuotas()  lib/features/ai-route-guard.ts:261
          +-- releaseFeature()  lib/features/feature-service.ts:545
```

Safety limits: max 200 total nodes, max 25 children per node. Cycle detection prevents infinite recursion.

| Flag | Default | Description |
|------|---------|-------------|
| `--call-graph FUNCTION` | - | Name of the function to start from |
| `--file FILE_PATH` | - | File containing the function (relative to scan root) |
| `--call-depth N` | `3` | Maximum depth to traverse |

---

### Structural Diff

Compare 2-3 similar files structurally using tree edit distance (AST-level comparison, not text diff). Finds shared patterns and divergences.

```bash
baseplain ./src --diff-structure \
  "features/builder/lib/field-registry.ts" \
  "features/builder/lib/theme-registry.ts"
```

Output:
```
STRUCTURAL COMPARISON
============================================================
  Files: field-registry.ts, theme-registry.ts

  Pairwise similarity:
    field-registry.ts
      <-> theme-registry.ts
      38.2% similar (edit distance: 218, nodes: 353)

  Shared patterns:
    + Shared hooks: (none - these are pure lib files)
    + All use async/await

  Divergences:
    x field-registry.ts: 105 functions
    x theme-registry.ts: 29 functions
```

| Flag | Description |
|------|-------------|
| `--diff-structure FILE1 FILE2 [FILE3]` | 2-3 files to compare structurally |

---

### Diff-Aware Mode

Show only files changed since a git revision, plus their dependents (files that import them). Perfect for pre-PR review.

```bash
# Files changed in last 5 commits + their dependents
baseplain ./src --since HEAD~5

# Changed files only, no dependents
baseplain ./src --since HEAD~5 --no-dependents

# Since diverging from main
baseplain ./src --since main
```

| Flag | Description |
|------|-------------|
| `--since REV` | Git revision (HEAD~5, main, commit hash, etc.) |
| `--no-dependents` | Don't expand to include files that import changed files |

---

### Annotation Queries

Search the annotation database. Query by tag name, value content, or cross-reference.

```bash
# Find all @CRITICAL annotations
baseplain ./src --query-annotations CRITICAL

# Find annotations mentioning a specific file
baseplain ./src --query-annotations DEPENDS --annotation-value "field-registry"

# Find all billing-domain files
baseplain ./src --query-annotations DOMAIN --annotation-value "billing"
```

Output:
```
ANNOTATION QUERY: @CRITICAL
============================================================
  Found 163 matches

  lib/billing/processor.ts:
    @CRITICAL: Never modify payment amount after validation
  lib/auth/session.ts:
    @CRITICAL: Session token must be HttpOnly secure cookie
```

| Flag | Description |
|------|-------------|
| `--query-annotations TAG` | Filter by tag name (CRITICAL, DEPENDS, PATTERN, etc.) |
| `--annotation-value PATTERN` | Filter annotation values by substring |

---

### Type Flow

Track a TypeScript type through the codebase: where it's defined, used as annotations, cast, serialized/deserialized. Detects type safety gaps.

```bash
baseplain ./src --type-flow "FieldConfig"
```

Output:
```
TYPE FLOW: FieldConfig
============================================================
  Definition: features/builder/types/field.ts:107 (interface)
  Used in 49 files, 144 references

  Type Annotations (61):
    features/builder/components/builder/BuilderChatDrawer.tsx:370
      fields: FieldConfig[],

  Type Assertions (casts) (11):
    app/api/cards/[id]/publish/route.ts:148
      const fields = (card.fields as unknown as FieldConfig[]) || []

  TYPE SAFETY GAPS (3):
    app/api/cards/[id]/publish/route.ts:148
      Unsafe double cast bypasses type checking
```

| Flag | Description |
|------|-------------|
| `--type-flow TYPE_NAME` | Name of the type/interface to track |

---

### Domain Grouping

Group the baseplain output by `@DOMAIN` annotation or by top-level directory.

```bash
# Group by @DOMAIN tag
baseplain ./src --group-by domain

# Group by directory structure
baseplain ./src --group-by directory
```

Output:
```
=== BILLING (12 files) ===
lib/billing/processor.ts | ... | m[processPayment,refund]
lib/billing/plans.ts | ... | m[getPlan,updatePlan]

=== AUTH (8 files) ===
lib/auth/session.ts | ... | m[createSession,validateSession]

=== UNCATEGORIZED (45 files) ===
utils/format.ts | ... | m[formatDate,formatCurrency]
```

| Flag | Description |
|------|-------------|
| `--group-by domain\|directory` | Group output by annotation domain or file path |

---

### AI Artifact Extraction

Extract AI-related artifacts: prompt/instruction files, tool declarations, and tool overlap between different modules.

```bash
baseplain ./src --ai-artifacts
```

Output:
```
AI ARTIFACTS
============================================================

  Prompt Files (5):
    integrations/google-gemini/prompts/loader.ts  (206 lines, 5 variables)
    integrations/google-imagen/prompts/registry.ts  (134 lines, 0 variables)

  Tool Declarations (14 tools in 3 files):
    integrations/google-gemini/tools/builder/index.ts:
      get_field_schemas
      scan_website
      add_fields

  Tool Overlap (2 shared names):
    ! respond_to_user defined in:
      - services/tools.ts
      - builder/tools.ts
```

| Flag | Description |
|------|-------------|
| `--ai-artifacts` | Extract prompts, tool declarations, and detect tool overlap |

---

### Verify Flow

Check whether expected function calls are reachable from an entry point. Catches missing wiring — planned steps that exist in the codebase but aren't connected to the execution path.

```bash
baseplain ./src --light \
  --verify-flow '["guardAiRouteQuotas","releaseAiRouteQuotas","getCurrentUser"]' \
  --from-function "POST" \
  --file "app/api/ai/scan-website/route.ts"
```

Resolves through registry dispatch patterns (`handlers[command](...)`), barrel file re-exports, and ref indirection (`someRef.current(...)`).

| Flag | Description |
|------|-------------|
| `--verify-flow JSON` | JSON array of function names that should be reachable |
| `--from-function FUNC` | Entry point function |
| `--file FILE` | File containing the entry point |

---

### Mutation Tracking

Analyze what a function writes: database, API calls, React state, cache, filesystem.

```bash
baseplain ./src --light --mutations "setupGoogleReviews" \
  --file "features/builder/components/builder/chat/executors/google-reviews.ts"

# Follow deeper into called functions
baseplain ./src --light --mutations "runExpiredSubscriptionCleanup" \
  --file "lib/subscription/cleanup-service.ts" --mutations-depth 3
```

Follows local function calls (same file) and imported function calls across files. Classifies: DB WRITE, API CALL, STATE, CACHE, FILESYSTEM, READ-ONLY.

| Flag | Description |
|------|-------------|
| `--mutations FUNC` | Function to analyze |
| `--mutations-depth N` | Levels of calls to follow (default: 2) |
| `--file FILE` | File containing the function |

---

### Data Flow / Taint Tracking

Track how a variable flows through a function: where it enters, what transforms are applied, where it reaches a sink.

```bash
baseplain ./src --light --data-flow "url" \
  --from-function "setupGoogleReviews" \
  --file "features/builder/components/builder/chat/executors/google-reviews.ts"

# Follow into API routes
baseplain ./src --light --data-flow "url" \
  --from-function "setupGoogleReviews" \
  --file "features/builder/components/builder/chat/executors/google-reviews.ts" \
  --data-flow-depth cross-file
```

Classifies transforms (CAST, SANITIZE, VALIDATE, PARSE, DERIVE), detects sinks (DB write, API call, state mutation, DOM render), reports validation coverage gaps, and unwraps `.then()` chains for fire-and-forget sinks.

| Flag | Description |
|------|-------------|
| `--data-flow VAR` | Variable to track |
| `--from-function FUNC` | Function containing the variable |
| `--file FILE` | File containing the function |
| `--data-flow-depth single\|cross-file` | Follow into API routes (default: single) |

---

### Annotation Validation

Detect annotation drift: stale `@DEPENDS`, missing declarations, orphaned references, `@CRITICAL` contradictions.

```bash
# Full validation
baseplain ./src --light --validate-annotations

# Specific checks
baseplain ./src --light --validate-annotations depends
baseplain ./src --light --validate-annotations domain
baseplain ./src --light --validate-annotations critical
baseplain ./src --light --validate-annotations orphaned
```

| Flag | Description |
|------|-------------|
| `--validate-annotations [CHECK]` | Run annotation checks. CHECK: `all`, `depends`, `domain`, `critical`, `orphaned` |

---

### Architecture Boundary Enforcement

Validate imports against declared domain boundary rules. Reads rules from `.baseplain/boundaries.yaml`.

```bash
# Generate starter config from current @DOMAIN patterns
baseplain ./src --light --init-boundaries

# Check boundaries
baseplain ./src --light --check-boundaries

# Check specific rule
baseplain ./src --light --check-boundaries --rule "engine"
```

Config format (`.baseplain/boundaries.yaml`):
```yaml
boundaries:
  - name: "Auth is a foundation layer"
    from:
      domains: ["auth"]
    cannot_import:
      domains: ["builder", "forms", "listings"]
```

| Flag | Description |
|------|-------------|
| `--check-boundaries` | Check rules from `.baseplain/boundaries.yaml` |
| `--rule NAME` | Only check rules matching this string |
| `--init-boundaries` | Generate starter config from current imports |

---

### AI Pipeline View

Map the full AI pipeline: prompt config, tool declarations, executor registry, side effects.

```bash
# Full pipeline for a prompt
baseplain ./src --light --ai-pipeline "builder-assistant"

# Overview of all pipelines
baseplain ./src --light --ai-pipeline "all"
```

Shows: prompt config (model, variables), tools-to-executors mapping with side-effect categories, unmapped tools, unregistered executors, client entry points.

| Flag | Description |
|------|-------------|
| `--ai-pipeline ID` | Pipeline view for a prompt. Use `all` for overview |

---

## Combining Features

Analysis features produce clean output without the full baseplain (only `--group-by` includes the baseplain since it reorganizes it).

```bash
# Dead exports for the whole project
baseplain ./src --light --dead-exports

# Impact analysis for an export
baseplain ./src --light --impact "createFieldConfig" --from "features/builder/lib/field-registry.ts"

# Domain-grouped baseplain for recently changed files
baseplain ./src --since HEAD~10 --group-by domain

# Full pipeline view for the builder AI
baseplain ./src --light --ai-pipeline "builder-assistant"

# Verify a plan's wiring is complete
baseplain ./src --light \
  --verify-flow '["guardAiRouteQuotas","releaseAiRouteQuotas"]' \
  --from-function "POST" --file "app/api/ai/scan-website/route.ts"

# Track data from user input to database
baseplain ./src --light --data-flow "url" \
  --from-function "setupGoogleReviews" \
  --file "features/builder/components/builder/chat/executors/google-reviews.ts" \
  --data-flow-depth cross-file

# Check architecture boundaries
baseplain ./src --light --check-boundaries

# Validate annotation accuracy
baseplain ./src --light --validate-annotations
```

---

## Performance

| Metric | Value |
|--------|-------|
| Parser | tree-sitter (native C, Python bindings) |
| Parallelism | ThreadPoolExecutor, 64 workers default |
| Codemap speed | ~1770 files in ~3 seconds |
| Symbol table build | ~3 seconds additional (only when analysis features used) |
| Graph generation | ~1-2 seconds |
| Call graph safety | Max 200 nodes, max 25 children/node |
| Memory | Scales with worker count; ASTs are not retained after extraction |

### Tips for large codebases

```bash
# Reduce workers if memory-constrained
baseplain ./src -w 16

# Use --light for fastest possible run
baseplain ./src --light

# Scope to a subdirectory
baseplain ./src/features/billing

# Use filters to focus
baseplain ./src --filter-filename '["billing"]' --light
```

---

## All Flags Reference

### Core
| Flag | Default | Description |
|------|---------|-------------|
| `directory` | `.` | Directory to scan |
| `-o, --output` | stdout | Output file path |
| `-e, --extensions` | `.ts .tsx .jsx` | File extensions |
| `-w, --workers` | `64` | Parallel workers |
| `--no-gitignore` | off | Skip .gitignore/.aiignore |
| `--no-annotations` | off | Skip annotation extraction |
| `--verbose-header` | off | Full explanatory header |
| `--light` | off | No graph, compact header |

### Filtering
| Flag | Default | Description |
|------|---------|-------------|
| `--filter` | - | Full JSON filter config |
| `--filter-filename` | - | JSON array of filename patterns |
| `--filter-content` | - | JSON array of content patterns |
| `--content-mode` | `OR` | Content filter logic: `OR` or `AND` |
| `--regex` | off | Treat patterns as regex |

### Dependency Graph
| Flag | Default | Description |
|------|---------|-------------|
| `--no-graph` | off | Disable graph generation |
| `--graph-depth` | `2` | Expansion depth (max 4) |
| `--graph-direction` | `both` | `both`, `out`, or `in` |
| `--graph-image-depth` | none | Trigger PNG generation at this depth |

### Analysis
| Flag | Default | Description |
|------|---------|-------------|
| `--dead-exports` | off | Find unused exports |
| `--dead-exports-ignore PAT` | - | Comma-separated path patterns to exclude (e.g., `_prototypes,__tests__`) |
| `--impact NAME` | - | Impact analysis for an export |
| `--from FILE` | - | Source file for `--impact` |
| `--trace VAR` | - | Trace a variable through the codebase (works with exports and local functions) |
| `--call-graph FUNC` | - | Build call tree from a function (follows registry dispatch, barrel re-exports) |
| `--file FILE` | - | Source file for `--call-graph`, `--trace`, `--mutations`, `--data-flow`, `--verify-flow` |
| `--call-depth N` | `3` | Max depth for `--call-graph` and `--verify-flow` |
| `--diff-structure F1 F2 [F3]` | - | Structural comparison of 2-3 files |
| `--since REV` | - | Diff-aware mode: files changed since REV |
| `--no-dependents` | off | With `--since`: skip dependent expansion |
| `--query-annotations TAG` | - | Query by annotation tag name |
| `--annotation-value PAT` | - | Filter annotation values by substring |
| `--group-by` | - | Group output: `domain` or `directory` |
| `--ai-artifacts` | off | Extract AI prompts and tool declarations |
| `--type-flow TYPE` | - | Track a type through the codebase |
| `--verify-flow JSON` | - | Verify function call reachability from `--from-function`. JSON array of expected function names |
| `--from-function FUNC` | - | Entry point for `--verify-flow` |
| `--mutations FUNC` | - | Analyze what a function writes: DB, API, state, cache, filesystem |
| `--mutations-depth N` | `2` | How many levels of called functions to follow for `--mutations` |
| `--data-flow VAR` | - | Track variable through transforms, validations, sinks. Requires `--from-function` + `--file` |
| `--data-flow-depth` | `single` | `single` (within function) or `cross-file` (follow into API routes) |
| `--validate-annotations [CHECK]` | - | Validate annotations match code. Checks: `all`, `depends`, `domain`, `critical`, `orphaned` |
| `--check-boundaries` | off | Check architecture boundary rules from `.baseplain/boundaries.yaml` |
| `--rule NAME` | - | With `--check-boundaries`: only check rules matching this string |
| `--init-boundaries` | off | Generate starter `.baseplain/boundaries.yaml` from current `@DOMAIN` patterns |
| `--ai-pipeline ID` | - | Show full AI pipeline: prompt config, tools, executors, side effects. Use `all` for overview |

---

## Troubleshooting

### Command not found
```bash
# Ensure GlobalScripts is in PATH
export PATH="$PATH:/Users/piotr/Desktop/GlobalScripts"
# Add to ~/.zshrc for persistence
```

### ModuleNotFoundError
```bash
# Check which Python is running
head -1 /Users/piotr/Desktop/GlobalScripts/baseplain
# Should show: #!/Users/piotr/miniconda3/bin/python

# Install missing packages
pip install tree-sitter tree-sitter-typescript networkx matplotlib apted gitpython
```

### Advanced features unavailable
```bash
# Check what's missing
python -c "from baseplain_lib.symbol_table import build_symbol_table; print('OK')"
# If this fails, ensure baseplain_lib/ exists next to the main script
```

### Output mixed with progress
```bash
# Data to file, progress on screen
baseplain ./src -o baseplain.txt

# Data to stdout, suppress progress
baseplain ./src 2>/dev/null

# Separate both
baseplain ./src > data.txt 2> progress.txt
```

### Graph generation fails
Graph failure never breaks the baseplain. If you see "Graph generation failed" on stderr, the baseplain is still complete. Check that `networkx` and `matplotlib` are installed.

---

## Architecture

```
baseplain                    # Main script (~1500 lines)
baseplain_lib/
  __init__.py
  graph_resolver.py                 # Import path resolution (tsconfig, @/ aliases)
  graph_builder.py                  # Dependency graph via networkx
  graph_output.py                   # Text/JSON/PNG graph output
  output_paths.py                   # Deterministic .baseplain/ filenames
  symbol_table.py                   # Cross-file symbol resolution (foundation)
  dead_exports.py                   # Unused export detection
  impact_analysis.py                # Export call site analysis
  trace.py                          # Variable flow tracing (exports + local functions)
  call_graph.py                     # Depth-limited call tree (registry dispatch, barrel following)
  diff_structure.py                 # AST structural comparison (apted)
  diff_aware.py                     # Git-based changed file detection
  annotation_query.py               # Annotation search engine
  domain_grouping.py                # Output grouping by domain/directory
  ai_artifacts.py                   # AI prompt/tool extraction
  type_flow.py                      # Type tracking and safety gap detection
  verify_flow.py                    # Function reachability verification
  mutations.py                      # Side-effect analysis (DB/API/state/cache/fs)
  data_flow.py                      # Variable taint tracking (transforms/validations/sinks)
  validate_annotations.py           # Annotation drift detection
  boundaries.py                     # Architecture boundary enforcement
  ai_pipeline.py                    # Prompt-to-executor pipeline mapping
```
