codegraph-engine 2.3.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 (118) hide show
  1. codegraph/__init__.py +1 -1
  2. codegraph/__main__.py +7 -0
  3. codegraph/agent_brain.py +253 -2
  4. codegraph/agent_capabilities.py +1348 -67
  5. codegraph/agent_rules.py +2 -1
  6. codegraph/api_drift.py +455 -0
  7. codegraph/architecture_rules.py +123 -0
  8. codegraph/async_queue/__init__.py +50 -0
  9. codegraph/async_queue/detectors/__init__.py +48 -0
  10. codegraph/async_queue/detectors/celery.py +160 -0
  11. codegraph/async_queue/detectors/kafka.py +168 -0
  12. codegraph/async_queue/detectors/rabbitmq.py +116 -0
  13. codegraph/async_queue/detectors/redis.py +130 -0
  14. codegraph/async_queue/detectors/sqs.py +135 -0
  15. codegraph/async_queue/models.py +161 -0
  16. codegraph/async_queue/otel_models.py +74 -0
  17. codegraph/async_queue/otel_parser.py +337 -0
  18. codegraph/async_queue/reconciler.py +427 -0
  19. codegraph/async_queue/scanner.py +291 -0
  20. codegraph/async_queue/traversal.py +447 -0
  21. codegraph/change_impact.py +320 -110
  22. codegraph/changelog.py +170 -0
  23. codegraph/cli.py +1605 -62
  24. codegraph/cli_output.py +17 -2
  25. codegraph/context.py +135 -24
  26. codegraph/context_freshness.py +2 -0
  27. codegraph/database/__init__.py +14 -0
  28. codegraph/database/extractor.py +712 -17
  29. codegraph/database/interrogation.py +388 -2
  30. codegraph/database/schema_drift.py +862 -0
  31. codegraph/dataflow_propagation.py +118 -0
  32. codegraph/dead_code.py +387 -0
  33. codegraph/epistemic.py +15 -0
  34. codegraph/evidence_contract.py +34 -3
  35. codegraph/federation.py +245 -0
  36. codegraph/frameworks.py +234 -12
  37. codegraph/frameworks_nestjs.py +502 -0
  38. codegraph/frameworks_nextjs.py +337 -0
  39. codegraph/frameworks_react.py +457 -0
  40. codegraph/freshness.py +2 -0
  41. codegraph/frontend_html.py +109 -0
  42. codegraph/git.py +2 -0
  43. codegraph/git_state.py +2 -0
  44. codegraph/graph/traversal.py +150 -7
  45. codegraph/graph_csr.py +218 -0
  46. codegraph/incremental.py +150 -0
  47. codegraph/indexing/__init__.py +7 -1
  48. codegraph/indexing/classifier.py +5 -0
  49. codegraph/indexing/indexer.py +292 -38
  50. codegraph/indexing/languages/__init__.py +1 -0
  51. codegraph/indexing/languages/cpp.py +457 -0
  52. codegraph/indexing/languages/go.py +459 -0
  53. codegraph/indexing/languages/jvm.py +583 -0
  54. codegraph/indexing/languages/rust.py +507 -0
  55. codegraph/indexing/models.py +15 -1
  56. codegraph/indexing/parser.py +385 -9
  57. codegraph/indexing/pool.py +136 -0
  58. codegraph/indexing/protocols.py +220 -0
  59. codegraph/indexing/scanner.py +23 -0
  60. codegraph/indexing/templates.py +418 -0
  61. codegraph/interrogation.py +207 -39
  62. codegraph/lsp.py +318 -0
  63. codegraph/lsp_bridge/__init__.py +16 -0
  64. codegraph/lsp_bridge/bridge.py +102 -0
  65. codegraph/lsp_bridge/client.py +207 -0
  66. codegraph/lsp_bridge/models.py +71 -0
  67. codegraph/mcp/server.py +502 -29
  68. codegraph/memory/trajectory.py +282 -0
  69. codegraph/models.py +7 -0
  70. codegraph/monorepo.py +3 -0
  71. codegraph/multi_agent/__init__.py +13 -0
  72. codegraph/multi_agent/coordinator.py +229 -0
  73. codegraph/multi_agent/models.py +76 -0
  74. codegraph/optimizer.py +42 -5
  75. codegraph/polymorphism.py +95 -0
  76. codegraph/pr_review.py +296 -0
  77. codegraph/process_lifecycle.py +50 -12
  78. codegraph/reachability.py +198 -0
  79. codegraph/reachability_index.py +74 -0
  80. codegraph/refactor/__init__.py +48 -0
  81. codegraph/refactor/models.py +114 -0
  82. codegraph/refactor/patcher.py +348 -0
  83. codegraph/refactor/renamer.py +844 -0
  84. codegraph/refactor/transactions.py +414 -0
  85. codegraph/repair.py +233 -0
  86. codegraph/resolver.py +1357 -161
  87. codegraph/retrieval_policy.py +22 -1
  88. codegraph/roblox.py +2174 -0
  89. codegraph/route_composer.py +7 -0
  90. codegraph/route_topology.py +172 -0
  91. codegraph/runtime/__init__.py +25 -0
  92. codegraph/runtime/collector.py +155 -0
  93. codegraph/runtime/db_watcher.py +191 -0
  94. codegraph/runtime/ingestor.py +30 -10
  95. codegraph/runtime/otel_receiver.py +208 -0
  96. codegraph/runtime/port_inspector.py +304 -0
  97. codegraph/runtime/runner.py +155 -6
  98. codegraph/runtime/trace_linker.py +175 -0
  99. codegraph/sandbox.py +215 -0
  100. codegraph/search/hybrid.py +26 -0
  101. codegraph/security/supply_chain.py +188 -0
  102. codegraph/security/taint.py +421 -0
  103. codegraph/semantic_decorators.py +34 -3
  104. codegraph/structural_diff.py +2 -0
  105. codegraph/styles.py +144 -0
  106. codegraph/symbol_history.py +2 -0
  107. codegraph/test_gen.py +437 -0
  108. codegraph/tsconfig.py +236 -0
  109. codegraph/ui/__init__.py +6 -0
  110. codegraph/ui/server.py +876 -0
  111. codegraph/watcher.py +323 -0
  112. {codegraph_engine-2.3.0.dist-info โ†’ codegraph_engine-3.0.1.dist-info}/METADATA +365 -67
  113. codegraph_engine-3.0.1.dist-info/RECORD +164 -0
  114. {codegraph_engine-2.3.0.dist-info โ†’ codegraph_engine-3.0.1.dist-info}/WHEEL +1 -1
  115. codegraph_engine-2.3.0.dist-info/RECORD +0 -94
  116. {codegraph_engine-2.3.0.dist-info โ†’ codegraph_engine-3.0.1.dist-info}/entry_points.txt +0 -0
  117. {codegraph_engine-2.3.0.dist-info โ†’ codegraph_engine-3.0.1.dist-info}/licenses/LICENSE +0 -0
  118. {codegraph_engine-2.3.0.dist-info โ†’ codegraph_engine-3.0.1.dist-info}/top_level.txt +0 -0
codegraph/optimizer.py CHANGED
@@ -41,7 +41,7 @@ _CONFIDENCE_RANK = {
41
41
 
42
42
  # Hard upper safety limits enforced even when omitted or exceeded
43
43
  HARD_MAX_TOKENS = 20_000
44
- HARD_MAX_FILES = 30
44
+ HARD_MAX_FILES = 40
45
45
  HARD_MAX_LINES = 1_500
46
46
  HARD_MAX_SYMBOLS = 50
47
47
  HARD_MAX_RELATIONSHIPS = 60
@@ -54,7 +54,7 @@ class ContextBudgetSpec:
54
54
  max_tokens: int = 20_000
55
55
  max_symbols: int = 25
56
56
  max_relationships: int = 30
57
- max_files: int = 15
57
+ max_files: int = 25
58
58
  max_lines: int = 500
59
59
  max_depth: int = 3
60
60
  max_package_depth: int = 2
@@ -94,7 +94,7 @@ class ContextBudget:
94
94
  tool_calls: int = 1
95
95
  max_symbols: int = 25
96
96
  max_relationships: int = 30
97
- max_files: int = 15
97
+ max_files: int = 25
98
98
  max_lines: int = 500
99
99
  max_depth: int = 3
100
100
  max_package_depth: int = 2
@@ -374,6 +374,17 @@ def compute_item_utility(
374
374
  dim_unseen = selected_dimensions is not None and dim not in selected_dimensions and dim != "GENERAL"
375
375
  coverage_factor = 1.3 if (layer_unseen or dim_unseen) else 1.0
376
376
 
377
+ # Priority boost for task-critical items over tangential ones
378
+ priority_dim_boost = 0.0
379
+ if dim == "TARGET" or item.relevance_score >= 0.80:
380
+ priority_dim_boost = 0.20
381
+ elif dim in ("ROUTE", "CALLER"):
382
+ priority_dim_boost = 0.12
383
+ elif dim == "CALLEE":
384
+ priority_dim_boost = 0.08
385
+ elif dim in ("TEST", "GIT", "PACKAGE", "GENERAL") and item.relevance_score < 0.50:
386
+ priority_dim_boost = -0.08
387
+
377
388
  # Redundancy penalty: heavily discount items sharing duplicate keys with already selected items
378
389
  redundancy_penalty = 0.5 if item.duplicate_key in selected_duplicate_keys else 0.0
379
390
 
@@ -384,6 +395,7 @@ def compute_item_utility(
384
395
  + (fresh_factor * 0.15)
385
396
  + (epistemic_factor * 0.10)
386
397
  + pkg_adj
398
+ + priority_dim_boost
387
399
  ) * coverage_factor
388
400
 
389
401
  final_score = max(0.01, utility - redundancy_penalty - conf_penalty - art_penalty - dist_penalty)
@@ -572,7 +584,7 @@ def optimize_context_budget(
572
584
  """Deterministically select the highest-utility, coverage-preserving subset of candidates."""
573
585
  raw_max_symbols = budget_spec.max_symbols if budget_spec else 25
574
586
  raw_max_relationships = budget_spec.max_relationships if budget_spec else 30
575
- raw_max_files = budget_spec.max_files if budget_spec else 15
587
+ raw_max_files = budget_spec.max_files if budget_spec else 25
576
588
  raw_max_lines = budget_spec.max_lines if budget_spec else 500
577
589
  max_depth = budget_spec.max_depth if budget_spec else 3
578
590
  max_package_depth = budget_spec.max_package_depth if budget_spec else 2
@@ -767,7 +779,32 @@ def optimize_context_budget(
767
779
  )
768
780
  break
769
781
 
770
- # Pass 1b: Architectural Layer Coverage pass โ€” ensure distinct layers
782
+ # Pass 1b: Task-Critical Candidates Priority pass โ€” ensure all direct targets,
783
+ # routes, and direct callers/callees are admitted into the file budget before
784
+ # tangential layer coverage files consume file slots.
785
+ for item in sorted_candidates:
786
+ if item in selected or _is_excluded(item, task_spec):
787
+ continue
788
+ if item.duplicate_key in selected_duplicate_keys:
789
+ continue
790
+ dim = item.infer_dimension()
791
+ is_task_critical = (
792
+ dim in ("TARGET", "ROUTE", "CALLER")
793
+ or item.relevance_score >= 0.70
794
+ or (dim == "CALLEE" and item.relevance_score >= 0.50)
795
+ )
796
+ if is_task_critical:
797
+ if _can_fit(item) or (dim == "TARGET" and len(selected) == 0 and _trim_to_fit(item)):
798
+ _accept(
799
+ item,
800
+ is_coverage_fill=False,
801
+ why=[
802
+ f"Task-critical priority candidate: dimension '{dim}'",
803
+ f"Relevance: {item.relevance_score:.2f}, Evidence: {item.evidence_quality:.2f}",
804
+ ],
805
+ )
806
+
807
+ # Pass 1c: Architectural Layer Coverage pass โ€” ensure distinct layers
771
808
  # (e.g. ENTRYPOINT, SERVICE, DATA, TEST, GIT) get represented if candidates exist
772
809
  for item in sorted_candidates:
773
810
  if item in selected or _is_excluded(item, task_spec):
@@ -0,0 +1,95 @@
1
+ """Polymorphic Trait & Interface Dynamic Dispatch Resolver for CodeGraph.
2
+
3
+ Resolves abstract interface and trait invocations to concrete implementing classes:
4
+ - Resolves Java/Kotlin interface methods (e.g. PaymentGateway.charge() -> StripeGateway.charge(), PayPalGateway.charge())
5
+ - Resolves Rust trait implementations (e.g. Handler::call -> AuthHandler::call)
6
+ - Resolves Go interface method dispatch via structural matching
7
+ - Resolves C++ pure virtual method overrides
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import sqlite3
12
+ from dataclasses import asdict, dataclass, field
13
+ from typing import Any
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class ConcreteMethodTarget:
18
+ """A concrete class or struct implementing an abstract interface method."""
19
+
20
+ implementing_class: str
21
+ method_canonical_id: str
22
+ file_path: str
23
+ line: int
24
+ relationship: str = "IMPLEMENTS"
25
+ evidence_class: str = "AST_VERIFIED"
26
+
27
+ def as_dict(self) -> dict[str, Any]:
28
+ return asdict(self)
29
+
30
+
31
+ @dataclass
32
+ class PolymorphicResolutionReport:
33
+ """Report resolving an abstract interface call to all concrete implementers."""
34
+
35
+ interface_symbol: str
36
+ method_name: str
37
+ total_implementations: int
38
+ implementations: list[ConcreteMethodTarget] = field(default_factory=list)
39
+
40
+ def as_dict(self) -> dict[str, Any]:
41
+ return {
42
+ "interface_symbol": self.interface_symbol,
43
+ "method_name": self.method_name,
44
+ "total_implementations": self.total_implementations,
45
+ "implementations": [i.as_dict() for i in self.implementations],
46
+ }
47
+
48
+
49
+ def resolve_polymorphic_callees(
50
+ con: sqlite3.Connection,
51
+ interface_symbol: str,
52
+ method_name: str,
53
+ ) -> PolymorphicResolutionReport:
54
+ """Resolve an interface/trait method to all concrete implementations in the workspace."""
55
+ cur = con.cursor()
56
+
57
+ # 1. Find all classes that inherit or implement interface_symbol
58
+ cur.execute("""
59
+ SELECT source_symbol, source_canonical_id, source_file, line
60
+ FROM inheritance
61
+ WHERE base_name = ? OR base_name LIKE ?;
62
+ """, (interface_symbol, f"%{interface_symbol}"))
63
+ implementing_types = cur.fetchall()
64
+
65
+ targets: list[ConcreteMethodTarget] = []
66
+
67
+ for sub_name, _sub_cid, sub_file, _ in implementing_types:
68
+ # 2. Look for the method on the implementing type
69
+ expected_method_qname = f"{sub_name}.{method_name}"
70
+ cur.execute("""
71
+ SELECT canonical_id, path, start_line
72
+ FROM symbols
73
+ WHERE (name = ? OR qualified_name = ?) AND (path = ? OR 1=1)
74
+ LIMIT 1;
75
+ """, (method_name, expected_method_qname, sub_file))
76
+ m_row = cur.fetchone()
77
+
78
+ if m_row:
79
+ targets.append(
80
+ ConcreteMethodTarget(
81
+ implementing_class=sub_name,
82
+ method_canonical_id=str(m_row[0]),
83
+ file_path=str(m_row[1]),
84
+ line=int(m_row[2]),
85
+ relationship="IMPLEMENTS",
86
+ evidence_class="AST_VERIFIED",
87
+ )
88
+ )
89
+
90
+ return PolymorphicResolutionReport(
91
+ interface_symbol=interface_symbol,
92
+ method_name=method_name,
93
+ total_implementations=len(targets),
94
+ implementations=targets,
95
+ )
codegraph/pr_review.py ADDED
@@ -0,0 +1,296 @@
1
+ """Native Pull Request Review & Semantic Blast-Radius Auditor for CodeGraph.
2
+
3
+ Performs deep structural AST diffs, caller contract verification, affected HTTP route
4
+ detection, database schema impact analysis, and test coverage gap identification to generate
5
+ an actionable, high-density PR review report for CI/CD pipelines (GitHub Actions, GitLab CI).
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import sqlite3
10
+ from dataclasses import dataclass, field
11
+ from enum import StrEnum
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from codegraph.change_impact import get_deep_change_impact
16
+ from codegraph.semantic_conflicts import detect_semantic_conflicts
17
+ from codegraph.structural_diff import compare_branches
18
+
19
+
20
+ class ReviewSeverity(StrEnum):
21
+ CRITICAL = "CRITICAL"
22
+ HIGH = "HIGH"
23
+ MEDIUM = "MEDIUM"
24
+ LOW = "LOW"
25
+ INFO = "INFO"
26
+
27
+
28
+ @dataclass
29
+ class ReviewFinding:
30
+ severity: ReviewSeverity
31
+ category: str
32
+ title: str
33
+ description: str
34
+ file_path: str
35
+ line: int | None = None
36
+ recommendation: str = ""
37
+
38
+ def as_dict(self) -> dict[str, Any]:
39
+ return {
40
+ "severity": self.severity.value,
41
+ "category": self.category,
42
+ "title": self.title,
43
+ "description": self.description,
44
+ "file_path": self.file_path,
45
+ "line": self.line,
46
+ "recommendation": self.recommendation,
47
+ }
48
+
49
+
50
+ @dataclass
51
+ class PRReviewReport:
52
+ base_ref: str
53
+ head_ref: str
54
+ verdict: str # APPROVE, COMMENT, REQUEST_CHANGES
55
+ summary: str
56
+ findings: list[ReviewFinding] = field(default_factory=list)
57
+ files_changed: list[str] = field(default_factory=list)
58
+ symbols_added: int = 0
59
+ symbols_modified: int = 0
60
+ symbols_removed: int = 0
61
+ affected_routes: list[dict[str, Any]] = field(default_factory=list)
62
+ affected_tests: list[str] = field(default_factory=list)
63
+ suggested_test_command: str = ""
64
+ markdown_report: str = ""
65
+
66
+ def as_dict(self) -> dict[str, Any]:
67
+ return {
68
+ "base_ref": self.base_ref,
69
+ "head_ref": self.head_ref,
70
+ "verdict": self.verdict,
71
+ "summary": self.summary,
72
+ "findings": [f.as_dict() for f in self.findings],
73
+ "files_changed": self.files_changed,
74
+ "symbols_added": self.symbols_added,
75
+ "symbols_modified": self.symbols_modified,
76
+ "symbols_removed": self.symbols_removed,
77
+ "affected_routes": self.affected_routes,
78
+ "affected_tests": self.affected_tests,
79
+ "suggested_test_command": self.suggested_test_command,
80
+ "markdown_report": self.markdown_report,
81
+ }
82
+
83
+
84
+ def generate_pr_review(
85
+ repository: Path,
86
+ base_ref: str = "main",
87
+ head_ref: str = "HEAD",
88
+ con: sqlite3.Connection | None = None,
89
+ ) -> PRReviewReport:
90
+ """Generate a comprehensive semantic PR review evaluating structural diffs, contract breaks, and tests."""
91
+ repo = repository.resolve()
92
+
93
+ # 1. Structural AST Diff
94
+ diff_report = compare_branches(repo, base_branch=base_ref, head_branch=head_ref, con=con)
95
+
96
+ # 2. Semantic Conflict & Contract Break Analysis
97
+ conflicts_report = detect_semantic_conflicts(repo, base_branch=base_ref, head_branch=head_ref, con=con)
98
+
99
+ # 3. Deep Change Impact Analysis
100
+ files_changed = sorted(
101
+ set(diff_report.added_files + diff_report.modified_files + diff_report.deleted_files)
102
+ )
103
+ impact_report = None
104
+ if files_changed and con is not None:
105
+ try:
106
+ impact_report = get_deep_change_impact(repo, con, base=base_ref, head=head_ref)
107
+ except Exception:
108
+ impact_report = None
109
+
110
+ # 4. Synthesize Findings
111
+ findings: list[ReviewFinding] = []
112
+
113
+ # Map semantic contract breaks
114
+ for conf in conflicts_report.conflicts:
115
+ sev = ReviewSeverity.CRITICAL if conf.severity == "CRITICAL" else ReviewSeverity.HIGH
116
+ findings.append(
117
+ ReviewFinding(
118
+ severity=sev,
119
+ category="CONTRACT_BREAK",
120
+ title=f"Semantic Contract Break: {conf.symbol}",
121
+ description=conf.description,
122
+ file_path=conf.head_file or conf.base_file,
123
+ line=conf.line,
124
+ recommendation="Update consuming call sites or maintain backward-compatible argument signatures.",
125
+ )
126
+ )
127
+
128
+ # Map removed symbols without replacement
129
+ for sym in diff_report.removed_symbols:
130
+ findings.append(
131
+ ReviewFinding(
132
+ severity=ReviewSeverity.HIGH,
133
+ category="DELETED_SYMBOL",
134
+ title=f"Deleted Symbol: {sym.name}",
135
+ description=f"{sym.kind} '{sym.name}' was removed from {sym.path}.",
136
+ file_path=sym.path,
137
+ line=sym.new_line or sym.old_line,
138
+ recommendation="Verify that no external packages or unindexed scripts rely on this symbol.",
139
+ )
140
+ )
141
+
142
+ # Map modified routes & missing test coverage
143
+ affected_routes_list: list[dict[str, Any]] = []
144
+ for r in diff_report.changed_routes:
145
+ affected_routes_list.append(r.as_dict())
146
+
147
+ if impact_report:
148
+ for r_item in impact_report.affected_routes:
149
+ r_dict = r_item.as_dict()
150
+ if r_dict not in affected_routes_list:
151
+ affected_routes_list.append(r_dict)
152
+
153
+ # Test coverage gap analysis: Check if modified routes have tests
154
+ covered_test_paths = set(diff_report.affected_tests)
155
+ if impact_report:
156
+ covered_test_paths.update(t.file for t in impact_report.affected_tests)
157
+
158
+ if affected_routes_list and not covered_test_paths:
159
+ findings.append(
160
+ ReviewFinding(
161
+ severity=ReviewSeverity.HIGH,
162
+ category="TEST_GAP",
163
+ title="Uncovered Route Modifications",
164
+ description=f"{len(affected_routes_list)} HTTP route(s) were added or modified without any associated test coverage.",
165
+ file_path=str(affected_routes_list[0].get("file_path") or "routes"),
166
+ recommendation="Add integration tests exercising the modified HTTP endpoints.",
167
+ )
168
+ )
169
+
170
+ # Verdict calculation
171
+ has_critical = any(f.severity == ReviewSeverity.CRITICAL for f in findings)
172
+ has_high = any(f.severity == ReviewSeverity.HIGH for f in findings)
173
+
174
+ if has_critical:
175
+ verdict = "REQUEST_CHANGES"
176
+ summary = f"Blocked: {len([f for f in findings if f.severity == ReviewSeverity.CRITICAL])} critical contract break(s) detected."
177
+ elif has_high:
178
+ verdict = "COMMENT"
179
+ summary = f"Caution: {len([f for f in findings if f.severity == ReviewSeverity.HIGH])} high-priority finding(s) require verification."
180
+ else:
181
+ verdict = "APPROVE"
182
+ summary = "Clean: No semantic contract breaks or uncovered route regressions detected."
183
+
184
+ # Build suggested test command
185
+ suggested_test_cmd = ""
186
+ if impact_report and impact_report.recommended_test_command:
187
+ suggested_test_cmd = impact_report.recommended_test_command
188
+ elif covered_test_paths:
189
+ suggested_test_cmd = f"pytest {' '.join(sorted(covered_test_paths)[:10])}"
190
+
191
+ # Build High-Density GitHub PR Markdown
192
+ markdown = _format_pr_markdown(
193
+ base_ref=base_ref,
194
+ head_ref=head_ref,
195
+ verdict=verdict,
196
+ summary=summary,
197
+ findings=findings,
198
+ files_changed=files_changed,
199
+ symbols_added=len(diff_report.added_symbols),
200
+ symbols_modified=len(diff_report.changed_symbols),
201
+ symbols_removed=len(diff_report.removed_symbols),
202
+ affected_routes=affected_routes_list,
203
+ affected_tests=sorted(covered_test_paths),
204
+ suggested_test_command=suggested_test_cmd,
205
+ )
206
+
207
+ return PRReviewReport(
208
+ base_ref=base_ref,
209
+ head_ref=head_ref,
210
+ verdict=verdict,
211
+ summary=summary,
212
+ findings=findings,
213
+ files_changed=files_changed,
214
+ symbols_added=len(diff_report.added_symbols),
215
+ symbols_modified=len(diff_report.changed_symbols),
216
+ symbols_removed=len(diff_report.removed_symbols),
217
+ affected_routes=affected_routes_list,
218
+ affected_tests=sorted(covered_test_paths),
219
+ suggested_test_command=suggested_test_cmd,
220
+ markdown_report=markdown,
221
+ )
222
+
223
+
224
+ def _format_pr_markdown(
225
+ base_ref: str,
226
+ head_ref: str,
227
+ verdict: str,
228
+ summary: str,
229
+ findings: list[ReviewFinding],
230
+ files_changed: list[str],
231
+ symbols_added: int,
232
+ symbols_modified: int,
233
+ symbols_removed: int,
234
+ affected_routes: list[dict[str, Any]],
235
+ affected_tests: list[str],
236
+ suggested_test_command: str,
237
+ ) -> str:
238
+ """Format markdown for GitHub PR review comment."""
239
+ verdict_badge = {
240
+ "APPROVE": "๐ŸŸข **APPROVED**",
241
+ "COMMENT": "๐ŸŸก **CAUTION / COMMENT**",
242
+ "REQUEST_CHANGES": "๐Ÿ”ด **CHANGES REQUESTED**",
243
+ }.get(verdict, verdict)
244
+
245
+ lines: list[str] = [
246
+ "## ๐Ÿ” CodeGraph Semantic PR Review",
247
+ "",
248
+ f"**Verdict**: {verdict_badge} &mdash; {summary}",
249
+ f"**Revisions**: `{base_ref}` &rarr; `{head_ref}`",
250
+ "",
251
+ "### ๐Ÿ“Š Blast-Radius & AST Metrics",
252
+ "",
253
+ "| Files Changed | Symbols Added | Symbols Modified | Symbols Removed | Affected Routes | Covered Tests |",
254
+ "| :---: | :---: | :---: | :---: | :---: | :---: |",
255
+ f"| {len(files_changed)} | {symbols_added} | {symbols_modified} | {symbols_removed} | {len(affected_routes)} | {len(affected_tests)} |",
256
+ "",
257
+ ]
258
+
259
+ if findings:
260
+ lines.append("### โš ๏ธ Key Findings")
261
+ lines.append("")
262
+ for f in findings:
263
+ badge = "๐Ÿ”ด" if f.severity == ReviewSeverity.CRITICAL else ("๐ŸŸ " if f.severity == ReviewSeverity.HIGH else "๐Ÿ”ต")
264
+ loc = f"`{f.file_path}:{f.line}`" if f.line else f"`{f.file_path}`"
265
+ lines.append(f"- {badge} **[{f.severity.value}] {f.title}** ({loc})")
266
+ lines.append(f" {f.description}")
267
+ if f.recommendation:
268
+ lines.append(f" *Recommendation*: {f.recommendation}")
269
+ lines.append("")
270
+
271
+ if affected_routes:
272
+ lines.append("<details><summary><b>๐ŸŒ Affected HTTP Routes (" + str(len(affected_routes)) + ")</b></summary>")
273
+ lines.append("")
274
+ lines.append("| Method | Path | Handler | File |")
275
+ lines.append("| :--- | :--- | :--- | :--- |")
276
+ for r in affected_routes[:20]:
277
+ m = r.get("method") or r.get("http_method") or "ANY"
278
+ p = r.get("path") or r.get("route_path") or "-"
279
+ h = r.get("handler") or r.get("handler_name") or "-"
280
+ f_path = r.get("file_path") or "-"
281
+ lines.append(f"| `{m}` | `{p}` | `{h}` | `{f_path}` |")
282
+ lines.append("")
283
+ lines.append("</details>")
284
+ lines.append("")
285
+
286
+ if suggested_test_command:
287
+ lines.append("### ๐Ÿงช Recommended Targeted Test Suite")
288
+ lines.append("```bash")
289
+ lines.append(suggested_test_command)
290
+ lines.append("```")
291
+ lines.append("")
292
+
293
+ lines.append("---")
294
+ lines.append("*Generated by [CodeGraph MCP](https://github.com/raghurammrsd/CODE_GRAPH_MCP) &bull; Deterministic Repository Intelligence*")
295
+
296
+ return "\n".join(lines)
@@ -316,6 +316,16 @@ def _win32_inspect_process(pid: int) -> LiveProcessInfo | None:
316
316
  access = 0x00100000 | 0x00001000
317
317
  handle = kernel32.OpenProcess(access, False, int(pid))
318
318
  if not handle:
319
+ err = kernel32.GetLastError()
320
+ if err == 5: # ERROR_ACCESS_DENIED: process exists and is active
321
+ return LiveProcessInfo(
322
+ pid=pid,
323
+ ppid=0,
324
+ create_token="access_denied",
325
+ executable="python",
326
+ command_summary="python",
327
+ is_zombie=False,
328
+ )
319
329
  return None
320
330
  try:
321
331
  exit_code = ctypes.c_ulong(0)
@@ -541,16 +551,38 @@ def is_parent_alive(
541
551
  ) -> bool:
542
552
  """Return True if the parent process `parent_pid` is still alive and owns this child."""
543
553
  if parent_pid <= 1:
544
- return False
554
+ # PID 0 and 1 represent init / systemd / launchd / container root; always considered alive
555
+ return True
545
556
 
546
- if sys.platform != "win32":
547
- actual_ppid = current_ppid if current_ppid is not None else os.getppid()
548
- if actual_ppid != parent_pid:
549
- # Reparented to PID 1 / launchd / systemd --user
557
+ # On Windows, os.kill(pid, 0) is not supported and raises WinError 87.
558
+ # Use native kernel32 inspection via get_live_process_info.
559
+ if sys.platform == "win32":
560
+ live = get_live_process_info(parent_pid)
561
+ if live is None:
562
+ return False
563
+ if live.is_zombie:
564
+ return False
565
+ if parent_create_token and live.create_token and live.create_token != parent_create_token:
550
566
  return False
567
+ return True
568
+
569
+ # 1. Direct probe whether parent PID exists via os.kill(pid, 0)
570
+ try:
571
+ os.kill(parent_pid, 0)
572
+ except ProcessLookupError:
573
+ # ESRCH: Process does not exist; parent is definitely dead
574
+ return False
575
+ except PermissionError:
576
+ # EPERM: Process exists, but caller lacks permissions to signal it (e.g. sandbox/different user)
577
+ return True
578
+ except OSError:
579
+ # Other OS error: safe fallback is alive
580
+ return True
551
581
 
552
582
  live = get_live_process_info(parent_pid)
553
- if live is None or live.is_zombie:
583
+ if live is None:
584
+ return True
585
+ if live.is_zombie:
554
586
  return False
555
587
 
556
588
  if parent_create_token and live.create_token and live.create_token != parent_create_token:
@@ -964,16 +996,22 @@ class MCPLifecycleController:
964
996
 
965
997
  def _watchdog_loop(self) -> None:
966
998
  """Low-overhead event-backed watchdog detecting parent termination or closed stdin."""
999
+ disable_parent_watchdog = (
1000
+ os.environ.get("CODEGRAPH_DISABLE_PARENT_WATCHDOG", "").strip().lower()
1001
+ in ("1", "true", "yes")
1002
+ or self.record.parent_pid <= 1
1003
+ )
967
1004
  while not self._stop_event.wait(timeout=self.poll_interval_sec):
968
1005
  if _is_stream_closed_or_eof(sys.stdin):
969
1006
  self.shutdown("stdin_closed")
970
1007
  return
971
- if not is_parent_alive(
972
- self.record.parent_pid,
973
- self.record.parent_create_token,
974
- ):
975
- self.shutdown("parent_process_terminated")
976
- return
1008
+ if not disable_parent_watchdog:
1009
+ if not is_parent_alive(
1010
+ self.record.parent_pid,
1011
+ self.record.parent_create_token,
1012
+ ):
1013
+ self.shutdown("parent_process_terminated")
1014
+ return
977
1015
 
978
1016
  def _atexit_cleanup(self) -> None:
979
1017
  self.shutdown("atexit")