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,429 @@
1
+ import ast
2
+ import fnmatch
3
+ import hashlib
4
+ import os
5
+ import re
6
+ import subprocess
7
+ import sys
8
+ from collections.abc import Iterator
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from . import lexmask
13
+ from .dependency_resolver import DependencyResolver, assign_symbol_ids
14
+ from .graph import FeatureGraph
15
+ from .parser_generic import GenericFeatureParser
16
+ from .parser_protocol import FeatureParser
17
+ from .parser_py import PythonFeatureParser
18
+ from .parser_ts import TypeScriptFeatureParser
19
+
20
+ DEFAULT_IGNORE = {
21
+ "venv", "node_modules", "dist", "build",
22
+ "__pycache__", "logs", "coverage"
23
+ }
24
+
25
+
26
+ _CATEGORY_SKIP = {
27
+ "lib", "bin", "src", "app", "components", "pages", "views",
28
+ "tests", "test", "featuregraph", "__pycache__",
29
+ }
30
+
31
+
32
+ def _id_slug(text: str) -> str:
33
+ return re.sub(r"[^A-Za-z0-9]+", "-", text).strip("-").upper()
34
+
35
+
36
+ def _parse_file(path: Path) -> list[dict[str, Any]]:
37
+ """Dispatch to the right parser for *path* (single chokepoint for parser selection)."""
38
+ parser: FeatureParser | None = None
39
+ if path.suffix == ".py":
40
+ parser = PythonFeatureParser
41
+ elif path.suffix in (".ts", ".tsx", ".js", ".jsx"):
42
+ parser = TypeScriptFeatureParser
43
+ elif GenericFeatureParser.is_supported(path):
44
+ parser = GenericFeatureParser
45
+ return parser.parse_file(path) if parser is not None else []
46
+
47
+
48
+ def _has_syntax_error(path: Path) -> bool:
49
+ """True when *path* is unreadable, fails Python AST parsing, or has unbalanced JS/TS braces."""
50
+ try:
51
+ source = path.read_bytes()
52
+ except OSError:
53
+ return True
54
+ if path.suffix == ".py":
55
+ try:
56
+ ast.parse(source, filename=str(path))
57
+ except (SyntaxError, ValueError):
58
+ return True
59
+ return False
60
+ if path.suffix in (".ts", ".tsx", ".js", ".jsx"):
61
+ code = lexmask.code_only(source.decode("utf-8", errors="replace"), "js")
62
+ return code.count("{") != code.count("}")
63
+ return False
64
+
65
+
66
+ def _category_for(rel_path: Path) -> str:
67
+ parts = list(rel_path.parts)
68
+ dirs = [p for p in parts[:-1] if p.lower() not in _CATEGORY_SKIP]
69
+ token = dirs[-1] if dirs else rel_path.stem
70
+ return re.sub(r"[^a-z0-9_]", "_", token.lower()).strip("_") or "general"
71
+
72
+
73
+ def _auto_feature_id(rel_path: Path, item: dict) -> str:
74
+ kind = item.get("type")
75
+ if kind == "file":
76
+ return f"FILE-{_id_slug(rel_path.as_posix())}"
77
+ stem = rel_path.with_suffix("")
78
+ if kind in ("model", "config") and stem.name in ("models", "settings") and len(stem.parts) > 1:
79
+ stem = Path(*stem.parts[:-1])
80
+ path = _id_slug(stem.as_posix())
81
+ symbol = _id_slug(str(item.get("symbol") or rel_path.stem))
82
+ prefix = item.get("prefix") or {"model": "MODEL", "config": "CONFIG"}.get(kind, "CJS")
83
+ return f"{prefix}-{path}-{symbol}"
84
+
85
+
86
+ def _file_level_item(path: Path, rel_path: Path) -> dict:
87
+ try:
88
+ line_count = len(path.read_text(encoding="utf-8", errors="replace").splitlines())
89
+ except OSError:
90
+ line_count = 1
91
+ return {
92
+ "feature_id": _auto_feature_id(rel_path, {"type": "file", "symbol": path.stem}),
93
+ "name": f"File {rel_path.as_posix()}",
94
+ "symbol": path.name,
95
+ "qualname": path.name,
96
+ "type": "file",
97
+ "start_line": 1,
98
+ "end_line": max(line_count, 1),
99
+ "depends_on": [],
100
+ "category": "file_index",
101
+ "auto": True,
102
+ "file": str(path),
103
+ "rel_path": rel_path.as_posix(),
104
+ }
105
+
106
+ class _GitignoreMatcher:
107
+ """Minimal .gitignore support for scans outside a git repository.
108
+
109
+ Last matching pattern wins; supports negation, dir-only and anchored patterns.
110
+ ponytail: root .gitignore only; ``*`` may cross ``/``; no ``**`` rules. Inside a
111
+ repo git itself supplies the exact list, so this fallback stays deliberately small.
112
+ """
113
+
114
+ def __init__(self, root_dir: Path):
115
+ self.rules: list[tuple] = []
116
+ ignore_file = root_dir / ".gitignore"
117
+ if not ignore_file.exists():
118
+ return
119
+ try:
120
+ lines = ignore_file.read_text(encoding="utf-8", errors="ignore").splitlines()
121
+ except OSError:
122
+ return
123
+ for raw in lines:
124
+ line = raw.rstrip()
125
+ if not line or line.startswith("#"):
126
+ continue
127
+ negated = line.startswith("!")
128
+ if negated:
129
+ line = line[1:]
130
+ if not line:
131
+ continue
132
+ dir_only = line.endswith("/")
133
+ pattern = line.rstrip("/")
134
+ anchored = pattern.startswith("/") or "/" in pattern
135
+ self.rules.append((pattern.lstrip("/"), negated, dir_only, anchored))
136
+
137
+ def ignores(self, rel_path: str, is_dir: bool = False) -> bool:
138
+ ignored = False
139
+ for pattern, negated, dir_only, anchored in self.rules:
140
+ if dir_only and not is_dir:
141
+ continue
142
+ if anchored:
143
+ matched = fnmatch.fnmatch(rel_path, pattern)
144
+ else:
145
+ matched = any(fnmatch.fnmatch(part, pattern) for part in rel_path.split("/"))
146
+ if matched:
147
+ ignored = not negated
148
+ return ignored
149
+
150
+
151
+ # @feature [SCANNER-01] Workspace scanner
152
+ class WorkspaceScanner:
153
+ """Recursively scans codebase directories and parses feature tags into a FeatureGraph."""
154
+
155
+ def __init__(self, root_dir: Path):
156
+ self.root_dir = root_dir
157
+ self.ignore_patterns = set(DEFAULT_IGNORE)
158
+ self._load_ignore_file()
159
+ # Filled by scan(); scan_meta() reads them without rescanning.
160
+ self.cycles: list[list[str]] = []
161
+ self.duplicate_ids: list[dict[str, Any]] = []
162
+ self.unresolved_depends: list[tuple[str, str]] = []
163
+
164
+ # @feature [SCANNER-02] Detect subprojects
165
+ def detect_subprojects(self) -> list[str]:
166
+ """Detects if current root is a multi-project workspace containing multiple repositories."""
167
+ subprojects = []
168
+ try:
169
+ for child in self.root_dir.iterdir():
170
+ if child.is_dir() and not self._should_ignore_dir(child.name):
171
+ if (child / ".git").exists() or (child / "pyproject.toml").exists() or (child / "package.json").exists():
172
+ subprojects.append(child.name)
173
+ except (PermissionError, OSError):
174
+ pass
175
+ return sorted(subprojects)
176
+
177
+ def _load_ignore_file(self):
178
+ ignore_file = self.root_dir / ".featureignore"
179
+ if ignore_file.exists():
180
+ for line in ignore_file.read_text(encoding="utf-8").splitlines():
181
+ line = line.strip()
182
+ if line and not line.startswith("#"):
183
+ self.ignore_patterns.add(line.rstrip("/"))
184
+
185
+ def _should_ignore_dir(self, dir_name: str) -> bool:
186
+ if dir_name.startswith(".") and dir_name not in [".", ".."]:
187
+ return True
188
+ return dir_name in self.ignore_patterns
189
+
190
+ def _git_file_list(self) -> list[str] | None:
191
+ """Tracked + untracked-but-not-ignored files via git, or None when git is unavailable."""
192
+ try:
193
+ proc = subprocess.run(
194
+ ["git", "-C", str(self.root_dir), "ls-files", "-z",
195
+ "--cached", "--others", "--exclude-standard"],
196
+ capture_output=True, text=True, timeout=30,
197
+ )
198
+ except (OSError, subprocess.SubprocessError):
199
+ return None
200
+ if proc.returncode != 0:
201
+ return None
202
+ return [p for p in proc.stdout.split("\0") if p]
203
+
204
+ def iter_files(self) -> Iterator[Path]:
205
+ """
206
+ Yields candidate source files. Inside a git repo uses git's file list so
207
+ .gitignore'd trees (vendor, target, .next, …) are never scanned; elsewhere the
208
+ walk is filtered by a minimal root-.gitignore matcher. Always honours
209
+ .featureignore and hidden dirs.
210
+ """
211
+ git_files = self._git_file_list()
212
+ if git_files is not None:
213
+ for rel in sorted(git_files):
214
+ parts = Path(rel).parts
215
+ if any(p.startswith(".") or p in self.ignore_patterns for p in parts[:-1]):
216
+ continue
217
+ if parts[-1].startswith("."):
218
+ continue
219
+ path = self.root_dir / rel
220
+ if path.is_file():
221
+ yield path
222
+ return
223
+
224
+ matcher = _GitignoreMatcher(self.root_dir)
225
+ for root, dirs, files in os.walk(self.root_dir, topdown=True):
226
+ dirs[:] = sorted(
227
+ d for d in dirs
228
+ if not self._should_ignore_dir(d)
229
+ and not matcher.ignores(
230
+ (Path(root) / d).relative_to(self.root_dir).as_posix(), is_dir=True
231
+ )
232
+ )
233
+ for file in sorted(files):
234
+ if file.startswith("."):
235
+ continue
236
+ rel = (Path(root) / file).relative_to(self.root_dir).as_posix()
237
+ if not matcher.ignores(rel):
238
+ yield Path(root) / file
239
+
240
+ def _source_files(self) -> Iterator[tuple[Path, Path, os.stat_result]]:
241
+ """Exact file set scan parses: supported, non-empty, selected by iter_files."""
242
+ for path in self.iter_files():
243
+ try:
244
+ st = path.stat()
245
+ except OSError:
246
+ continue
247
+ if st.st_size == 0:
248
+ continue # empty files (e.g. __init__.py) are not "unparsed"
249
+ if not (
250
+ path.suffix == ".py"
251
+ or path.suffix in (".ts", ".tsx", ".js", ".jsx")
252
+ or GenericFeatureParser.is_supported(path)
253
+ ):
254
+ continue
255
+ yield path, path.relative_to(self.root_dir), st
256
+
257
+ def tree_hash(self) -> str:
258
+ """sha256 over sorted (relpath, bytes) plus .featureignore content.
259
+
260
+ Content hashing makes touch/checkout a no-op and catches same-size edits;
261
+ .featuregraph is hidden, so iter_files skips it.
262
+ """
263
+ h = hashlib.sha256()
264
+ ignore_file = self.root_dir / ".featureignore"
265
+ if ignore_file.is_file():
266
+ try:
267
+ h.update(b".featureignore\0" + ignore_file.read_bytes() + b"\n")
268
+ except OSError:
269
+ pass
270
+ for path, rel_path, _st in sorted(self._source_files(), key=lambda f: f[1].as_posix()):
271
+ try:
272
+ payload = path.read_bytes()
273
+ except OSError:
274
+ continue
275
+ h.update(rel_path.as_posix().encode())
276
+ h.update(b"\0")
277
+ h.update(payload)
278
+ h.update(b"\n")
279
+ return h.hexdigest()
280
+
281
+ @staticmethod
282
+ def _disambiguate_auto_ids(items: list[dict[str, Any]]) -> None:
283
+ """Suffix auto IDs whose slug collides across files (a/b.py vs a_b.py)."""
284
+ owners: dict[str, set[str]] = {}
285
+ for item in items:
286
+ if item.get("auto"):
287
+ owners.setdefault(item["feature_id"], set()).add(item["rel_path"])
288
+ for item in items:
289
+ if not item.get("auto"):
290
+ continue
291
+ feature_id = item["feature_id"]
292
+ if len(owners.get(feature_id, ())) > 1:
293
+ digest = hashlib.sha1(item["rel_path"].encode()).hexdigest()[:6].upper()
294
+ item["feature_id"] = f"{feature_id}-{digest}"
295
+
296
+ # @feature [SCANNER-03] Scan
297
+ def scan(self, quiet: bool = False) -> FeatureGraph:
298
+ graph = FeatureGraph()
299
+ resolver = DependencyResolver()
300
+
301
+ # Pass 1: Parse all files & index defined symbols
302
+ scanned_files = []
303
+ unparsed: list[str] = []
304
+ syntax_errors: list[str] = []
305
+ total_files = 0
306
+
307
+ for path, rel_path, _st in sorted(self._source_files(), key=lambda f: f[1].as_posix()):
308
+ total_files += 1
309
+
310
+ parsed = _parse_file(path)
311
+
312
+ if parsed:
313
+ for item in parsed:
314
+ item["rel_path"] = rel_path.as_posix()
315
+ if not item.get("feature_id"):
316
+ item["feature_id"] = _auto_feature_id(rel_path, item)
317
+ item["category"] = item.get("category") or _category_for(rel_path)
318
+ scanned_files.append((path, rel_path, parsed))
319
+ else:
320
+ unparsed.append(str(rel_path))
321
+ if _has_syntax_error(path):
322
+ syntax_errors.append(str(rel_path))
323
+ scanned_files.append((path, rel_path, [_file_level_item(path, rel_path)]))
324
+
325
+ all_features = [item for _, _, parsed in scanned_files for item in parsed]
326
+ self._disambiguate_auto_ids(all_features)
327
+
328
+ if unparsed and not quiet:
329
+ sample = ", ".join(unparsed[:3])
330
+ suffix = f" (+{len(unparsed) - 3} more)" if len(unparsed) > 3 else ""
331
+ print(
332
+ f"⚠ {len(unparsed)} file(s) with no parseable features (untagged, unreadable, or syntax error): {sample}{suffix}",
333
+ file=sys.stderr,
334
+ )
335
+
336
+ # Pass 2: Infer cross-feature dependencies & populate graph
337
+ assign_symbol_ids(all_features)
338
+ # Auto-indexed models/functions still own their symbols, so real callers wire
339
+ # edges; FILE-* items are whole-file coverage, not call-graph nodes.
340
+ resolver.register_feature_symbols(
341
+ [item for item in all_features if item.get("type") != "file"], assign=False
342
+ )
343
+
344
+ for path, rel_path, parsed in scanned_files:
345
+ real_items = [item for item in parsed if not item.get("auto")]
346
+ inferred_deps = (
347
+ resolver.resolve_file_dependencies(path, real_items) if real_items else {}
348
+ )
349
+
350
+ for item in parsed:
351
+ feat_id = item["feature_id"]
352
+ auto_deps = inferred_deps.get(feat_id, set())
353
+ manual_deps = set(item.get("depends_on", []))
354
+ all_deps = sorted(list(manual_deps | auto_deps))
355
+
356
+ item_loc = [{
357
+ "file": str(rel_path),
358
+ "lines": [item["start_line"], item["end_line"]],
359
+ "symbol": item["symbol"],
360
+ "symbol_id": item.get("symbol_id", item["symbol"]),
361
+ "type": item["type"],
362
+ }]
363
+ data = {
364
+ "name": item["name"],
365
+ "depends_on": all_deps,
366
+ "locations": item_loc,
367
+ }
368
+ if item.get("category"):
369
+ data["category"] = item["category"]
370
+ for tag_key in ("boundaries", "invariants", "tests"):
371
+ if item.get(tag_key):
372
+ data[tag_key] = item[tag_key]
373
+ graph.add_feature(feat_id, data)
374
+
375
+ # Explicit @depends tags may point at features that do not exist (typo, rename, deletion).
376
+ # Inferred deps can't dangle — the resolver only knows registered feature IDs.
377
+ unresolved = sorted({
378
+ (feat_id, dep)
379
+ for feat_id, deps in graph.edges.items()
380
+ for dep in deps
381
+ if dep not in graph.nodes
382
+ })
383
+ if unresolved and not quiet:
384
+ sample = ", ".join(f"{feat} → {dep}" for feat, dep in unresolved[:3])
385
+ suffix = "…" if len(unresolved) > 3 else ""
386
+ print(
387
+ f"⚠ {len(unresolved)} unresolved @depends reference(s) — no such feature: {sample}{suffix}",
388
+ file=sys.stderr,
389
+ )
390
+
391
+ # Diagnostics survive the scan so scan_meta() can report them.
392
+ self.cycles = graph.find_cycles()
393
+ self.duplicate_ids = list(graph.duplicate_ids)
394
+ self.unresolved_depends = unresolved
395
+
396
+ # B4: truthful manifest fields; empty wins regardless of file counts.
397
+ self.tree_hash_value = self.tree_hash()
398
+ self.total_files = total_files
399
+ self.indexed_files = len(scanned_files)
400
+ self.unindexed = sorted(syntax_errors)
401
+ self.unparsed_syntax_errors = sorted(syntax_errors)
402
+ self.file_level = sorted(unparsed)
403
+ self.status = (
404
+ "empty" if not graph.nodes else "ok" if not unparsed else "partial"
405
+ )
406
+
407
+ return graph
408
+
409
+ def scan_meta(self) -> dict:
410
+ meta = {
411
+ "tree_hash": self.tree_hash_value,
412
+ "status": self.status,
413
+ "total_files": self.total_files,
414
+ "indexed_files": self.indexed_files,
415
+ "unindexed_files": len(self.unindexed),
416
+ "unparsed_syntax_errors": len(self.unparsed_syntax_errors),
417
+ "file_level_files": len(self.file_level),
418
+ "cycles": len(self.cycles),
419
+ "duplicate_ids": len(self.duplicate_ids),
420
+ "unresolved_depends": len(self.unresolved_depends),
421
+ }
422
+ if self.cycles or self.duplicate_ids or self.unresolved_depends:
423
+ meta["diagnostics"] = {
424
+ "cycles": self.cycles,
425
+ "duplicate_ids": self.duplicate_ids,
426
+ "unresolved_depends": [list(pair) for pair in self.unresolved_depends],
427
+ }
428
+ return meta
429
+
@@ -0,0 +1,51 @@
1
+ """Shared tag regexes used by all language parsers.
2
+
3
+ Keeping them in one place prevents drift between the Python, TypeScript/JS,
4
+ and generic parsers, all of which honour the same @feature / @depends syntax.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+
11
+ FEATURE_TAG_REGEX = re.compile(r"@feature\s+\[([A-Za-z0-9_\-]+)\](?:\s+(.*))?", re.IGNORECASE)
12
+ DEPENDS_TAG_REGEX = re.compile(r"@depends(?:_on)?\s+\[([A-Za-z0-9_\-,\s]+)\]", re.IGNORECASE)
13
+
14
+ # Contract/security tags. Only comment text is ever scanned for these, so a tag
15
+ # inside a string literal or template cannot declare a boundary or a test.
16
+ BOUNDARY_TAG_REGEX = re.compile(r"@boundary\s+\[([A-Za-z0-9_\-,\s]+)\]", re.IGNORECASE)
17
+ INVARIANT_TAG_REGEX = re.compile(r"@invariant\s+(.+)", re.IGNORECASE)
18
+ TEST_TAG_REGEX = re.compile(r"@test\s+(.+)", re.IGNORECASE)
19
+
20
+
21
+ def _split_values(raw: str) -> list[str]:
22
+ return [part.strip() for part in re.split(r"[,\s]+", raw) if part.strip()]
23
+
24
+
25
+ def extract_contract_tags(text: str) -> dict[str, list[str]]:
26
+ """boundaries / invariants / tests from one comment-only window.
27
+
28
+ Empty results are omitted so callers can splice the dict straight into the
29
+ feature record and keep the JSON compact.
30
+ """
31
+ tags: dict[str, list[str]] = {}
32
+ boundaries: list[str] = []
33
+ for match in BOUNDARY_TAG_REGEX.findall(text):
34
+ for name in _split_values(match):
35
+ normalised = name.lower()
36
+ if normalised not in boundaries:
37
+ boundaries.append(normalised)
38
+ if boundaries:
39
+ tags["boundaries"] = boundaries
40
+ invariants = [value.strip() for value in INVARIANT_TAG_REGEX.findall(text) if value.strip()]
41
+ if invariants:
42
+ tags["invariants"] = invariants
43
+ tests: list[str] = []
44
+ for match in TEST_TAG_REGEX.findall(text):
45
+ for value in _split_values(match):
46
+ if value not in tests:
47
+ tests.append(value)
48
+ if tests:
49
+ tags["tests"] = tests
50
+ return tags
51
+
@@ -0,0 +1,164 @@
1
+ import json
2
+ import os
3
+ import re
4
+ import shutil
5
+ import tempfile
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ # Single source of truth so index output is identical whether run as a script or installed
10
+ from featuregraph import __version__ as _VERSION
11
+
12
+
13
+ # @feature [JSON_FORMATT-01] Jsonformatter
14
+ class JSONFormatter:
15
+ """Formats feature graph into a 2-Tier Hierarchical (Manifest + Categories) token-efficient index."""
16
+
17
+ @staticmethod
18
+ def _extract_category(feat_id: str, data: dict[str, Any]) -> str:
19
+ """Derives a clean lowercase category slug from category field, ID prefix, or file path."""
20
+ cat = data.get("category")
21
+ if cat and cat != "General":
22
+ slug = re.sub(r"[^a-zA-Z0-9_]", "_", cat.lower()).strip("_")
23
+ if slug:
24
+ return slug
25
+
26
+ # Extract from prefix before '-' (e.g. AUTH-01 -> auth, ROUTE-LOGIN -> api_routes)
27
+ if "-" in feat_id:
28
+ prefix = re.sub(r"[^a-z0-9_]", "_", feat_id.split("-")[0].lower()).strip("_")
29
+ if prefix == "route":
30
+ # Check file location if available
31
+ locs = data.get("locations", [])
32
+ if locs:
33
+ f = locs[0].get("file", "")
34
+ parts = Path(f).parts
35
+ if len(parts) > 1:
36
+ return re.sub(r"[^a-zA-Z0-9_]", "_", parts[-2].lower()).strip("_")
37
+ return "routes"
38
+ return prefix or "general"
39
+
40
+ return "general"
41
+
42
+ @staticmethod
43
+ def split_by_category(graph_dict: dict[str, Any]) -> dict[str, dict[str, Any]]:
44
+ """Splits the full feature graph dictionary into domain categories."""
45
+ categories: dict[str, dict[str, Any]] = {}
46
+ for feat_id, data in graph_dict.items():
47
+ cat = JSONFormatter._extract_category(feat_id, data)
48
+ categories.setdefault(cat, {})[feat_id] = data
49
+ return categories
50
+
51
+ @staticmethod
52
+ def format_manifest(graph_dict: dict[str, Any], meta: dict[str, Any] = None) -> str:
53
+ """
54
+ Generates the Tier-1 manifest: one line per feature, grouped by category.
55
+ Size scales linearly with feature count (~0.5 kB per 10 features).
56
+ """
57
+ categories = JSONFormatter.split_by_category(graph_dict)
58
+ manifest_data = {
59
+ "_meta": {
60
+ "generator": "featuregraph",
61
+ "version": _VERSION,
62
+ "total_features": len(graph_dict),
63
+ **(meta or {}),
64
+ "total_categories": len(categories),
65
+ "instruction": "Read this manifest to find the category, then read only .featuregraph/categories/<category>.json for exact lines (#Lstart-Lend)."
66
+ },
67
+ "categories": {
68
+ cat: {fid: fdata.get("name", fid) for fid, fdata in sorted(features.items())}
69
+ for cat, features in sorted(categories.items())
70
+ }
71
+ }
72
+ return json.dumps(manifest_data, indent=2)
73
+
74
+ @staticmethod
75
+ # @feature [JSON_FORMATT-02] Format
76
+ def format(graph_dict: dict[str, Any], root_dir: Path, meta: dict[str, Any] = None) -> str:
77
+ data = {
78
+ "_meta": {
79
+ "generator": "featuregraph",
80
+ "version": _VERSION,
81
+ "total_features": len(graph_dict),
82
+ **(meta or {}),
83
+ "instruction": "Inspect [locations] for exact #Lstart-Lend before reading source code. Check [depends_on] to preserve cross-cutting invariants."
84
+ },
85
+ "features": graph_dict
86
+ }
87
+ return json.dumps(data, indent=2)
88
+
89
+ @staticmethod
90
+ # @feature [JSON_FORMATT-03] Write to file
91
+ def write_to_file(graph_dict: dict[str, Any], output_path: Path, root_dir: Path, meta: dict[str, Any] = None):
92
+ output_path.parent.mkdir(parents=True, exist_ok=True)
93
+ content = JSONFormatter.format(graph_dict, root_dir, meta)
94
+ output_path.write_text(content, encoding="utf-8")
95
+
96
+ @staticmethod
97
+ def write_unindexed(unindexed: list, fg_dir: Path):
98
+ (fg_dir / "unindexed.json").write_text(json.dumps(sorted(unindexed), indent=2), encoding="utf-8")
99
+
100
+ @staticmethod
101
+ def _atomic_write(path: Path, content: str) -> None:
102
+ """Write *content* to *path* via a sibling temp file + os.replace."""
103
+ tmp_path = None
104
+ try:
105
+ fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp")
106
+ tmp_path = Path(tmp)
107
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
108
+ handle.write(content)
109
+ os.chmod(tmp_path, 0o644)
110
+ os.replace(tmp_path, path)
111
+ tmp_path = None
112
+ finally:
113
+ if tmp_path is not None:
114
+ try:
115
+ tmp_path.unlink()
116
+ except OSError:
117
+ pass
118
+
119
+ @staticmethod
120
+ def _replace_categories(cat_dir: Path, categories: dict[str, dict[str, Any]]) -> None:
121
+ """Build the category tree in a temp dir, then swap it in with os.replace."""
122
+ cat_dir.parent.mkdir(parents=True, exist_ok=True)
123
+ staging = Path(tempfile.mkdtemp(dir=cat_dir.parent, prefix=f".{cat_dir.name}."))
124
+ try:
125
+ for cat_name, cat_features in categories.items():
126
+ (staging / f"{cat_name}.json").write_text(
127
+ json.dumps(cat_features, indent=2), encoding="utf-8"
128
+ )
129
+ if cat_dir.exists():
130
+ retired = cat_dir.parent / f".{cat_dir.name}.old.{os.getpid()}"
131
+ if retired.exists():
132
+ shutil.rmtree(retired)
133
+ os.replace(cat_dir, retired)
134
+ try:
135
+ os.replace(staging, cat_dir)
136
+ except BaseException:
137
+ os.replace(retired, cat_dir)
138
+ raise
139
+ shutil.rmtree(retired)
140
+ else:
141
+ os.replace(staging, cat_dir)
142
+ finally:
143
+ if staging.exists():
144
+ shutil.rmtree(staging, ignore_errors=True)
145
+
146
+ @staticmethod
147
+ def write_all(graph_dict: dict[str, Any], fg_dir: Path, root_dir: Path, meta: dict[str, Any] = None):
148
+ """Writes manifest.json, unified index.json, and all category files atomically."""
149
+ fg_dir.mkdir(parents=True, exist_ok=True)
150
+
151
+ # 1. Tier-1 Manifest
152
+ JSONFormatter._atomic_write(
153
+ fg_dir / "manifest.json", JSONFormatter.format_manifest(graph_dict, meta)
154
+ )
155
+
156
+ # 2. Unified index.json
157
+ JSONFormatter._atomic_write(
158
+ fg_dir / "index.json", JSONFormatter.format(graph_dict, root_dir, meta)
159
+ )
160
+
161
+ # 3. Tier-2 Category Chunks (directory swapped as one unit)
162
+ JSONFormatter._replace_categories(
163
+ fg_dir / "categories", JSONFormatter.split_by_category(graph_dict)
164
+ )