featuregraph-cli 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,110 @@
1
+ from pathlib import Path
2
+ from typing import Any
3
+
4
+
5
+ # @feature [MARKDOWN_FOR-01] Markdown formatter
6
+ class MarkdownFormatter:
7
+ """Formats feature graph into a rich Markdown table and Mermaid dependency diagram."""
8
+
9
+ @staticmethod
10
+ def _escape_mermaid(text: str) -> str:
11
+ """Neutralise characters that break Mermaid labels or inject markup."""
12
+ replacements = {
13
+ '"': "#quot;", "[": "#91;", "]": "#93;",
14
+ "<": "#60;", ">": "#62;", "{": "#123;", "}": "#125;",
15
+ }
16
+ out = str(text)
17
+ for char, entity in replacements.items():
18
+ out = out.replace(char, entity)
19
+ return " ".join(out.splitlines())
20
+
21
+ @staticmethod
22
+ def _escape_md_cell(text: str) -> str:
23
+ """Escape a GFM table cell: pipes split cells, angle brackets allow raw HTML."""
24
+ out = str(text).replace("|", "\\|")
25
+ out = out.replace("<", "&lt;").replace(">", "&gt;")
26
+ return " ".join(out.splitlines())
27
+
28
+ @staticmethod
29
+ # @feature [MARKDOWN_FOR-02] Format
30
+ def format(graph_dict: dict[str, Any], root_dir: Path) -> str:
31
+ rows = []
32
+ mermaid_edges = []
33
+
34
+ for feat_id, data in sorted(graph_dict.items()):
35
+ name = data.get("name", feat_id)
36
+ desc = data.get("description", "")
37
+ deps = data.get("depends_on", [])
38
+ called_by = data.get("called_by", [])
39
+ locations = data.get("locations", [])
40
+
41
+ # Mermaid edge construction
42
+ node_label = MarkdownFormatter._escape_mermaid(f"{feat_id}: {name}")
43
+ for dep in deps:
44
+ mermaid_edges.append(f' {feat_id}["{node_label}"] --> {dep}')
45
+
46
+ dep_str = " ".join([f"`[{d}]`" for d in deps]) if deps else "—"
47
+ call_str = " ".join([f"`[{c}]`" for c in called_by]) if called_by else "—"
48
+
49
+ loc_links = []
50
+ for loc in locations[:4]: # cap at 4 per feature to keep table scannable
51
+ file_rel = loc.get("file", "")
52
+ lines = loc.get("lines") or [loc.get("start_line", 1), loc.get("end_line", 1)]
53
+ s_line, e_line = lines[0], lines[1]
54
+ label = MarkdownFormatter._escape_md_cell(f"{file_rel}#L{s_line}-L{e_line}")
55
+ href = file_rel.replace(" ", "%20")
56
+ loc_links.append(f"[`{label}`]({href}#L{s_line}-L{e_line})")
57
+
58
+ loc_str = "<br>".join(loc_links) if loc_links else "—"
59
+ rows.append(
60
+ f"| **`{MarkdownFormatter._escape_md_cell(feat_id)}`** "
61
+ f"| **{MarkdownFormatter._escape_md_cell(name)}** "
62
+ f"| {MarkdownFormatter._escape_md_cell(desc) or '—'} "
63
+ f"| {MarkdownFormatter._escape_md_cell(dep_str)} "
64
+ f"| {MarkdownFormatter._escape_md_cell(call_str)} "
65
+ f"| {loc_str} |"
66
+ )
67
+
68
+ isolated = [fid for fid, d in sorted(graph_dict.items())
69
+ if not d.get("depends_on") and not d.get("called_by")]
70
+ isolated_line = ""
71
+ if isolated:
72
+ sample = ", ".join(f"`{f}`" for f in isolated[:10])
73
+ more = f" (+{len(isolated) - 10} more)" if len(isolated) > 10 else ""
74
+ isolated_line = f"\n**Isolated features** (no dependencies, no dependents — verify intent): {sample}{more}"
75
+
76
+ mermaid_block = ""
77
+ if mermaid_edges:
78
+ mermaid_block = "```mermaid\ngraph TD\n" + "\n".join(mermaid_edges[:40]) + "\n```\n\n---\n" # cap at 40 edges for readable Mermaid output
79
+
80
+ return f"""# System Feature Dependency Graph
81
+
82
+ > **CRITICAL CONTRACT FOR AI ASSISTANTS & DEVELOPERS:**
83
+ > This graph is generated by `featuregraph`.
84
+ > Always inspect dependencies before modifying or deleting code.
85
+
86
+ ---
87
+
88
+ ## 1. Visual Dependency Graph
89
+
90
+ {mermaid_block}## 2. Feature Map & Exact Line Reference Matrix
91
+
92
+ | Feature ID | Feature Name | Description | Depends On | Called By | Exact Line References |
93
+ | :--- | :--- | :--- | :--- | :--- | :--- |
94
+ """ + "\n".join(rows) + isolated_line + """
95
+
96
+ ---
97
+
98
+ ## 3. Token-Efficient Reading Protocol
99
+
100
+ When working on any feature:
101
+ 1. Lookup `.featuregraph/manifest.json` to find category and exact line slice (`#Lstart-Lend`).
102
+ 2. Read **only** those lines with your editor tool.
103
+ 3. Check `[Depends On]` features before committing changes.
104
+ """
105
+
106
+ @staticmethod
107
+ # @feature [MARKDOWN_FOR-03] Write to file
108
+ def write_to_file(graph_dict: dict[str, Any], output_path: Path, root_dir: Path):
109
+ content = MarkdownFormatter.format(graph_dict, root_dir)
110
+ output_path.write_text(content, encoding="utf-8")
@@ -0,0 +1,82 @@
1
+ import subprocess
2
+ from pathlib import Path
3
+
4
+ HOOK_MARKER = "# featuregraph-managed-hook"
5
+
6
+ HOOK_SCRIPT = f"""#!/usr/bin/env bash
7
+ set -e
8
+ {HOOK_MARKER}
9
+ # Auto-sync FeatureGraph on every git commit
10
+ if command -v featuregraph >/dev/null 2>&1; then
11
+ if ! git diff --quiet || [ -n "$(git ls-files --others --exclude-standard)" ]; then
12
+ echo "⚠ [FeatureGraph] Unstaged or untracked changes present — skipping index sync."
13
+ exit 0
14
+ fi
15
+ echo "⚡ [FeatureGraph] Auto-syncing Feature Graph & Line Index..."
16
+ featuregraph scan --quiet
17
+ if ! git check-ignore -q .featuregraph; then
18
+ git add .featuregraph/
19
+ fi
20
+ fi
21
+ """
22
+
23
+
24
+ def _hook_path(repo_root: Path) -> Path | None:
25
+ """Resolve the pre-commit hook path, including worktrees and core.hooksPath."""
26
+ try:
27
+ result = subprocess.run(
28
+ ["git", "-C", str(repo_root), "rev-parse", "--git-path", "hooks"],
29
+ capture_output=True, text=True, check=True,
30
+ )
31
+ raw = result.stdout.strip()
32
+ if raw:
33
+ hooks = Path(raw)
34
+ if not hooks.is_absolute():
35
+ hooks = repo_root / hooks
36
+ return hooks / "pre-commit"
37
+ except (OSError, subprocess.SubprocessError):
38
+ pass
39
+
40
+ git_dir = repo_root / ".git"
41
+ if git_dir.is_dir():
42
+ return git_dir / "hooks" / "pre-commit"
43
+ return None
44
+
45
+ # @feature [GIT_HOOK-01] Git hook manager
46
+ class GitHookManager:
47
+ """Installs or removes the git pre-commit hook. Never touches foreign hooks."""
48
+
49
+ @staticmethod
50
+ # @feature [GIT_HOOK-02] Install
51
+ def install(repo_root: Path) -> str:
52
+ """Returns 'installed', 'upgraded', 'no-git', or 'foreign-hook' (foreign hooks untouched)."""
53
+ hook_path = _hook_path(repo_root)
54
+ if hook_path is None:
55
+ return "no-git"
56
+
57
+ if hook_path.exists():
58
+ existing = hook_path.read_text(encoding="utf-8", errors="ignore")
59
+ if HOOK_MARKER not in existing:
60
+ # Pre-marker FeatureGraph hooks carry the same banner; take them over.
61
+ if "Auto-sync FeatureGraph" not in existing:
62
+ return "foreign-hook"
63
+ hook_path.write_text(HOOK_SCRIPT, encoding="utf-8")
64
+ hook_path.chmod(0o755)
65
+ return "upgraded"
66
+
67
+ hook_path.parent.mkdir(parents=True, exist_ok=True)
68
+ hook_path.write_text(HOOK_SCRIPT, encoding="utf-8")
69
+ hook_path.chmod(0o755)
70
+ return "installed"
71
+
72
+ @staticmethod
73
+ # @feature [GIT_HOOK-03] Uninstall
74
+ def uninstall(repo_root: Path) -> bool:
75
+ """Removes the hook only if FeatureGraph installed it. Returns True if removed."""
76
+ hook_path = _hook_path(repo_root)
77
+ if hook_path is None:
78
+ return False
79
+ if hook_path.exists() and HOOK_MARKER in hook_path.read_text(encoding="utf-8", errors="ignore"):
80
+ hook_path.unlink()
81
+ return True
82
+ return False
@@ -0,0 +1,3 @@
1
+ from .skill_manager import SkillManager
2
+
3
+ __all__ = ["SkillManager"]
@@ -0,0 +1,211 @@
1
+ ---
2
+ name: featuregraph
3
+ description: >-
4
+ Runs featuregraph commands on the current project. Use when the user mentions
5
+ featuregraph, wants to init a project, scan for features, annotate code,
6
+ query a feature ID, measure the blast radius of a change (impact), gate a
7
+ change (check), or generate a visual graph. Also pairs with ponytail: index first, then review.
8
+ license: MIT
9
+ ---
10
+
11
+ # FeatureGraph Skill
12
+
13
+ FeatureGraph is a CLI tool that AST-scans a codebase and generates a 2-Tier Hierarchical topology index:
14
+ - `.featuregraph/manifest.json` — Tier-1 directory (one line per feature) of domains & feature summaries
15
+ - `.featuregraph/categories/<category>.json` — Tier-2 exact line maps (#Lstart-Lend) per domain
16
+ - `.featuregraph/graph.md` — markdown table + Mermaid dependency diagram
17
+ - `AGENTS.md` — AI circuit-breaker directive (read manifest first, stop scanning)
18
+ - `.git/hooks/pre-commit` — auto-syncs index on every commit
19
+
20
+ ---
21
+
22
+ ## Step 0: Always Check First (MANDATORY)
23
+
24
+ **Before doing anything with the feature index — whether the user asked for it or not — check if it exists:**
25
+
26
+ ```bash
27
+ (test -f .featuregraph/manifest.json || test -f .featuregraph/index.json || test -f FEATURE_INDEX.json) && echo "EXISTS" || echo "MISSING"
28
+ ```
29
+
30
+ ### If MISSING → Auto-init without asking
31
+ Run `featuregraph init` immediately. Do not ask the user. Do not tell them to run it.
32
+ Just do it, then continue with their original request.
33
+
34
+ ```bash
35
+ featuregraph init
36
+ ```
37
+
38
+ ### If EXISTS → 2-Tier Inspection Workflow (Max Token Efficiency)
39
+ 1. **Turn 1:** Read `.featuregraph/manifest.json` to find which category owns the target feature.
40
+ 2. **Turn 2:** Read only that domain's file: `.featuregraph/categories/<category>.json`.
41
+ 3. **Turn 3:** Read and edit **ONLY** the exact line spans (`#Lstart-Lend`). Never do full-file exploratory reads.
42
+
43
+ ### If EXISTS → Check status and freshness
44
+ Read `_meta` first:
45
+ - `_meta.status` is `ok` (everything parsed), `partial` (some files yielded no named symbols), or `empty` (no features). Only `partial` with `unparsed_syntax_errors > 0` means the manifest is actually broken: fix the syntax error, then rescan. Files indexed only at file granularity (tests, scripts, configs reported as `file_level_files`) do not invalidate the manifest.
46
+ - `query` and `search` refuse stale results (nonzero exit); run `featuregraph scan`. Use `--force` only to inspect an already-stale index.
47
+
48
+ ---
49
+
50
+ ## When to Activate
51
+
52
+ - User types `/featuregraph` or mentions featuregraph
53
+ - User asks to "init", "index", "scan", "annotate", or "map" a project
54
+ - User references `manifest.json` or a feature ID (e.g. AUTH-01)
55
+ - User is about to edit shared code (run `featuregraph impact --diff`) or finish a task (run `featuregraph check --strict`)
56
+ - User combines with `/ponytail` — index first, then review
57
+ - **Any time you are about to read `manifest.json` and it may not exist**
58
+
59
+ ## Installation
60
+
61
+ This skill is installed automatically when you run `featuregraph init` or `featuregraph skill --global`.
62
+
63
+ To install manually:
64
+ ```bash
65
+ pip install git+https://github.com/Pakheria/featuregraph.git
66
+ featuregraph skill --global
67
+ ```
68
+
69
+ Or copy this file to your agent's skill directory:
70
+ ```bash
71
+ mkdir -p ~/.config/opencode/skills/featuregraph
72
+ cp SKILL.md ~/.config/opencode/skills/featuregraph/
73
+ ```
74
+
75
+ ---
76
+
77
+ ## Commands
78
+
79
+ ### Init (first time setup in repository)
80
+ ```bash
81
+ featuregraph init
82
+ ```
83
+ Generates `.featuregraph/manifest.json`, `.featuregraph/graph.md`, AGENTS.md, workspace skill, and pre-commit hook.
84
+
85
+ ### Re-scan
86
+ ```bash
87
+ featuregraph scan
88
+ featuregraph scan --quiet
89
+ featuregraph scan --dir ./src --json index.json --md GRAPH.md
90
+ ```
91
+
92
+ ### Auto-suggest & write feature tags
93
+ ```bash
94
+ # Preview suggestions without modifying files (dry-run)
95
+ featuregraph annotate --dry-run
96
+ # Apply suggestions directly to un-annotated symbols
97
+ featuregraph annotate --yes
98
+ # Annotate specific directory with limit
99
+ featuregraph annotate --dir ./src --yes --limit 50
100
+ ```
101
+
102
+ ### Query a feature
103
+ ```bash
104
+ featuregraph query AUTH-01
105
+ # Symbol IDs: bare when unique, path-qualified on collision
106
+ featuregraph query web.app.docs.layout
107
+ # Ambiguous bare name -> exit 1 + candidate qualified IDs
108
+ featuregraph query layout
109
+ ```
110
+
111
+ ### Impact (blast radius before editing shared code)
112
+ ```bash
113
+ # Transitive callers of one feature
114
+ featuregraph impact AUTH-01
115
+ # Everything the current working-tree diff touches, plus its transitive callers
116
+ featuregraph impact --diff
117
+ featuregraph impact --staged
118
+ featuregraph impact --diff --json
119
+ ```
120
+ Reports `touched`, `downstream` (transitive `called_by`), `affected_endpoints`, `boundaries` crossed, `invariants` to preserve, and `tests` to run. Run `featuregraph impact <feature_id>` **before** editing shared code so you know which callers and endpoints you can break; run `featuregraph impact --diff` after editing to verify the blast radius, then `featuregraph check --strict`.
121
+
122
+ ### Check (enforcement gate, exit 0 = pass / 1 = fail)
123
+ ```bash
124
+ featuregraph check # index exists, is fresh, parses, no dangling @depends
125
+ featuregraph check --strict # also fails on cycles and unguarded API endpoints
126
+ featuregraph check --rescan # fresh in-memory scan, no index write
127
+ featuregraph check --strict --json
128
+ ```
129
+ Always fails on syntax errors, unresolved `@depends`, and 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]`. Run `featuregraph check --strict` before reporting a task complete.
130
+
131
+ ### Hook management
132
+ ```bash
133
+ featuregraph hook --install
134
+ featuregraph hook --uninstall
135
+ ```
136
+
137
+ ---
138
+
139
+ ## Pairing with Ponytail
140
+
141
+ When user invokes both `/featuregraph` and `/ponytail`:
142
+ 1. Check/init index (Step 0 above)
143
+ 2. Read `manifest.json` to understand what features exist
144
+ 3. Run ponytail review on the changed files with feature context
145
+
146
+ ---
147
+
148
+ ## Annotating Code for Indexing
149
+
150
+ **Python:**
151
+ ```python
152
+ # @feature [AUTH-01] JWT Cookie Session Gate
153
+ # @depends [FIREWALL-01], [RBAC-01]
154
+ async def get_current_user(...):
155
+ ```
156
+
157
+ **TypeScript/React:**
158
+ ```tsx
159
+ // @feature [DASH-01] Executive Analytics Widget
160
+ // @depends [AUTH-01]
161
+ export const AnalyticsWidget = () => { ... }
162
+ ```
163
+
164
+ Feature IDs: `[A-Za-z0-9_-]+`, normalised to UPPER.
165
+
166
+ Symbol IDs are separate aliases. Each tagged location gets its bare symbol when unique, or a deterministic path-qualified ID on collision (e.g. `web.app.layout` vs `web.app.docs.layout`). `query`/`search` resolve feature IDs, qualified symbol IDs, and unambiguous bare symbols; an ambiguous bare name exits 1 with candidates. Inferred call edges use the same qualification with path affinity (same file > same directory > longest shared path); equally-near ties keep all candidate IDs rather than dropping the edge.
167
+
168
+ Tag rules:
169
+ - Tags must sit on a real comment line. Text inside strings, template literals, and Python docstrings is ignored by every parser. Real comment lines are honoured in every language, including `//`, `#`, and `/* ... */`.
170
+ - Python: place the tag within 6 lines above the `def`/`class`. Docstrings are not scanned.
171
+ - TypeScript/JS: place the tag above the export; the parser associates the export within 6 lines below it.
172
+ - Other languages: place the tag above the declaration; the parser looks 6 lines below.
173
+ - Untagged `.js` files are auto-indexed as `CJS-<path>-<symbol>` for classes, functions, arrow functions, class/prototype methods, and `exports`/`module.exports` members. Untagged `.ts`/`.tsx`/`.jsx` exports become `TS-<path>-<symbol>`. Untagged Django `models.py` gets `MODEL-*`, `settings.py` gets `CONFIG-*` (sensitive keys redacted). Tagged files keep tag-only behavior, so existing feature IDs and inferred edges do not churn.
174
+ - Files with no symbols still get a `FILE-<path>` file-level entry. They remain in the warning list but count as indexed (`unindexed_files: 0`) and are reported as `_meta.file_level_files`.
175
+ - `annotate --yes` refuses insertion points that are not code, writes atomically, and verifies each tag by re-parsing.
176
+
177
+ ### Contract tags (`@boundary`, `@invariant`, `@test`)
178
+
179
+ Same rule: comment lines only, in the same comment window as `@feature`/`@depends`.
180
+
181
+ ```python
182
+ # @feature [BILLING-CHARGE] Charge endpoint
183
+ # @boundary [auth, tenant]
184
+ # @invariant Amounts stay in integer cents; never charge twice for one idempotency key.
185
+ # @test tests/test_billing.py::test_charge_is_idempotent, tests/test_billing.py::test_amount_rounding
186
+ @router.post("/charge")
187
+ def charge(...):
188
+ ...
189
+ ```
190
+
191
+ - `@boundary [a, b]` declares the security boundary a feature sits behind (normalised lowercase, values stored as `boundaries`).
192
+ - `@invariant <text>` is repeatable and stores each line under `invariants`.
193
+ - `@test <path>::<nodeid>` (or a comma/space separated list) stores the tests that must run under `tests`.
194
+ - `featuregraph impact` reports these for everything the change touches; `featuregraph check --strict` blocks unguarded endpoints.
195
+
196
+ ### Anti-slop workflow (use on every non-trivial change)
197
+
198
+ 1. `featuregraph impact <feature_id>` before editing shared code: know the callers, endpoints, and contracts you can break. After editing, `featuregraph impact --diff` verifies the blast radius.
199
+ 2. Read only the reported `#Lstart-Lend` spans; preserve listed `invariants`.
200
+ 3. Tag new security-relevant entry points `@boundary`, repeatable `@invariant`, and `@test`.
201
+ 4. Run the reported `tests`.
202
+ 5. `featuregraph check --strict` before saying the task is done.
203
+
204
+ ---
205
+
206
+ ## After Running
207
+
208
+ Always show the user:
209
+ - How many features were indexed
210
+ - Whether AGENTS.md was created (first init only)
211
+ - If the project was auto-inited, tell them: "Project wasn't indexed yet — ran `featuregraph init` automatically."
@@ -0,0 +1,51 @@
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ _SKILL_DIR = Path(__file__).parent / "featuregraph"
7
+
8
+ # @feature [SKILL-01] Skill Manager
9
+ class SkillManager:
10
+ """Manages installation of the FeatureGraph skill across workspaces and AI agent environments."""
11
+
12
+ @staticmethod
13
+ def get_skill_content() -> str:
14
+ skill_file = _SKILL_DIR / "SKILL.md"
15
+ if not skill_file.exists():
16
+ raise FileNotFoundError(f"Packaged SKILL.md not found at {skill_file}")
17
+ return skill_file.read_text(encoding="utf-8")
18
+
19
+ @staticmethod
20
+ def install_workspace_skill(project_root: Path) -> Path:
21
+ """Installs the skill in the workspace's .agents/skills/ directory."""
22
+ target_dir = project_root / ".agents" / "skills" / "featuregraph"
23
+ target_dir.mkdir(parents=True, exist_ok=True)
24
+ skill_file = target_dir / "SKILL.md"
25
+ skill_file.write_text(SkillManager.get_skill_content(), encoding="utf-8")
26
+ return skill_file
27
+
28
+ @staticmethod
29
+ def install_global_skills() -> list[Path]:
30
+ """Installs the skill across user-global AI agent configurations."""
31
+ installed: list[Path] = []
32
+ home = Path.home()
33
+
34
+ targets = [
35
+ home / ".agents" / "skills" / "featuregraph" / "SKILL.md",
36
+ home / ".gemini" / "config" / "skills" / "featuregraph" / "SKILL.md",
37
+ home / ".claude" / "skills" / "featuregraph" / "SKILL.md",
38
+ home / ".cursor" / "skills" / "featuregraph" / "SKILL.md",
39
+ home / ".config" / "opencode" / "skills" / "featuregraph" / "SKILL.md",
40
+ ]
41
+
42
+ content = SkillManager.get_skill_content()
43
+ for target in targets:
44
+ try:
45
+ target.parent.mkdir(parents=True, exist_ok=True)
46
+ target.write_text(content, encoding="utf-8")
47
+ installed.append(target)
48
+ except OSError as exc:
49
+ print(f"warning: could not install skill to {target}: {exc}", file=sys.stderr)
50
+
51
+ return installed