codegraph-engine 3.0.0__py3-none-any.whl → 3.0.1__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.
Files changed (69) hide show
  1. codegraph/__init__.py +1 -1
  2. codegraph/__main__.py +7 -0
  3. codegraph/agent_brain.py +81 -0
  4. codegraph/agent_capabilities.py +1037 -73
  5. codegraph/agent_rules.py +1 -0
  6. codegraph/architecture_rules.py +123 -0
  7. codegraph/changelog.py +170 -0
  8. codegraph/cli.py +793 -1
  9. codegraph/context.py +97 -13
  10. codegraph/dataflow_propagation.py +118 -0
  11. codegraph/dead_code.py +387 -0
  12. codegraph/epistemic.py +8 -0
  13. codegraph/evidence_contract.py +13 -3
  14. codegraph/federation.py +245 -0
  15. codegraph/frameworks.py +63 -6
  16. codegraph/graph/traversal.py +150 -7
  17. codegraph/graph_csr.py +218 -0
  18. codegraph/incremental.py +150 -0
  19. codegraph/indexing/classifier.py +5 -0
  20. codegraph/indexing/indexer.py +1 -0
  21. codegraph/indexing/languages/__init__.py +1 -0
  22. codegraph/indexing/languages/cpp.py +457 -0
  23. codegraph/indexing/languages/go.py +459 -0
  24. codegraph/indexing/languages/jvm.py +583 -0
  25. codegraph/indexing/languages/rust.py +507 -0
  26. codegraph/indexing/models.py +9 -1
  27. codegraph/indexing/parser.py +146 -9
  28. codegraph/indexing/protocols.py +220 -0
  29. codegraph/indexing/scanner.py +17 -0
  30. codegraph/interrogation.py +80 -20
  31. codegraph/lsp.py +318 -0
  32. codegraph/lsp_bridge/__init__.py +16 -0
  33. codegraph/lsp_bridge/bridge.py +102 -0
  34. codegraph/lsp_bridge/client.py +207 -0
  35. codegraph/lsp_bridge/models.py +71 -0
  36. codegraph/mcp/server.py +312 -1
  37. codegraph/memory/trajectory.py +282 -0
  38. codegraph/multi_agent/__init__.py +13 -0
  39. codegraph/multi_agent/coordinator.py +229 -0
  40. codegraph/multi_agent/models.py +76 -0
  41. codegraph/polymorphism.py +95 -0
  42. codegraph/pr_review.py +296 -0
  43. codegraph/process_lifecycle.py +22 -2
  44. codegraph/reachability.py +198 -0
  45. codegraph/reachability_index.py +74 -0
  46. codegraph/refactor/__init__.py +12 -0
  47. codegraph/refactor/patcher.py +348 -0
  48. codegraph/refactor/renamer.py +3 -3
  49. codegraph/refactor/transactions.py +23 -12
  50. codegraph/repair.py +233 -0
  51. codegraph/resolver.py +155 -2
  52. codegraph/retrieval_policy.py +16 -1
  53. codegraph/roblox.py +2174 -0
  54. codegraph/route_composer.py +7 -0
  55. codegraph/runtime/__init__.py +6 -0
  56. codegraph/runtime/db_watcher.py +2 -2
  57. codegraph/runtime/otel_receiver.py +208 -0
  58. codegraph/sandbox.py +215 -0
  59. codegraph/security/supply_chain.py +188 -0
  60. codegraph/security/taint.py +421 -0
  61. codegraph/test_gen.py +437 -0
  62. codegraph/ui/server.py +200 -39
  63. codegraph/watcher.py +2 -2
  64. {codegraph_engine-3.0.0.dist-info → codegraph_engine-3.0.1.dist-info}/METADATA +255 -69
  65. {codegraph_engine-3.0.0.dist-info → codegraph_engine-3.0.1.dist-info}/RECORD +69 -34
  66. {codegraph_engine-3.0.0.dist-info → codegraph_engine-3.0.1.dist-info}/WHEEL +1 -1
  67. {codegraph_engine-3.0.0.dist-info → codegraph_engine-3.0.1.dist-info}/entry_points.txt +0 -0
  68. {codegraph_engine-3.0.0.dist-info → codegraph_engine-3.0.1.dist-info}/licenses/LICENSE +0 -0
  69. {codegraph_engine-3.0.0.dist-info → codegraph_engine-3.0.1.dist-info}/top_level.txt +0 -0
codegraph/agent_rules.py CHANGED
@@ -338,6 +338,7 @@ Synthesize the final answer or apply the code edit:
338
338
  | `STATIC_VERIFIED` | Directly proven by static SQL DDL/DML or migration parsing (`CREATE TABLE`, `INSERT INTO`, `MIGRATES_TABLE`) | Verified Fact (`FACT`) | Cite with SQL/migration file and line coordinates. |
339
339
  | `FRAMEWORK_VERIFIED` | Proven by deterministic framework rules (`HANDLED_BY`, `MOUNTS`, `INJECTS`, `PROVIDES`, `MAPS_TO_TABLE`, `TASK_HANDLER`, `EVENT_LISTENER`) | Verified Fact (`FACT`) | Cite with framework relationship type; never collapse into `CALLS`. |
340
340
  | `DATAFLOW_VERIFIED` | Proven by conservative local/attribute/registry binding (`BINDS_TO`, `RESOLVES_DEPENDENCY`, `REGISTERS`, `DISPATCHES_TO`) | Verified Fact (`FACT`) | Cite with resolved target and binding location. |
341
+ | `ROJO_VERIFIED` | Proven by deterministic Rojo `default.project.json` DataModel-to-filesystem mapping (`REQUIRES_MODULE`) | Verified Fact (`FACT`) | Cite with virtual DataModel path and resolved physical file. |
341
342
  | `RUNTIME_OBSERVED` | Observed in an ingested runtime trace (`observation_count`, `first_seen`, `last_seen`, `runtime_generation`) | Observed Runtime Fact | Cite as runtime observation; never promote into static `AST_VERIFIED` proof. |
342
343
  | `RUNTIME_UNOBSERVED` | Static edge not observed in the ingested runtime trace sample (`NOT_OBSERVED_AT_RUNTIME`) | Unobserved in Sample | Never claim the path is dead code or impossible at runtime. |
343
344
  | `POSSIBLE` | Plausible static candidate (`POSSIBLE_CALLS`, `POSSIBLE_TABLE`, conditional registration, multiple providers) | Candidate Lead (`POSSIBLE`) | Inspect cited lines via `get_file` / `read_file` before making a definitive claim. |
@@ -0,0 +1,123 @@
1
+ """Declarative Architecture Invariant Engine for CodeGraph.
2
+
3
+ Enforces architectural rules, layered clean architecture boundaries, and forbidden dependencies:
4
+ - Reads declarative architectural rules from .codegraph/rules.yaml
5
+ - Checks forbidden import edges (e.g. controllers importing database tables directly)
6
+ - Enforces layer isolation (domain layer cannot import infrastructure or UI)
7
+ - Enforces naming conventions and required interface implementations
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import fnmatch
12
+ import json
13
+ import sqlite3
14
+ from dataclasses import asdict, dataclass, field
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class RuleViolation:
21
+ """An architectural invariant violation."""
22
+
23
+ rule_name: str
24
+ source_file: str
25
+ line: int
26
+ target_entity: str
27
+ severity: str # ERROR | WARNING
28
+ message: str
29
+
30
+ def as_dict(self) -> dict[str, Any]:
31
+ return asdict(self)
32
+
33
+
34
+ @dataclass
35
+ class ArchitectureComplianceReport:
36
+ """Consolidated compliance report across all architectural rules."""
37
+
38
+ workspace: str
39
+ status: str # COMPLIANT | VIOLATIONS_DETECTED
40
+ total_rules_checked: int
41
+ violations_count: int
42
+ violations: list[RuleViolation] = field(default_factory=list)
43
+
44
+ def as_dict(self) -> dict[str, Any]:
45
+ return {
46
+ "workspace": self.workspace,
47
+ "status": self.status,
48
+ "total_rules_checked": self.total_rules_checked,
49
+ "violations_count": self.violations_count,
50
+ "violations": [v.as_dict() for v in self.violations],
51
+ }
52
+
53
+
54
+ def evaluate_architecture_rules(
55
+ repository: Path,
56
+ con: sqlite3.Connection,
57
+ rules: list[dict[str, Any]] | None = None,
58
+ ) -> ArchitectureComplianceReport:
59
+ """Evaluate architectural boundaries against the repository graph index."""
60
+ repo = repository.resolve()
61
+ violations: list[RuleViolation] = []
62
+
63
+ # If rules not passed, load from .codegraph/rules.yaml or rules.json
64
+ active_rules: list[dict[str, Any]] = rules or []
65
+ if not active_rules:
66
+ rule_file_json = repo / ".codegraph" / "rules.json"
67
+ if rule_file_json.is_file():
68
+ try:
69
+ active_rules = json.loads(rule_file_json.read_text(encoding="utf-8"))
70
+ except Exception:
71
+ pass
72
+
73
+ # Default starter rules if none defined
74
+ if not active_rules:
75
+ active_rules = [
76
+ {
77
+ "name": "prevent-controller-to-db-leakage",
78
+ "source_pattern": "*controller*.*",
79
+ "cannot_import": ["*models*", "*db*", "*entities*"],
80
+ "message": "Controller must not import database models directly; route through services.",
81
+ }
82
+ ]
83
+
84
+ # Query all imports from database
85
+ cur = con.cursor()
86
+ cur.execute("PRAGMA table_info(imports);")
87
+ imp_cols = {col[1] for col in cur.fetchall()}
88
+ src_col = "source_path" if "source_path" in imp_cols else "source_file"
89
+ cur.execute(f"SELECT {src_col}, module, name, line FROM imports;")
90
+ all_imports = cur.fetchall()
91
+
92
+ for r in active_rules:
93
+ name = r.get("name", "unnamed-rule")
94
+ src_pat = r.get("source_pattern", "*")
95
+ cannot_import = r.get("cannot_import", [])
96
+ msg = r.get("message", f"Rule '{name}' violated.")
97
+
98
+ for imp_source, imp_module, imp_name, imp_line in all_imports:
99
+ # Check if file matches source pattern
100
+ if fnmatch.fnmatch(imp_source, src_pat) or fnmatch.fnmatch(Path(imp_source).name, src_pat):
101
+ # Check forbidden targets
102
+ full_import_target = f"{imp_module}.{imp_name}" if imp_name else imp_module
103
+ for forbidden in cannot_import:
104
+ if fnmatch.fnmatch(full_import_target, forbidden) or fnmatch.fnmatch(imp_module, forbidden):
105
+ violations.append(
106
+ RuleViolation(
107
+ rule_name=name,
108
+ source_file=imp_source,
109
+ line=imp_line,
110
+ target_entity=full_import_target,
111
+ severity="ERROR",
112
+ message=msg,
113
+ )
114
+ )
115
+
116
+ status = "COMPLIANT" if not violations else "VIOLATIONS_DETECTED"
117
+ return ArchitectureComplianceReport(
118
+ workspace=str(repo),
119
+ status=status,
120
+ total_rules_checked=len(active_rules),
121
+ violations_count=len(violations),
122
+ violations=violations,
123
+ )
codegraph/changelog.py ADDED
@@ -0,0 +1,170 @@
1
+ """Semantic Breaking-Change & Release Changelog Synthesizer for CodeGraph.
2
+
3
+ Generates human-readable, semantically accurate release changelogs from AST diffs:
4
+ - Categorizes Breaking Changes (removed parameters, dropped endpoints, renamed APIs)
5
+ - Categorizes New Features (new HTTP endpoints, new exported symbols)
6
+ - Categorizes Database Schema Mutations (new tables, altered column constraints)
7
+ - Formats production-ready Markdown changelogs
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import subprocess
12
+ from dataclasses import asdict, dataclass, field
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class SemanticChangeEntry:
19
+ """A single semantic change item categorized from AST diffs."""
20
+
21
+ category: str # BREAKING_CHANGE | NEW_FEATURE | SCHEMA_MUTATION | REFACTOR
22
+ title: str
23
+ description: str
24
+ file_path: str
25
+ line: int = 1
26
+
27
+ def as_dict(self) -> dict[str, Any]:
28
+ return asdict(self)
29
+
30
+
31
+ @dataclass
32
+ class SemanticChangelogReport:
33
+ """Consolidated semantic changelog comparing two Git revisions."""
34
+
35
+ base_ref: str
36
+ head_ref: str
37
+ total_changes: int
38
+ breaking_changes_count: int
39
+ new_features_count: int
40
+ schema_mutations_count: int
41
+ markdown_changelog: str
42
+ entries: list[SemanticChangeEntry] = field(default_factory=list)
43
+
44
+ def as_dict(self) -> dict[str, Any]:
45
+ return {
46
+ "base_ref": self.base_ref,
47
+ "head_ref": self.head_ref,
48
+ "total_changes": self.total_changes,
49
+ "breaking_changes_count": self.breaking_changes_count,
50
+ "new_features_count": self.new_features_count,
51
+ "schema_mutations_count": self.schema_mutations_count,
52
+ "markdown_changelog": self.markdown_changelog,
53
+ "entries": [e.as_dict() for e in self.entries],
54
+ }
55
+
56
+
57
+ def generate_semantic_changelog(
58
+ repository: Path,
59
+ base_ref: str = "HEAD~1",
60
+ head_ref: str = "HEAD",
61
+ ) -> SemanticChangelogReport:
62
+ """Synthesize a semantic release changelog from git diffs and AST symbols."""
63
+ repo = repository.resolve()
64
+ diff_text = ""
65
+ try:
66
+ proc = subprocess.run(
67
+ ["git", "diff", f"{base_ref}..{head_ref}"],
68
+ cwd=str(repo),
69
+ capture_output=True,
70
+ text=True,
71
+ encoding="utf-8",
72
+ errors="replace",
73
+ )
74
+ if proc.returncode == 0:
75
+ diff_text = proc.stdout
76
+ except Exception:
77
+ diff_text = ""
78
+
79
+ entries: list[SemanticChangeEntry] = []
80
+ lines = diff_text.splitlines()
81
+
82
+ cur_file = ""
83
+ for line in lines:
84
+ if line.startswith("diff --git"):
85
+ parts = line.split()
86
+ if len(parts) >= 4:
87
+ cur_file = parts[3].lstrip("b/")
88
+ elif line.startswith("+++ "):
89
+ cur_file = line[4:].lstrip("b/")
90
+ elif line.startswith("-") and not line.startswith("---"):
91
+ stripped = line[1:].strip()
92
+ # Check if function or route was deleted
93
+ if stripped.startswith("def ") or stripped.startswith("func ") or stripped.startswith("fn "):
94
+ fn_name = stripped.split("(")[0].split()[-1]
95
+ entries.append(
96
+ SemanticChangeEntry(
97
+ category="BREAKING_CHANGE",
98
+ title=f"Removed API symbol `{fn_name}`",
99
+ description=f"Function or method `{fn_name}` was deleted or renamed in `{cur_file}`.",
100
+ file_path=cur_file,
101
+ )
102
+ )
103
+ elif any(verb in stripped for verb in ("@app.get", "@app.post", "@router.", "r.GET", "r.POST")):
104
+ entries.append(
105
+ SemanticChangeEntry(
106
+ category="BREAKING_CHANGE",
107
+ title=f"Removed HTTP route in `{cur_file}`",
108
+ description=f"Route definition `{stripped[:60]}` was removed.",
109
+ file_path=cur_file,
110
+ )
111
+ )
112
+ elif line.startswith("+") and not line.startswith("+++"):
113
+ stripped = line[1:].strip()
114
+ if any(verb in stripped for verb in ("@app.get", "@app.post", "@router.", "r.GET", "r.POST", "@GetMapping", "@PostMapping")):
115
+ entries.append(
116
+ SemanticChangeEntry(
117
+ category="NEW_FEATURE",
118
+ title=f"Added new endpoint `{stripped[:60]}`",
119
+ description=f"New HTTP endpoint registered in `{cur_file}`.",
120
+ file_path=cur_file,
121
+ )
122
+ )
123
+ elif stripped.startswith("CREATE TABLE ") or "ALTER TABLE " in stripped:
124
+ entries.append(
125
+ SemanticChangeEntry(
126
+ category="SCHEMA_MUTATION",
127
+ title="Database schema mutation",
128
+ description=f"Schema altered: `{stripped[:80]}` in `{cur_file}`.",
129
+ file_path=cur_file,
130
+ )
131
+ )
132
+
133
+ breaking = [e for e in entries if e.category == "BREAKING_CHANGE"]
134
+ features = [e for e in entries if e.category == "NEW_FEATURE"]
135
+ schemas = [e for e in entries if e.category == "SCHEMA_MUTATION"]
136
+
137
+ md_lines: list[str] = [
138
+ f"# Release Changelog ({base_ref}..{head_ref})\n",
139
+ ]
140
+ if breaking:
141
+ md_lines.append("## 🚨 Breaking Changes")
142
+ for b in breaking:
143
+ md_lines.append(f"- **{b.title}**: {b.description} (`{b.file_path}`)")
144
+ md_lines.append("")
145
+
146
+ if features:
147
+ md_lines.append("## 🚀 New Features & Endpoints")
148
+ for f in features:
149
+ md_lines.append(f"- **{f.title}**: {f.description} (`{f.file_path}`)")
150
+ md_lines.append("")
151
+
152
+ if schemas:
153
+ md_lines.append("## 🗄️ Database & Schema Mutations")
154
+ for s in schemas:
155
+ md_lines.append(f"- **{s.title}**: {s.description} (`{s.file_path}`)")
156
+ md_lines.append("")
157
+
158
+ if not entries:
159
+ md_lines.append("No public API contract breaks or new endpoints detected in this diff range.")
160
+
161
+ return SemanticChangelogReport(
162
+ base_ref=base_ref,
163
+ head_ref=head_ref,
164
+ total_changes=len(entries),
165
+ breaking_changes_count=len(breaking),
166
+ new_features_count=len(features),
167
+ schema_mutations_count=len(schemas),
168
+ markdown_changelog="\n".join(md_lines),
169
+ entries=entries,
170
+ )