repodna-engine 1.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 (173) hide show
  1. repodna/__init__.py +3 -0
  2. repodna/__main__.py +10 -0
  3. repodna/advisor/__init__.py +17 -0
  4. repodna/advisor/engine.py +502 -0
  5. repodna/advisor/models.py +101 -0
  6. repodna/agent/__init__.py +87 -0
  7. repodna/agent/context.py +558 -0
  8. repodna/agent/deltas.py +198 -0
  9. repodna/agent/evidence.py +134 -0
  10. repodna/agent/expansion.py +447 -0
  11. repodna/agent/localization.py +518 -0
  12. repodna/agent/models.py +695 -0
  13. repodna/agent/patch.py +378 -0
  14. repodna/agent/postflight.py +278 -0
  15. repodna/agent/preflight.py +336 -0
  16. repodna/agent/ranking.py +318 -0
  17. repodna/agent/repo_map.py +392 -0
  18. repodna/agent/safety.py +111 -0
  19. repodna/agent/service.py +574 -0
  20. repodna/agent/sessions.py +264 -0
  21. repodna/agent/task.py +660 -0
  22. repodna/agent/telemetry.py +101 -0
  23. repodna/agent/token_budget.py +231 -0
  24. repodna/api/__init__.py +1 -0
  25. repodna/api/agent_routes.py +248 -0
  26. repodna/api/app.py +2904 -0
  27. repodna/benchmarks/__init__.py +29 -0
  28. repodna/benchmarks/baselines.py +126 -0
  29. repodna/benchmarks/budget_bench.py +162 -0
  30. repodna/benchmarks/engine.py +418 -0
  31. repodna/benchmarks/evaluator.py +310 -0
  32. repodna/benchmarks/metrics.py +206 -0
  33. repodna/benchmarks/models.py +194 -0
  34. repodna/benchmarks/scalability.py +166 -0
  35. repodna/brain/__init__.py +46 -0
  36. repodna/brain/evidence.py +276 -0
  37. repodna/brain/extractor.py +1207 -0
  38. repodna/brain/indexer.py +766 -0
  39. repodna/brain/models.py +275 -0
  40. repodna/brain/multilang_extractors.py +889 -0
  41. repodna/brain/retrieval.py +469 -0
  42. repodna/brain/tracer.py +203 -0
  43. repodna/cli/__init__.py +1 -0
  44. repodna/cli/__main__.py +10 -0
  45. repodna/cli/agent_cmd.py +228 -0
  46. repodna/cli/installer.py +590 -0
  47. repodna/cli/main.py +2173 -0
  48. repodna/cli/plugin_cmd.py +130 -0
  49. repodna/cli/workspace_cmd.py +211 -0
  50. repodna/context/__init__.py +9 -0
  51. repodna/context/builder.py +379 -0
  52. repodna/context/models.py +133 -0
  53. repodna/contract/__init__.py +39 -0
  54. repodna/contract/evaluator.py +318 -0
  55. repodna/contract/loader.py +260 -0
  56. repodna/contract/models.py +185 -0
  57. repodna/core/__init__.py +1 -0
  58. repodna/core/analyzer.py +1424 -0
  59. repodna/diff/__init__.py +35 -0
  60. repodna/diff/engine.py +332 -0
  61. repodna/diff/models.py +117 -0
  62. repodna/diff/snapshot.py +248 -0
  63. repodna/ecosystem/__init__.py +27 -0
  64. repodna/ecosystem/contracts.py +129 -0
  65. repodna/ecosystem/doctor.py +253 -0
  66. repodna/git_insights/__init__.py +1 -0
  67. repodna/git_insights/analyzer.py +273 -0
  68. repodna/graph/__init__.py +1 -0
  69. repodna/graph/engine.py +562 -0
  70. repodna/guardian/__init__.py +17 -0
  71. repodna/guardian/engine.py +369 -0
  72. repodna/guardian/models.py +104 -0
  73. repodna/history/__init__.py +40 -0
  74. repodna/history/cache.py +240 -0
  75. repodna/history/diff.py +394 -0
  76. repodna/history/engine.py +557 -0
  77. repodna/history/evidence.py +160 -0
  78. repodna/history/models.py +258 -0
  79. repodna/history/timeline.py +164 -0
  80. repodna/intelligence/__init__.py +33 -0
  81. repodna/intelligence/models.py +165 -0
  82. repodna/intelligence/service.py +570 -0
  83. repodna/live/__init__.py +94 -0
  84. repodna/live/alerts.py +443 -0
  85. repodna/live/coordinator.py +351 -0
  86. repodna/live/diff.py +444 -0
  87. repodna/live/events.py +471 -0
  88. repodna/live/filtering.py +329 -0
  89. repodna/live/history.py +637 -0
  90. repodna/live/models.py +505 -0
  91. repodna/live/observer.py +653 -0
  92. repodna/live/reconciliation.py +253 -0
  93. repodna/live/session.py +1547 -0
  94. repodna/mcp/__init__.py +5 -0
  95. repodna/mcp/__main__.py +6 -0
  96. repodna/mcp/agent_tools.py +258 -0
  97. repodna/mcp/server.py +3283 -0
  98. repodna/mcp/workspace_tools.py +200 -0
  99. repodna/parsers/__init__.py +13 -0
  100. repodna/parsers/base.py +126 -0
  101. repodna/parsers/capabilities.py +361 -0
  102. repodna/parsers/project_metadata.py +232 -0
  103. repodna/parsers/resolver.py +621 -0
  104. repodna/parsers/treesitter_parser.py +830 -0
  105. repodna/passport/__init__.py +64 -0
  106. repodna/passport/generator.py +546 -0
  107. repodna/passport/migrator.py +139 -0
  108. repodna/passport/models.py +224 -0
  109. repodna/passport/validator.py +143 -0
  110. repodna/performance/__init__.py +89 -0
  111. repodna/performance/cache.py +1584 -0
  112. repodna/performance/identity.py +341 -0
  113. repodna/performance/incremental.py +317 -0
  114. repodna/performance/models.py +157 -0
  115. repodna/performance/parallel.py +291 -0
  116. repodna/plugins/__init__.py +47 -0
  117. repodna/plugins/evaluator.py +334 -0
  118. repodna/plugins/models.py +113 -0
  119. repodna/plugins/validator.py +256 -0
  120. repodna/quality/__init__.py +91 -0
  121. repodna/quality/complexity.py +352 -0
  122. repodna/quality/config.py +159 -0
  123. repodna/quality/debt.py +73 -0
  124. repodna/quality/duplicates.py +330 -0
  125. repodna/quality/engine.py +282 -0
  126. repodna/quality/impact.py +198 -0
  127. repodna/quality/models.py +427 -0
  128. repodna/quality/rules.py +364 -0
  129. repodna/quality/sarif.py +107 -0
  130. repodna/quality/security_signals.py +278 -0
  131. repodna/quality/test_mapping.py +271 -0
  132. repodna/quality/unused.py +201 -0
  133. repodna/reports/__init__.py +1 -0
  134. repodna/reports/exporter.py +374 -0
  135. repodna/rules/__init__.py +1 -0
  136. repodna/rules/health.py +436 -0
  137. repodna/schemas/__init__.py +1 -0
  138. repodna/schemas/models.py +348 -0
  139. repodna/security/__init__.py +1 -0
  140. repodna/security/safe_yaml.py +81 -0
  141. repodna/security/validators.py +583 -0
  142. repodna/skills/__init__.py +0 -0
  143. repodna/skills/repodna/SKILL.md +59 -0
  144. repodna/skills/repodna/__init__.py +0 -0
  145. repodna/skills/repodna/examples/workflows.md +85 -0
  146. repodna/skills/repodna/references/architecture-rules.md +26 -0
  147. repodna/storage/__init__.py +1 -0
  148. repodna/storage/workspace.py +199 -0
  149. repodna/webui/__init__.py +1 -0
  150. repodna/webui/assets/DependencyGraph-km_Qo-nG.js +43 -0
  151. repodna/webui/assets/HealthReportView-WVL39aNO.js +1 -0
  152. repodna/webui/assets/index-ByZ5e5pe.js +506 -0
  153. repodna/webui/assets/index-CDj3e8hw.css +1 -0
  154. repodna/webui/index.html +21 -0
  155. repodna/workspace/__init__.py +131 -0
  156. repodna/workspace/compatibility.py +317 -0
  157. repodna/workspace/context.py +175 -0
  158. repodna/workspace/contracts.py +369 -0
  159. repodna/workspace/federation.py +411 -0
  160. repodna/workspace/identity.py +202 -0
  161. repodna/workspace/impact.py +111 -0
  162. repodna/workspace/manifest.py +266 -0
  163. repodna/workspace/models.py +461 -0
  164. repodna/workspace/packages.py +494 -0
  165. repodna/workspace/policies.py +142 -0
  166. repodna/workspace/services.py +238 -0
  167. repodna/workspace/topology.py +316 -0
  168. repodna_engine-1.0.1.dist-info/METADATA +129 -0
  169. repodna_engine-1.0.1.dist-info/RECORD +173 -0
  170. repodna_engine-1.0.1.dist-info/WHEEL +5 -0
  171. repodna_engine-1.0.1.dist-info/entry_points.txt +2 -0
  172. repodna_engine-1.0.1.dist-info/licenses/LICENSE +21 -0
  173. repodna_engine-1.0.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,329 @@
1
+ """Repository boundary enforcement, ignore filtering, and self-event prevention for live watching."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+
9
+ import pathspec
10
+
11
+ from repodna.core.analyzer import BINARY_EXTENSIONS, IGNORED_DIRS, IGNORED_LOCKFILES
12
+ from repodna.performance.identity import (
13
+ RESOLVER_CONFIG_FILENAMES,
14
+ WORKSPACE_CONFIG_RELATIVE_PATHS,
15
+ get_default_cache_dir,
16
+ )
17
+ from repodna.security.validators import is_safe_subpath
18
+
19
+ # IDE temporary / swap / atomic-save scratch patterns
20
+ _TEMP_FILE_SUFFIXES = (
21
+ ".swp",
22
+ ".swo",
23
+ ".swx",
24
+ ".tmp",
25
+ ".temp",
26
+ ".bak",
27
+ ".orig",
28
+ ".part",
29
+ ".crdownload",
30
+ "~",
31
+ )
32
+ _TEMP_FILE_PREFIXES = (".#", "#")
33
+
34
+ # RepoDNA internal generated artifacts that MUST NEVER trigger self-event loops
35
+ _REPODNA_INTERNAL_PREFIXES = (
36
+ ".repodna/history_cache",
37
+ ".repodna/live",
38
+ ".repodna/cache",
39
+ ".repodna_tmp",
40
+ )
41
+ _REPODNA_GENERATED_FILES = frozenset(
42
+ {
43
+ ".repodna/passport.json",
44
+ ".repodna/passport.md",
45
+ ".repodna/baseline.json",
46
+ }
47
+ )
48
+
49
+ # Targeted Git metadata files whose change indicates revision/branch/index state changes
50
+ _GIT_STATE_FILES = frozenset(
51
+ {
52
+ "HEAD",
53
+ "index",
54
+ "packed-refs",
55
+ "MERGE_HEAD",
56
+ "REBASE_HEAD",
57
+ "CHERRY_PICK_HEAD",
58
+ "FETCH_HEAD",
59
+ "commondir",
60
+ }
61
+ )
62
+
63
+ _WORKSPACE_CONFIG_SET = frozenset(p.lower() for p in WORKSPACE_CONFIG_RELATIVE_PATHS)
64
+
65
+
66
+ @dataclass(frozen=True)
67
+ class PathClassification:
68
+ """Result of validating and classifying a raw filesystem path against workspace policy."""
69
+
70
+ accepted: bool
71
+ rel_posix: str = ""
72
+ reason: str = "accepted"
73
+ is_config: bool = False
74
+ is_git_metadata: bool = False
75
+ is_ignore_file: bool = False
76
+
77
+
78
+ class LivePathFilter:
79
+ """
80
+ Validates raw watcher paths against strict repository boundary containment,
81
+ symlinks/junctions, RepoDNA self-event loops, IDE temporary files, and
82
+ repository ignore rules (`.gitignore`, `.repodnaignore`, and core analyzer rules).
83
+ """
84
+
85
+ def __init__(self, root_path: Path, extra_ignore_dirs: set[Path] | None = None) -> None:
86
+ self.root_resolved = root_path.resolve(strict=True)
87
+ self._cache_dir = get_default_cache_dir().resolve()
88
+ self._extra_ignore_dirs: list[Path] = [self._cache_dir]
89
+ if extra_ignore_dirs:
90
+ for d in extra_ignore_dirs:
91
+ try:
92
+ self._extra_ignore_dirs.append(d.resolve())
93
+ except OSError:
94
+ continue
95
+ self._git_dir: Path | None = self._resolve_git_dir(self.root_resolved)
96
+ self._ignore_spec: pathspec.PathSpec | None = None
97
+ self.reload_ignore_rules()
98
+
99
+ @property
100
+ def git_dir(self) -> Path | None:
101
+ return self._git_dir
102
+
103
+ @staticmethod
104
+ def _resolve_git_dir(root_resolved: Path) -> Path | None:
105
+ """Resolve `.git` directory or Git worktree `.git` pointer file safely without executing git."""
106
+ dot_git = root_resolved / ".git"
107
+ if not dot_git.exists():
108
+ return None
109
+ try:
110
+ if dot_git.is_dir() and not dot_git.is_symlink():
111
+ return dot_git.resolve()
112
+ if dot_git.is_file() and not dot_git.is_symlink():
113
+ raw = dot_git.read_text(encoding="utf-8", errors="replace").strip()
114
+ if raw.lower().startswith("gitdir:"):
115
+ target = raw.split(":", 1)[1].strip()
116
+ p = Path(target)
117
+ if not p.is_absolute():
118
+ p = (root_resolved / p).resolve()
119
+ else:
120
+ p = p.resolve()
121
+ if p.exists() and p.is_dir():
122
+ return p
123
+ except OSError:
124
+ return None
125
+ return None
126
+
127
+ def reload_ignore_rules(self) -> None:
128
+ """Load `.gitignore` and `.repodnaignore` patterns from workspace root safely."""
129
+ lines: list[str] = []
130
+ for fname in (".gitignore", ".repodnaignore"):
131
+ candidate = self.root_resolved / fname
132
+ try:
133
+ if candidate.is_symlink() or not candidate.is_file():
134
+ continue
135
+ if not is_safe_subpath(self.root_resolved, candidate):
136
+ continue
137
+ st = candidate.stat(follow_symlinks=False)
138
+ if st.st_size > 512 * 1024:
139
+ continue
140
+ text = candidate.read_text(encoding="utf-8", errors="replace")
141
+ for line in text.splitlines():
142
+ stripped = line.strip()
143
+ if stripped and not stripped.startswith("#"):
144
+ lines.append(stripped)
145
+ except OSError:
146
+ continue
147
+ self._ignore_spec = pathspec.PathSpec.from_lines("gitignore", lines) if lines else None
148
+
149
+ def is_in_excluded_external_dir(self, path: Path) -> bool:
150
+ """Prevent self-events from RepoDNA cache or external artifact directories."""
151
+ try:
152
+ resolved = path.resolve(strict=False)
153
+ except OSError:
154
+ return True
155
+ for ext in self._extra_ignore_dirs:
156
+ try:
157
+ if resolved == ext or resolved.is_relative_to(ext):
158
+ return True
159
+ except (ValueError, OSError):
160
+ continue
161
+ return False
162
+
163
+ def is_temp_or_editor_scratch(self, filename: str) -> bool:
164
+ """Return True for transient IDE/editor swap or scratch filenames."""
165
+ lower = filename.lower()
166
+ if lower.startswith(_TEMP_FILE_PREFIXES) or lower.endswith(_TEMP_FILE_SUFFIXES):
167
+ return True
168
+ if ".___jb_" in lower:
169
+ return True
170
+ # VS Code / Antigravity atomic save temp files like `file.py.tmp.1234` or `.file.py.swp`
171
+ if ".tmp." in lower or (lower.startswith(".") and lower.endswith(".swp")):
172
+ return True
173
+ if lower.endswith((".log", ".pid", ".lck")):
174
+ return True
175
+ return False
176
+
177
+ def classify_git_metadata_path(self, raw_path: Path) -> PathClassification | None:
178
+ """
179
+ Check if `raw_path` is one of the targeted lightweight Git metadata files
180
+ (`.git/HEAD`, `.git/index`, `.git/packed-refs`, `.git/refs/heads/*`, worktree gitdir).
181
+ Explicitly ignores `.git/objects/*`, `.git/logs/*`, and `.git/*.lock` storms.
182
+ """
183
+ if self._git_dir is None:
184
+ return None
185
+ try:
186
+ resolved = raw_path.resolve(strict=False)
187
+ if not resolved.is_relative_to(self._git_dir):
188
+ return None
189
+ rel_git = resolved.relative_to(self._git_dir).as_posix()
190
+ except (ValueError, OSError):
191
+ return None
192
+
193
+ if not rel_git or rel_git == ".":
194
+ return PathClassification(accepted=False, reason="git_dir_root_ignored")
195
+
196
+ lower_git = rel_git.lower()
197
+ if lower_git.endswith(".lock"):
198
+ return PathClassification(accepted=False, reason="git_lock_ignored")
199
+ if lower_git.startswith(("objects/", "logs/", "hooks/", "info/")):
200
+ return PathClassification(accepted=False, reason="git_internal_ignored")
201
+
202
+ if rel_git in _GIT_STATE_FILES or rel_git.startswith("refs/heads/") or rel_git.startswith("refs/tags/"):
203
+ return PathClassification(
204
+ accepted=True,
205
+ rel_posix=f".git/{rel_git}",
206
+ reason="git_metadata",
207
+ is_config=True,
208
+ is_git_metadata=True,
209
+ )
210
+ return PathClassification(accepted=False, reason="git_other_ignored")
211
+
212
+ def classify_path(self, raw_path: str | Path, *, allow_deleted: bool = True) -> PathClassification:
213
+ """
214
+ Validate boundary containment and classify a raw filesystem path.
215
+
216
+ Security invariants:
217
+ - Rejects paths containing null bytes or resolving outside `root_resolved`.
218
+ - Rejects symlinks, NTFS junctions, and reparse points (never watches outside root).
219
+ - Blocks self-events from RepoDNA cache & generated artifacts.
220
+ - Always accepts semantic config / ignore files (`.gitignore`, `.repodnaignore`,
221
+ `.repodna/architecture.yml`, `tsconfig.json`, `pyproject.toml`, etc.) even when
222
+ located in dot-directories.
223
+ """
224
+ raw_str = str(raw_path)
225
+ if not raw_str or "\x00" in raw_str:
226
+ return PathClassification(accepted=False, reason="invalid_path")
227
+
228
+ candidate = Path(raw_str)
229
+
230
+ # 0. Targeted Git metadata (including external Git worktree gitdir)
231
+ git_cls = self.classify_git_metadata_path(candidate)
232
+ if git_cls is not None:
233
+ return git_cls
234
+
235
+ # 1. Self-event block for RepoDNA cache dir
236
+ if self.is_in_excluded_external_dir(candidate):
237
+ return PathClassification(accepted=False, reason="self_cache_ignored")
238
+
239
+ # 2. Strict repository boundary containment + symlink/junction protection
240
+ try:
241
+ if not candidate.is_absolute():
242
+ candidate = self.root_resolved / candidate
243
+
244
+ # Check every existing ancestor from candidate up to root for symlink/junction escape
245
+ is_junction_fn = getattr(os.path, "isjunction", None)
246
+ check_p = candidate
247
+ while True:
248
+ if check_p == self.root_resolved:
249
+ break
250
+ if os.path.islink(check_p) or (is_junction_fn is not None and is_junction_fn(check_p)):
251
+ return PathClassification(accepted=False, reason="symlink_or_junction_blocked")
252
+ if check_p.exists() and not is_safe_subpath(self.root_resolved, check_p):
253
+ return PathClassification(accepted=False, reason="boundary_escape_blocked")
254
+ parent = check_p.parent
255
+ if parent == check_p:
256
+ break
257
+ check_p = parent
258
+
259
+ resolved_candidate = candidate.resolve(strict=False)
260
+ if resolved_candidate == self.root_resolved:
261
+ return PathClassification(accepted=False, reason="repo_root_self")
262
+ if not resolved_candidate.is_relative_to(self.root_resolved):
263
+ return PathClassification(accepted=False, reason="outside_repository_root")
264
+
265
+ if not allow_deleted and not resolved_candidate.exists():
266
+ return PathClassification(accepted=False, reason="nonexistent")
267
+
268
+ rel_posix = resolved_candidate.relative_to(self.root_resolved).as_posix()
269
+ except (ValueError, OSError):
270
+ return PathClassification(accepted=False, reason="boundary_error")
271
+
272
+ rel_lower = rel_posix.lower()
273
+
274
+ # 3. RepoDNA generated artifacts self-event prevention
275
+ if rel_lower in _REPODNA_GENERATED_FILES or any(
276
+ rel_lower == pfx or rel_lower.startswith(pfx + "/")
277
+ for pfx in _REPODNA_INTERNAL_PREFIXES
278
+ ):
279
+ return PathClassification(accepted=False, reason="repodna_artifact_ignored")
280
+
281
+ parts = rel_posix.split("/")
282
+ filename = parts[-1]
283
+ filename_lower = filename.lower()
284
+
285
+ # 4. Semantic workspace config / ignore / contract files MUST ALWAYS be accepted
286
+ if rel_lower in _WORKSPACE_CONFIG_SET or filename_lower in RESOLVER_CONFIG_FILENAMES:
287
+ # Make sure it's not inside an ignored dir like node_modules/pkg/package.json
288
+ if not any(part in IGNORED_DIRS for part in parts[:-1]):
289
+ return PathClassification(
290
+ accepted=True,
291
+ rel_posix=rel_posix,
292
+ reason="semantic_config",
293
+ is_config=True,
294
+ is_ignore_file=filename_lower in (".gitignore", ".repodnaignore"),
295
+ )
296
+
297
+ # 5. Ignored directories (matches core/analyzer.py discovery semantics)
298
+ for part in parts[:-1]:
299
+ if (
300
+ part in IGNORED_DIRS
301
+ or part.endswith(".egg-info")
302
+ or (part.startswith(".") and part not in {".github"})
303
+ ):
304
+ return PathClassification(accepted=False, reason="ignored_directory")
305
+
306
+ # Also ignore directory events for ignored dir names themselves
307
+ if (
308
+ filename in IGNORED_DIRS
309
+ or filename.endswith(".egg-info")
310
+ or (filename.startswith(".") and filename not in {".github", ".gitignore", ".repodnaignore", ".mailmap", ".env"})
311
+ ):
312
+ return PathClassification(accepted=False, reason="ignored_hidden_or_dir")
313
+
314
+ # 6. IDE scratch / temporary files & lockfiles & binaries
315
+ if self.is_temp_or_editor_scratch(filename):
316
+ return PathClassification(accepted=False, reason="temp_or_editor_file")
317
+
318
+ if filename_lower in IGNORED_LOCKFILES:
319
+ return PathClassification(accepted=False, reason="lockfile_ignored")
320
+
321
+ ext = Path(filename).suffix.lower()
322
+ if ext in BINARY_EXTENSIONS:
323
+ return PathClassification(accepted=False, reason="binary_ignored")
324
+
325
+ # 7. Repository `.gitignore` / `.repodnaignore` rules (via pathspec)
326
+ if self._ignore_spec is not None and self._ignore_spec.match_file(rel_posix):
327
+ return PathClassification(accepted=False, reason="gitignore_matched")
328
+
329
+ return PathClassification(accepted=True, rel_posix=rel_posix, reason="accepted")