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.
featuregraph/cli.py ADDED
@@ -0,0 +1,758 @@
1
+ import argparse
2
+ import json
3
+ import re
4
+ import subprocess
5
+ import sys
6
+ import tempfile
7
+ from pathlib import Path
8
+ from typing import NoReturn
9
+
10
+ # Support running as a standalone script or installed module
11
+ if __name__ == "__main__" and __package__ is None:
12
+ file_path = Path(__file__).resolve()
13
+ sys.path.insert(0, str(file_path.parent.parent))
14
+ __package__ = "featuregraph"
15
+
16
+ from featuregraph import __version__
17
+ from featuregraph.core.annotator import (
18
+ _comment_prefix,
19
+ apply_suggestions,
20
+ collect_suggestions,
21
+ )
22
+ from featuregraph.core.dependency_resolver import build_symbol_aliases
23
+ from featuregraph.core.scanner import WorkspaceScanner
24
+ from featuregraph.formatters.json_formatter import JSONFormatter
25
+ from featuregraph.formatters.markdown_formatter import MarkdownFormatter
26
+ from featuregraph.hooks.git_hook import GitHookManager
27
+ from featuregraph.skills.skill_manager import SkillManager
28
+
29
+
30
+ def _fail(msg: str, as_json: bool = False, stderr: bool = False) -> NoReturn:
31
+ """Print a plain or JSON error and exit 1."""
32
+ if as_json:
33
+ print(json.dumps({"error": msg}, indent=2))
34
+ else:
35
+ print(msg, file=sys.stderr if stderr else sys.stdout)
36
+ sys.exit(1)
37
+
38
+
39
+ def _guard_fresh(root: Path, index_file: Path, force: bool, as_json: bool = False) -> None:
40
+ """Refuse stale results; the recorded stat fingerprint must match the current tree."""
41
+ if force or not index_file.is_file():
42
+ return
43
+ try:
44
+ meta = json.loads(index_file.read_text(encoding="utf-8")).get("_meta", {})
45
+ except OSError as exc:
46
+ _fail(f"Error: cannot read index {index_file}: {exc}", as_json, stderr=True)
47
+ except ValueError as exc:
48
+ _fail(f"Error: corrupt index {index_file}: {exc}. Run 'featuregraph scan'.", as_json, stderr=True)
49
+ recorded = meta.get("tree_hash")
50
+ if not recorded:
51
+ return # ponytail: indexes that predate fingerprints skip the check
52
+ if WorkspaceScanner(root).tree_hash() != recorded:
53
+ _fail("index is stale (tree changed since scan); run: featuregraph scan", as_json, stderr=True)
54
+
55
+ def _print_ambiguous(query: str, candidates, as_json: bool):
56
+ if as_json:
57
+ print(json.dumps({
58
+ "error": "ambiguous",
59
+ "query": query,
60
+ "candidates": [
61
+ {"id": symbol_id, "feature_id": feature_id, "file": file_path}
62
+ for symbol_id, feature_id, file_path in candidates
63
+ ],
64
+ }, indent=2))
65
+ else:
66
+ print(f"Ambiguous name '{query}' — {len(candidates)} candidates:")
67
+ for symbol_id, feature_id, file_path in candidates:
68
+ print(f" {symbol_id} -> {feature_id} ({file_path})")
69
+ print("Use a qualified ID.")
70
+ sys.exit(1)
71
+
72
+
73
+ def _lookup_feature(features: dict, query: str, as_json: bool):
74
+ """Feature ID, qualified symbol ID, or unambiguous bare symbol -> (id, feature)."""
75
+ feat_id = query.upper()
76
+ if feat_id in features:
77
+ return feat_id, features[feat_id]
78
+ by_id, by_symbol = build_symbol_aliases(features)
79
+ target = by_id.get(query.casefold())
80
+ if target:
81
+ return target, features.get(target)
82
+ candidates = by_symbol.get(query.casefold(), [])
83
+ if len(candidates) > 1:
84
+ _print_ambiguous(query, candidates, as_json)
85
+ if candidates:
86
+ target = candidates[0][1]
87
+ return target, features.get(target)
88
+ return None, None
89
+
90
+
91
+ _HUNK_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
92
+ # Boundaries that count as an explicit access guard for an endpoint.
93
+ _GUARD_BOUNDARIES = {"auth", "admin", "tenant", "internal"}
94
+
95
+
96
+ def _git_changed_lines(root: Path, staged: bool) -> list[tuple[str, int, int]]:
97
+ """(file relative to root, start, end) for every changed hunk in the working tree."""
98
+ cmd = ["git", "-C", str(root), "diff", "--unified=0", "--no-color"]
99
+ if staged:
100
+ cmd.append("--cached")
101
+ proc = subprocess.run(cmd, capture_output=True, text=True)
102
+ if proc.returncode != 0:
103
+ raise RuntimeError(proc.stderr.strip() or "git diff failed")
104
+ prefix_proc = subprocess.run(
105
+ ["git", "-C", str(root), "rev-parse", "--show-prefix"],
106
+ capture_output=True, text=True,
107
+ )
108
+ prefix = prefix_proc.stdout.strip() if prefix_proc.returncode == 0 else ""
109
+
110
+ changed: list[tuple[str, int, int]] = []
111
+ current = None
112
+ for line in proc.stdout.splitlines():
113
+ if line.startswith("+++ b/"):
114
+ current = line[len("+++ b/"):]
115
+ if prefix and current.startswith(prefix):
116
+ current = current[len(prefix):]
117
+ elif line.startswith("+++ "):
118
+ current = None
119
+ else:
120
+ match = _HUNK_RE.match(line)
121
+ if match and current:
122
+ # Pre-edit range: pure deletions have new_count == 0 but still own old lines.
123
+ old_start = int(match.group(1))
124
+ old_count = int(match.group(2) or 1)
125
+ if old_count == 0:
126
+ changed.append((current, old_start, old_start))
127
+ else:
128
+ changed.append((current, old_start, old_start + old_count - 1))
129
+ return changed
130
+
131
+
132
+ def _features_touching(features: dict, changed: list[tuple[str, int, int]]) -> set[str]:
133
+ touched: set[str] = set()
134
+ for feat_id, feat in features.items():
135
+ for loc in feat.get("locations", []):
136
+ lines = loc.get("lines") or [loc.get("start_line", 1), loc.get("end_line", 1)]
137
+ for rel_path, start, end in changed:
138
+ if loc.get("file") != rel_path:
139
+ continue
140
+ if end < lines[0] or start > lines[1]:
141
+ continue
142
+ touched.add(feat_id)
143
+ return touched
144
+
145
+
146
+ def _called_by_closure(features: dict, seeds: set[str]) -> set[str]:
147
+ seen = set(seeds)
148
+ queue = list(seeds)
149
+ while queue:
150
+ node = queue.pop()
151
+ for caller in features.get(node, {}).get("called_by", []):
152
+ if caller not in seen:
153
+ seen.add(caller)
154
+ queue.append(caller)
155
+ return seen
156
+
157
+
158
+ def _collect_tag_values(features: dict, key: str, feat_ids) -> list[str]:
159
+ values: list[str] = []
160
+ for feat_id in feat_ids:
161
+ for value in features.get(feat_id, {}).get(key, []):
162
+ if value not in values:
163
+ values.append(value)
164
+ return values
165
+
166
+
167
+ def _build_impact(features: dict, seeds: set[str]) -> dict:
168
+ closure = _called_by_closure(features, seeds)
169
+ touched = sorted(seeds)
170
+ downstream = sorted(closure - set(seeds))
171
+ affected_endpoints = sorted(
172
+ feat_id
173
+ for feat_id in closure
174
+ if feat_id.startswith("ROUTE-")
175
+ or any(
176
+ loc.get("type") == "endpoint"
177
+ for loc in features.get(feat_id, {}).get("locations", [])
178
+ )
179
+ )
180
+ return {
181
+ "touched": touched,
182
+ "downstream": downstream,
183
+ "affected_endpoints": affected_endpoints,
184
+ "boundaries": _collect_tag_values(features, "boundaries", touched),
185
+ "invariants": _collect_tag_values(features, "invariants", touched + downstream),
186
+ "tests": _collect_tag_values(features, "tests", touched + downstream),
187
+ }
188
+
189
+
190
+ def _unguarded_endpoints(features: dict) -> list[str]:
191
+ unguarded: list[str] = []
192
+ for feat_id, feat in features.items():
193
+ is_endpoint = (
194
+ feat_id.startswith("ROUTE-")
195
+ or feat.get("type") == "endpoint"
196
+ or any(loc.get("type") == "endpoint" for loc in feat.get("locations", []))
197
+ )
198
+ if not is_endpoint:
199
+ continue
200
+ if feat.get("boundaries"):
201
+ continue
202
+ guarded = any(
203
+ {str(name).lower() for name in features.get(dep, {}).get("boundaries", [])}
204
+ & _GUARD_BOUNDARIES
205
+ for dep in feat.get("depends_on", [])
206
+ )
207
+ if not guarded:
208
+ unguarded.append(feat_id)
209
+ return sorted(unguarded)
210
+
211
+
212
+ # @feature [CLI-01] Main
213
+ def main():
214
+ parser = argparse.ArgumentParser(
215
+ prog="featuregraph",
216
+ description="Token-efficient AST-indexed feature topology map for AI coding agents."
217
+ )
218
+ subparsers = parser.add_subparsers(dest="command", help="Command to run")
219
+ parser.add_argument("--version", action="version", version=f"featuregraph {__version__}")
220
+
221
+ # Command: scan
222
+ scan_parser = subparsers.add_parser("scan", help="Scan codebase and generate feature graph files")
223
+ scan_parser.add_argument("--dir", default=".", help="Root directory to scan (default: .)")
224
+ scan_parser.add_argument("--json", default=None, help="Write an extra copy of the JSON index to this path")
225
+ scan_parser.add_argument("--md", default=None, help="Output Markdown path (default: .featuregraph/graph.md)")
226
+ scan_parser.add_argument("--quiet", action="store_true", help="Suppress console output")
227
+
228
+ # Command: init
229
+ subparsers.add_parser("init", help="Initialize FeatureGraph in current repository with pre-commit hook")
230
+
231
+ # Command: query
232
+ query_parser = subparsers.add_parser("query", help="Query a feature ID or symbol ID and print its exact line ranges and dependencies")
233
+ query_parser.add_argument("feature_id", help="Feature ID, qualified symbol ID, or unambiguous symbol (e.g. AUTH-01 or web.app.layout)")
234
+ query_parser.add_argument("--dir", default=".", help="Project root containing .featuregraph/ (default: .)")
235
+ query_parser.add_argument("--json", action="store_true", help="Machine-readable JSON output (for agents/CI)")
236
+ query_parser.add_argument("--force", action="store_true", help="Return results even if the tree changed since scan")
237
+
238
+ # Command: search
239
+ search_parser = subparsers.add_parser("search", help="Search features by symbol ID, name, or keyword")
240
+ search_parser.add_argument("query", help="Symbol ID, unambiguous symbol, or search terms (e.g. 'web.app.layout', 'parser')")
241
+ search_parser.add_argument("--dir", default=".", help="Project root containing .featuregraph/ (default: .)")
242
+ search_parser.add_argument("--json", action="store_true", help="Machine-readable JSON output (for agents/CI)")
243
+ search_parser.add_argument("--force", action="store_true", help="Return results even if the tree changed since scan")
244
+
245
+ # Command: impact
246
+ impact_parser = subparsers.add_parser(
247
+ "impact",
248
+ help="Blast radius for a feature/symbol ID or for the current git diff (transitive callers)"
249
+ )
250
+ impact_parser.add_argument("target", nargs="?", default=None, help="Feature ID or symbol ID (e.g. AUTH-01)")
251
+ impact_parser.add_argument("--dir", default=".", help="Project root containing .featuregraph/ (default: .)")
252
+ impact_parser.add_argument("--diff", action="store_true", help="Use changed lines from `git diff` as the target")
253
+ impact_parser.add_argument("--staged", action="store_true", help="Use changed lines from `git diff --cached`")
254
+ impact_parser.add_argument("--json", action="store_true", help="Machine-readable JSON output (for agents/CI)")
255
+
256
+ # Command: check
257
+ check_parser = subparsers.add_parser(
258
+ "check",
259
+ help="Enforcement gate: index freshness, parse/depends/duplicate health, optional strict contract rules"
260
+ )
261
+ check_parser.add_argument("--dir", default=".", help="Project root containing .featuregraph/ (default: .)")
262
+ check_parser.add_argument("--strict", action="store_true", help="Also fail on cycles and unguarded API endpoints")
263
+ check_parser.add_argument("--rescan", action="store_true", help="Run a fresh scan before checking")
264
+ check_parser.add_argument("--json", action="store_true", help="Machine-readable JSON output (for agents/CI)")
265
+
266
+ # Command: hook
267
+ hook_parser = subparsers.add_parser("hook", help="Install or remove git pre-commit hook")
268
+ hook_parser.add_argument("--install", action="store_true", help="Install git pre-commit hook")
269
+ hook_parser.add_argument("--uninstall", action="store_true", help="Uninstall git pre-commit hook")
270
+
271
+ # Command: annotate
272
+ ann_parser = subparsers.add_parser(
273
+ "annotate",
274
+ help="Auto-suggest @feature tags for un-annotated symbols (dry-run by default)"
275
+ )
276
+ ann_parser.add_argument("--dir", default=".", help="Root directory to annotate (default: .)")
277
+ ann_parser.add_argument(
278
+ "--dry-run", action="store_true", default=False,
279
+ help="Preview suggestions without writing to files (default unless --yes)"
280
+ )
281
+ ann_parser.add_argument(
282
+ "--yes", "-y", action="store_true", default=False,
283
+ help="Write @feature tags to files without prompting"
284
+ )
285
+ ann_parser.add_argument(
286
+ "--limit", type=int, default=0,
287
+ help="Limit suggestions to first N symbols (0 = all)"
288
+ )
289
+
290
+ # Command: skill
291
+ skill_parser = subparsers.add_parser(
292
+ "skill",
293
+ help="Install or display the FeatureGraph skill for AI coding agents"
294
+ )
295
+ skill_parser.add_argument("--install", action="store_true", help="Install workspace skill in .agents/skills/featuregraph")
296
+ skill_parser.add_argument("--global", dest="is_global", action="store_true", help="Install globally across agent configs (~/.gemini, ~/.claude, ~/.cursor)")
297
+ skill_parser.add_argument("--show", action="store_true", help="Print SKILL.md definition to stdout")
298
+
299
+ args = parser.parse_args()
300
+
301
+ if not args.command:
302
+ parser.print_help()
303
+ sys.exit(0)
304
+
305
+ if args.command == "scan":
306
+ root = Path(getattr(args, "dir", ".")).resolve()
307
+ quiet = getattr(args, "quiet", False)
308
+
309
+ scanner = WorkspaceScanner(root)
310
+ fg_dir = root / ".featuregraph"
311
+ try:
312
+ fg_dir.mkdir(parents=True, exist_ok=True)
313
+ with tempfile.NamedTemporaryFile(dir=fg_dir):
314
+ pass
315
+ except OSError as exc:
316
+ print(f"Error: cannot write .featuregraph in {root}: {exc}. Check directory permissions.", file=sys.stderr)
317
+ sys.exit(1)
318
+
319
+ if not quiet:
320
+ subprojects = scanner.detect_subprojects()
321
+ if subprojects:
322
+ print(f"⚡ [FeatureGraph] Multi-Project Workspace detected ({len(subprojects)} projects: {', '.join(subprojects)})")
323
+ print(f"⚡ [FeatureGraph] Scanning codebase in {root}...")
324
+
325
+ graph = scanner.scan(quiet=quiet)
326
+ graph_dict = graph.to_dict()
327
+
328
+ fg_dir = root / ".featuregraph"
329
+ fg_dir.mkdir(parents=True, exist_ok=True)
330
+ meta = scanner.scan_meta()
331
+ JSONFormatter.write_unindexed(scanner.unindexed, fg_dir)
332
+
333
+ JSONFormatter.write_all(graph_dict, fg_dir, root, meta=meta)
334
+ if getattr(args, "json", None):
335
+ JSONFormatter.write_to_file(graph_dict, root / args.json, root, meta=meta)
336
+
337
+ md_out = root / args.md if getattr(args, "md", None) else fg_dir / "graph.md"
338
+ MarkdownFormatter.write_to_file(graph_dict, md_out, root)
339
+
340
+ if not quiet:
341
+ categories = JSONFormatter.split_by_category(graph_dict)
342
+ if not graph_dict:
343
+ print("⚠ No features found — the index is empty. Add @feature tags or run 'featuregraph annotate'.")
344
+ else:
345
+ print(f"✓ Mapped {len(graph_dict)} features across {len(categories)} domain categories.")
346
+ print("✓ Created 2-Tier Manifest: .featuregraph/manifest.json")
347
+ print(f"✓ Created Category Chunks: .featuregraph/categories/ ({len(categories)} files)")
348
+ print(f"✓ Created markdown graph: {md_out.relative_to(root) if md_out.is_relative_to(root) else md_out}")
349
+
350
+ elif args.command == "init":
351
+ root = Path(".").resolve()
352
+ hook_status = GitHookManager.install(root)
353
+ if hook_status == "installed":
354
+ print("✓ Installed git pre-commit hook.")
355
+ elif hook_status == "upgraded":
356
+ print("✓ Upgraded legacy FeatureGraph pre-commit hook.")
357
+ elif hook_status == "foreign-hook":
358
+ print("ℹ Skipped git hook: existing pre-commit hook found (not overwritten).")
359
+ else:
360
+ print("ℹ Skipped git hook (no .git directory found).")
361
+
362
+ scanner = WorkspaceScanner(root)
363
+ graph = scanner.scan()
364
+ graph_dict = graph.to_dict()
365
+ meta = scanner.scan_meta()
366
+
367
+ fg_dir = root / ".featuregraph"
368
+ fg_dir.mkdir(parents=True, exist_ok=True)
369
+ JSONFormatter.write_all(graph_dict, fg_dir, root, meta=meta)
370
+ JSONFormatter.write_unindexed(scanner.unindexed, fg_dir)
371
+ md_out = fg_dir / "graph.md"
372
+ MarkdownFormatter.write_to_file(graph_dict, md_out, root)
373
+
374
+ # Generate or append AGENTS.md Circuit-Breaker Directive
375
+ agents_md = root / "AGENTS.md"
376
+ directive = """# AI AGENT SHORT-CIRCUIT CONSTITUTION
377
+
378
+ > 🛑 **MANDATORY SHORT-CIRCUIT DIRECTIVE:**
379
+ > When asked about features, architecture, onboarding, or where code lives:
380
+ > 1. **READ `.featuregraph/manifest.json`** to identify the domain category, feature IDs, and symbol IDs. Symbol IDs are bare when unique and path-qualified on collision (e.g. `web.app.layout` vs `web.app.docs.layout`); an ambiguous bare name exits 1 with candidates.
381
+ > 2. **READ `.featuregraph/categories/<category>.json`** to get exact line spans (`#Lstart-Lend`).
382
+ > 3. Read **ONLY** the specific lines required for the task.
383
+ > 4. `_meta.status != ok` is only broken when `unparsed_syntax_errors > 0` — fix the syntax error, then rescan. Files indexed at file granularity (`FILE-*`, tests/scripts/config) do not invalidate the manifest; they are counted in `_meta.file_level_files`.
384
+ > 5. `_meta.file_level_files` counts files indexed only at file granularity (data/shell/config or no named symbols); query them by `FILE-...` ID.
385
+ > 6. If `query` refuses as stale, run `featuregraph scan`.
386
+ > 7. Before editing shared code: run `featuregraph impact <feature_id>` for its callers, endpoints, `boundaries`, `invariants`, and `tests`. After editing: run `featuregraph impact --diff` to verify the blast radius, then `featuregraph check --strict`.
387
+ > 8. Declare contracts on comment lines: `@boundary [auth, tenant]`, `@invariant <rule>` (repeatable), `@test <path>::<nodeid>`.
388
+ > 9. Before reporting a task complete: run the reported tests and `featuregraph check --strict`.
389
+ > Do NOT execute recursive ListDir sweeps or multi-file exploratory reads.
390
+ """
391
+ if not agents_md.exists():
392
+ agents_md.write_text(directive, encoding="utf-8")
393
+ print("✓ Generated AI Agent Constitution: AGENTS.md")
394
+ elif "SHORT-CIRCUIT DIRECTIVE" not in agents_md.read_text(encoding="utf-8", errors="ignore"):
395
+ with open(agents_md, "a", encoding="utf-8") as f:
396
+ f.write("\n" + directive)
397
+ print("✓ Appended Short-Circuit Directive to existing AGENTS.md")
398
+
399
+ # Install workspace skill
400
+ skill_file = SkillManager.install_workspace_skill(root)
401
+ print(f"✓ Installed workspace AI agent skill: {skill_file.relative_to(root)}")
402
+
403
+ categories = JSONFormatter.split_by_category(graph_dict)
404
+ if not graph_dict:
405
+ print("⚠ No features found — the index is empty. Add @feature tags or run 'featuregraph annotate'.")
406
+ else:
407
+ print(f"✓ Initialized 2-Tier Index: {len(graph_dict)} features in {len(categories)} categories.")
408
+
409
+ elif args.command == "query":
410
+ root = Path(args.dir).resolve()
411
+ idx_file = root / ".featuregraph" / "index.json"
412
+ if not idx_file.exists():
413
+ idx_file = root / "FEATURE_INDEX.json"
414
+ if not idx_file.exists():
415
+ _fail(
416
+ f"Error: Feature index not found under {root}. Run 'featuregraph scan' first.",
417
+ args.json,
418
+ )
419
+
420
+ _guard_fresh(root, idx_file, args.force, as_json=args.json)
421
+ try:
422
+ data = json.loads(idx_file.read_text(encoding="utf-8"))
423
+ except OSError as exc:
424
+ _fail(f"Error: cannot read index {idx_file}: {exc}", args.json, stderr=True)
425
+ except ValueError as exc:
426
+ _fail(f"Error: corrupt index {idx_file}: {exc}. Run 'featuregraph scan'.", args.json, stderr=True)
427
+ features = data.get("features", {})
428
+ feat_id, feat = _lookup_feature(features, args.feature_id, args.json)
429
+ if not feat:
430
+ _fail(f"Feature '{args.feature_id.upper()}' not found in index.", args.json)
431
+
432
+ if args.json:
433
+ print(json.dumps({"id": feat_id, **feat}, indent=2))
434
+ else:
435
+ print("\n=======================================================")
436
+ print(f" FEATURE: [{feat_id}] {feat.get('name', '')}")
437
+ print("=======================================================")
438
+ print(f"Description : {feat.get('description', 'N/A')}")
439
+ print(f"Depends On : {', '.join(feat.get('depends_on', [])) or 'None'}")
440
+ print(f"Called By : {', '.join(feat.get('called_by', [])) or 'None'}")
441
+ print("\nExact Line Locations:")
442
+ for loc in feat.get("locations", []):
443
+ lines = loc.get("lines") or [loc.get("start_line", 1), loc.get("end_line", 1)]
444
+ print(f" • {loc['file']} #L{lines[0]}-L{lines[1]} ({loc.get('symbol', 'module')})")
445
+ print("=======================================================\n")
446
+
447
+ elif args.command == "search":
448
+ root = Path(args.dir).resolve()
449
+ manifest_file = root / ".featuregraph" / "manifest.json"
450
+ idx_file = root / ".featuregraph" / "index.json"
451
+
452
+ if not manifest_file.exists() and not idx_file.exists():
453
+ _fail(
454
+ f"Error: No .featuregraph index found under {root}. Run 'featuregraph scan' first.",
455
+ args.json,
456
+ )
457
+
458
+ _guard_fresh(
459
+ root, idx_file if idx_file.exists() else manifest_file, args.force,
460
+ as_json=args.json,
461
+ )
462
+ query_text = args.query
463
+ q_lower = query_text.lower()
464
+ q_words = set(q_lower.split())
465
+
466
+ features = {}
467
+ categories = {}
468
+ cats_dir = root / ".featuregraph" / "categories"
469
+ if cats_dir.is_dir():
470
+ for cat_json in cats_dir.glob("*.json"):
471
+ cat_name = cat_json.stem
472
+ try:
473
+ cat_data = json.loads(cat_json.read_text(encoding="utf-8"))
474
+ except (OSError, ValueError) as exc:
475
+ _fail(
476
+ f"Error: corrupt category file {cat_json}: {exc}. Run 'featuregraph scan'.",
477
+ args.json,
478
+ stderr=True,
479
+ )
480
+ for fid, fmeta in cat_data.items():
481
+ features[fid] = fmeta
482
+ categories[fid] = cat_name
483
+ elif idx_file.exists():
484
+ try:
485
+ idx_data = json.loads(idx_file.read_text(encoding="utf-8"))
486
+ except (OSError, ValueError) as exc:
487
+ _fail(
488
+ f"Error: corrupt index {idx_file}: {exc}. Run 'featuregraph scan'.",
489
+ args.json,
490
+ stderr=True,
491
+ )
492
+ for fid, fmeta in idx_data.get("features", {}).items():
493
+ features[fid] = fmeta
494
+ categories[fid] = fmeta.get("category", "core")
495
+
496
+ matched_features = []
497
+ target = query_text.upper() if query_text.upper() in features else None
498
+ if not target:
499
+ by_id, by_symbol = build_symbol_aliases(features)
500
+ target = by_id.get(query_text.casefold())
501
+ if not target:
502
+ candidates = by_symbol.get(query_text.casefold(), [])
503
+ if len(candidates) > 1:
504
+ _print_ambiguous(query_text, candidates, args.json)
505
+ if candidates:
506
+ target = candidates[0][1]
507
+
508
+ if target:
509
+ matched_features.append((categories.get(target, "core"), target, features[target]))
510
+ else:
511
+ for fid, fmeta in features.items():
512
+ cat_name = categories.get(fid, fmeta.get("category", "core"))
513
+ name = fmeta.get("name", "").lower()
514
+ desc = fmeta.get("description", "").lower()
515
+ locs = " ".join(loc.get("symbol", "").lower() for loc in fmeta.get("locations", []))
516
+ text = f"{cat_name.lower()} {fid.lower()} {name} {desc} {locs}"
517
+ if any(w in text for w in q_words) or q_lower in text:
518
+ matched_features.append((cat_name, fid, fmeta))
519
+
520
+ if args.json:
521
+ print(json.dumps(
522
+ [{"id": fid, "category": cat, **fmeta} for cat, fid, fmeta in matched_features],
523
+ indent=2,
524
+ ))
525
+ elif matched_features:
526
+ by_cat = {}
527
+ for cat, fid, fmeta in matched_features:
528
+ by_cat.setdefault(cat, []).append((fid, fmeta))
529
+ print(f"\n⚡ [FeatureGraph] Match for '{query_text}':")
530
+ for cat, feats in sorted(by_cat.items()):
531
+ print(f" Category '{cat}':")
532
+ for fid, fmeta in feats:
533
+ print(f" [{fid}] {fmeta.get('name', '')} ({fmeta.get('description', '')})")
534
+ for loc in fmeta.get("locations", []):
535
+ lines = loc.get("lines") or [loc.get("start_line", 1), loc.get("end_line", 1)]
536
+ print(f" • {loc['file']} #L{lines[0]}-L{lines[1]} ({loc.get('symbol', 'module')})")
537
+ print()
538
+ else:
539
+ print(f"No match for '{query_text}'. Try 'featuregraph scan' or inspect .featuregraph/graph.md.")
540
+
541
+ elif args.command == "impact":
542
+ root = Path(args.dir).resolve()
543
+ idx_file = root / ".featuregraph" / "index.json"
544
+ if not idx_file.exists():
545
+ idx_file = root / "FEATURE_INDEX.json"
546
+ if not idx_file.exists():
547
+ _fail(
548
+ f"Error: Feature index not found under {root}. Run 'featuregraph scan' first.",
549
+ args.json,
550
+ )
551
+ try:
552
+ data = json.loads(idx_file.read_text(encoding="utf-8"))
553
+ except OSError as exc:
554
+ _fail(f"Error: cannot read index {idx_file}: {exc}", args.json, stderr=True)
555
+ except ValueError as exc:
556
+ _fail(f"Error: corrupt index {idx_file}: {exc}. Run 'featuregraph scan'.", args.json, stderr=True)
557
+ features = data.get("features", {})
558
+
559
+ if not args.target and not (args.diff or args.staged):
560
+ _fail("Error: pass a feature/symbol ID, or --diff/--staged.", args.json, stderr=True)
561
+
562
+ # No freshness guard: --diff exists precisely because the tree moved past the index.
563
+ seeds: set[str] = set()
564
+ if args.target:
565
+ feat_id, feat = _lookup_feature(features, args.target, args.json)
566
+ if not feat:
567
+ _fail(f"Feature '{args.target.upper()}' not found in index.", args.json)
568
+ seeds.add(feat_id)
569
+ if args.diff or args.staged:
570
+ try:
571
+ changed = _git_changed_lines(root, args.staged)
572
+ except (OSError, RuntimeError) as exc:
573
+ _fail(f"Error: cannot read git diff in {root}: {exc}", args.json, stderr=True)
574
+ seeds |= _features_touching(features, changed)
575
+
576
+ report = _build_impact(features, seeds)
577
+ if args.json:
578
+ print(json.dumps(report, indent=2))
579
+ else:
580
+ print("\n=======================================================")
581
+ print(" IMPACT — transitive blast radius")
582
+ print("=======================================================")
583
+ print(f"Touched : {', '.join(report['touched']) or 'None'}")
584
+ print(f"Downstream : {', '.join(report['downstream']) or 'None'}")
585
+ print(f"Endpoints : {', '.join(report['affected_endpoints']) or 'None'}")
586
+ print(f"Boundaries : {', '.join(report['boundaries']) or 'None'}")
587
+ print("Invariants :")
588
+ for invariant in report["invariants"] or ["None"]:
589
+ print(f" • {invariant}")
590
+ print("Tests :")
591
+ for test in report["tests"] or ["None"]:
592
+ print(f" • {test}")
593
+ print("=======================================================\n")
594
+
595
+ elif args.command == "check":
596
+ root = Path(args.dir).resolve()
597
+ idx_file = root / ".featuregraph" / "index.json"
598
+ errors: list[str] = []
599
+ warnings: list[str] = []
600
+ features: dict = {}
601
+ meta: dict = {}
602
+
603
+ if args.rescan:
604
+ scanner = WorkspaceScanner(root)
605
+ features = scanner.scan().to_dict()
606
+ meta = scanner.scan_meta()
607
+ elif not idx_file.is_file():
608
+ if args.json:
609
+ _fail(f"index missing at {idx_file}; run 'featuregraph scan'", True)
610
+ errors.append(f"index missing at {idx_file}; run 'featuregraph scan'")
611
+ else:
612
+ try:
613
+ data = json.loads(idx_file.read_text(encoding="utf-8"))
614
+ except OSError as exc:
615
+ if args.json:
616
+ _fail(f"cannot read index {idx_file}: {exc}", True)
617
+ errors.append(f"cannot read index {idx_file}: {exc}")
618
+ except ValueError as exc:
619
+ if args.json:
620
+ _fail(f"corrupt index {idx_file}: {exc}; run 'featuregraph scan'", True)
621
+ errors.append(f"corrupt index {idx_file}: {exc}; run 'featuregraph scan'")
622
+ else:
623
+ meta = data.get("_meta", {}) or {}
624
+ features = data.get("features", {}) or {}
625
+ recorded = meta.get("tree_hash")
626
+ if not recorded:
627
+ errors.append("index has no tree_hash fingerprint; run 'featuregraph scan'")
628
+ elif WorkspaceScanner(root).tree_hash() != recorded:
629
+ msg = "index is stale (tree changed since scan); run 'featuregraph scan'"
630
+ if args.json:
631
+ _fail(msg, True)
632
+ errors.append(msg)
633
+
634
+ def _count(key: str) -> int:
635
+ value = meta.get(key)
636
+ return value if isinstance(value, int) else 0
637
+
638
+ if _count("unparsed_syntax_errors"):
639
+ errors.append(f"{_count('unparsed_syntax_errors')} file(s) failed to parse (syntax errors)")
640
+ if _count("unresolved_depends"):
641
+ errors.append(f"{_count('unresolved_depends')} unresolved @depends reference(s)")
642
+ if _count("duplicate_ids"):
643
+ errors.append(f"{_count('duplicate_ids')} duplicate feature ID(s)")
644
+ if _count("file_level_files"):
645
+ warnings.append(
646
+ f"{_count('file_level_files')} file(s) indexed at file granularity only (FILE-*); not an error"
647
+ )
648
+ if args.strict:
649
+ if _count("cycles"):
650
+ errors.append(f"{_count('cycles')} dependency cycle(s)")
651
+ for feat_id in _unguarded_endpoints(features):
652
+ errors.append(
653
+ f"unguarded endpoint [{feat_id}] — tag @boundary [auth] (or [public]) "
654
+ "or depend on an auth/admin/tenant/internal guarded feature"
655
+ )
656
+
657
+ ok = not errors
658
+ if args.json:
659
+ print(json.dumps({"ok": ok, "errors": errors, "warnings": warnings}, indent=2))
660
+ elif ok:
661
+ print(f"✓ featuregraph check passed ({len(features)} features){' [strict]' if args.strict else ''}.")
662
+ for warning in warnings:
663
+ print(f" ℹ {warning}")
664
+ else:
665
+ print(f"✗ featuregraph check failed ({len(errors)} error(s)):")
666
+ for error in errors:
667
+ print(f" • {error}")
668
+ for warning in warnings:
669
+ print(f" ℹ {warning}")
670
+ if not ok:
671
+ sys.exit(1)
672
+
673
+ elif args.command == "hook":
674
+ root = Path(".").resolve()
675
+ if args.uninstall:
676
+ if GitHookManager.uninstall(root):
677
+ print("✓ Git pre-commit hook uninstalled.")
678
+ else:
679
+ print("ℹ No featuregraph-managed pre-commit hook found.")
680
+ else:
681
+ status = GitHookManager.install(root)
682
+ if status == "installed":
683
+ print("✓ Git pre-commit hook installed.")
684
+ elif status == "upgraded":
685
+ print("✓ Upgraded legacy FeatureGraph pre-commit hook.")
686
+ elif status == "foreign-hook":
687
+ print("ℹ Existing pre-commit hook found — not overwritten.")
688
+ else:
689
+ print("ℹ No .git directory found.")
690
+
691
+ elif args.command == "annotate":
692
+ root = Path(getattr(args, "dir", ".")).resolve()
693
+ dry_run = getattr(args, "dry_run", False)
694
+ auto_yes = getattr(args, "yes", False)
695
+ limit = getattr(args, "limit", 0)
696
+
697
+ print(f"⚡ [FeatureGraph] Scanning for un-annotated symbols in {root}...")
698
+ suggestions = collect_suggestions(root)
699
+
700
+ if not suggestions:
701
+ print("✓ All symbols are already annotated — nothing to do.")
702
+ sys.exit(0)
703
+
704
+ if limit > 0:
705
+ suggestions = suggestions[:limit]
706
+
707
+ # ── Pretty preview ──────────────────────────────────────────────────
708
+ total = len(suggestions)
709
+ files_hit = len({s.file for s in suggestions})
710
+ print(f"\n{'─'*60}")
711
+ print(f" Found {total} un-annotated symbol(s) across {files_hit} file(s)")
712
+ print(f"{'─'*60}\n")
713
+
714
+ current_file = None
715
+ for sg in sorted(suggestions, key=lambda s: (s.file, s.line)):
716
+ rel = sg.file.relative_to(root)
717
+ if sg.file != current_file:
718
+ print(f" 📄 {rel}")
719
+ current_file = sg.file
720
+ prefix = _comment_prefix(sg.lang)
721
+ print(f" L{sg.line:>4} {sg.indent}{prefix} @feature [{sg.feature_id}] {sg.name}")
722
+
723
+ print(f"\n{'─'*60}")
724
+
725
+ # ── Write decision ──────────────────────────────────────────────────
726
+ if dry_run or not auto_yes:
727
+ print(" ℹ Dry-run mode. Run with --yes to write these tags.")
728
+ print(f"{'─'*60}\n")
729
+ sys.exit(0)
730
+
731
+ written = apply_suggestions(suggestions)
732
+ tag_count = sum(written.values())
733
+ print(f"\n✓ Wrote {tag_count} @feature tag(s) across {len(written)} file(s).")
734
+ print(" Run 'featuregraph scan' to rebuild the index.\n")
735
+
736
+ elif args.command == "skill":
737
+ root = Path(".").resolve()
738
+ if getattr(args, "show", False):
739
+ print(SkillManager.get_skill_content())
740
+ elif getattr(args, "is_global", False):
741
+ installed = SkillManager.install_global_skills()
742
+ for p in installed:
743
+ print(f"✓ Installed global AI agent skill: {p}")
744
+ if not installed:
745
+ print("ℹ No global skill directories could be written.")
746
+ elif getattr(args, "install", False):
747
+ skill_file = SkillManager.install_workspace_skill(root)
748
+ print(f"✓ Installed workspace AI agent skill: {skill_file}")
749
+ else:
750
+ # Default: install workspace + global
751
+ skill_file = SkillManager.install_workspace_skill(root)
752
+ print(f"✓ Installed workspace AI agent skill: {skill_file}")
753
+ installed = SkillManager.install_global_skills()
754
+ for p in installed:
755
+ print(f"✓ Installed global AI agent skill: {p}")
756
+
757
+ if __name__ == "__main__":
758
+ main()