Metadata-Version: 2.5
Name: featuregraph-cli
Version: 0.1.1
Summary: Zero-dependency AST call graph, line-span index, and security gate (impact + check --strict) for AI coding agents.
Project-URL: Homepage, https://github.com/Pakheria/featuregraph
Project-URL: Repository, https://github.com/Pakheria/featuregraph.git
Project-URL: Issues, https://github.com/Pakheria/featuregraph/issues
Author-email: ProximaLink <faizan@proximalink.pk>, Pakheria <faizan@proximalink.pk>
License-Expression: MIT
License-File: LICENSE
Keywords: agentic-ai,ai,antigravity,ast,claude-code,code-indexing,context-window,cursor,feature-graph,llm,polyglot-ast,token-optimization
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Code Generators
Classifier: Topic :: Software Development :: Documentation
Requires-Python: >=3.10
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Description-Content-Type: text/markdown

# FeatureGraph ⚡

> **AST-indexed feature topology maps for AI coding agents: exact line spans, inferred call edges, and a contract gate for changes. Zero runtime dependencies.**

[![PyPI version](https://img.shields.io/pypi/v/featuregraph-cli.svg)](https://pypi.org/project/featuregraph-cli/)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://github.com/Pakheria/featuregraph/blob/main/LICENSE)
[![Python Version](https://img.shields.io/badge/Python-3.10%2B-blue)](https://github.com/Pakheria/featuregraph/blob/main/pyproject.toml)
[![GitHub Repository](https://img.shields.io/badge/GitHub-Pakheria%2Ffeaturegraph-black?logo=github)](https://github.com/Pakheria/featuregraph)

![FeatureGraph Demo — impact & strict security gate](https://raw.githubusercontent.com/Pakheria/featuregraph/main/assets/demo.gif)

---

## 🎯 The Problem

1. **No caller visibility:** An AI coding agent editing a function cannot see who calls it across files. Unreferenced-looking helpers and security gates get deleted, and downstream callers break.
2. **Context spend:** Pasting whole files every turn costs tokens and pushes relevant code out of the window.
3. **Coarse graphs:** Many graph tools produce file-level nodes, so the agent still has to open the file.
4. **No change gate:** Nothing tells the agent which endpoints, auth boundaries, invariants, and tests a change touches.

FeatureGraph addresses these with a small index of named features, exact line ranges, deterministic call edges, and two commands built for the edit loop: `impact` and `check`.

---

## ⚡ How It Works

```text
AI Coding Agent / Developer
            │
            ▼
 [1. Read .featuregraph/manifest.json]  ──> Tier-1: category -> feature names
            │
            ▼
 [2. Read categories/<category>.json]   ──> Tier-2: exact #Lstart-Lend per feature
            │
            ▼
 [3. Edit only that span]               ──> impact <id> first, impact --diff after
            │
            ▼
 [4. Commit]                            ──> pre-commit hook rescans the index
```

The index is generated in two passes:

1. **Symbol indexing:** parse every supported file, map tagged declarations to feature IDs, and assign deterministic symbol IDs (bare when unique, path-qualified on collision).
2. **Dependency inference:** walk each feature's span, collect call sites, decorators, class bases, dependency-injection arguments, imports, JSX tags, and inheritance, then wire `depends_on` / `called_by`.

Inference is textual/AST based, not a full type-checker. It resolves names by path affinity (same file > same directory > longest shared path); equally-near candidates are all kept rather than dropping the edge.

---

## 📦 Index Layout

| Artifact | Contents |
| :--- | :--- |
| `.featuregraph/manifest.json` | Tier-1 directory: category -> feature IDs and names, plus `_meta` |
| `.featuregraph/categories/<category>.json` | Tier-2 map: locations (`file`, `lines`), dependencies, contract tags |
| `.featuregraph/index.json` | Full graph (`features` + `_meta`) |
| `.featuregraph/graph.md` | Markdown table and Mermaid dependency diagram |
| `.featuregraph/unindexed.json` | Files that failed to parse (Python AST syntax errors, brace-unbalanced JS/TS files, or read errors) |
| `AGENTS.md` | Agent short-circuit directive (read the manifest first) |
| `.git/hooks/pre-commit` | Rescans and stages `.featuregraph/` when it is not gitignored |

`_meta.tree_hash` is a SHA-256 over sorted `(relative path, file bytes)` plus `.featureignore`. Content hashing means a `touch` or a checkout without edits is a no-op, and a same-size edit is still detected. `query`/`search` refuse stale results unless `--force` is passed.

`_meta.status` is `ok` (everything parsed), `partial` (some files yielded no named symbols), or `empty` (no features). A Python AST syntax error or a brace-unbalanced JS/TS file is the only thing that makes the manifest unreliable, reported as `unparsed_syntax_errors > 0`. Files indexed at file granularity (tests, scripts, configs) are reported separately as `_meta.file_level_files` and do not invalidate the manifest.

---

## 🧠 Dependency Resolution

- **Python:** AST call sites, decorator references, class bases, and dependency-injection wrappers (`Depends`, `Security`, `Body`, `Header`, `Cookie`). Import aliases (`import x as y`, `from m import a as b`) resolve to the original symbol.
- **TypeScript / JavaScript:** call sites, JSX component tags, `extends`/`implements`, ES `import` bindings, and CommonJS `require()` bindings from the code-only view (strings and comments masked).
- **Other languages:** call sites, inheritance, and route patterns from a lexed code-only view.
- **Manual edges:** `@depends [ID]` / `@depends_on [ID]` add explicit edges; dangling references are reported as `unresolved_depends`.
- **Containment guard:** a tagged method inside a tagged class does not create a fake class <-> method cycle from overlapping spans alone.

Isolated features (no dependencies, no callers) are listed in `graph.md` for dead-code review.

---

## 🏷️ Tag Rules & Coverage

Tags count only on a **real comment line**. Every parser, the annotator, and dependency inference share one lexical mask, so a tag inside a string, template literal, or Python docstring can never create a feature. Real comment lines are honoured in every language, including `//`, `#`, and `/* ... */`.

| Language | Tag placement | Symbol window |
| :--- | :--- | :--- |
| Python | Comment above `def` / `class` | 6 lines above |
| TypeScript / JS | Comment above the export | 6 lines below the tag |
| Go, Rust, Java, C#, PHP, Ruby, Swift, Dart, Shell | Comment above the declaration | 6 lines below the tag |

### Line spans

- **Python:** exact, from the AST (`lineno`..`end_lineno`).
- **TypeScript / JS:** the tag attaches to the export within 6 lines below it. The end line is found by brace-matching from the declaration's opening brace on the masked view, so braces in strings, comments, and template literals cannot close the block early. `const X = () => (` JSX arrows track balanced parentheses the same way. A fixed 35-line fallback is used only when no block brace is found (single-line or unbraced expressions).
- **Other languages:** brace matching (or `def`/`end` counting for Ruby) from the declaration.

### Untagged coverage

| Source | Auto feature IDs |
| :--- | :--- |
| Untagged `.js` | `CJS-<path>-<symbol>` for classes, functions, arrow functions, class/prototype methods, and `exports`/`module.exports` members |
| Untagged `.ts` / `.tsx` / `.jsx` | `TS-<path>-<symbol>` for exported declarations |
| Untagged Django `models.py` (or any class with a Django model base) | `MODEL-<path>-<symbol>` |
| Untagged Django `settings.py` (`UPPER_CASE` names) | `CONFIG-<path>-<symbol>`; sensitive key names (`SECRET`, `PASSWORD`, `TOKEN`, `API_KEY`, `PRIVATE_KEY`, `DATABASE_URL`, `CREDENTIAL`) are redacted and never emit values |
| Any supported file with no named symbols | `FILE-<path>` file-level entry (counted in `_meta.file_level_files`) |

Tagged files keep tag-only behavior, so adding explicit tags never churns existing IDs or inferred edges.

`featuregraph annotate` suggests tags for un-annotated symbols, refuses insertion points that are not code, writes atomically, and re-parses every write; a tag that would not round-trip restores the original file.

---

## 🔐 Contract Tags & Anti-Slop Workflow

Three additional comment-only tags describe the contracts a change must not break:

```python
# @feature [BILLING-CHARGE] Charge endpoint
# @boundary [auth, tenant]
# @invariant Amounts stay in integer cents; never charge twice for one idempotency key.
# @test tests/test_billing.py::test_charge_is_idempotent, tests/test_billing.py::test_amount_rounding
@router.post("/charge")
def charge(...):
    ...
```

- `@boundary [a, b]` — security boundary the feature sits behind. Normalised lowercase, stored as `boundaries`.
- `@invariant <text>` — repeatable rule to preserve. Stored under `invariants`.
- `@test <path>::<nodeid>` — repeatable test selector (single value or comma/space separated list). Stored under `tests`.

Empty values are omitted from the JSON. `featuregraph impact` reports them; `featuregraph check --strict` enforces boundaries on endpoints.

**Before editing shared code:**

```bash
featuregraph impact <feature_id>      # callers, endpoints, boundaries, invariants, tests
```

**After editing:**

```bash
featuregraph impact --diff            # verify the blast radius of the change
featuregraph check --strict
```

Prints `touched` features, transitive `downstream` callers, `affected_endpoints`, `boundaries` crossed, `invariants` to preserve, and `tests` to run. Add `--json` for agents, or `--staged` to inspect staged changes instead of the working tree.

**Before declaring a task complete:**

```bash
featuregraph check --strict
```

Exit 0 = pass, exit 1 = fail. Always fails when the index is missing, corrupt, or stale, or when there are syntax errors, unresolved `@depends`, or duplicate feature IDs. `--strict` also fails on dependency cycles and on any endpoint (`ROUTE-*` / `type: endpoint`) with no `@boundary` and no dependency on an `auth`/`admin`/`tenant`/`internal` guarded feature. Mark intentionally public routes `@boundary [public]`.

---

## 🚨 Scan Warnings

Warnings are aggregated to one line each per scan:

```bash
⚠ 6 file(s) with no parseable features (untagged, unreadable, or syntax error): src/legacy.py, … (+3 more)
⚠ 1 unresolved @depends reference(s) — no such feature: DANGLE-01 → GHOST-77
```

### Symbol IDs & collisions

A tagged location's symbol ID is its bare symbol when unique (`validate_token`) and a deterministic path prefix on collision (`web.app.layout` vs `web.app.docs.layout`; if the directory still repeats, the full path is used). Explicit `@feature [ID]` tags remain the canonical feature ID.

`query`, `search`, and `impact` accept a feature ID, a qualified symbol ID, or an unambiguous bare symbol. An ambiguous bare name exits 1 and lists the candidate qualified IDs.

---

## ⚡ Fast AST Feature Search

```bash
featuregraph search "parser"
# Output gives exact file paths and surgical #Lstart-Lend ranges:
# • featuregraph/core/parser_py.py #L10-L95 (PythonFeatureParser)

featuregraph query web.app.docs.layout   # qualified symbol ID
featuregraph query layout                # ambiguous -> exit 1 + candidate IDs
```

---

## 🚀 Installation & Quickstart

### 1. Install via pip / uv (PyPI)
```bash
pip install featuregraph-cli

# Or install as an isolated CLI tool:
uv tool install featuregraph-cli

# Or run without installing:
uvx --from featuregraph-cli featuregraph check --rescan --strict
```

### 2. Initialize in Your Repository
```bash
cd your-project
featuregraph init
```

This command:
- scans the codebase and writes `.featuregraph/manifest.json`, `.featuregraph/categories/`, `.featuregraph/index.json`, `.featuregraph/graph.md`
- creates or extends the **`AGENTS.md`** short-circuit directive
- installs the workspace agent skill at `.agents/skills/featuregraph/SKILL.md`
- installs `.git/hooks/pre-commit` when no foreign pre-commit hook exists

The hook rescans on commit, skips when unstaged or untracked changes are present, and stages `.featuregraph/` only when `git check-ignore` says it is not ignored. It never force-adds a gitignored directory.

### 3. Install Global Agent Skills
```bash
featuregraph skill --global
```

Targets: `~/.agents`, `~/.gemini/config`, `~/.claude/skills`, `~/.cursor/skills`, `~/.config/opencode/skills`.

---

## 🌐 Multi-Language Support

| Language | Extensions | Comment style |
| :--- | :--- | :--- |
| **Python** | `.py` | `# @feature [ID] Name` |
| **TypeScript / JavaScript** | `.ts`, `.tsx`, `.js`, `.jsx` | `// @feature [ID] Name` |
| **Go** | `.go` | `// @feature [ID] Name` |
| **Rust** | `.rs` | `// @feature [ID] Name` |
| **Java / Kotlin** | `.java`, `.kt`, `.kts` | `// @feature [ID] Name` |
| **C# / .NET** | `.cs` | `// @feature [ID] Name` |
| **C / C++** | `.c`, `.cpp`, `.cc`, `.h`, `.hpp` | `// @feature [ID] Name` |
| **PHP** | `.php` | `// @feature [ID] Name` |
| **Ruby** | `.rb` | `# @feature [ID] Name` |
| **Swift / Dart** | `.swift`, `.dart` | `// @feature [ID] Name` |
| **Shell** | `.sh`, `.bash`, `.zsh` | `# @feature [ID] Name` |

Go double-quoted strings honour backslash escapes; backtick raw strings do not. The lexer handles both, so `\"` inside a Go string never leaks a fake comment.

---

## 🛠️ CLI Reference

```bash
featuregraph --help

# Initialize repo, pre-commit hook, AGENTS.md directive and workspace skill
featuregraph init

# Auto-suggest and write @feature tags for un-annotated symbols
featuregraph annotate --dry-run
featuregraph annotate --yes
featuregraph annotate --dir ./src --limit 50 --yes

# Scan codebase, infer call edges, rebuild the 2-tier index
featuregraph scan
featuregraph scan --dir ./my-project --json index.json --md GRAPH.md --quiet

# Query exact lines and dependencies for a feature or symbol ID
featuregraph query AUTH-01
featuregraph query AUTH-01 --json
featuregraph search "parser" --dir ./app --json

# Blast radius: impact <feature_id> before editing, impact --diff after
featuregraph impact AUTH-01
featuregraph impact --diff
featuregraph impact --staged --json

# Enforcement gate (exit 0 = pass, 1 = fail)
featuregraph check
featuregraph check --strict
featuregraph check --strict --rescan --json

# Agent skills
featuregraph skill --install
featuregraph skill --global
featuregraph skill --show

# Pre-commit hook
featuregraph hook --install
featuregraph hook --uninstall
```

---

## 🤖 AI Agent Integration Protocol

1. **Auto-discovery:** agents find the `/featuregraph` skill in `.agents/skills/` or their global config.
2. **Short-circuit directive:** `AGENTS.md` tells the agent to read `.featuregraph/manifest.json` instead of walking the tree.
3. **Exact slices:** the agent reads only the target `#Lstart-Lend` span.
4. **Impact before and after edit:** `featuregraph impact <feature_id>` names the callers, endpoints, boundaries, invariants, and tests at risk before editing; `featuregraph impact --diff` verifies the blast radius afterwards.
5. **Gate before done:** `featuregraph check --strict` plus the reported tests.

---

## 🔄 CI Gate (GitHub Actions)

Drop FeatureGraph into pull requests to block stale indexes, broken `@depends`, cycles, and unguarded endpoints:

```yaml
- name: FeatureGraph security gate
  run: |
    pip install featuregraph-cli
    featuregraph check --rescan --strict
```

Want to try `impact` and `check --strict` in 10 seconds? See [`examples/fastapi-react-demo/`](https://github.com/Pakheria/featuregraph/tree/main/examples/fastapi-react-demo).

---

## 📄 License

MIT © [ProximaLink](https://proximalink.pk) / [Pakheria](https://github.com/Pakheria)
